Bundle: redb-identity / src/redb.Identity.Core (src.redb.Identity.Core.txt), 283 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/ChangeEmail/IChangeEmailTokenStore.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/ChangeEmail/IChangeEmailTokenStore.cs ---- using System; using System.Threading; using System.Threading.Tasks; namespace redb.Identity.Core.ChangeEmail; /// /// N-4 (Session E, sub-step N4-7): server-side store for single-use /// change-of-e-mail tokens. Direct mirror of /// with two extra bindings — /// the address the user wants to switch to (newEmail) and a snapshot of /// the address at issue time (currentEmail) so the confirm step can detect a /// race where the e-mail was modified through another path between request and confirm. /// public interface IChangeEmailTokenStore { /// /// Issues a new change-of-e-mail token. Generates a 32-byte CSPRNG secret /// (base64url-encoded), persists its peppered SHA-256 hash + the bound /// and snapshots, and /// returns the jti + plaintext token so the caller can embed both into the /// confirm URL. /// /// User the change is bound to. /// Lower-cased target address (committed on confirm). /// Lower-cased snapshot of the user's e-mail at issue time. /// Caller-supplied landing URL captured at issue time. /// Time-to-live for this token. Typically 1 hour. /// When true, mark all prior unconsumed tokens /// for this user as Consumed so a stolen earlier link cannot race the new one. Task IssueAsync( long userId, string newEmail, string currentEmail, string callerConfirmUrl, TimeSpan ttl, bool invalidatePrevious, CancellationToken ct = default); /// /// Verifies and atomically consumes a change-of-e-mail token keyed by . /// On success the row is marked Consumed and the bound user id + new/current /// snapshots are returned so the caller can apply the race-guard and atomic swap. /// Task VerifyAndConsumeAsync( Guid jti, string token, CancellationToken ct = default); } /// Result of . public readonly record struct ChangeEmailIssueResult( Guid Jti, string PlaintextToken, DateTimeOffset ExpiresAt); /// Result of . /// Whether the token verified AND the row was successfully consumed. /// Owner user id when is true; otherwise 0. /// Lower-cased target address bound at issue time; empty when is false. /// Lower-cased snapshot of the e-mail at issue time; empty when is false. /// Diagnostic reason; values: ok, not_found, expired, already_consumed, bad_token. public readonly record struct ChangeEmailVerifyResult( bool Success, long UserId, string NewEmail, string CurrentEmail, string Reason); Path: redb-identity/src/redb.Identity.Core/ChangeEmail/RedbChangeEmailTokenStore.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/ChangeEmail/RedbChangeEmailTokenStore.cs ---- using System; using System.Security.Cryptography; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Core; using redb.Core.Models.Entities; using redb.Identity.Core.Models; using redb.Identity.Core.Services; namespace redb.Identity.Core.ChangeEmail; /// /// N-4 (Session E, sub-step N4-7): redb-backed /// . Direct mirror of /// RedbEmailVerificationTokenStore with two extra fields on the persisted props /// ( + /// ) and the /// invalidatePrevious housekeeping pass at issue time. /// public sealed class RedbChangeEmailTokenStore : IChangeEmailTokenStore { private readonly IServiceScopeFactory _scopeFactory; private readonly RecoveryCodePepperProvider _pepperProvider; private readonly ILogger _logger; private readonly TimeProvider _timeProvider; public RedbChangeEmailTokenStore( IServiceScopeFactory scopeFactory, RecoveryCodePepperProvider pepperProvider, ILogger logger, TimeProvider? timeProvider = null) { _scopeFactory = scopeFactory ?? throw new ArgumentNullException(nameof(scopeFactory)); _pepperProvider = pepperProvider ?? throw new ArgumentNullException(nameof(pepperProvider)); _logger = logger ?? throw new ArgumentNullException(nameof(logger)); _timeProvider = timeProvider ?? TimeProvider.System; } /// public async Task IssueAsync( long userId, string newEmail, string currentEmail, string callerConfirmUrl, TimeSpan ttl, bool invalidatePrevious, CancellationToken ct = default) { if (userId <= 0) throw new ArgumentOutOfRangeException(nameof(userId)); if (string.IsNullOrWhiteSpace(newEmail)) throw new ArgumentException("newEmail is required", nameof(newEmail)); if (string.IsNullOrWhiteSpace(currentEmail)) throw new ArgumentException("currentEmail is required", nameof(currentEmail)); if (ttl <= TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(ttl)); var jti = Guid.NewGuid(); var token = GenerateToken(); var now = _timeProvider.GetUtcNow(); var expires = now + ttl; var hash = RecoveryCodePepperProvider.PepperedSha256Hex(_pepperProvider.Pepper, token); await using var scope = _scopeFactory.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); // Housekeeping: invalidate any prior unconsumed tokens for this user so a // previously-issued link cannot race the new one. if (invalidatePrevious) { var prior = await redb.Query() .Where(o => o.UserId == userId && !o.Consumed) .ToListAsync() .ConfigureAwait(false); if (prior.Count > 0) { foreach (var p in prior) p.Props.Consumed = true; await redb.SaveAsync(prior).ConfigureAwait(false); } } var obj = new RedbObject(new ChangeEmailTokenProps { Jti = jti.ToString("N"), UserId = userId, NewEmail = newEmail.Trim().ToLowerInvariant(), CurrentEmail = currentEmail.Trim().ToLowerInvariant(), TokenHash = hash, PepperId = _pepperProvider.PepperId, IssuedAt = now, ExpiresAt = expires, Consumed = false, Attempts = 0, CallerConfirmUrl = callerConfirmUrl ?? string.Empty, }); obj.name = jti.ToString("N"); await redb.SaveAsync(obj).ConfigureAwait(false); return new ChangeEmailIssueResult(jti, token, expires); } /// public async Task VerifyAndConsumeAsync( Guid jti, string token, CancellationToken ct = default) { if (jti == Guid.Empty) return new ChangeEmailVerifyResult(false, 0, "", "", "not_found"); if (string.IsNullOrEmpty(token)) return new ChangeEmailVerifyResult(false, 0, "", "", "bad_token"); await using var scope = _scopeFactory.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); var key = jti.ToString("N"); await using var tx = await redb.Context.BeginTransactionAsync().ConfigureAwait(false); var row = await redb.Query() .Where(o => o.Jti == key) .FirstOrDefaultAsync() .ConfigureAwait(false); if (row is null) { await tx.RollbackAsync().ConfigureAwait(false); return new ChangeEmailVerifyResult(false, 0, "", "", "not_found"); } if (row.key.HasValue) await redb.LockForUpdateAsync(row.key.Value).ConfigureAwait(false); var p = row.Props; var now = _timeProvider.GetUtcNow(); if (p.Consumed) { await tx.CommitAsync().ConfigureAwait(false); return new ChangeEmailVerifyResult(false, 0, "", "", "already_consumed"); } if (p.ExpiresAt < now) { await tx.CommitAsync().ConfigureAwait(false); return new ChangeEmailVerifyResult(false, 0, "", "", "expired"); } if (_pepperProvider.PeppersFor(p.PepperId).Count == 0) _logger.LogWarning("The token was hashed with pepper {PepperId}, which is no longer configured.", p.PepperId); var ok = _pepperProvider.MatchesTokenHash(token.Trim(), p.TokenHash, p.PepperId); p.Attempts++; if (ok) { p.Consumed = true; } try { await redb.SaveAsync(row).ConfigureAwait(false); await tx.CommitAsync().ConfigureAwait(false); } catch { await tx.RollbackAsync().ConfigureAwait(false); throw; } return ok ? new ChangeEmailVerifyResult(true, p.UserId, p.NewEmail, p.CurrentEmail, "ok") : new ChangeEmailVerifyResult(false, 0, "", "", "bad_token"); } private static string GenerateToken() { Span buf = stackalloc byte[32]; RandomNumberGenerator.Fill(buf); return Base64UrlEncode(buf); } private static string Base64UrlEncode(ReadOnlySpan bytes) { var s = Convert.ToBase64String(bytes); return s.TrimEnd('=').Replace('+', '-').Replace('/', '_'); } } Path: redb-identity/src/redb.Identity.Core/Configuration/AdminScopeEntitlementOptions.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/Configuration/AdminScopeEntitlementOptions.cs ---- namespace redb.Identity.Core.Configuration; /// /// Role-driven entitlement for administrative scopes. /// /// OAuth checks a scope against the client: may this application ask for it? That answer says /// nothing about the person signing in, so a console permitted to request identity:manage handed /// the master management scope to every account that could log into it. This gate adds the missing half /// for user-bound grants: an administrative scope survives only when the user's effective roles carry /// it. The client_credentials grant is untouched — it has no user, and the application's /// scp:{scope} permission remains its authoritative gate. /// /// /// What counts as administrative is deliberately narrow and explicit: Identity's own management surface /// (identity:*) and SCIM. An operator's own scopes are none of this gate's business unless they /// are listed here. identity:account is exempt — it is the self-service scope every signed-in /// user is meant to hold. /// /// public sealed class AdminScopeEntitlementOptions { /// /// Master switch, on by default. Turning it off restores the pre-gate behaviour, where any account /// that can sign in to a console permitted to request identity:manage holds it. Present so a /// deployment that locks itself out can recover from configuration alone, without a rebuild. /// public bool Enabled { get; set; } = true; /// Scope-name prefixes that require an entitling role. Default: identity:. public List GatedPrefixes { get; set; } = new() { "identity:" }; /// Individual scope names that require an entitling role. Default: scim. public List GatedScopes { get; set; } = new() { "scim" }; /// /// Scopes never gated even when a prefix matches. Default: identity:account — self-service /// over one's own profile, which every signed-in user is supposed to have. /// public List Exempt { get; set; } = new() { "identity:account" }; /// True when may only be issued to a user whose roles carry it. public bool IsGated(string scope) { if (string.IsNullOrEmpty(scope)) return false; foreach (var exempt in Exempt) { if (string.Equals(scope, exempt, StringComparison.Ordinal)) return false; } foreach (var gated in GatedScopes) { if (string.Equals(scope, gated, StringComparison.Ordinal)) return true; } foreach (var prefix in GatedPrefixes) { if (!string.IsNullOrEmpty(prefix) && scope.StartsWith(prefix, StringComparison.Ordinal)) return true; } return false; } } Path: redb-identity/src/redb.Identity.Core/Configuration/BackchannelLogoutOptions.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/Configuration/BackchannelLogoutOptions.cs ---- namespace redb.Identity.Core.Configuration; /// /// Which addresses a client's backchannel_logout_uri (OIDC Back-Channel Logout 1.0) may point at. The server /// POSTs a logout_token there when a session of that client ends, so the address is checked by the outbound /// URL guard when it is registered (management API, dynamic registration) and again before every POST. /// public sealed class BackchannelLogoutOptions { /// /// Require https for backchannel_logout_uri. Default: . Set to /// only for relying parties on a trusted network that serve plain HTTP. /// public bool RequireHttps { get; set; } = true; /// /// Allow backchannel_logout_uri to resolve to loopback, private (RFC 1918), link-local or otherwise /// non-public addresses. Default: . Enable it when relying parties are reached on an /// internal network (a container network, a private subnet); then any registrant can make the server POST to /// such an address, so keep dynamic registration behind an initial access token. /// public bool AllowPrivateNetworkTargets { get; set; } } Path: redb-identity/src/redb.Identity.Core/Configuration/ChangeEmailOptions.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/Configuration/ChangeEmailOptions.cs ---- using System; namespace redb.Identity.Core.Configuration; /// /// N-4 (Session E, sub-step N4-7): tunables for the verify-then-commit change-of-e-mail /// flow (direct-vm://identity-me-change-email-request + /// direct-vm://identity-change-email-confirm). /// /// Unlike the soft path on /me/profile (which overwrites the e-mail immediately /// and lazily resets EmailVerified=false), the change-email flow defers the /// commit until the user proves control of the new address: the confirmation link is /// e-mailed to the new address; the current address remains the canonical login /// until the link is clicked. On successful confirm the swap is atomic and /// EmailVerified is set to true in the same transaction. /// /// /// Feature-gated by : when false (default), neither route is /// registered and the HTTP facade returns 404. Per-client URL whitelisting lives on /// ApplicationProps.ChangeEmailUris. /// /// public sealed class ChangeEmailOptions { /// /// Master switch. When false (default), the request + confirm direct-vm routes /// are not registered. Opt-in until a host wires an IEmailNotificationChannel /// and configures per-client ApplicationProps.ChangeEmailUris. /// public bool Enabled { get; set; } = false; /// /// Time-to-live for an issued single-use change-of-e-mail token. Recommended range: /// 30 minutes – 24 hours. Default: 1 hour — short enough to limit the window during /// which a stolen link can hijack the address, long enough for a user to retrieve /// the e-mail from spam folders. /// public TimeSpan TokenTtl { get; set; } = TimeSpan.FromHours(1); /// /// When true (default), issuing a new change-of-e-mail token marks any prior /// unconsumed tokens for the same user as Consumed. Prevents an attacker who /// previously coerced the user into requesting a change from racing the legitimate /// new request. /// public bool InvalidatePreviousTokensOnRequest { get; set; } = true; /// /// When true, ignores the /// email field on inbound MeUpdateProfileRequest bodies so users /// cannot bypass verification by hitting the soft path. Default false keeps /// the soft path functional alongside the strict path (back-office deployments). /// public bool RejectSoftEmailChange { get; set; } = false; } Path: redb-identity/src/redb.Identity.Core/Configuration/ClientKeysOptions.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/Configuration/ClientKeysOptions.cs ---- namespace redb.Identity.Core.Configuration; /// /// Governs how the server fetches a client's JWKS from its jwks_uri /// (RFC 7517), used to verify things the client signed: JAR request objects (RFC 9101) /// and private_key_jwt assertions (RFC 7523). /// /// These are SSRF controls, not tuning knobs. The URL comes from the client record, /// so a fetch makes the server issue an outbound request to an address someone else chose. /// Without the restrictions below that is a probe into the internal network — including cloud /// metadata endpoints such as 169.254.169.254, which hand out credentials to anyone /// who can reach them. Loosen them only for local development. /// /// public sealed class ClientKeysOptions { /// /// How long a fetched JWKS is reused before a background refresh. Default: 12 hours. /// A kid miss triggers one immediate out-of-band refresh regardless of this value, /// so client key rotation is picked up without waiting for the TTL. /// public TimeSpan CacheLifetime { get; set; } = TimeSpan.FromHours(12); /// /// Minimum interval between forced refreshes of the same URL. Bounds how often an /// unauthenticated caller can make us fetch by replaying requests with unknown kids. /// Default: 5 minutes. /// public TimeSpan MinimumRefreshInterval { get; set; } = TimeSpan.FromMinutes(5); /// /// Timeout for a single JWKS fetch. Default: 5 seconds — an authorization request is /// waiting on it, so this must stay short. /// public TimeSpan FetchTimeout { get; set; } = TimeSpan.FromSeconds(5); /// /// Maximum accepted JWKS document size in bytes. Default: 512 KiB. A real key set is a /// few KiB; the cap stops a hostile endpoint from streaming an endless body at us. /// public int MaxDocumentBytes { get; set; } = 512 * 1024; /// /// Most jwks_uri addresses whose key sets are kept at once. With open dynamic registration every new /// client can name its own address, so the cache is bounded: over the limit, entries whose cache lifetime has /// passed go first, then the least recently used; an entry with a fetch in flight stays. A dropped address is /// fetched again the next time it is needed. Worst-case memory is this times . /// Default: 256. /// public int MaxCachedKeySets { get; set; } = 256; /// /// Require https for jwks_uri. Default: true. /// Only set to false for local development against a plain-HTTP test client — /// over HTTP the key set can be swapped in transit, which defeats the signature check /// it is supposed to anchor. /// public bool RequireHttps { get; set; } = true; /// /// Allow jwks_uri to resolve to loopback, private (RFC 1918), link-local or /// otherwise non-public addresses. Default: false. /// Only enable for local development or integration tests that host a JWKS on /// localhost; in production this is the difference between an outbound fetch and /// an internal port scan driven by whoever can edit a client record. /// public bool AllowPrivateNetworkTargets { get; set; } } Path: redb-identity/src/redb.Identity.Core/Configuration/DeliveryOptions.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/Configuration/DeliveryOptions.cs ---- namespace redb.Identity.Core.Configuration; /// /// Delivery of events to webhook subscribers and to the external audit targets through the outbox table /// identity_delivery_outbox. /// /// Guarantee: at least once, no order. An event reaches the outbox in the same pass that writes its /// audit row, after the request that caused it has committed; a delivery whose success was not /// recorded (the node stopped between the answer and the status update) is sent again with the same /// X-RedbIdentity-Delivery id. Receivers deduplicate by that id (or by the event's /// EventId) and order by the event's Timestamp, not by arrival. /// /// public sealed class DeliveryOptions { /// How often a node looks for due deliveries. Default: 2 seconds. public TimeSpan PollInterval { get; set; } = TimeSpan.FromSeconds(2); /// Due rows read per pass. Default: 50. public int BatchSize { get; set; } = 50; /// Deliveries in flight at once on one node. Default: 8. public int MaxParallel { get; set; } = 8; /// /// Deliveries in flight at once for one destination: a subscriber that hangs holds at most this /// many slots, the others keep the rest. Default: 2. /// public int MaxParallelPerDestination { get; set; } = 2; /// /// How long a claimed row stays reserved to the node that took it. Raised to the delivery timeout /// plus a margin when a subscription's timeout is longer. Default: 60 seconds. /// public TimeSpan Lease { get; set; } = TimeSpan.FromSeconds(60); /// /// How long the list of enabled subscriptions is kept in memory. The webhook management API /// refreshes it on this node at once; other nodes see a change within this time. Default: 30 seconds. /// public TimeSpan SubscriptionCache { get; set; } = TimeSpan.FromSeconds(30); /// How long a delivered row is kept before the cleanup deletes it. Default: 7 days. public TimeSpan DeliveredRetention { get; set; } = TimeSpan.FromDays(7); /// /// How long a failed or cancelled row is kept, for inspection and redelivery through the management /// API, before the cleanup deletes it. Default: 30 days. /// public TimeSpan FailedRetention { get; set; } = TimeSpan.FromDays(30); /// /// How often the cleanup runs (leader-only under a Tsak cluster); 0 or infinite turns it off. /// Default: 1 hour. /// public TimeSpan CleanupInterval { get; set; } = TimeSpan.FromHours(1); /// Rows one cleanup statement deletes, so no statement holds the table long. Default: 1000. public int CleanupBatchSize { get; set; } = 1000; /// /// The module reports itself Degraded when the oldest undelivered row is older than this: the /// worker is not running, or a destination has been down that long. Default: 5 minutes. /// public TimeSpan DegradedAfter { get; set; } = TimeSpan.FromMinutes(5); } Path: redb-identity/src/redb.Identity.Core/Configuration/DpopOptions.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/Configuration/DpopOptions.cs ---- namespace redb.Identity.Core.Configuration; /// /// Z4 (RFC 9449): Demonstrating Proof-of-Possession at the Application Layer. /// Configures DPoP proof validation and replay prevention for the Identity server's /// token endpoint. When = false, all DPoP headers are ignored /// and access tokens are issued as plain bearer tokens. /// /// Default policy: SOFT — clients MAY send a DPoP proof; absence of one yields /// a normal bearer token. Per-client strict enforcement is opt-in via /// ApplicationProps.RequireDpop (when present) or via /// =true (server-wide). /// /// public sealed class DpopOptions { /// /// Master switch for DPoP support (validation + cnf.jkt binding + discovery). /// Default: false. /// public bool Enabled { get; set; } /// /// When true, every access-token request MUST present a valid DPoP proof /// or be rejected with invalid_dpop_proof. Default: false (soft mode — /// clients opt-in by sending the header). /// public bool RequireForAccessTokens { get; set; } /// /// Allowed JWS algorithms in DPoP proofs. RFC 9449 §4.2 mandates asymmetric /// algorithms only. Defaults to ES256, ES384, RS256, PS256. /// public string[] AllowedSigningAlgorithms { get; set; } = ["ES256", "ES384", "ES512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512"]; /// /// Maximum age of the iat claim in seconds (clock-skew + transit tolerance). /// RFC 9449 §11.1 recommends a small window. Default: 60 seconds. /// public int IatToleranceSeconds { get; set; } = 60; /// /// Replay-store backend selector — see . /// public DpopReplayStoreOptions ReplayStore { get; set; } = new(); /// /// Z4 P2 (RFC 9449 §8): when true, every DPoP proof MUST carry a valid /// server-issued nonce claim, and proofs without one are rejected with /// use_dpop_nonce + DPoP-Nonce response header. Default: false. /// public bool RequireNonce { get; set; } /// /// Z4 P2 (RFC 9449 §8): nonce validity window for stateless HMAC nonces. The /// server emits a fresh nonce on every response; clients have this much time to /// reuse it before they MUST request a new one. Default: 5 minutes. /// public TimeSpan NonceLifetime { get; set; } = TimeSpan.FromMinutes(5); /// /// Z4 P2 (RFC 9449 §8): override secret used to sign stateless HMAC nonces. /// When unset, a process-stable random secret is generated at startup so a /// cluster of servers will not honour each other's nonces unless this is /// pinned to a shared value (e.g. via IConfiguration). /// public string? NonceSigningSecret { get; set; } } /// /// Replay-store configuration for DPoP proof jti de-duplication. /// /// SECURITY: the in-process Memory backend is single-instance only. In /// multi-node deployments behind a load balancer the same DPoP proof can land on /// different nodes, defeating replay protection. Switch to redis or /// redb for any multi-instance setup. /// /// public sealed class DpopReplayStoreOptions { /// /// Backend identifier — memory (default), redis, or redb. /// public string Backend { get; set; } = "memory"; /// /// Connection string for the Redis backend. Falls back to /// 's Redis CS when omitted. /// public string? RedisConnectionString { get; set; } /// Key prefix for Redis entries. Default: identity:dpop:jti:. public string RedisKeyPrefix { get; set; } = "identity:dpop:jti:"; /// /// Sweep interval for the in-memory backend (cleanup of expired entries). /// Default: 5 minutes. /// public TimeSpan MemorySweepInterval { get; set; } = TimeSpan.FromMinutes(5); } Path: redb-identity/src/redb.Identity.Core/Configuration/EmailVerificationOptions.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/Configuration/EmailVerificationOptions.cs ---- using System; namespace redb.Identity.Core.Configuration; /// /// N-4 (Session C, sub-step N4-6): tunables for the e-mail-verification flow /// (direct-vm://identity-me-email-verify-send + /// direct-vm://identity-email-verify-confirm). /// /// Defaults follow common practice (Auth0=5d, Okta=7d, Cognito=24h, Microsoft Entra B2C=24h) /// at the conservative end. A 24-hour TTL is long enough for a user to retrieve the e-mail /// from spam folders / corporate quarantines but short enough to limit replay risk if the /// inbox is later compromised. /// /// /// The flow itself is feature-gated by : when false, neither /// the send nor the confirm direct-vm route is registered and the HTTP facade returns 404. /// Per-client URL whitelisting lives on ApplicationProps.EmailVerifyUris (mirror of /// PasswordResetUris) so multi-tenant deployments can scope each BFF to its own /// verify page. /// /// public sealed class EmailVerificationOptions { /// /// Master switch. When false (default), the send + confirm direct-vm routes /// are not registered and Core does NOT automatically clear /// UserProps.EmailVerified on /me e-mail change. Opt-in until a host wires an /// IEmailNotificationChannel and configures per-client /// ApplicationProps.EmailVerifyUris. /// public bool Enabled { get; set; } = false; /// /// Time-to-live for an issued single-use verification token. Recommended range: /// 1 hour – 7 days. Default: 24 hours. /// public TimeSpan TokenTtl { get; set; } = TimeSpan.FromHours(24); /// /// When true (default) Core flips UserProps.EmailVerified to false /// as soon as a /me profile update changes the user's e-mail address. The BFF is then /// expected to call POST /api/v1/identity/me/verify-email/send to dispatch a /// fresh verification e-mail. When false, the flag is preserved across changes /// (legacy behaviour — only suitable for trusted-back-office deployments). /// public bool AutoResetOnChange { get; set; } = true; } Path: redb-identity/src/redb.Identity.Core/Configuration/IdempotencyOptions.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/Configuration/IdempotencyOptions.cs ---- namespace redb.Identity.Core.Configuration; /// /// E2 — RFC-style Idempotency-Key support for admin/SCIM mutation endpoints. /// /// When enabled, repeated requests carrying the same Idempotency-Key header (within /// ) replay the cached response body and HTTP status code instead of /// re-executing the underlying mutation. Storage backend: redb PROPS /// (identity.idempotency_record) with TTL cleanup via /// — no Redis dependency. /// /// /// Token issuance is auto-idempotent through the one-time code grant (see C11), so /// the protocol routes do not consult this cache. /// /// public sealed class IdempotencyOptions { /// /// Master switch for idempotency caching. When false, the /// Idempotency-Key header is ignored and every mutation executes normally. /// Default: true. /// public bool Enabled { get; set; } = true; /// /// How long a cached response is replayed for the same key. After this window the /// stored record is eligible for background deletion and a fresh request creates a new /// resource. Default: 24 hours (de-facto industry standard, e.g. Stripe). /// public TimeSpan Ttl { get; set; } = TimeSpan.FromHours(24); /// /// Maximum accepted length of the inbound Idempotency-Key header value. Keys /// longer than this limit are silently ignored (treated as if no key was supplied) so a /// caller cannot blow up the PROPS name index with arbitrary payload. Default: 200. /// public int MaxKeyLength { get; set; } = 200; } Path: redb-identity/src/redb.Identity.Core/Configuration/IdentityAuditOptions.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/Configuration/IdentityAuditOptions.cs ---- namespace redb.Identity.Core.Configuration; /// /// Configuration for the identity audit subsystem. /// Audit events are dispatched to one or more configurable targets (any redb.Route URI). /// public class IdentityAuditOptions { /// /// Master switch for audit event dispatch. Default: true. /// When disabled, events are still logged via ILogger but not sent to any target. /// /// R1 made local persistence cheap (single INSERT into a flat /// identity_audit_log table instead of a multi-row props write), /// so the gate flipped to opt-out — every operator's first question on a /// fresh Identity deployment was "where's the audit log?". /// /// public bool Enabled { get; set; } = true; /// /// Global event type filter. "*" means all events. /// Comma-separated whitelist: "TokenIssued,UserLoggedOut,AuthorizationGranted". /// Applies to all targets uniformly. /// public string Filter { get; set; } = "*"; /// /// H9 (v1.0 DoD): When true and is also true, every event is persisted to the /// built-in identity.audit_event PROPS store (queryable via GET /api/v1/identity/audit). /// External streaming remain independent. Default: true. /// public bool PersistToProps { get; set; } = true; /// /// Events of one route that go to the events route at the same time (the wire taps' thread pool profile /// identity-audit). Up to 1000 more wait; past that the request that raised the event runs it /// itself. Default: 8. /// public int TapConcurrency { get; set; } = 8; /// /// List of audit targets. Each target is a redb.Route URI endpoint. /// public List Targets { get; set; } = []; } /// /// A single audit target — any redb.Route producer URI (sql:, kafka:, es:, rabbitmq:, log:, etc.). /// public class AuditTarget { /// /// Name of this target, required and unique among the enabled targets: the outbox rows of the target /// carry it (at most 200 characters), and logs and metrics name the target by it. Renaming a target /// leaves its pending rows behind as cancelled. /// public string Name { get; set; } = string.Empty; /// Attempts before a delivery to this target ends failed. Default: 10. public int MaxAttempts { get; set; } = 10; /// /// Wait before the second attempt, in milliseconds; it doubles with every attempt, up to 60 seconds. /// Default: 1000. /// public int RetryBackoffMs { get; set; } = 1000; /// Time one attempt may take, in milliseconds. Default: 10000. public int TimeoutMs { get; set; } = 10_000; /// /// Whether this target is active. Default: false. /// public bool Enabled { get; set; } /// /// redb.Route URI for the target endpoint. /// /// SQL parameters are written :#name (the Camel form). @name is NOT a parameter — /// it reaches the database as-is, because it collides with T-SQL and MySQL variables. A target /// still carrying the old @name form stops writing rows and fails with a database error. /// Each parameter is bound by param.name=..., then a header of that name, then a key of /// the body dictionary; casts work (:#details::jsonb). /// /// Examples: /// /// sql:INSERT INTO identity_audit_log(event_id, details) VALUES(:#event_id, :#details::jsonb)?dataSource=#pg-audit&param.event_id=${header.event_id}&param.details=${header.details} /// kafka:identity-audit?brokers=localhost:29092 /// es:identity-audit?server=localhost&port=9200 /// rabbitmq:identity-audit?host=localhost /// log:identity-audit?level=Information /// /// public string Uri { get; set; } = string.Empty; } Path: redb-identity/src/redb.Identity.Core/Configuration/IdentityWebAuthnOptions.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/Configuration/IdentityWebAuthnOptions.cs ---- namespace redb.Identity.Core.Configuration; /// /// MFA-3 (WebAuthn / FIDO2 / Passkeys): Relying-Party configuration. /// /// Crypto-binding fields are explicit and fail-fast on misconfig. RpId and Origins /// participate in WebAuthn signature verification — once a credential is registered against /// a given RpId, that credential is permanently bound to that RpId (the RpIdHash is part /// of the signed authenticatorData). Changing RpId after deployment invalidates every /// existing credential. To prevent that footgun, the validator () /// requires RpId and at least one Origin to be explicitly set; null/empty defaults are /// rejected with at startup. A wrong default would /// cause silent breakage on the next domain rename. /// /// /// is cosmetic-only (shown in the OS authenticator UI as /// "Sign in to {RpName}") and is auto-derived from the Identity issuer when unset. /// /// public sealed class IdentityWebAuthnOptions { /// /// Master switch. When false (default) WebAuthn registration/assertion routes are /// not exposed and the WebAuthn challenge store is not required to be registered. /// When true, is invoked at startup and will throw if /// / are unset. /// public bool Enabled { get; set; } /// /// WebAuthn Relying Party ID — typically the registrable domain or a subdomain of it /// (e.g. auth.example.com or just example.com). Must NOT include scheme, /// port, or path. The browser will only release a credential to an RP whose origin's /// effective domain equals this value or is a registrable suffix. /// /// Required. No default — must be set explicitly because changing it after /// credentials are registered breaks all of them. /// /// public string? RpId { get; set; } /// /// Display name shown in the OS authenticator's prompt ("Sign in to {RpName} on /// auth.example.com"). Cosmetic only, not part of the cryptographic binding. /// Auto-derives from 's host if null. /// public string? RpName { get; set; } /// /// Allowed origins for WebAuthn ceremonies, including scheme and port for non-default /// ports (e.g. https://auth.example.com, https://auth.example.com:8443). /// The browser includes the origin in clientDataJSON; the server rejects any /// origin not listed here. Multiple origins are valid for multi-app SSO scenarios where /// several apps share a single registrable domain. /// /// Required: must contain at least one origin. /// /// public List Origins { get; set; } = new(); /// /// Browser-side ceremony timeout in milliseconds. Authenticator will cancel after this /// elapses without user interaction. Default: 60 000 (60s) — WebAuthn-spec recommended /// for cross-platform / sync-passkey ceremonies. Server-side challenge TTL /// () is independent. /// public int TimeoutMs { get; set; } = 60_000; /// /// Server-side TTL of issued challenges, in seconds. Must be ≥ TimeoutMs/1000 to give /// the browser ceremony enough time. Default: 300 (5 min) — matches OTP TTL and aligns /// with the encrypted setup-token / mfa_state TTL in MfaStateProtector. /// Consumed-challenge markers () are /// retained until this point past completion to anchor anti-replay. /// public int ChallengeTtlSeconds { get; set; } = 300; /// /// User-verification requirement: required | preferred | discouraged. /// /// required = AAL2-strict; PIN/biometric every time. Breaks /// older U2F-only authenticators (Yubikey 4 / Neo without FIPS firmware). /// preferred = AAL2 with graceful downgrade for legacy keys /// (default). NIST AAL2 satisfied for credentials registered with UV; per-credential /// ratchet (registered-with-UV → /// must-assert-with-UV) blocks downgrade attacks. /// discouraged = single-factor (do NOT use for MFA). /// /// Default: preferred. /// public string UserVerification { get; set; } = "preferred"; /// /// Attestation conveyance preference: none | indirect | direct | /// enterprise. none is recommended for passkey/MFA scenarios because /// sync-passkeys (iCloud Keychain, Google Password Manager) never produce attestation /// chains and would break under direct. Use direct only when AAL3 / FIDO L2 /// certification is in scope (typically gov / regulated industries) — and have an /// AaguidBlocklist or MDS in place to act on the data. Default: none. /// public string Attestation { get; set; } = "none"; /// /// Whether to fetch the FIDO Metadata Service (MDS3) on startup for AAGUID lookups /// (vendor name / icon / certification status / revocation list). Disabled by default /// — MDS requires HTTPS reachability of https://mds3.fidoalliance.org/ and a /// JWT chain validation up to GlobalSign root, which is unsuitable for air-gapped / /// on-prem deployments. When false, is the only AAGUID /// gating. v1.0 default: false (MFA AAL2 satisfied without MDS). /// public bool UseFidoMetadataService { get; set; } /// /// Manual list of banned authenticator AAGUIDs (16-byte GUIDs in the canonical /// xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx form). A registration request whose /// attested AAGUID matches an entry is rejected with aaguid_blocked. Useful for /// known-bad models (compromised supply-chain runs, recalled hardware) without bringing /// up MDS infra. Null/empty disables blocklist enforcement. /// public List? AaguidBlocklist { get; set; } /// /// Interval between automatic cleanup of expired /// rows. Set to /// or to disable. /// Default: 1 hour. Clustered — runs on the route-leader node only. /// public TimeSpan ChallengeCleanupInterval { get; set; } = TimeSpan.FromHours(1); /// /// Throws if required fields are unset or invalid. /// Called from RedbIdentityServiceExtensions.AddRedbIdentity after /// Configure<IdentityWebAuthnOptions> binds the appsettings section, so a /// misconfigured deployment fails on startup rather than at first registration request. /// public void Validate() { if (string.IsNullOrWhiteSpace(RpId)) throw new InvalidOperationException( "IdentityWebAuthnOptions.RpId is required (e.g. \"auth.example.com\"). " + "Note: changing RpId after credentials are registered invalidates them — choose carefully."); if (RpId.Contains("://", StringComparison.Ordinal) || RpId.Contains('/', StringComparison.Ordinal)) throw new InvalidOperationException( $"IdentityWebAuthnOptions.RpId must be a bare host name without scheme/path, got '{RpId}'."); if (Origins is null || Origins.Count == 0) throw new InvalidOperationException( "IdentityWebAuthnOptions.Origins is required and must contain at least one https:// origin " + "(e.g. [\"https://auth.example.com\"])."); foreach (var origin in Origins) { if (!Uri.TryCreate(origin, UriKind.Absolute, out var uri) || (uri.Scheme != "https" && !(uri.Scheme == "http" && uri.Host == "localhost"))) { throw new InvalidOperationException( $"IdentityWebAuthnOptions.Origins entry '{origin}' must be an absolute https:// URL " + "(http://localhost is also allowed for local dev)."); } } if (TimeoutMs <= 0) throw new InvalidOperationException( $"IdentityWebAuthnOptions.TimeoutMs must be positive, got {TimeoutMs}."); if (ChallengeTtlSeconds <= 0 || ChallengeTtlSeconds * 1000 < TimeoutMs) throw new InvalidOperationException( $"IdentityWebAuthnOptions.ChallengeTtlSeconds ({ChallengeTtlSeconds}) must be positive " + $"and ≥ TimeoutMs/1000 ({TimeoutMs / 1000})."); if (UserVerification is not ("required" or "preferred" or "discouraged")) throw new InvalidOperationException( $"IdentityWebAuthnOptions.UserVerification must be one of required/preferred/discouraged, got '{UserVerification}'."); if (Attestation is not ("none" or "indirect" or "direct" or "enterprise")) throw new InvalidOperationException( $"IdentityWebAuthnOptions.Attestation must be one of none/indirect/direct/enterprise, got '{Attestation}'."); if (AaguidBlocklist is { Count: > 0 }) { foreach (var entry in AaguidBlocklist) { if (!Guid.TryParse(entry, out _)) throw new InvalidOperationException( $"IdentityWebAuthnOptions.AaguidBlocklist entry '{entry}' is not a valid GUID."); } } } } Path: redb-identity/src/redb.Identity.Core/Configuration/JarOptions.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/Configuration/JarOptions.cs ---- namespace redb.Identity.Core.Configuration; /// /// How strictly a client's declared request_object_signing_alg is enforced once /// JAR (RFC 9101) is switched on. /// public enum JarEnforcementMode { /// /// The declared algorithm is ignored: any algorithm this server supports is accepted, /// as long as the signature itself verifies. /// Off, /// /// A mismatch is logged as a warning and the request proceeds. Use this to find out who /// would break before switching to — the values were editable /// long before anything read them, so some are guesses rather than statements of fact. /// LogOnly, /// /// A mismatch is rejected with invalid_request_object. The intended end state. /// Enforce, } /// /// JAR (RFC 9101) — JWT-Secured Authorization Request. Applies only when /// Features.EnableJar is . /// public sealed class JarOptions { /// /// How to treat a mismatch between the request object's alg and the client's stored /// RequestObjectSigningAlg. Default: . /// /// The default is deliberately not . Those per-client /// values were accepted by the admin API and UI for releases while nothing enforced them, so an /// existing deployment may hold values nobody verified. Starting in LogOnly surfaces the /// mismatches in the log instead of turning them into sign-in failures on upgrade day. /// /// public JarEnforcementMode EnforcementMode { get; set; } = JarEnforcementMode.LogOnly; /// /// Signature algorithms accepted on a request object. Asymmetric only — see /// IClientKeyResolver for why HS* cannot work here (the client secret is /// stored as a BCrypt hash). none is never accepted and cannot be added. /// public string[] AllowedSigningAlgorithms { get; set; } = ["RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512"]; /// /// Clock-skew tolerance when checking exp / nbf / iat. Default: 60 seconds. /// public TimeSpan ClockSkew { get; set; } = TimeSpan.FromSeconds(60); /// /// Maximum accepted size of the request parameter in characters. Default: 50 000. /// A real request object is a few hundred bytes; the cap keeps a hostile client from making /// us parse megabytes on an unauthenticated endpoint. /// public int MaxRequestObjectLength { get; set; } = 50_000; /// /// Require that exp be present. RFC 9101 §4 lists it as required; some clients omit it. /// Default: — without an expiry a captured request object stays /// replayable forever. /// public bool RequireExpiration { get; set; } = true; /// /// Accept a request_uri parameter (the request object by reference, fetched over HTTP) /// in addition to an inline request. Default: when JAR is on. /// /// PAR's urn:ietf:params:oauth:request_uri:* values are never affected by this — those /// are resolved by the PAR pipeline, not fetched. /// /// public bool EnableRequestUri { get; set; } = true; /// /// Fetch a request_uri only when it equals one of the client's registered request_uris /// (OIDC Dynamic Client Registration 1.0 §2), compared exactly: the whole value, query and fragment included. /// A client without registered values cannot use request_uri; an inline request is not affected. /// Discovery publishes the value as require_request_uri_registration. Default: . /// /// With a client that registered values is still held to them, and a client without /// any may use any address, as before 4.8.0; every such use is logged as a warning naming the client, so the /// clients to register can be found before this is switched back on. /// /// public bool RequireRequestUriRegistration { get; set; } = true; /// /// Timeout for fetching a request_uri. Default: 5 seconds — an authorization request is /// blocked on it. /// public TimeSpan RequestUriFetchTimeout { get; set; } = TimeSpan.FromSeconds(5); /// /// Require https for a request_uri. Default: . Over plain /// HTTP the request object could be swapped in transit, defeating the signature it carries. /// Relax only for local development. /// public bool RequestUriRequireHttps { get; set; } = true; /// /// Allow a request_uri to resolve to a non-public address (loopback, private, link-local). /// Default: — the URL comes from the client, so an internal target is an /// SSRF attempt. Enable only for local development / integration tests. /// public bool RequestUriAllowPrivateNetworkTargets { get; set; } } Path: redb-identity/src/redb.Identity.Core/Configuration/MintingKeySource.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/Configuration/MintingKeySource.cs ---- namespace redb.Identity.Core.Configuration; /// /// Which key source signs and encrypts new tokens when both configured credentials /// ( / ) /// and the props signing-key store () are present. /// Both sources are trusted for validation and published in the JWKS either way; only the minting key differs. /// public enum MintingKeySource { /// /// The configured credentials mint; the store's keys only validate. The state of a deployment moving its /// keys to an HSM or a certificate: tokens signed by the store keep validating until they expire. /// Configured, /// /// The store's active key mints; the configured credentials only validate. The state of a deployment /// moving off configured keys onto the store. /// Store, } Path: redb-identity/src/redb.Identity.Core/Configuration/PasswordHashingOptions.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/Configuration/PasswordHashingOptions.cs ---- namespace redb.Identity.Core.Configuration; /// /// C12 — password hashing configuration. /// /// selects the primary algorithm used for new password hashes. /// On successful verification of a legacy hash (different algorithm, or same algorithm with /// weaker parameters than the current configuration), the login flow re-hashes the plaintext /// and persists it — the standard OWASP upgrade-on-login pattern. See /// Security.MultiFormatPasswordHasher + Services.LoginService for the /// implementation. /// /// public sealed class PasswordHashingOptions { /// /// Primary algorithm used for new hashes. Default: /// (OWASP 2023+ recommendation for password storage; memory-hard, GPU-resistant). /// public PasswordHashAlgorithm Algorithm { get; set; } = PasswordHashAlgorithm.Argon2id; /// Argon2id parameters (used when = ). public Argon2idHashOptions Argon2id { get; set; } = new(); /// BCrypt parameters (used when = /// and for verifying legacy BCrypt hashes). public BcryptHashOptions Bcrypt { get; set; } = new(); } /// Enumeration of supported primary password-hashing algorithms. public enum PasswordHashAlgorithm { /// Argon2id — OWASP 2023+ recommended primary. Argon2id, /// BCrypt — legacy-compatible fallback. Bcrypt, } /// /// Argon2id parameters. Defaults match OWASP 2023 guidance for password storage: /// m=64 MiB, t=3, p=4, salt=16 bytes, hash=32 bytes (≈50–150 ms per verify on a modern CPU). /// Tune per deployment and measure with identity.password.verify.duration histogram. /// public sealed class Argon2idHashOptions { /// Memory cost in KiB. Default: 65536 (64 MiB). public int MemoryKib { get; set; } = 65536; /// Iterations (time cost). Default: 3. public int Iterations { get; set; } = 3; /// Degree of parallelism (lanes). Default: 4. public int Parallelism { get; set; } = 4; /// Salt length in bytes. Default: 16 (128 bit). public int SaltBytes { get; set; } = 16; /// Hash length in bytes. Default: 32 (256 bit). public int HashBytes { get; set; } = 32; } /// /// BCrypt parameters. Defaults match current redb.Core.Security.BcryptPasswordHasher. /// public sealed class BcryptHashOptions { /// BCrypt work factor. Default: 12 (~250 ms per verify on a modern CPU). public int WorkFactor { get; set; } = 12; } Path: redb-identity/src/redb.Identity.Core/Configuration/PasswordPolicyOptions.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/Configuration/PasswordPolicyOptions.cs ---- namespace redb.Identity.Core.Configuration; /// /// H10 — server-side password policy applied by management, self-service and SCIM /// password mutations. All knobs are exposed via the standard Tsak 5-layer config /// pipeline (see redb.Identity.Core.config.json:Identity.PasswordPolicy). /// Defaults are STRICT (NIST SP 800-63B Draft + OWASP ASVS 4.0.3 §2.1) so a freshly /// bootstrapped deployment is secure-by-default; tune per environment. /// public sealed class PasswordPolicyOptions { /// Minimum number of characters required. Default 12. public int MinLength { get; set; } = 12; /// /// Maximum number of characters accepted. Acts as a DoS guard against pathologically /// long inputs reaching the Argon2id hasher. Default 512. /// public int MaxLength { get; set; } = 512; /// Require at least one ASCII digit (0-9). Default true. public bool RequireDigit { get; set; } = true; /// Require at least one ASCII uppercase letter (A-Z). Default true. public bool RequireUppercase { get; set; } = true; /// Require at least one ASCII lowercase letter (a-z). Default true. public bool RequireLowercase { get; set; } = true; /// /// Require at least one character from . Default false /// — modern guidance (NIST SP 800-63B §5.1.1.2) deprecates forced symbol classes in /// favour of length + breach screening. /// public bool RequireSpecial { get; set; } = false; /// /// Set of characters that count as "special" when is on. /// Default covers the OWASP-recommended ASCII punctuation set. /// public string SpecialChars { get; set; } = "!@#$%^&*()-_=+[]{}|;:,.<>?/`~\"'\\"; /// /// Number of recent password hashes (per user) to retain and reject on reuse. Set to /// 0 to disable history checks. Default 5. /// public int HistoryCount { get; set; } = 5; /// /// Maximum age of a password before the user is forced to change it on next login. /// Use to disable expiration entirely. Default /// 90 days (industry baseline; turn off in deployments using passkeys/MFA-only). /// public System.TimeSpan MaxAge { get; set; } = System.TimeSpan.FromDays(90); /// /// When true, the configured IBreachedPasswordChecker is consulted on /// every change/set. Default false — opt in by registering a checker /// implementation (e.g. redb.Identity.PasswordPolicy.Hibp). With no checker /// registered the flag is a no-op. /// public bool BreachCheckEnabled { get; set; } = false; } Path: redb-identity/src/redb.Identity.Core/Configuration/PasswordRecoveryOptions.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/Configuration/PasswordRecoveryOptions.cs ---- using System; namespace redb.Identity.Core.Configuration; /// /// N-4 (Session C): tunables for the password-recovery flow /// (direct-vm://identity-password-forgot + /// direct-vm://identity-password-reset). /// /// Defaults follow OWASP ASVS V6.1.3 ("reset token expires within 60 minutes") and the /// industry midpoint (Auth0=60m, Okta=60m, Microsoft=15m, Cognito=60m) at the lower end /// to minimise the window in which a leaked link is exploitable. /// /// public sealed class PasswordRecoveryOptions { /// /// Time-to-live for an issued single-use reset token. Recommended range: 15–60 minutes. /// Default: 30 minutes. /// public TimeSpan TokenTtl { get; set; } = TimeSpan.FromMinutes(30); } Path: redb-identity/src/redb.Identity.Core/Configuration/RateLimitOptions.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/Configuration/RateLimitOptions.cs ---- namespace redb.Identity.Core.Configuration; /// /// C1 — Configuration for per-IP / per-(IP+username) rate limiting that sits in front of /// /connect/token, /login, /mfa/verify, /mfa/recovery and /// /mfa/methods routes. /// /// /// /// The per-IP limit drops distributed brute-force attempts pooled across many usernames; the /// per-(IP+username) failure counter blocks credential-stuffing against a single account from /// one source. They run orthogonally to the per-account lockout enforced inside /// (B5/B6). /// /// /// In-memory backend (default). A ConcurrentDictionary-backed sliding-window /// counter PER NODE — across an N-node cluster the effective ceiling is N × limit /// (acceptable trade-off for online brute-force; matches NGINX/Envoy node-local limits). /// /// /// Redis backend (opt-in). Sliding window via a sorted set (ZADD/ZREMRANGEBYSCORE/ /// ZCARD/EXPIRE) executed atomically — gives a true global limit across the cluster but /// adds one round-trip per gated request. /// /// public sealed class RateLimitOptions { /// Master switch. false = no rate-limit processors are wired into routes. public bool Enabled { get; set; } /// /// Per-IP requests-per-minute ceiling. Bucket = client IP (after C2 trust resolution). /// Applies to /login and /connect/token. Default: 30. /// public int PerIpPerMinute { get; set; } = 30; /// /// Per-(IP+username) failure ceiling within . /// Counts every login / MFA / token failure tied to a particular (IP, username) pair. /// Default: 5. /// public int PerIpUsernameFailures { get; set; } = 5; /// Window for the per-(IP+username) failure counter. Default: 15 minutes. public TimeSpan PerIpUsernameWindow { get; set; } = TimeSpan.FromMinutes(15); /// /// Value sent as the Retry-After header on 429 responses when the store cannot /// compute a precise hint. Default: 60 (seconds). /// public int DefaultRetryAfterSeconds { get; set; } = 60; /// /// Backing store identifier. "memory" (default) keeps counters per node; /// "redis" requires and gives a global limit. /// public string Backend { get; set; } = "memory"; /// /// StackExchange.Redis connection string used when is "redis". /// Example: localhost:6379. Ignored otherwise. /// public string? RedisConnectionString { get; set; } /// /// Optional prefix applied to Redis keys to scope counters per environment / tenant. /// Default: redb:identity:rl:. /// public string RedisKeyPrefix { get; set; } = "redb:identity:rl:"; } Path: redb-identity/src/redb.Identity.Core/Configuration/RedbIdentityOptions.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/Configuration/RedbIdentityOptions.cs ---- using Microsoft.IdentityModel.Tokens; using redb.Identity.Contracts.Configuration; namespace redb.Identity.Core.Configuration; /// /// Configuration options for redb.Identity. /// public class RedbIdentityOptions { /// /// Named redb instance to use. When null or empty, resolves default IRedbService. /// public string? RedbInstanceName { get; set; } /// /// Cross-module shared options (Issuer + Features). Single source of truth /// for both Core (DI registration, OpenIddict configuration, direct-vm /// route registration) and Http (discovery URL formatting, cookie Secure /// detection, HTTP endpoint mounting). Bound from the Identity:* /// section of context.json. The convenience properties /// and are proxies onto this /// instance so existing call-sites keep working unchanged. /// public IdentitySharedOptions Shared { get; set; } = new(); /// /// Cross-module feature toggles. Proxy onto .. /// public IdentityFeatureFlags Features { get => Shared.Features; set => Shared.Features = value; } /// /// Token endpoint throttle: max requests per period per client. /// Default: 10. /// public int TokenThrottleMaxPerPeriod { get; set; } = 10; /// /// Token endpoint throttle period. /// Default: 1 second. /// public TimeSpan TokenThrottlePeriod { get; set; } = TimeSpan.FromSeconds(1); /// /// Retention period (days) for expired/revoked tokens before cleanup deletes them. /// Default: 30. /// public int TokenRetentionDays { get; set; } = 30; /// /// Interval between automatic token cleanup runs. /// Set to or Timeout.InfiniteTimeSpan to disable automatic cleanup. /// Default: 1 hour. /// public TimeSpan TokenCleanupInterval { get; set; } = TimeSpan.FromHours(1); /// /// Batch size for soft-delete purge operations in . /// Default: 50. /// public int TokenCleanupBatchSize { get; set; } = 50; /// /// Retention period (days) for revoked sessions before cleanup deletes them. /// Default: 14. /// public int SessionRetentionDays { get; set; } = 14; /// /// S-track: idle timeout. A session whose LastAccessedAt is older /// than this is auto-revoked on the next SessionService.ListAsync / /// SessionCleanupProcessor pass. Mirrors industry defaults /// (Keycloak 30 min, Okta 2 h, Auth0 3 days). Default: 24 h — middle of /// the range, lets active dev / cli sessions stay alive overnight while /// killing forgotten ones within a day. /// public TimeSpan SessionIdleTimeout { get; set; } = TimeSpan.FromHours(24); /// /// S-track: absolute timeout regardless of activity. A session whose /// DateCreate is older than this is auto-revoked even if it was /// just refreshed. Cap on total lifetime so a long-lived refresh-token /// chain doesn't keep one cookie alive forever. Default: 30 days. /// public TimeSpan SessionAbsoluteTimeout { get; set; } = TimeSpan.FromDays(30); /// /// Interval between automatic session cleanup runs. /// Set to or Timeout.InfiniteTimeSpan to disable. /// Default: 1 hour. /// public TimeSpan SessionCleanupInterval { get; set; } = TimeSpan.FromHours(1); /// /// B3: interval between automatic cleanup runs for expired server-side MFA OTP rows /// (). Set to or /// Timeout.InfiniteTimeSpan to disable. Default: 1 hour. Clustered — runs on /// the route-leader node only. /// public TimeSpan MfaOtpCleanupInterval { get; set; } = TimeSpan.FromHours(1); /// /// W6-0: maximum lifetime of an entry in the backchannel revoked-sids list. Server clamps /// any client-supplied ExpiresAt to now + RevokedSidsMaxRetention. Should be /// at least the longest cookie / refresh-token lifetime among Relying Parties. /// Default: 24 hours. /// public TimeSpan RevokedSidsMaxRetention { get; set; } = TimeSpan.FromHours(24); /// /// W6-0: interval between cleanup runs that purge expired entries from the /// identity.revoked_sid PROPS table. Set to or /// Timeout.InfiniteTimeSpan to disable. Clustered — runs on the route-leader /// node only. Default: 1 hour. /// public TimeSpan RevokedSidsCleanupInterval { get; set; } = TimeSpan.FromHours(1); /// /// Interval between cleanup runs that delete idempotency records whose time to live /// () has ended. Set to or /// Timeout.InfiniteTimeSpan to disable. Clustered: runs on the route-leader node only. /// Default: 1 hour. /// public TimeSpan IdempotencyCleanupInterval { get; set; } = TimeSpan.FromHours(1); /// /// Records deleted per batch by the idempotency record cleanup. A run deletes batch after batch until no /// expired record is left. Default: 500. /// public int IdempotencyCleanupBatchSize { get; set; } = 500; /// /// Interval at which each replica reloads the DataProtection XML key-ring snapshot /// () from PROPS storage. Runs per-node /// (NOT cluster-leader-only) so every replica picks up keys rotated by other nodes, /// preventing split-key-ring windows after rotation. /// Set to or to disable /// — safe for single-instance deployments where initial snapshot at /// RedbXmlRepositoryInitListener.OnContextStarting is sufficient. /// Default: 12 hours (≤ half of KeyManagementOptions.AutoRefreshIntervalForActiveKey 24h, per Nyquist). /// public TimeSpan XmlRepositoryRefreshInterval { get; set; } = TimeSpan.FromHours(12); /// /// MFA-3: WebAuthn (FIDO2 / Passkey) configuration. Disabled by default; set /// to true and configure /// + /// to expose /connect/mfa/webauthn/* routes and the per-credential CRUD endpoints. /// public IdentityWebAuthnOptions WebAuthn { get; set; } = new(); /// /// Issuer URI for the identity server (appears in iss claim and discovery document). /// Required for production; defaults to https://localhost/ for development. /// Proxy onto .. /// public Uri Issuer { get => Shared.Issuer; set => Shared.Issuer = value; } /// /// Signing credentials for JWT tokens. When empty, ephemeral keys are used (dev only). /// public List SigningCredentials { get; set; } = []; /// /// Encryption credentials for token payloads. When empty, ephemeral keys are used (dev only). /// public List EncryptionCredentials { get; set; } = []; /// /// When true, allows AddRedbIdentityServer to fall back to ephemeral signing / /// encryption keys if no / /// were configured. Must remain false in production — ephemeral keys split the /// JWKS across cluster replicas (tokens issued by one node fail validation on another) and /// invalidate every live token on restart. Set to true only in Development / /// integration-test fixtures. Default: false. /// public bool AllowEphemeralKeys { get; set; } = false; /// /// A3: when true, OpenIddict signing / encryption credentials are populated from /// the PROPS-backed . Initial keys are generated on /// first context start () if the store is /// empty; private PEM material is encrypted with the DataProtection key ring. Cluster /// replicas share one JWKS because they read from the same PROPS rows. /// /// Can be combined with pre-populated / /// — the state of a deployment moving its keys to or from /// configured ones. Both sources are then trusted for validation and published in the JWKS, and /// must say which one signs and encrypts new tokens. Not with /// : ephemeral keys stand in for persistent ones, and this is them. /// /// Default: false (feature is opt-in until rotation automation ships). /// public bool UsePropsSigningKeyStore { get; set; } = false; /// /// Which key source signs and encrypts new tokens when both / /// and the props signing-key store /// () are configured. Both sources are always trusted for /// validation and published in the JWKS; this decides the minting key only. Required when both sources /// are present and refused when they are not: the pair is a migration state, and who mints during it is /// the operator's decision, not the order two registrations happen to run in. /// public MintingKeySource? MintingKeySource { get; set; } /// Access token lifetime. Default: 1 hour. public TimeSpan AccessTokenLifetime { get; set; } = TimeSpan.FromHours(1); /// Refresh token lifetime. Default: 14 days. public TimeSpan RefreshTokenLifetime { get; set; } = TimeSpan.FromDays(14); /// /// Refresh token reuse leeway. After rotation, the old token remains valid for this window. /// TimeSpan.Zero = strict rotation (old token rejected immediately). /// Default: TimeSpan.Zero (strict). /// public TimeSpan RefreshTokenReuseLeeway { get; set; } = TimeSpan.Zero; /// Authorization code lifetime. Default: 5 minutes. public TimeSpan AuthorizationCodeLifetime { get; set; } = TimeSpan.FromMinutes(5); /// Identity token lifetime. Default: 5 minutes. public TimeSpan IdentityTokenLifetime { get; set; } = TimeSpan.FromMinutes(5); /// /// Issue access tokens as plain JWS (signed, not encrypted). Only access tokens: authorization codes, /// refresh tokens, device and user codes and OpenIddict's state tokens stay encrypted, so an encryption /// credential is required either way. Default: false. /// public bool DisableAccessTokenEncryption { get; set; } /// /// The OP's own audience for access tokens (RFC 9068 §3 default resource indicator). /// Issued access tokens carry it whenever an identity:* scope is granted, or when /// the granted scopes' Resources and the application's AccessTokenAudiences /// are both empty; the local validation stack (management API) accepts only tokens that /// carry it. null resolves to {Issuer}/resources /// (see ). /// public string? DefaultAccessTokenAudience { get; set; } /// /// Resolves the effective OP audience: a configured value wins (trimmed), otherwise /// {issuer}/resources with a single slash regardless of the issuer's trailing slash. /// public static string ResolveDefaultAccessTokenAudience(Uri issuer, string? configured) { ArgumentNullException.ThrowIfNull(issuer); if (!string.IsNullOrWhiteSpace(configured)) return configured.Trim(); return issuer.AbsoluteUri.TrimEnd('/') + "/resources"; } /// /// Required OAuth scope for management API access. /// Clients must request this scope to call /api/v1/identity/* endpoints. /// Default: identity:manage. /// public string ManagementScope { get; set; } = "identity:manage"; /// /// OAuth scope granting self-service access to the management API (B8). /// A token bearing this scope may invoke management endpoints only when the body / route /// userId matches the token's sub claim. Tokens bearing /// are treated as administrators and may target any user. /// Modeled on Keycloak's manage-account (self) vs realm-admin (cross-user) /// split. Default: identity:account. /// public string AccountScope { get; set; } = "identity:account"; /// /// Group-membership gate for selected OAuth scopes. Maps /// scopeName → groupName. When a user-bound token request /// (authorization_code, password, device_code, or a refresh_token derived from /// these) requests one of the listed scopes, the OpenIddict pipeline rejects the /// request with error=access_denied unless the authenticated user is a /// (non-expired) member of the required group. /// /// The client_credentials grant is intentionally unaffected — it has no /// user identity, so the existing scp:{scope} permission on the /// application is the authoritative gate for that flow. /// /// /// Typical bootstrap configuration: /// { ["identity:manage"] = "identity-admins" } — restricts the /// management scope to members of the admin group. /// /// Default: empty (no scope restrictions). /// public Dictionary ScopeRequiredGroups { get; set; } = new(StringComparer.Ordinal); /// /// Role-driven entitlement for administrative scopes — the user-side half of the scope check that /// OAuth only performs against the client. See . /// /// Complements rather than replacing it: that one gates by group /// membership and stays available for deployments modelling access with groups. /// /// public AdminScopeEntitlementOptions AdminScopeEntitlement { get; set; } = new(); // ── Dynamic Client Registration (RFC 7591) ── // Note: the on/off toggle moved to .EnableDynamicRegistration. /// /// Grant types allowed for dynamically registered clients. /// Default: ["authorization_code", "refresh_token"]. /// public string[] DynamicRegistrationAllowedGrantTypes { get; set; } = ["authorization_code", "refresh_token"]; /// /// Scopes allowed for dynamically registered clients. /// Default: ["openid", "profile", "email", "phone", "address", "offline_access", "groups", "roles"]. /// All of these are user-info scopes (claims about the user) and standard OIDC profile/contact /// scopes — none grant API privilege. Admin scopes (identity:*) and SCIM are intentionally /// excluded so anonymous DCR cannot self-elevate. Override the list to restrict further if needed. /// public string[] DynamicRegistrationAllowedScopes { get; set; } = ["openid", "profile", "email", "phone", "address", "offline_access", "groups", "roles"]; /// /// Optional initial access token (RFC 7591 §1.2). When set, the POST /connect/register /// request must include Authorization: Bearer {token}. When null, empty or whitespace, no token /// is configured: the endpoint is open (rate-limited only) and an anonymous registrant is refused /// every administrative scope (see ), whatever /// lists. /// public string? DynamicRegistrationInitialAccessToken { get; set; } /// /// Per-IP throttle for the Dynamic Client Registration endpoint: max requests per /// . Tunable independently from /// because DCR is a write-heavy admin /// endpoint with very different traffic shape than the token endpoint. /// Default: 5. /// public int DynamicRegistrationThrottleMaxPerPeriod { get; set; } = 5; /// /// Window for . Default: 10 seconds. /// public TimeSpan DynamicRegistrationThrottlePeriod { get; set; } = TimeSpan.FromSeconds(10); // ── Device Code Flow (RFC 8628) ── // Note: the on/off toggle moved to .EnableDeviceCodeFlow. // ── Pushed Authorization Requests (RFC 9126 / Z6) ── // Note: the on/off toggle moved to .EnablePushedAuthorization. /// /// Z6 (RFC 9126 §2.1): when true, the authorization endpoint REJECTS requests /// that did not originate as a PAR (i.e. requests not carrying a request_uri issued /// by this server). Effective only when /// is also true. Default: false. /// public bool RequirePushedAuthorizationRequests { get; set; } /// /// Z6: lifetime of a request_uri issued by the PAR endpoint. RFC 9126 §2.2 mandates /// it MUST be SHORT-LIVED; the typical value is 60 seconds. Default: 90 seconds. /// public TimeSpan PushedAuthorizationRequestLifetime { get; set; } = TimeSpan.FromSeconds(90); /// /// Z4 (RFC 9449): DPoP support — proof-of-possession-bound access tokens. /// See for full configuration. /// public DpopOptions Dpop { get; set; } = new(); /// /// How the server fetches a client's JWKS from its jwks_uri — SSRF limits, /// cache lifetime and timeouts. Used to verify what a client signed: JAR request objects /// (Z7 / RFC 9101) and private_key_jwt assertions. See . /// public ClientKeysOptions ClientKeys { get; set; } = new(); /// /// Which addresses a client's backchannel_logout_uri may point at, checked at registration and before /// every logout POST. See . /// public BackchannelLogoutOptions BackchannelLogout { get; set; } = new(); /// /// Z7 (RFC 9101): JWT-Secured Authorization Request. Effective only when /// is . /// See . /// public JarOptions Jar { get; set; } = new(); /// /// Webhook delivery through the outbox: polling, parallelism, lease and the subscription cache. /// See . /// public DeliveryOptions Delivery { get; set; } = new(); /// /// Lifetime of the device_code / user_code pair. /// Default: 10 minutes (RFC 8628 §3.2 recommends ≤ 15 min). /// public TimeSpan DeviceCodeLifetime { get; set; } = TimeSpan.FromMinutes(10); /// /// Polling interval in seconds returned to the client in the device authorization response. /// Default: 5 seconds (per RFC 8628 §3.2). /// public int DeviceCodePollingInterval { get; set; } = 5; // ── Resource Owner Password Credentials (RFC 6749 §4.3) ── /// /// Enable the ROPC grant (grant_type=password). Opt-in only. /// Allows direct username/password to token exchange via POST /connect/token. /// Default: false. /// public bool EnablePasswordFlow { get; set; } // ── PKCE (RFC 7636) ── /// /// Require Proof Key for Code Exchange (PKCE) on EVERY authorization_code request. /// When true (default), an /connect/authorize request without a code_challenge /// is rejected — the OAuth 2.1 hardening posture. Set to false to also accept plain /// authorization_code flows without PKCE (e.g. legacy clients, or to certify the OpenID /// "Basic OP" profile, whose non-PKCE tests require the OP to accept such requests). /// PKCE, when present, is ALWAYS S256-only (RFC 7636 §4.2 — plain is never accepted), /// regardless of this flag. /// Default: true. /// public bool RequirePkce { get; set; } = true; /// /// RFC 8252 §7.3 — accept any port on a client's registered loopback redirect URI. /// /// A native or CLI app (think az login, gh auth login) cannot know its callback /// port before it starts: it asks the OS for an ephemeral one, so the port changes on every run /// and cannot be registered ahead of time. §7.3 requires the authorization server to compare /// everything about a loopback redirect URI EXCEPT the port. With this off, desktop clients /// simply cannot use this provider. /// /// /// The widening is narrow by construction: it applies only when the client has ALREADY /// registered a redirect URI whose host is the loopback literal 127.0.0.1 or /// [::1] (never the name localhost — §8.3 warns that a name goes through /// resolution and can be pointed elsewhere), and only the port is ignored — scheme, host, path, /// query and fragment must still match exactly. A web client registered at /// https://app.example.com/cb has no loopback URI to match, so nothing about it changes. /// /// Default: true — this is a MUST in RFC 8252 §7.3, not an opt-in feature. /// public bool AllowLoopbackRedirectPortWildcard { get; set; } = true; // ── Token Exchange (RFC 8693) ── /// /// Enable the Token Exchange grant (grant_type=urn:ietf:params:oauth:grant-type:token-exchange). /// Allows delegation and impersonation token flows (RFC 8693). /// Default: false. /// public bool EnableTokenExchange { get; set; } /// /// Allow impersonation token exchange (the actor disappears — the new token looks like /// it was issued directly to the subject). When false, only delegation is allowed /// (the act claim preserves the actor chain). /// Default: false. /// public bool TokenExchangeAllowImpersonation { get; set; } /// /// Maximum depth of the act claim delegation chain. /// Prevents runaway chained exchanges. 0 = unlimited. /// Default: 5. /// public int TokenExchangeMaxDelegationDepth { get; set; } = 5; // ── Session / Login ── /// /// Path to the login page. Used for redirect when login_required on authorize. /// Default: /login. /// public string LoginPath { get; set; } = "/login"; /// /// Path to the consent page. Used for redirect when consent_required on authorize. /// Default: /consent. /// public string ConsentPath { get; set; } = "/consent"; /// /// Path to the MFA verification page. Used for redirect when MFA is required after login. /// Default: /mfa. /// public string MfaPath { get; set; } = "/mfa"; /// /// Path to the MFA recovery code page. /// Default: /mfa/recovery. /// public string MfaRecoveryPath { get; set; } = "/mfa/recovery"; /// /// Minimum delay between consecutive OTP send requests (SMS/Email). /// Prevents spamming an end user / running up SMS bills. Default: 60 seconds. /// public TimeSpan OtpCooldown { get; set; } = TimeSpan.FromSeconds(60); /// /// Maximum OTP sends per user per rolling hour (SMS/Email combined). /// Default: 5. /// public int OtpMaxPerHour { get; set; } = 5; /// /// Tolerance (clock skew) applied to MFA lockout-window comparisons (B9 / BUG-5). /// A user is treated as locked out while now < LockedUntil + skew and unlocked /// once now >= LockedUntil + skew. Prevents premature unlock when the server /// clock is slightly fast relative to the clock that wrote LockedUntil. /// Default: 5 seconds. /// public TimeSpan MfaLockoutClockSkew { get; set; } = TimeSpan.FromSeconds(5); // ── MFA recovery codes (B4: PBKDF2 + per-user salt + pepper) ── /// /// Server-wide pepper applied to recovery-code hashing in addition to the per-user salt /// (base64-encoded, 16+ bytes recommended). When null: /// /// If is true, an ephemeral random /// pepper is generated at startup. Recovery codes are then unverifiable across restarts / /// across replicas. /// If is false, registration of /// the identity server fails with an explanatory exception. /// /// Production deployments must configure a stable pepper distributed via a secret store. /// public string? RecoveryCodePepper { get; set; } /// /// Earlier values of , kept so that a rotation does not void what was issued /// under them: MFA recovery codes and the open password-reset, e-mail-verification and change-e-mail links. /// Each value is base64 of 16 or more bytes and differs from the current pepper; a bad value fails the start. /// New hashes always use ; these are only tried on verification. Every stored /// hash records the id of its pepper, so a record is checked against that one pepper; records written before /// 4.8.0 carry no id and are tried with the current pepper, then with these in order. /// /// While the list is not empty the leader logs once after start and then daily, per previous pepper id, how many /// users still hold recovery codes under it. A value can be removed when its count is 0 and the longest link /// lifetime has passed since the rotation. Set the same values on every node at once. Default: none. /// /// public string[]? RecoveryCodePreviousPeppers { get; set; } /// /// PBKDF2-HMAC-SHA256 work factor (iterations) used when hashing newly generated recovery /// codes. OWASP guidance (2024) recommends ≥ 600 000 for SHA-256. Existing stored hashes /// continue to verify against the iteration count embedded in their format string. /// Default: 600 000. /// public int RecoveryCodePbkdf2Iterations { get; set; } = 600_000; /// /// Lifetime of the session cookie. After this the user must log in again. /// Default: 8 hours. /// public TimeSpan SessionCookieLifetime { get; set; } = TimeSpan.FromHours(8); // ── UI Customization ── /// /// Title shown on the login page. Default: Sign In. /// public string LoginTitle { get; set; } = "Sign In"; /// /// URL of a logo image shown above the login form. When null, no logo is rendered. /// public string? LogoUrl { get; set; } /// /// Primary color for buttons and accents (CSS color value). Default: #2563eb. /// public string PrimaryColor { get; set; } = "#2563eb"; /// /// Primary color hover state. Default: #1d4ed8. /// public string PrimaryColorHover { get; set; } = "#1d4ed8"; /// /// Extra CSS injected into every identity page (login, consent, logout). /// public string? CustomCss { get; set; } // ── SCIM 2.0 (RFC 7643/7644) ── // Note: the on/off toggles moved to .EnableScim / EnableScimBulk. /// /// Required OAuth scope for SCIM API access. /// Clients must request this scope to call /scim/v2/* endpoints. /// Default: scim. /// public string ScimScope { get; set; } = "scim"; /// /// H1: maximum number of operations accepted in one SCIM Bulk request. Mirrors the /// bulk.maxOperations field advertised in /scim/v2/ServiceProviderConfig. /// Default: 1000. /// public int ScimBulkMaxOperations { get; set; } = 1000; /// /// H1: maximum payload size (bytes) accepted in one SCIM Bulk request. Mirrors the /// bulk.maxPayloadSize field advertised in /scim/v2/ServiceProviderConfig. /// Default: 1 MiB. /// public int ScimBulkMaxPayloadSize { get; set; } = 1_048_576; // ── Federation (OIDC / external IdP) ── // Note: the on/off toggle moved to .EnableFederation. /// Configured external OIDC federation providers. public List FederationProviders { get; set; } = []; // ── C2: Trusted reverse-proxy whitelist for client-IP resolution ── /// /// Whitelist of trusted reverse-proxy IPs / networks consulted by /// when sanitizing the /// redbHttp.RemoteAddress exchange header before per-IP throttling (C1) sees it. /// /// Secure-by-default: is false, /// so X-Forwarded-For / Forwarded headers are ignored entirely and the socket /// IP is always used. To enable forwarded-IP resolution behind a reverse proxy, set /// TrustForwardedFor=true AND populate /// or with the proxy address(es). /// /// public ReverseProxyOptions ReverseProxies { get; set; } = new(); // ── C1: Per-IP / per-(IP+username) rate limiting ── /// /// Configuration for the C1 rate-limit guard sitting in front of /connect/token, /// /login and the MFA endpoints. See for trust model /// and backend selection. Disabled by default; enable + select a backend to activate. /// public RateLimitOptions RateLimit { get; set; } = new(); /// /// Length / size limits applied by management & registration processors when validating /// inbound payloads. Defaults match historical hardcoded values; tune per deployment. /// public IdentityValidationOptions Validation { get; set; } = new(); /// /// Hardening knobs for the OIDC federation state parameter (anti-replay, browser-binding, TTL). /// public FederationStateOptions FederationState { get; set; } = new(); /// /// N-4 (Session C): outbound SMTP transport used by the transactional e-mail channel /// (password recovery, MFA delivery, account notices). Disabled by default — a host /// that does not enable SMTP must register an alternative IEmailNotificationChannel /// (e.g. the in-memory channel used by integration tests, or a SendGrid adapter). /// public SmtpOptions Smtp { get; set; } = new(); /// /// N-4 (Session C): tunables for the anonymous password-recovery flow (TTL etc.). /// public PasswordRecoveryOptions PasswordRecovery { get; set; } = new(); /// /// N-4 (Session C, sub-step N4-6): tunables + feature gate for the e-mail-verification /// flow. Disabled by default — opt-in until a host wires an /// and configures per-client /// ApplicationProps.EmailVerifyUris. /// public EmailVerificationOptions EmailVerification { get; set; } = new(); /// /// N-4 (Session E, sub-step N4-7): tunables + feature gate for the strict /// verify-then-commit change-of-e-mail flow. Disabled by default — opt-in until a /// host wires an and configures /// per-client ApplicationProps.ChangeEmailUris. When this option is enabled /// hosts SHOULD also set to /// true so the soft /me/profile path stops accepting an unverified /// e-mail update and forces all e-mail changes through the strict flow. /// public ChangeEmailOptions ChangeEmail { get; set; } = new(); /// /// N-3 (sub-step N3-7): feature gate + tunables for the anonymous self-service /// account-registration flow. Disabled by default — corporate identity deployments /// that provision users via admin / SCIM should leave this off. /// public RegistrationOptions Registration { get; set; } = new(); /// /// C9 — cookie security defaults: __Host-/__Secure- name prefixes, /// SameSite mode, etc. All cookies emitted by Identity inherit /// HttpOnly and Secure (when issuer is https) automatically; /// these knobs cover the spec-defined extras. /// public IdentityCookieOptions Cookies { get; set; } = new(); /// /// C10 — at-rest encryption for the ASP.NET DataProtection key-ring stored in redb PROPS. /// Without an encryptor configured, key-ring elements live in the database in plaintext; /// a database leak then compromises every Identity-issued cookie / federation state / /// MFA setup token. /// public DataProtectionOptions DataProtection { get; set; } = new(); /// /// E2 — Idempotency-Key response cache for admin/SCIM mutations. See /// for behaviour and storage details. /// public IdempotencyOptions Idempotency { get; set; } = new(); /// /// C12 — password hashing algorithm + parameters for newly stored passwords, and /// auto-rehash of legacy formats on successful login. See /// . /// public PasswordHashingOptions PasswordHashing { get; set; } = new(); /// /// H10 — server-side password policy: length, composition, history reuse, /// expiration, breach screening. Defaults are STRICT (NIST SP 800-63B / OWASP /// ASVS 4.0.3 §2.1) so a freshly bootstrapped deployment is secure-by-default; /// every knob is overridable via the standard 5-layer config pipeline. /// public PasswordPolicyOptions PasswordPolicy { get; set; } = new(); /// /// B1 — emergency local-admin bootstrap endpoint (POST /internal/bootstrap-admin). /// On a brand-new deployment with an empty identity database (no users, groups, OIDC /// clients) there is no way to log in — even client_credentials requires a /// pre-registered confidential client. This endpoint atomically creates the first /// admin user, the identity-admins group, the identity-web OIDC client /// and a SystemFlag(name=bootstrap_completed) sentinel; subsequent calls /// return 410 Gone. Disabled by default — set /// + /// (env-only!) to enable. /// public BootstrapOptions Bootstrap { get; set; } = new(); /// /// Default-credential seeder for the well-known admin user that ships /// in the base redb SQL seed (_users.id = 1, login = "admin", /// empty password). On host startup, SeedAdminPasswordHostedService /// looks up the user by ; if found and its /// stored password is empty or still the default admin (a Tsak dashboard on the /// same database writes admin/admin first), is /// hashed via the configured and persisted, so a fresh /// install supports admin/admin sign-in out-of-the-box. Logs a loud /// startup WARNING when the password is the default admin. /// public SeedAdminOptions SeedAdmin { get; set; } = new(); /// /// Default OIDC-client seeder that ensures the canonical Web Console client /// () exists in the OpenIddict /// application store on host startup. Sister to — /// fully idempotent (no-op when the client already exists), opinionated /// defaults wired for the bundled redb.Identity.Web BFF running on /// https://localhost:7000. For non-default deployments override /// and /// via /// context.json / env-vars. /// public SeedWebClientOptions SeedWebClient { get; set; } = new(); /// /// W6-0 — default seeder for the client_credentials service-account /// used by a polling Web BFF to push/poll the backchannel revoked-sids list. /// Sister to ; disabled by default so it does not /// inflate the OpenIddict client store on hosts that don't run the Web BFF. /// public SeedBackchannelClientOptions SeedBackchannelClient { get; set; } = new(); } /// /// Options for the default-admin password seeder that ensures the well-known /// admin user from the base redb SQL seed has a usable password on a fresh /// install. Idempotent: only updates when the stored password is empty or still the /// default admin; a password the operator changed is never overwritten. /// public sealed class SeedAdminOptions { /// Default plaintext password used when no override is supplied. public const string DefaultPassword = "admin"; /// Master switch; default true. Set to false to disable seeding entirely. public bool Enabled { get; set; } = true; /// Login of the seed admin user; default admin. public string Login { get; set; } = "admin"; /// /// Plain-text password to hash and store when the user has no password. Default /// admin. Convenience for fresh deployments only — change this /// (or rotate the password via the management API) before exposing the host to /// untrusted networks. Leaving the default produces a startup WARNING. /// public string Password { get; set; } = DefaultPassword; } /// /// Options for the default OIDC-client seeder that ensures the canonical /// identity-web client exists in the OpenIddict application store on a /// fresh install. Idempotent: skips when a client with the same /// already exists. Defaults are wired for the bundled /// redb.Identity.Web BFF. /// public sealed class SeedWebClientOptions { /// Master switch; default true. Set to false to disable seeding entirely. public bool Enabled { get; set; } = true; /// OIDC client identifier; default identity-web (matches Web BFF appsettings). public string ClientId { get; set; } = "identity-web"; /// /// Optional client secret. When empty the client is registered as a Public /// client (PKCE-only). The bundled redb.Identity.Web BFF runs as a /// public client by default — leave this empty unless you flip Web to /// confidential mode. /// public string ClientSecret { get; set; } = string.Empty; /// Display name shown on the consent page; default "Identity Web Console". public string DisplayName { get; set; } = "Identity Web Console"; /// /// Allowed redirect URIs (post-authorization callback). Default points at /// https://localhost:7000/signin-oidc (Web BFF dev binding). /// public List RedirectUris { get; set; } = new() { "https://localhost:7000/signin-oidc", }; /// /// Allowed post-logout redirect URIs. Default points at /// https://localhost:7000/signout-callback-oidc. /// public List PostLogoutRedirectUris { get; set; } = new() { "https://localhost:7000/signout-callback-oidc", }; /// /// Allowed scopes the client may request. Default mirrors the Web BFF /// requested scopes (openid, profile, email, roles, offline_access, /// identity:manage, identity:account). Standard OIDC scopes are always permitted /// regardless of this list — entries here additionally grant non-standard scopes via /// Permissions.Prefixes.Scope. identity:account is included so the /// BFF can call self-service /me/* endpoints (e.g. native consent grant) /// on behalf of the signed-in user without further deployment configuration. /// public List Scopes { get; set; } = new() { "openid", "profile", "email", "roles", "offline_access", "identity:manage", "identity:account", }; } /// /// Options for the W6-0 backchannel service-account seeder. Ensures a confidential /// client_credentials OpenIddict application exists so a polling Web BFF /// can push and read revoked-sids without holding an end-user token. Idempotent: /// skipped when an application with the same already exists. /// public sealed class SeedBackchannelClientOptions { /// Master switch. Default false — opt-in per deployment. public bool Enabled { get; set; } = false; /// Client identifier of the service account. Default identity-backchannel. public string ClientId { get; set; } = "identity-backchannel"; /// /// Client secret. Must be non-empty when is true — the /// seeder logs and skips when missing rather than registering a public client /// (client_credentials requires a confidential client per RFC 6749 §4.4). /// public string ClientSecret { get; set; } = string.Empty; /// Display name shown in admin UI / logs. public string DisplayName { get; set; } = "Identity Backchannel Service Account"; /// /// Scopes the service account is allowed to request. Default identity:manage /// — sufficient to call /api/v1/identity/revoked-sids. /// public List Scopes { get; set; } = new() { "identity:manage" }; } /// /// B1 — emergency local-admin bootstrap: a one-shot internal endpoint /// (POST /internal/bootstrap-admin). The secret MUST come from environment /// (e.g. IDENTITY__BOOTSTRAP__SECRET) and never from context.json /// (which is checked into source control). /// public sealed class BootstrapOptions { /// /// Master switch. When false (default) the route is registered but /// always returns 404 Not Found — operators can leave the option in /// context.json permanently disabled and only flip it via env-var on /// the very first deploy. /// public bool Enabled { get; set; } = false; /// /// Shared secret required in the X-Bootstrap-Secret header. /// Compared with /// so the comparison does not leak information through timing. /// Must be at least 32 characters when is true /// (validated at startup); env-only by convention. /// public string? Secret { get; set; } /// /// Name of the group that the freshly-created admin user joins. Should /// match RedbIdentityOptions.ScopeRequiredGroups["identity:admin"] /// so the new admin can immediately use the management scope. Default /// identity-admins. /// public string AdminGroupName { get; set; } = "identity-admins"; /// /// OAuth scope that the bootstrap admin needs in order to call the /// management surface. Defaults to the conventional /// identity:admin. The processor creates the scope (if absent), /// the gating entry, /// and a mapping /// group() → scope(). /// public string AdminScope { get; set; } = "identity:admin"; /// /// ClientId issued for the canonical first-party admin web application. /// Default identity-web. /// public string WebClientId { get; set; } = "identity-web"; } /// /// Server-side input-length limits used by Identity validation helpers. /// All values default to the original hardcoded constants. /// public sealed class IdentityValidationOptions { /// Max length for identifier-like fields (login, name, etc.). Default 128. public int MaxIdentifierLength { get; set; } = 128; /// Max length for free-form display names. Default 256. public int MaxDisplayNameLength { get; set; } = 256; /// Max length for free-form descriptions. Default 1024. public int MaxDescriptionLength { get; set; } = 1024; /// Minimum length for passwords / client secrets. Default 8. public int MinPasswordLength { get; set; } = 8; /// Maximum length for passwords / client secrets. Default 512. public int MaxPasswordLength { get; set; } = 512; /// /// Optional override for the identifier regex (logins, role names, etc.). /// Default (when null/empty): ^[a-zA-Z0-9\-_.]+$. /// Invalid patterns silently fall back to the default. /// public string? IdentifierPattern { get; set; } /// /// Optional override for the email regex. /// Default (when null/empty): ^[^@\s]+@[^@\s]+\.[^@\s]+$. /// public string? EmailPattern { get; set; } /// /// Optional override for the phone-number regex. /// Default (when null/empty): E.164 — ^\+[1-9]\d{1,14}$. /// public string? PhonePattern { get; set; } } /// /// C6 — hardening for the encrypted federation state blob and the /// surrounding callback ceremony. /// public sealed class FederationStateOptions { /// /// Maximum lifetime of an encrypted state blob from issuance to redeem. /// Default: 5 minutes (matches OIDC spec recommendation for short-lived /// authorization-request artefacts). /// public TimeSpan StateMaxAge { get; set; } = TimeSpan.FromMinutes(5); /// /// When true (default), every state blob carries a unique jti /// that is recorded in the nonce store on first use; subsequent presentations /// with the same jti are rejected (one-time-use, RFC 6749 §10.12-style). /// Disable only for testing. /// public bool RequireOneTimeUse { get; set; } = true; /// /// When true, the challenge processor mints a per-flow secret, hashes it /// into the state blob, and the HTTP layer pins the secret to the user-agent via /// a Secure HttpOnly SameSite=Lax cookie. The callback rejects the flow /// if the cookie is absent or its hash mismatches. Default: false — /// opt-in because non-HTTP callers (CLI / SPA without cookie jar) cannot satisfy /// the binding contract. See . /// public bool RequireBrowserBinding { get; set; } = false; /// /// Name of the cookie that carries the per-flow browser-binding secret when /// is enabled. Default: redb_fed_b. /// public string BindingCookieName { get; set; } = "redb_fed_b"; /// /// Backend for the one-time-use nonce store. memory (default) is single-node; /// redis is required for multi-instance Identity deployments to make the /// guarantee cluster-global. See . /// public string Backend { get; set; } = "memory"; /// /// Redis connection string for the nonce store. When null/empty and /// = redis, falls back to .. /// public string? RedisConnectionString { get; set; } /// /// Key prefix used by the Redis nonce store. Default: redb:identity:fed:nonce:. /// public string RedisKeyPrefix { get; set; } = "redb:identity:fed:nonce:"; } /// /// C10 — DataProtection at-rest hardening. /// Three variants are supported (in priority order if multiple are set): /// /// Custom KMS via — caller supplies an /// IXmlEncryptor wired to Vault / Azure Key Vault / AWS KMS / etc. /// X.509 certificate via — thumbprint lookup in /// the local store, or PFX path on disk. Cross-platform; preferred for cluster. /// AES-GCM master key via — 32-byte key in base64. /// Smallest deployments / single-node dev. /// /// If is true AND /// is false AND none of the above /// is configured, AddRedbIdentityServer throws on startup. /// Migration: existing plaintext key-ring entries stay readable /// (ASP.NET DataProtection handles mixed plain+encrypted entries natively). /// New keys written after enabling encryption are encrypted; rotation eventually /// retires the plaintext entries. /// public sealed class DataProtectionOptions { /// /// When true (default) and ephemeral keys are not allowed, startup fails /// unless one of , , or /// is configured. /// public bool RequireAtRestEncryption { get; set; } = true; /// /// 32-byte AES-256 key, base64-encoded. Used by the built-in /// AES-GCM XML encryptor when no certificate or KMS hook is configured. /// public string? MasterKey { get; set; } /// /// X.509 certificate options. If /// or is set, the certificate-based /// encryptor is used. Takes precedence over . /// public DataProtectionCertificateOptions Certificate { get; set; } = new(); /// /// Optional callback that returns a custom IXmlEncryptor. The /// IServiceProvider argument is the application root provider — caller can resolve /// any registered service. Takes precedence over and /// . Use this hook for KMS-backed encryptors. /// public Func? CustomEncryptorFactory { get; set; } /// /// A file key ring directory to import into redb at startup, in addition to the ASP.NET Core default /// directory of the process user. Up to 4.3 the key ring was written to the file system instead of /// redb; set this when that ring was kept somewhere else (for example a volume mounted on a custom /// path). Keys already in redb are skipped, so leaving it set is harmless. /// public string? ImportKeysFromPath { get; set; } /// /// True when at least one of the three variants is configured. /// public bool HasEncryptorConfigured => CustomEncryptorFactory is not null || Certificate.IsConfigured || !string.IsNullOrWhiteSpace(MasterKey); } /// /// X.509 certificate selector for the DataProtection key-ring encryptor. /// Either (local store lookup) or /// (file on disk, optional password) must be set. If both are set, the PFX path wins. /// public sealed class DataProtectionCertificateOptions { /// SHA-1 (or SHA-256) thumbprint of the certificate to look up. Case- and whitespace-insensitive. public string? Thumbprint { get; set; } /// Certificate store name when looking up by thumbprint. Default: My. public string StoreName { get; set; } = "My"; /// /// Certificate store location. Default: CurrentUser. Use LocalMachine /// when running as a service account that doesn't have a personal user store. /// public string StoreLocation { get; set; } = "CurrentUser"; /// Path to a PFX/PKCS#12 file on disk. Mutually exclusive-ish with . public string? PfxPath { get; set; } /// Password for the PFX file. Leave null for password-less PFX. public string? PfxPassword { get; set; } /// True when at least one source is set (thumbprint or PFX path). public bool IsConfigured => !string.IsNullOrWhiteSpace(Thumbprint) || !string.IsNullOrWhiteSpace(PfxPath); } Path: redb-identity/src/redb.Identity.Core/Configuration/RegistrationOptions.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/Configuration/RegistrationOptions.cs ---- namespace redb.Identity.Core.Configuration; /// /// N-3 (sub-step N3-7): tunables + feature gate for the self-service account /// registration flow (direct-vm://identity-account-register + /// POST /api/v1/identity/account/register). /// /// Disabled by default — opt-in for deployments that want public sign-up; corporate /// identity deployments that provision users via admin / SCIM should leave this off. /// /// public sealed class RegistrationOptions { /// Master switch. When false the route is not built and the facade returns 404. public bool Enabled { get; set; } = false; /// /// When true and is also /// enabled, the processor automatically dispatches an e-mail verification link after /// account creation. The user's EmailVerified flag stays false until /// the link is consumed. Defaults to true. /// public bool SendVerifyEmail { get; set; } = true; /// /// When true (default) the processor enforces e-mail uniqueness alongside /// login uniqueness. Set to false only for deployments that explicitly allow /// the same e-mail to back multiple accounts. /// public bool RequireUniqueEmail { get; set; } = true; } Path: redb-identity/src/redb.Identity.Core/Configuration/ReverseProxyOptions.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/Configuration/ReverseProxyOptions.cs ---- using System.Net; namespace redb.Identity.Core.Configuration; /// /// C2 — Configuration for the trusted-reverse-proxy whitelist consulted by /// . /// /// /// Secure-by-default: with = false (the default), /// the resolver ignores all X-Forwarded-For / Forwarded headers and the /// socket IP carried by redbHttp.RemoteAddress is propagated unchanged. This means /// per-IP throttling (C1) sees only the immediate TCP peer — correct when the service is /// exposed directly. Enable forwarded-IP resolution only when the service sits behind a /// trusted reverse proxy whose IPs are listed here; otherwise an attacker can spoof /// X-Forwarded-For and bypass per-IP rate limits. /// public sealed class ReverseProxyOptions { /// /// When true, the resolver consults the X-Forwarded-For header on requests /// arriving from a peer in / , walks /// the chain right-to-left skipping any further trusted hops, and uses the first untrusted /// IP as the client address. When false (default), the socket IP is used as-is. /// public bool TrustForwardedFor { get; set; } /// Individual IP addresses of trusted reverse proxies. public List KnownProxies { get; set; } = new(); /// CIDR networks of trusted reverse proxies. public List KnownNetworks { get; set; } = new(); } Path: redb-identity/src/redb.Identity.Core/Configuration/SmtpOptions.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/Configuration/SmtpOptions.cs ---- namespace redb.Identity.Core.Configuration; /// /// N-4 (Session C): SMTP transport configuration consumed by the e-mail dispatch route /// (direct-vm://identity-email-send) and the SmtpEmailNotificationChannel. /// Empty / disabled by default — a host either enables SMTP here or registers an /// alternative IEmailNotificationChannel implementation (e.g. SendGrid, in-memory /// channel for tests, or a noop channel that drops messages). /// public sealed class SmtpOptions { /// Master switch. When false the route is not built and no SMTP channel is registered. public bool Enabled { get; set; } = false; /// SMTP server host (e.g. smtp.gmail.com, 127.0.0.1). public string? Host { get; set; } /// SMTP server port. Common values: 25 (plain), 465 (Ssl), 587 (StartTls), 3025 (greenmail no-auth). public int Port { get; set; } = 25; /// /// Security mode passed straight to the redb.Route.Mail builder /// (None, StartTls, Ssl, Auto). Defaults to None; /// production deployments should set StartTls or Ssl. /// public string Security { get; set; } = "None"; /// Optional username (omit for unauthenticated greenmail-style relays). public string? Username { get; set; } /// Optional password (omit for unauthenticated greenmail-style relays). public string? Password { get; set; } /// Envelope From address used when the channel does not supply one per message. public string FromAddress { get; set; } = "noreply@redb.local"; /// Skip TLS certificate validation. Test / dev only — never enable in production. public bool SkipCertificateValidation { get; set; } = false; } Path: redb-identity/src/redb.Identity.Core/DataProtection/CertificateLoader.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/DataProtection/CertificateLoader.cs ---- using System.Security.Cryptography.X509Certificates; using redb.Identity.Core.Configuration; namespace redb.Identity.Core.DataProtection; /// /// C10 — loads an X.509 certificate from configuration. Supports two sources: /// /// PFX file on disk via /// (+ optional ). /// Local certificate store by thumbprint via /// in /// / /// . /// /// PFX-on-disk wins when both are set. /// internal static class CertificateLoader { public static X509Certificate2 Load(DataProtectionCertificateOptions options) { ArgumentNullException.ThrowIfNull(options); if (!string.IsNullOrWhiteSpace(options.PfxPath)) return LoadFromPfx(options.PfxPath!, options.PfxPassword); if (!string.IsNullOrWhiteSpace(options.Thumbprint)) return LoadFromStore(options.Thumbprint!, options.StoreName, options.StoreLocation); throw new InvalidOperationException( "DataProtection.Certificate is not configured: set Thumbprint or PfxPath."); } private static X509Certificate2 LoadFromPfx(string path, string? password) { if (!File.Exists(path)) throw new InvalidOperationException( $"DataProtection.Certificate.PfxPath '{path}' does not exist."); // X509KeyStorageFlags.EphemeralKeySet keeps the private key in memory only — avoids // writing key material to %APPDATA%/.dotnet on every load (Linux/macOS especially). // MachineKeySet is not used because Identity may run as a service account that // doesn't have write access to the machine key store. try { return X509CertificateLoader.LoadPkcs12FromFile( path, password, X509KeyStorageFlags.EphemeralKeySet); } catch (Exception ex) { throw new InvalidOperationException( $"Failed to load PFX from '{path}'. Verify the file is a valid PKCS#12 archive " + "and the password (if any) is correct.", ex); } } private static X509Certificate2 LoadFromStore(string thumbprint, string storeName, string storeLocation) { // Thumbprints are typically pasted from MMC with spaces / mixed case — normalise. var normalised = new string(thumbprint.Where(char.IsLetterOrDigit).ToArray()).ToUpperInvariant(); if (!Enum.TryParse(storeLocation, ignoreCase: true, out var loc)) throw new InvalidOperationException( $"DataProtection.Certificate.StoreLocation '{storeLocation}' is not a valid X509 StoreLocation. " + "Use 'CurrentUser' or 'LocalMachine'."); StoreName parsedStoreName; if (Enum.TryParse(storeName, ignoreCase: true, out var sn)) { parsedStoreName = sn; using var store = new X509Store(parsedStoreName, loc); return FindByThumbprint(store, normalised, storeName, storeLocation); } // Custom store name (e.g. operator's own store) — X509Store ctor takes the string as-is. using var customStore = new X509Store(storeName, loc); return FindByThumbprint(customStore, normalised, storeName, storeLocation); } private static X509Certificate2 FindByThumbprint( X509Store store, string normalisedThumbprint, string storeName, string storeLocation) { store.Open(OpenFlags.ReadOnly); // validOnly=false: an expired cert is still useful for DECRYPTING old key-ring entries // (the new ones will be encrypted with whatever cert is configured next). var matches = store.Certificates.Find( X509FindType.FindByThumbprint, normalisedThumbprint, validOnly: false); if (matches.Count == 0) throw new InvalidOperationException( $"No certificate found with thumbprint '{normalisedThumbprint}' " + $"in {storeLocation}\\{storeName}."); var cert = matches[0]; if (!cert.HasPrivateKey) throw new InvalidOperationException( $"Certificate '{normalisedThumbprint}' in {storeLocation}\\{storeName} " + "does not have an accessible private key — DataProtection key-ring decryption " + "would fail. Grant the service account read access to the private key, or " + "supply a PFX file via DataProtection.Certificate.PfxPath."); return cert; } } Path: redb-identity/src/redb.Identity.Core/DataProtection/RedbAesGcmXmlEncryptor.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/DataProtection/RedbAesGcmXmlEncryptor.cs ---- using System.Security.Cryptography; using System.Xml.Linq; using Microsoft.AspNetCore.DataProtection.XmlEncryption; namespace redb.Identity.Core.DataProtection; /// /// C10 — AES-GCM XML encryptor for the DataProtection key-ring. /// /// Encrypts each key-ring with AES-256-GCM using a 32-byte master /// key supplied by the caller (typically from RedbIdentityOptions.DataProtection.MasterKey). /// The decryptor type recorded in the descriptor is ; /// ASP.NET DataProtection instantiates it via IActivator on key load, so the decryptor /// pulls the master key from DI through the same singleton. /// /// /// Wire format (single base64 token): /// [12-byte nonce][16-byte tag][ciphertext]. /// /// internal sealed class RedbAesGcmXmlEncryptor : IXmlEncryptor { internal const string AlgorithmId = "aes-gcm-256"; internal const int NonceSize = 12; internal const int TagSize = 16; private readonly RedbMasterKeyProvider _keyProvider; public RedbAesGcmXmlEncryptor(RedbMasterKeyProvider keyProvider) { ArgumentNullException.ThrowIfNull(keyProvider); _keyProvider = keyProvider; } public EncryptedXmlInfo Encrypt(XElement plaintextElement) { ArgumentNullException.ThrowIfNull(plaintextElement); var plaintextBytes = System.Text.Encoding.UTF8.GetBytes( plaintextElement.ToString(SaveOptions.DisableFormatting)); var nonce = RandomNumberGenerator.GetBytes(NonceSize); var ciphertext = new byte[plaintextBytes.Length]; var tag = new byte[TagSize]; using (var aes = new AesGcm(_keyProvider.Key, TagSize)) { aes.Encrypt(nonce, plaintextBytes, ciphertext, tag); } // Pack nonce | tag | ciphertext into a single base64 blob — keeps the XML compact // and the decryptor doesn't need to juggle separate child elements. var blob = new byte[NonceSize + TagSize + ciphertext.Length]; Buffer.BlockCopy(nonce, 0, blob, 0, NonceSize); Buffer.BlockCopy(tag, 0, blob, NonceSize, TagSize); Buffer.BlockCopy(ciphertext, 0, blob, NonceSize + TagSize, ciphertext.Length); var encrypted = new XElement("encryptedKey", new XElement("encryptionAlgorithm", AlgorithmId), new XElement("value", Convert.ToBase64String(blob))); return new EncryptedXmlInfo(encrypted, typeof(RedbAesGcmXmlDecryptor)); } } /// /// Companion decryptor for . /// Resolved by ASP.NET DataProtection's IActivator at key-load time. /// internal sealed class RedbAesGcmXmlDecryptor : IXmlDecryptor { private readonly RedbMasterKeyProvider _keyProvider; public RedbAesGcmXmlDecryptor(IServiceProvider services) { ArgumentNullException.ThrowIfNull(services); _keyProvider = (RedbMasterKeyProvider?)services.GetService(typeof(RedbMasterKeyProvider)) ?? throw new InvalidOperationException( "RedbAesGcmXmlDecryptor was activated but no RedbMasterKeyProvider is registered. " + "This indicates the key-ring contains entries encrypted under the AES-GCM master key " + "but the master key is no longer configured. Restore RedbIdentityOptions.DataProtection.MasterKey."); } public XElement Decrypt(XElement encryptedElement) { ArgumentNullException.ThrowIfNull(encryptedElement); var algorithm = encryptedElement.Element("encryptionAlgorithm")?.Value; if (!string.Equals(algorithm, RedbAesGcmXmlEncryptor.AlgorithmId, StringComparison.Ordinal)) throw new InvalidOperationException( $"Unsupported algorithm '{algorithm}' for {nameof(RedbAesGcmXmlDecryptor)}; expected '{RedbAesGcmXmlEncryptor.AlgorithmId}'."); var b64 = encryptedElement.Element("value")?.Value ?? throw new InvalidOperationException("Encrypted XML element is missing child."); var blob = Convert.FromBase64String(b64); if (blob.Length < RedbAesGcmXmlEncryptor.NonceSize + RedbAesGcmXmlEncryptor.TagSize) throw new InvalidOperationException("Encrypted blob is too short to contain nonce + tag."); var nonce = new byte[RedbAesGcmXmlEncryptor.NonceSize]; var tag = new byte[RedbAesGcmXmlEncryptor.TagSize]; var ciphertext = new byte[blob.Length - RedbAesGcmXmlEncryptor.NonceSize - RedbAesGcmXmlEncryptor.TagSize]; Buffer.BlockCopy(blob, 0, nonce, 0, RedbAesGcmXmlEncryptor.NonceSize); Buffer.BlockCopy(blob, RedbAesGcmXmlEncryptor.NonceSize, tag, 0, RedbAesGcmXmlEncryptor.TagSize); Buffer.BlockCopy(blob, RedbAesGcmXmlEncryptor.NonceSize + RedbAesGcmXmlEncryptor.TagSize, ciphertext, 0, ciphertext.Length); var plaintext = new byte[ciphertext.Length]; using (var aes = new AesGcm(_keyProvider.Key, RedbAesGcmXmlEncryptor.TagSize)) { aes.Decrypt(nonce, ciphertext, tag, plaintext); } return XElement.Parse(System.Text.Encoding.UTF8.GetString(plaintext)); } } /// /// Holds the raw 32-byte AES-256 master key. Singleton; the byte array is owned by this /// instance and is not exposed via mutable accessors. /// internal sealed class RedbMasterKeyProvider { private readonly byte[] _key; public RedbMasterKeyProvider(byte[] key) { ArgumentNullException.ThrowIfNull(key); if (key.Length != 32) throw new ArgumentException("AES-256 master key must be exactly 32 bytes.", nameof(key)); _key = (byte[])key.Clone(); } /// Direct access to the raw key bytes. Do not mutate. public byte[] Key => _key; } Path: redb-identity/src/redb.Identity.Core/DataProtection/XmlRepositoryRefreshProcessor.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/DataProtection/XmlRepositoryRefreshProcessor.cs ---- using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Core; using redb.Identity.DataProtection; using redb.Route.Abstractions; using redb.Identity.Core.Routes; namespace redb.Identity.Core.DataProtection; /// /// Reloads the DataProtection XML key-ring snapshot from PROPS storage into /// . Fired per-tick by a timer:// route /// (see ). Runs on every replica — /// this is intentionally NOT cluster-leader-only because each node maintains its own /// in-process snapshot and must pick up keys rotated by other replicas. /// internal sealed class XmlRepositoryRefreshProcessor : IProcessor { private readonly IServiceProvider _sp; public XmlRepositoryRefreshProcessor(IServiceProvider sp) { ArgumentNullException.ThrowIfNull(sp); _sp = sp; } public async Task Process(IExchange exchange, CancellationToken ct) { await using var scope = _sp.CreateAsyncScope(); var repo = scope.ServiceProvider.GetRequiredService(); var redb = scope.ServiceProvider.GetRequiredService(); var logger = scope.ServiceProvider .GetRequiredService() .CreateLogger(); var count = await repo.ReloadAsync(redb, ct).ConfigureAwait(false); logger.LogDebug( "redb.Identity: DataProtection key-ring snapshot refreshed ({Count} keys)", count); } } Path: redb-identity/src/redb.Identity.Core/EmailVerification/IEmailVerificationTokenStore.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/EmailVerification/IEmailVerificationTokenStore.cs ---- using System; using System.Threading; using System.Threading.Tasks; namespace redb.Identity.Core.EmailVerification; /// /// N-4 (Session C, sub-step N4-6): server-side e-mail-verification token store. Mirror of /// with one extra binding — the /// token is tied to the specific e-mail value snapshot captured at issue time, so a /// stale link cannot vouch for an address the user has since changed. /// public interface IEmailVerificationTokenStore { /// /// Issues a new verification token. Generates a 32-byte CSPRNG secret /// (base64url-encoded), persists its peppered SHA-256 hash + the bound /// snapshot, and returns the jti + plaintext token so /// the caller can embed both into the verify URL. /// /// User the verification is bound to. /// /// Lower-cased snapshot of the user's e-mail at issue time. Confirm rejects the token /// when the user's current e-mail no longer matches this value (double-change race). /// /// /// Caller-supplied landing URL captured at issue time. Recorded for audit; the /// whitelist check is enforced by the issuing processor against /// ApplicationProps.EmailVerifyUris. /// /// Time-to-live for this token. Typically 24 hours. Task IssueAsync( long userId, string email, string callerVerifyUrl, TimeSpan ttl, CancellationToken ct = default); /// /// Verifies and atomically consumes a verification token keyed by . /// On success the row is marked Consumed and the bound UserId + e-mail /// snapshot are returned so the caller can apply the e-mail-match guard before /// flipping UserProps.EmailVerified. /// Task VerifyAndConsumeAsync( Guid jti, string token, CancellationToken ct = default); } /// Result of . public readonly record struct EmailVerificationIssueResult( Guid Jti, string PlaintextToken, DateTimeOffset ExpiresAt); /// Result of . /// Whether the token verified AND the row was successfully consumed. /// Owner user id when is true; otherwise 0. /// Lower-cased e-mail snapshot bound at issue time; empty when is false. /// Diagnostic reason; values: ok, not_found, expired, already_consumed, bad_token. public readonly record struct EmailVerificationVerifyResult( bool Success, long UserId, string Email, string Reason); Path: redb-identity/src/redb.Identity.Core/EmailVerification/RedbEmailVerificationTokenStore.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/EmailVerification/RedbEmailVerificationTokenStore.cs ---- using System; using System.Security.Cryptography; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Core; using redb.Core.Models.Entities; using redb.Identity.Core.Models; using redb.Identity.Core.Services; namespace redb.Identity.Core.EmailVerification; /// /// N-4 (Session C, sub-step N4-6): redb-backed /// . Direct mirror of /// RedbPasswordResetTokenStore with one extra field on the persisted props /// () and one extra field on the verify /// result so the caller can guard against the double-change race. /// public sealed class RedbEmailVerificationTokenStore : IEmailVerificationTokenStore { private readonly IServiceScopeFactory _scopeFactory; private readonly RecoveryCodePepperProvider _pepperProvider; private readonly ILogger _logger; private readonly TimeProvider _timeProvider; public RedbEmailVerificationTokenStore( IServiceScopeFactory scopeFactory, RecoveryCodePepperProvider pepperProvider, ILogger logger, TimeProvider? timeProvider = null) { _scopeFactory = scopeFactory ?? throw new ArgumentNullException(nameof(scopeFactory)); _pepperProvider = pepperProvider ?? throw new ArgumentNullException(nameof(pepperProvider)); _logger = logger ?? throw new ArgumentNullException(nameof(logger)); _timeProvider = timeProvider ?? TimeProvider.System; } /// public async Task IssueAsync( long userId, string email, string callerVerifyUrl, TimeSpan ttl, CancellationToken ct = default) { if (userId <= 0) throw new ArgumentOutOfRangeException(nameof(userId)); if (string.IsNullOrWhiteSpace(email)) throw new ArgumentException("email is required", nameof(email)); if (ttl <= TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(ttl)); var jti = Guid.NewGuid(); var token = GenerateToken(); var now = _timeProvider.GetUtcNow(); var expires = now + ttl; var hash = RecoveryCodePepperProvider.PepperedSha256Hex(_pepperProvider.Pepper, token); await using var scope = _scopeFactory.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); var obj = new RedbObject(new EmailVerificationTokenProps { Jti = jti.ToString("N"), UserId = userId, Email = email.Trim().ToLowerInvariant(), TokenHash = hash, PepperId = _pepperProvider.PepperId, IssuedAt = now, ExpiresAt = expires, Consumed = false, Attempts = 0, CallerVerifyUrl = callerVerifyUrl ?? string.Empty, }); obj.name = jti.ToString("N"); await redb.SaveAsync(obj).ConfigureAwait(false); return new EmailVerificationIssueResult(jti, token, expires); } /// public async Task VerifyAndConsumeAsync( Guid jti, string token, CancellationToken ct = default) { if (jti == Guid.Empty) return new EmailVerificationVerifyResult(false, 0, string.Empty, "not_found"); if (string.IsNullOrEmpty(token)) return new EmailVerificationVerifyResult(false, 0, string.Empty, "bad_token"); await using var scope = _scopeFactory.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); var key = jti.ToString("N"); await using var tx = await redb.Context.BeginTransactionAsync().ConfigureAwait(false); var row = await redb.Query() .Where(o => o.Jti == key) .FirstOrDefaultAsync() .ConfigureAwait(false); if (row is null) { await tx.RollbackAsync().ConfigureAwait(false); return new EmailVerificationVerifyResult(false, 0, string.Empty, "not_found"); } if (row.key.HasValue) await redb.LockForUpdateAsync(row.key.Value).ConfigureAwait(false); var p = row.Props; var now = _timeProvider.GetUtcNow(); if (p.Consumed) { await tx.CommitAsync().ConfigureAwait(false); return new EmailVerificationVerifyResult(false, 0, string.Empty, "already_consumed"); } if (p.ExpiresAt < now) { await tx.CommitAsync().ConfigureAwait(false); return new EmailVerificationVerifyResult(false, 0, string.Empty, "expired"); } if (_pepperProvider.PeppersFor(p.PepperId).Count == 0) _logger.LogWarning("The token was hashed with pepper {PepperId}, which is no longer configured.", p.PepperId); var ok = _pepperProvider.MatchesTokenHash(token.Trim(), p.TokenHash, p.PepperId); p.Attempts++; if (ok) { p.Consumed = true; } try { await redb.SaveAsync(row).ConfigureAwait(false); await tx.CommitAsync().ConfigureAwait(false); } catch { await tx.RollbackAsync().ConfigureAwait(false); throw; } return ok ? new EmailVerificationVerifyResult(true, p.UserId, p.Email, "ok") : new EmailVerificationVerifyResult(false, 0, string.Empty, "bad_token"); } private static string GenerateToken() { Span buf = stackalloc byte[32]; RandomNumberGenerator.Fill(buf); return Base64UrlEncode(buf); } private static string Base64UrlEncode(ReadOnlySpan bytes) { var s = Convert.ToBase64String(bytes); return s.TrimEnd('=').Replace('+', '-').Replace('/', '_'); } } Path: redb-identity/src/redb.Identity.Core/Events/DeliveryBacklog.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/Events/DeliveryBacklog.cs ---- using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Core; using redb.Core.Query; namespace redb.Identity.Core.Events; /// /// The backlog of the delivery outbox (pending rows, age of the oldest), read from the database at most /// once per and shared by the health check and the metric gauges /// identity.delivery.pending and identity.delivery.oldest_pending_age. Every node reads the /// same table, so every node reports the same backlog, whichever of them runs the worker. /// public sealed class DeliveryBacklog { /// How long one reading is reused. public static readonly TimeSpan MaxAge = TimeSpan.FromSeconds(15); private readonly IServiceScopeFactory _scopes; private readonly TimeProvider _time; private readonly ILogger _logger; private readonly SemaphoreSlim _refresh = new(1, 1); private OutboxStats? _current; private DateTimeOffset _readAt = DateTimeOffset.MinValue; public DeliveryBacklog(IServiceScopeFactory scopes, TimeProvider time, ILogger logger) { _scopes = scopes; _time = time; _logger = logger; } /// The last reading, or null before the first one. Starts a new reading in the background when stale. public OutboxStats? Current { get { if (Stale) _ = Task.Run(() => GetAsync(CancellationToken.None)); return _current; } } /// A reading no older than ; null when the table cannot be read. public async Task GetAsync(CancellationToken ct) { if (!Stale) return _current; await _refresh.WaitAsync(ct).ConfigureAwait(false); try { if (!Stale) return _current; await using var scope = _scopes.CreateAsyncScope(); var store = new IdentityEventStore( scope.ServiceProvider.GetRequiredService(), scope.ServiceProvider.GetRequiredService()); _current = await store.StatsAsync(ct).ConfigureAwait(false); _readAt = _time.GetUtcNow(); return _current; } catch (Exception ex) when (ex is not OperationCanceledException) { _logger.LogWarning(ex, "Delivery backlog: the outbox could not be read."); return null; } finally { _refresh.Release(); } } private bool Stale => _time.GetUtcNow() - _readAt > MaxAge; } Path: redb-identity/src/redb.Identity.Core/Events/IdentityEventStore.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/Events/IdentityEventStore.cs ---- using System.Collections.Concurrent; using System.Text.Json.Serialization; using redb.Core; using redb.Core.Query; namespace redb.Identity.Core.Events; /// /// The flat SQL of the event pipeline: the audit row and the delivery outbox /// (identity_delivery_outbox). No statement lives in a processor; each one is a section of an /// embedded per-dialect resource (sql/events/{pg,mssql,sqlite}.sql), run through redb's /// so it shares the connection and transaction handling of redb. /// /// Every time the outbox stores or compares comes from the database clock, inside the statement: two /// nodes whose clocks disagree still agree on who holds a lease and on what is due. /// /// public sealed class IdentityEventStore { private static readonly ConcurrentDictionary> Statements = new(); private readonly IRedbService _redb; private readonly IReadOnlyDictionary _sql; public IdentityEventStore(IRedbService redb, ISqlDialect dialect) { _redb = redb ?? throw new ArgumentNullException(nameof(redb)); ArgumentNullException.ThrowIfNull(dialect); _sql = StatementsFor(dialect.ProviderName); } /// Creates the outbox table and its indexes when they are missing; idempotent. public Task EnsureOutboxAsync(CancellationToken ct = default) => _redb.Context.ExecuteAsync(_sql["create_outbox"], Array.Empty(), ct); /// One row of identity_audit_log. public Task InsertAuditAsync(object[] values, CancellationToken ct = default) => _redb.Context.ExecuteAsync(_sql["insert_audit"], values, ct); /// /// The outbox rows of one event, all or none: one transaction of their own. The audit row is not in /// it: it is written first and stays when this fails. /// public async Task InsertOutboxAsync(IReadOnlyList entries, CancellationToken ct = default) { if (entries.Count == 0) return; await using var tx = await _redb.Context.BeginTransactionAsync(cancellationToken: ct).ConfigureAwait(false); foreach (var e in entries) { await _redb.Context.ExecuteAsync(_sql["insert_outbox"], new object[] { e.DeliveryId, e.EventId, e.Kind, e.Destination, e.EventType, e.Payload }, ct) .ConfigureAwait(false); } await tx.CommitAsync().ConfigureAwait(false); } /// Pending rows that are due and not leased, oldest first, at most . public Task> DueAsync(int limit, CancellationToken ct = default) => _redb.Context.QueryAsync(_sql["due"], new object[] { limit }, ct); /// /// Takes a lease on one row for ; true when this node holds it. The row must /// still have the the caller read: a pass that read it before another pass's /// attempt loses the claim instead of sending the next attempt under the number of the previous one. /// public async Task TryClaimAsync(long id, int attempts, int leaseSeconds, string node, CancellationToken ct = default) => await _redb.Context.ExecuteAsync(_sql["claim"], new object[] { id, leaseSeconds, node, attempts }, ct).ConfigureAwait(false) == 1; public Task MarkDeliveredAsync(long id, string node, CancellationToken ct = default) => _redb.Context.ExecuteAsync(_sql["delivered"], new object[] { id, node }, ct); public Task ScheduleRetryAsync(long id, string node, int delayMilliseconds, string error, CancellationToken ct = default) => _redb.Context.ExecuteAsync(_sql["retry"], new object[] { id, node, delayMilliseconds, Truncate(error) }, ct); public Task MarkFailedAsync(long id, string node, string error, CancellationToken ct = default) => _redb.Context.ExecuteAsync(_sql["failed"], new object[] { id, node, Truncate(error) }, ct); /// /// The destination went away before delivery (subscription deleted or disabled, audit target /// removed): an operator's own act, not a failure. /// public Task MarkCancelledAsync(long id, string node, string reason, CancellationToken ct = default) => _redb.Context.ExecuteAsync(_sql["cancelled"], new object[] { id, node, Truncate(reason) }, ct); /// /// Deletes one batch of finished rows past their retention (delivered after /// , failed and cancelled after ) and returns how /// many went. Pending rows are never deleted. /// public Task CleanupAsync(TimeSpan delivered, TimeSpan finished, int batch, CancellationToken ct = default) => _redb.Context.ExecuteAsync(_sql["cleanup"], new object[] { Seconds(delivered), Seconds(finished), batch }, ct); /// The pending rows and the age of the oldest of them, by the database clock. public async Task StatsAsync(CancellationToken ct = default) => (await _redb.Context.QueryAsync(_sql["stats"], Array.Empty(), ct).ConfigureAwait(false)) .FirstOrDefault() ?? new OutboxStats(); /// Rows newest first; an empty filter means any value. public Task> ListAsync(string status, string kind, string destination, int limit, int offset, CancellationToken ct = default) => _redb.Context.QueryAsync(_sql["list"], new object[] { status, kind, destination, limit, offset }, ct); /// /// Makes a failed or cancelled row due again with its attempts reset; true when the row was one of /// those. A pending or delivered row is left as it is. /// public async Task RedeliverAsync(long id, CancellationToken ct = default) => await _redb.Context.ExecuteAsync(_sql["redeliver"], new object[] { id }, ct).ConfigureAwait(false) == 1; /// The status of one row, or null when there is no such row. public async Task StatusOfAsync(long id, CancellationToken ct = default) => await _redb.Context.ExecuteScalarAsync(_sql["status_of"], new object[] { id }, ct).ConfigureAwait(false); private static int Seconds(TimeSpan span) => (int)Math.Min(int.MaxValue, Math.Max(0, span.TotalSeconds)); private static string Truncate(string s) => s.Length <= 1000 ? s : s[..1000]; internal static IReadOnlyDictionary StatementsFor(string provider) => Statements.GetOrAdd(ResourceOf(provider), Load); private static string ResourceOf(string provider) => provider switch { _ when provider.Equals("PostgreSQL", StringComparison.OrdinalIgnoreCase) => "redb.Identity.Core.sql.events.pg.sql", _ when provider.Equals("MSSql", StringComparison.OrdinalIgnoreCase) || provider.Equals("SqlServer", StringComparison.OrdinalIgnoreCase) => "redb.Identity.Core.sql.events.mssql.sql", _ when provider.Equals("SQLite", StringComparison.OrdinalIgnoreCase) => "redb.Identity.Core.sql.events.sqlite.sql", _ => throw new NotSupportedException($"redb.Identity: no event-store statements for the SQL dialect '{provider}'."), }; private static IReadOnlyDictionary Load(string resource) { using var stream = typeof(IdentityEventStore).Assembly.GetManifestResourceStream(resource) ?? throw new InvalidOperationException($"redb.Identity: embedded resource '{resource}' is missing."); using var reader = new StreamReader(stream); var text = reader.ReadToEnd(); var result = new Dictionary(StringComparer.Ordinal); string? name = null; var body = new System.Text.StringBuilder(); foreach (var raw in text.Split('\n')) { var line = raw.TrimEnd('\r'); if (line.StartsWith("-- @name ", StringComparison.Ordinal)) { if (name is not null) result[name] = body.ToString().Trim(); name = line["-- @name ".Length..].Trim(); body.Clear(); continue; } if (name is not null) body.AppendLine(line); } if (name is not null) result[name] = body.ToString().Trim(); return result; } } /// The backlog of the outbox. public sealed class OutboxStats { /// Rows not yet delivered, failed or cancelled. [JsonPropertyName("pending")] public long Pending { get; set; } /// Seconds since the oldest pending row was written; 0 with none. [JsonPropertyName("oldest_seconds")] public double OldestSeconds { get; set; } } /// One outbox row as the management API shows it. The payload is not part of it. public sealed class OutboxDelivery { [JsonPropertyName("id")] public long Id { get; set; } [JsonPropertyName("delivery_id")] public object? DeliveryId { get; set; } [JsonPropertyName("event_id")] public object? EventId { get; set; } [JsonPropertyName("kind")] public string Kind { get; set; } = ""; [JsonPropertyName("destination")] public string Destination { get; set; } = ""; [JsonPropertyName("event_type")] public string EventType { get; set; } = ""; [JsonPropertyName("status")] public string Status { get; set; } = ""; [JsonPropertyName("attempts")] public int Attempts { get; set; } [JsonPropertyName("last_error")] public string? LastError { get; set; } [JsonPropertyName("created_at")] public string? CreatedAt { get; set; } [JsonPropertyName("next_attempt_at")] public string? NextAttemptAt { get; set; } [JsonPropertyName("finished_at")] public string? FinishedAt { get; set; } } /// One outbox row to write. public sealed record OutboxEntry(Guid DeliveryId, Guid EventId, string Kind, string Destination, string EventType, string Payload); /// One due outbox row, as the worker reads it. public sealed class OutboxRow { [JsonPropertyName("id")] public long Id { get; set; } [JsonPropertyName("delivery_id")] public object? DeliveryId { get; set; } [JsonPropertyName("kind")] public string Kind { get; set; } = ""; [JsonPropertyName("destination")] public string Destination { get; set; } = ""; [JsonPropertyName("event_type")] public string EventType { get; set; } = ""; [JsonPropertyName("payload")] public string Payload { get; set; } = ""; [JsonPropertyName("attempts")] public int Attempts { get; set; } /// The delivery id as text, whatever the provider returned it as. public string DeliveryIdText => DeliveryId switch { Guid g => g.ToString("N"), string s => Guid.TryParse(s, out var g) ? g.ToString("N") : s, _ => DeliveryId?.ToString() ?? "", }; } Path: redb-identity/src/redb.Identity.Core/Events/WebhookSubscriptionCache.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/Events/WebhookSubscriptionCache.cs ---- using redb.Core; using redb.Core.Models.Entities; using redb.Identity.Core.Models; using redb.Identity.Core.Services; namespace redb.Identity.Core.Events; /// /// The enabled webhook subscriptions, kept in memory for Delivery.SubscriptionCache. Every event /// asks which subscriptions it goes to; without the cache that is one database read per event, token /// issuance included. The webhook management processor drops the cached list on every change, so this /// node sees a change at once and other nodes within the cache time. /// /// Events that find no list while a read is already running wait for that read instead of starting their /// own, so a burst of events costs one read. A read that fails answers the events waiting for it with its /// error and is not kept; the next event reads again. /// /// /// A read that was already running when the list was dropped may have missed the change: its result /// answers the events that waited for it but is not kept, and events after the drop do not join it, so /// the next event reads the list again. /// /// public sealed class WebhookSubscriptionCache { private readonly TimeProvider _time; private readonly TimeSpan _ttl; private readonly object _gate = new(); private (IReadOnlyList> Items, DateTimeOffset LoadedAt)? _current; private TaskCompletionSource>>? _loading; private long _generation; public WebhookSubscriptionCache(TimeProvider time, TimeSpan ttl) { _time = time; _ttl = ttl; } /// /// Number of reads of the list from the database, counted when a read starts, failed reads included; /// for tests and diagnostics. /// public int Loads { get; private set; } /// /// The enabled subscriptions, read through 's database. The read is shared by every /// event waiting for it, so it runs on a scope of its own, never on the scope of the event that started it: /// that scope ends with its exchange, which may finish (its wait cancelled) while others still wait. A service /// built without a container has no scope to end and is read directly. /// public Task>> GetEnabledAsync( IRedbService redb, CancellationToken ct = default) => GetEnabledAsync(async token => { if (!redb.CanCreateScope) return await new WebhookSubscriptionService(redb).ListEnabledAsync(token).ConfigureAwait(false); await using var scope = redb.CreateScope(); return await new WebhookSubscriptionService(scope.Service).ListEnabledAsync(token).ConfigureAwait(false); }, ct); /// /// The cached list, or the result of the read that is running, or of a new read. The read itself is /// shared by every event waiting for it, so it is not cancelled by one of them; /// only stops this caller's wait. /// internal async Task>> GetEnabledAsync( Func>>> load, CancellationToken ct = default) { TaskCompletionSource>> loading; long generation = 0; var starts = false; lock (_gate) { if (_current is { } c && _time.GetUtcNow() - c.LoadedAt < _ttl) return c.Items; if (_loading is { } running) { loading = running; } else { loading = _loading = new(TaskCreationOptions.RunContinuationsAsynchronously); // Every waiter may have left by its token before a failed read ends: observe the error here. _ = loading.Task.ContinueWith(static t => _ = t.Exception, CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); generation = _generation; starts = true; Loads++; } } // LoadAsync never throws: the outcome of the read goes to the waiters through the completion source. if (starts) _ = LoadAsync(load, loading, generation); return await loading.Task.WaitAsync(ct).ConfigureAwait(false); } private async Task LoadAsync( Func>>> load, TaskCompletionSource>> loading, long generation) { IReadOnlyList> items; try { items = await load(CancellationToken.None).ConfigureAwait(false); } catch (Exception ex) { lock (_gate) { if (ReferenceEquals(_loading, loading)) _loading = null; } loading.SetException(ex); return; } lock (_gate) { if (ReferenceEquals(_loading, loading)) _loading = null; if (generation == _generation) _current = (items, _time.GetUtcNow()); } loading.SetResult(items); } /// Drops the cached list; the next event reads it again, without joining a read already running. public void Invalidate() { lock (_gate) { _current = null; _loading = null; _generation++; } } } Path: redb-identity/src/redb.Identity.Core/Exceptions/MfaDeliveryException.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/Exceptions/MfaDeliveryException.cs ---- namespace redb.Identity.Core.Exceptions; /// /// Thrown by implementations when OTP delivery fails. /// public sealed class MfaDeliveryException : Exception { public string ChannelId { get; } public string? Destination { get; } public MfaDeliveryException(string channelId, string? destination, string message, Exception? inner = null) : base(message, inner) { ChannelId = channelId; Destination = destination; } } Path: redb-identity/src/redb.Identity.Core/Exceptions/WebAuthnException.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/Exceptions/WebAuthnException.cs ---- namespace redb.Identity.Core.Exceptions; /// /// MFA-3: thrown by when a WebAuthn ceremony fails /// for a reason that the caller (a processor) needs to surface as a structured client error /// rather than a 500. Each instance carries a short, stable suitable /// for inclusion in the JSON response ({"error":"uv_downgrade", ...}). /// public sealed class WebAuthnException : Exception { public WebAuthnException(string errorCode, string message) : base(message) { ErrorCode = errorCode; } public WebAuthnException(string errorCode, string message, Exception inner) : base(message, inner) { ErrorCode = errorCode; } /// Short, stable identifier (e.g. uv_downgrade, sign_counter_rollback). public string ErrorCode { get; } } Path: redb-identity/src/redb.Identity.Core/Extensions/RedbIdentityServiceExtensions.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/Extensions/RedbIdentityServiceExtensions.cs ---- using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.DataProtection.KeyManagement; using Microsoft.AspNetCore.DataProtection.Repositories; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using OpenIddict.Abstractions; using OpenIddict.Server; using OpenIddict.Validation; using redb.Core.Models.Entities; using redb.Core.Security; using redb.Identity.Core.Configuration; using redb.Identity.Core.DataProtection; using redb.Identity.DataProtection; using redb.Identity.Contracts.Cors; using redb.Identity.Core.Routes.Processors; using redb.Identity.Core.Models; using redb.Identity.Core.OpenIddict; using redb.Identity.Core.Health; using redb.Identity.Core.Security; using redb.Identity.Core.Serialization; using redb.Identity.Core.Services; using redb.Identity.Core.Stores; using redb.Route.Extensions; using redb.Tsak.Contracts; using redb.Identity.Core.Routes; namespace redb.Identity.Core; public static class RedbIdentityServiceExtensions { /// /// Registers a named for an address a client chose (its jwks_uri, a JAR /// request_uri, its back-channel logout URI), on : it /// connects only to an address its own resolution approved and does not follow redirects (a redirect answer is a /// failed request, HTTP 3xx). reads the setting of that use. /// internal static void AddClientChosenAddressHttpClient( IServiceCollection services, string name, Func allowPrivateNetworkTargets) => services.AddHttpClient(name) .ConfigurePrimaryHttpMessageHandler(sp => Services.ClientChosenAddressHandler.Create( allowPrivateNetworkTargets(sp.GetRequiredService>().Value))); /// /// Registers the full redb Identity Server: OpenIddict Core (stores) + Server (pipeline + flows + keys). /// This is the single production entry point. Tests may call this with options configured for test scenarios. /// public static IServiceCollection AddRedbIdentityServer( this IServiceCollection services, RedbIdentityOptions options) { ArgumentNullException.ThrowIfNull(services); ArgumentNullException.ThrowIfNull(options); // Ephemeral keys stand in for keys that persist; the props signing-key store is the keys that // persist. Set together, the ephemeral key is registered first (AddServer below) and stays in the // credential lists beside the store's keys: in this replica's JWKS only, trusted for validation, // and the encryption key for every token until the store has one of its own — the per-process // failure the store exists to remove. Refuse the pair instead of resolving it by list order. if (options.AllowEphemeralKeys && options.UsePropsSigningKeyStore) { throw new InvalidOperationException( "redb.Identity: AllowEphemeralKeys=true and UsePropsSigningKeyStore=true are set together. " + "Ephemeral keys are the Development / test stand-in for persistent keys; the props signing-key " + "store provides persistent keys. With both, an ephemeral key generated by this process would sit " + "in the credential lists beside the store's keys — published in this replica's JWKS only, " + "trusted for validation, and used for token encryption whenever the store has no encryption " + "key yet. Set exactly one of the two."); } // Configured credentials and the props store together are a migration state (to or from an HSM // or a certificate). Both sources validate and are published; which one mints is not for a list // order to decide, so MintingKeySource has to say it — and has nothing to say otherwise. var configuredKeys = options.SigningCredentials.Count > 0 || options.EncryptionCredentials.Count > 0; if (options.UsePropsSigningKeyStore && configuredKeys && options.MintingKeySource is null) { throw new InvalidOperationException( "redb.Identity: SigningCredentials / EncryptionCredentials are configured and " + "UsePropsSigningKeyStore=true, but MintingKeySource is not set. Both sources are trusted for " + "validation and published in the JWKS; MintingKeySource decides which one signs and encrypts " + "new tokens: Configured (the store's keys only validate, as while moving keys to an HSM) or " + "Store (the configured keys only validate, as while moving off one). Set it."); } if (options.MintingKeySource is not null && !(options.UsePropsSigningKeyStore && configuredKeys)) { throw new InvalidOperationException( "redb.Identity: MintingKeySource is set, but only one key source is configured. It chooses " + "between configured SigningCredentials / EncryptionCredentials and the props signing-key store " + "and applies only when both are present. Remove it, or configure the second source."); } // Ensure TimeProvider is registered for non-tpkg DI paths (IdentityModuleHost // already registers it explicitly; this covers direct AddRedbIdentityServer use). services.TryAddSingleton(TimeProvider.System); // Register locked Identity codec profiles (SCIM, Problem Details) into the // route context's IDataFormatRegistry at engine-start time. OAuth/OIDC/DCR // profile is intentionally not registered — it is used directly by processors // so app-level ConfigureJsonCodec cannot reshape the OAuth wire format. services.AddSingleton(); // Apply configurable input-length limits used by the validation helpers. Routes.Processors.IdentityProcessorHelpers.Configure(options.Validation); // H10 — register the password policy options + default validator. The validator // resolves IPasswordHistoryStore / IBreachedPasswordChecker as optional deps from // the same scope, so Phase 2/5 plug in without re-registering anything here. services.AddSingleton(options.PasswordPolicy); services.AddSingleton(); services.AddScoped(sp => new Security.DefaultPasswordPolicyValidator( sp.GetRequiredService(), sp.GetService(), sp.GetService())); services.AddOpenIddict() .AddCore(core => { core.UseRedbStores(); // Disable OpenIddict's built-in entity cache (OpenIddictApplicationCache<>, // OpenIddictAuthorizationCache<>, etc.). Those caches are registered as // Singletons and capture a scoped IOpenIddictXxxStore on first resolve, // which transitively captive-captures the underlying scoped IRedbService // (and its single NpgsqlConnection). Under concurrent load the captive // connection then races with itself and throws // NpgsqlOperationInProgressException ("A command is already in progress" // / "connection is already in state 'Copy'"). Disabling the cache makes // managers call the store directly through the current request scope, so // each request gets its own IRedbService/connection from the DI scope // factory (host bridge or root SP). The cost is a few extra SELECTs per // OAuth flow which is negligible against PROPS query overhead. core.DisableEntityCaching(); // RFC 8252 §7.3 — loopback redirect URIs are compared without their port, because a // native app cannot know the ephemeral port it will get until it starts. Done by // overriding ValidateRedirectUriAsync rather than a server handler: that method is // the ONE place both OpenIddict's request validation and our own error-redirect gate // ask "does this redirect_uri belong to this client". Widening it anywhere else // would let those two answers disagree — request rejected, error still redirected — // which is the open redirect we closed (RFC 6749 §4.1.2.1). core.ReplaceApplicationManager(typeof(RedbApplicationManager<>)); }) .AddServer(server => { server.SetIssuer(options.Issuer); // Endpoint URIs (relative — OpenIddict resolves against issuer) server.SetTokenEndpointUris("/connect/token"); server.SetAuthorizationEndpointUris("/connect/authorize"); server.SetUserInfoEndpointUris("/connect/userinfo"); server.SetIntrospectionEndpointUris("/connect/introspect"); server.SetRevocationEndpointUris("/connect/revoke"); server.SetConfigurationEndpointUris("/.well-known/openid-configuration"); server.SetJsonWebKeySetEndpointUris("/.well-known/jwks"); // Grant types server.AllowClientCredentialsFlow(); server.AllowAuthorizationCodeFlow(); server.AllowRefreshTokenFlow(); // PKCE. Mandatory by default (OAuth 2.1 hardening). Configurable via // RedbIdentityOptions.RequirePkce=false to also accept plain authorization_code // flows without a code_challenge (legacy clients / OpenID "Basic OP" non-PKCE tests). if (options.RequirePkce) server.RequireProofKeyForCodeExchange(); // RFC 7636 §4.2: forbid `plain`, allow only S256 — always, whether or not PKCE is // mandatory (when a client DOES send a challenge it must be S256). server.Configure(o => { o.CodeChallengeMethods.Clear(); o.CodeChallengeMethods.Add(OpenIddictConstants.CodeChallengeMethods.Sha256); }); // Device Code Flow (RFC 8628) if (options.Features.EnableDeviceCodeFlow) { server.SetDeviceAuthorizationEndpointUris("/connect/deviceauthorization"); server.SetEndUserVerificationEndpointUris("/connect/device/verify"); server.AllowDeviceAuthorizationFlow(); } // Pushed Authorization Requests (RFC 9126 / Z6) if (options.Features.EnablePushedAuthorization) { server.SetPushedAuthorizationEndpointUris("/connect/par"); if (options.RequirePushedAuthorizationRequests) server.RequirePushedAuthorizationRequests(); } // ROPC: grant_type=password (opt-in) if (options.EnablePasswordFlow) server.AllowPasswordFlow(); // Token Exchange: grant_type=urn:ietf:params:oauth:grant-type:token-exchange (opt-in, RFC 8693). // OpenIddict's built-in grant validates the subject / actor tokens; HandleTokenRequestHandler // builds the issued principal. Only access tokens go in and come out. if (options.EnableTokenExchange) { server.AllowTokenExchangeFlow(); server.Configure(o => { o.SubjectTokenTypes.Clear(); o.SubjectTokenTypes.Add(OpenIddictConstants.TokenTypeIdentifiers.AccessToken); o.ActorTokenTypes.Clear(); o.ActorTokenTypes.Add(OpenIddictConstants.TokenTypeIdentifiers.AccessToken); o.RequestedTokenTypes.Clear(); o.RequestedTokenTypes.Add(OpenIddictConstants.TokenTypeIdentifiers.AccessToken); o.DefaultRequestedTokenType = OpenIddictConstants.TokenTypeIdentifiers.AccessToken; }); } // RFC 8707 resource indicators (OpenIddict 7). The known resources are the Resources of the // scopes, edited at runtime, so the static RegisterResources set is not used: the built-in // check against it is off and ValidateResourcesAgainstScopes checks the scope store instead. // The format check and the client permission check (rsrc:) stay built in. server.DisableResourceValidation(); // Token lifetimes server.SetAccessTokenLifetime(options.AccessTokenLifetime); server.SetRefreshTokenLifetime(options.RefreshTokenLifetime); server.SetRefreshTokenReuseLeeway(options.RefreshTokenReuseLeeway); server.SetAuthorizationCodeLifetime(options.AuthorizationCodeLifetime); server.SetIdentityTokenLifetime(options.IdentityTokenLifetime); if (options.Features.EnableDeviceCodeFlow) server.SetDeviceCodeLifetime(options.DeviceCodeLifetime); // Signing & encryption credentials if (options.SigningCredentials.Count > 0) { foreach (var cred in options.SigningCredentials) server.AddSigningCredentials(cred); } else if (options.AllowEphemeralKeys) { server.AddEphemeralSigningKey(); } else if (options.UsePropsSigningKeyStore) { // A3: credentials are appended from the PROPS store via a deferred // IPostConfigureOptions below. Nothing to do here. } else { throw new InvalidOperationException( "redb.Identity: no signing credentials configured and AllowEphemeralKeys=false. " + "Ephemeral keys split the JWKS across cluster replicas and invalidate every live " + "token on restart — they are blocked in production. " + "Either populate RedbIdentityOptions.SigningCredentials with persistent keys, " + "enable UsePropsSigningKeyStore=true for the A3 persistent PROPS store, " + "or set RedbIdentityOptions.AllowEphemeralKeys=true for Development / test scenarios."); } if (options.EncryptionCredentials.Count > 0) { foreach (var cred in options.EncryptionCredentials) server.AddEncryptionCredentials(cred); } else if (options.AllowEphemeralKeys) { server.AddEphemeralEncryptionKey(); } else if (options.UsePropsSigningKeyStore) { // A3: appended from PROPS store below. } else { // DisableAccessTokenEncryption leaves only access tokens as plain JWS. OpenIddict // encrypts authorization codes, refresh tokens, device and user codes and its own // state tokens regardless, and refuses to build its options without an encryption // credential. Say so here, with the operator's options in hand, rather than at the // first options build with a message about a setting the operator never saw. throw new InvalidOperationException( "redb.Identity: no encryption credentials configured and AllowEphemeralKeys=false. " + "DisableAccessTokenEncryption only leaves access tokens unencrypted; authorization " + "codes, refresh tokens, device codes and state tokens are always encrypted, so at " + "least one encryption key is required. Either populate " + "RedbIdentityOptions.EncryptionCredentials, enable UsePropsSigningKeyStore=true for " + "the A3 persistent PROPS store, or set AllowEphemeralKeys=true for Development / test " + "scenarios."); } if (options.DisableAccessTokenEncryption) server.DisableAccessTokenEncryption(); // Register scopes server.RegisterScopes( OpenIddictConstants.Scopes.OpenId, OpenIddictConstants.Scopes.Profile, OpenIddictConstants.Scopes.Email, OpenIddictConstants.Scopes.Phone, OpenIddictConstants.Scopes.Address, OpenIddictConstants.Scopes.OfflineAccess, options.ManagementScope, options.AccountScope, "groups", "roles"); // N7-1 — register granular admin scopes so OpenIddict accepts them in // /connect/token requests. The per-path GranularScopeGuardProcessor in // the HTTP facade enforces which routes accept which scope at runtime. // Tokens carrying Manage retain full access (master scope). server.RegisterScopes(redb.Identity.Contracts.Configuration.IdentityScopes.GranularAdmin); // SCIM scope (RFC 7644) if (options.Features.EnableScim) server.RegisterScopes(options.ScimScope); // B0.1: Register any custom scopes that are gated by group membership // via RestrictScopeByGroupMembershipHandler. They must be advertised // here so OpenIddict accepts them in /connect/token requests; the // handler then enforces the group requirement at sign-in time. if (options.ScopeRequiredGroups is { Count: > 0 } gated) { foreach (var gatedScope in gated.Keys) { if (!string.IsNullOrWhiteSpace(gatedScope)) server.RegisterScopes(gatedScope); } } // D1: Register claims advertised in /.well-known/openid-configuration // (claims_supported field). Without this OpenIddict emits an empty list // which fails OIDC Discovery 1.0 §3 conformance. server.RegisterClaims( OpenIddictConstants.Claims.Subject, OpenIddictConstants.Claims.Issuer, OpenIddictConstants.Claims.Audience, OpenIddictConstants.Claims.ExpiresAt, OpenIddictConstants.Claims.IssuedAt, OpenIddictConstants.Claims.Nonce, OpenIddictConstants.Claims.AuthenticationTime, OpenIddictConstants.Claims.AuthenticationMethodReference, OpenIddictConstants.Claims.AuthorizedParty, OpenIddictConstants.Claims.JwtId, OpenIddictConstants.Claims.Name, OpenIddictConstants.Claims.PreferredUsername, OpenIddictConstants.Claims.Email, OpenIddictConstants.Claims.EmailVerified, OpenIddictConstants.Claims.PhoneNumber, OpenIddictConstants.Claims.PhoneNumberVerified, OpenIddictConstants.Claims.Role, OpenIddictConstants.Claims.Scope, "groups", "sid"); // Register the redb.Route host adapter server.UseRedbRoute(); }) .AddValidation(validation => { // Server-local token validation (shares signing/encryption keys with the server) validation.UseLocalServer(); validation.UseDataProtection(); // The token must still be valid in the store: a revoked token, or one whose client was deleted, // stops working at once instead of at its expiry. The check reads only the token's object row // (its status mirror in value_bool); it takes the place of the built-in entry check, left off. validation.AddEventHandler(redb.Identity.Core.OpenIddict.Handlers.ValidateTokenEntryStatusHandler.Descriptor); // RFC 9068 §4: the OP's own resource side verifies aud. Tokens minted for an // external API only (scope Resources without an identity:* scope) are // rejected here with 401 — see AttachAccessTokenResources for the composition. validation.AddAudiences(RedbIdentityOptions.ResolveDefaultAccessTokenAudience( options.Issuer, options.DefaultAccessTokenAudience)); // Custom handler: inject bearer token for programmatic validation // (runs early in the pipeline, before built-in extraction handlers) validation.AddEventHandler(builder => builder.UseInlineHandler(context => { if (context.Transaction.Properties.TryGetValue( ManagementBearerAuthProcessor.TokenPropertyKey, out var rawToken) && rawToken is string token) { context.AccessToken = token; context.ExtractAccessToken = false; } return default; }) .SetOrder(int.MinValue + 500) .Build()); // Batch 14 — bearer rejection for disabled / soft-deleted users. // JWT bearer tokens stay cryptographically valid until exp, but if the // underlying user has been DELETE'd (soft-delete sets _enabled=false) // the bearer must stop authorizing protected endpoints immediately. validation.AddEventHandler(redb.Identity.Core.Services.DisabledUserRejectionHandler.Descriptor); // DPoP-bound access tokens carry cnf.jkt, which OpenIddict 7's proof-of-possession check // (mTLS only) throws on; this handler verifies the DPoP proof in its place (RFC 9449 §7). validation.AddEventHandler(OpenIddict.Handlers.DpopConfirmationValidationPassThroughHandler.Descriptor); // **Batch 12 diagnostic.** Class-based handler dumps key picture on // every rejected validation so we can see which layer holds the stale // snapshot after rotate. Registered via DI for proper IOptionsMonitor access. validation.AddEventHandler(redb.Identity.Core.Keys.JwksRefreshDiagnosticHandler.Descriptor); }); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); // Identity options (used by RouteBuilder for timer interval, retention, etc.) services.AddSingleton(Options.Create(options)); // Login service (credential verification) services.TryAddScoped(); // User profile service (loads Core + OIDC + groups, builds ClaimsPrincipal) services.TryAddScoped(); // C15 / per-route CORS: registry of allowed origins derived from registered OAuth // clients' redirect URIs. Singleton (in-memory cache, invalidated by management ops). // The HTTP transport's resolver wraps this for browser CORS preflights. // IMPORTANT: the registry takes IServiceScopeFactory (NOT IOpenIddictApplicationManager // directly) — capturing the Scoped manager into a Singleton would transitively pin a // single IRedbService / NpgsqlConnection across all CORS preflights and surface as // "A command is already in progress" under any concurrent test/request load. services.TryAddSingleton(sp => new RegisteredClientOriginRegistry( sp.GetRequiredService(), additionalOriginsCsv: null)); // F1: per-module health probe surfaced under "module:identity" in the aggregated // /api/health/{startup,live,ready} endpoints exposed by redb.Tsak. // Singleton — internal scope created per probe to honour IRedbService scoped lifetime. services.TryAddEnumerable( ServiceDescriptor.Singleton()); // DataProtection (used by federation state, MFA setup tokens, etc.). // SessionTicketService lives in redb.Identity.Http (HTTP-cookie-only concern) // and is registered there. services.AddDataProtection() .PersistKeysToRedb() .ProtectKeysWithRedbIdentity(options); // Federation state protector (DataProtection-based state encrypt/decrypt) // C6: nonce store backs one-time-use enforcement; backend selected via FederationState.Backend. switch (options.FederationState.Backend?.ToLowerInvariant()) { case "redis": var fedRedisCs = options.FederationState.RedisConnectionString ?? options.RateLimit.RedisConnectionString; if (string.IsNullOrWhiteSpace(fedRedisCs)) throw new InvalidOperationException( "FederationState.Backend='redis' requires FederationState.RedisConnectionString " + "(or a fallback RateLimit.RedisConnectionString)."); services.TryAddSingleton(_ => { var factory = new redb.Route.Redis.RedisConnectionFactory { ConnectionString = fedRedisCs!, }; return new RedisFederationStateNonceStore(factory, options.FederationState.RedisKeyPrefix); }); break; case "memory": case null: case "": services.TryAddSingleton(sp => new InMemoryFederationStateNonceStore(sp.GetService())); break; default: throw new InvalidOperationException( $"FederationState.Backend='{options.FederationState.Backend}' is not recognised. " + "Use 'memory' or 'redis'."); } services.TryAddSingleton(sp => new FederationStateProtector( sp.GetRequiredService(), sp.GetService(), sp.GetService(), options.FederationState)); // Z4 (RFC 9449): DPoP replay-store backend selection + validator. // Memory is the default; cluster deployments must opt-in to redis or redb. // NB: the OpenIddict handlers (ValidateDpopProofHandler, AttachDpopConfirmationClaimHandler) // are registered unconditionally in RedbRouteOpenIddictServerBuilderExtensions, so the // validator + replay store MUST always be resolvable from DI even when DPoP is disabled — // the handlers no-op at runtime by checking _options.Enabled. switch (options.Dpop.ReplayStore.Backend?.ToLowerInvariant()) { case "redis": var dpopRedisCs = options.Dpop.ReplayStore.RedisConnectionString ?? options.RateLimit.RedisConnectionString; if (options.Dpop.Enabled && string.IsNullOrWhiteSpace(dpopRedisCs)) throw new InvalidOperationException( "Dpop.ReplayStore.Backend='redis' requires Dpop.ReplayStore.RedisConnectionString " + "(or a fallback RateLimit.RedisConnectionString)."); if (!string.IsNullOrWhiteSpace(dpopRedisCs)) { services.TryAddSingleton(_ => { var factory = new redb.Route.Redis.RedisConnectionFactory { ConnectionString = dpopRedisCs!, }; return new RedisDpopReplayStore(factory, options.Dpop.ReplayStore.RedisKeyPrefix); }); } else { services.TryAddSingleton(sp => new MemoryDpopReplayStore( sp.GetService(), options.Dpop.ReplayStore.MemorySweepInterval)); } break; case "redb": services.TryAddSingleton(); break; case "memory": case null: case "": services.TryAddSingleton(sp => new MemoryDpopReplayStore( sp.GetService(), options.Dpop.ReplayStore.MemorySweepInterval)); break; default: throw new InvalidOperationException( $"Dpop.ReplayStore.Backend='{options.Dpop.ReplayStore.Backend}' is not recognised. " + "Use 'memory', 'redis' or 'redb'."); } services.TryAddSingleton(); // Z7 (RFC 9101) phase 1: resolves a CLIENT's public signing keys — inline JWKS, or a // cached, SSRF-guarded fetch of its jwks_uri. Registered unconditionally: it is inert // until something asks it for keys, and it is shared by JAR and private_key_jwt. AddClientChosenAddressHttpClient(services, ClientKeyResolver.HttpClientName, o => o.ClientKeys.AllowPrivateNetworkTargets); services.TryAddSingleton(); // Z7 (RFC 9101) phase 3: fetching a request_uri (SSRF-guarded in the handler). AddClientChosenAddressHttpClient(services, OpenIddict.Handlers.ValidateRequestObjectHandler.HttpClientName, o => o.Jar.RequestUriAllowPrivateNetworkTargets); // C8: Backchannel logout — signed logout_token JWT + best-effort POST fan-out to RPs. // Uses the OpenIddict signing keys (so RPs validate via the same JWKS as id_tokens). AddClientChosenAddressHttpClient(services, "redb-identity-backchannel-logout", o => o.BackchannelLogout.AllowPrivateNetworkTargets); services.TryAddSingleton(); services.TryAddScoped(); // MFA protectors (DataProtection-based encrypt/decrypt for TOTP secrets and MFA state) services.TryAddSingleton(); services.TryAddSingleton(); // The confirmation-page state for /connect/logout: bound to user and session, five minutes. services.TryAddSingleton(); // Expose MfaStateProtector via the minimal Contracts surface so transport facades // (HTTP, gRPC, …) can render MFA-method selectors without referencing Core. services.TryAddSingleton( sp => sp.GetRequiredService()); // H8 (DoD §4 gap (e)): encrypts PROPS-stored federation provider client secrets. services.TryAddSingleton(); // B5: setup-token protector — encrypts candidate secret/destination during MFA setup. services.TryAddSingleton(); // B4: server-wide pepper for recovery-code hashing. services.TryAddSingleton(); // MFA method implementations + orchestrator // Multiple methods registered via TryAddEnumerable so they all get injected as IEnumerable. services.TryAddEnumerable(ServiceDescriptor.Singleton()); services.TryAddEnumerable(ServiceDescriptor.Singleton()); services.TryAddEnumerable(ServiceDescriptor.Singleton()); services.TryAddScoped(); // H3-SSO device auto-fill: bounded memory-cached User-Agent parser. Registers // IHttpUserAgentParserProvider as singleton; subsequent calls reuse cached // HttpUserAgentInformation by UA string. Size cap prevents unbounded growth // under adversarial unique-UA floods. if (!services.Any(d => d.ServiceType == typeof(MyCSharp.HttpUserAgentParser.Providers.IHttpUserAgentParserProvider))) { MyCSharp.HttpUserAgentParser.MemoryCache.DependencyInjection .HttpUserAgentParserMemoryCacheServiceCollectionExtensions .AddHttpUserAgentMemoryCachedParser(services, o => { o.CacheEntryOptions.SlidingExpiration = TimeSpan.FromHours(6); o.CacheOptions.SizeLimit = 2048; }); } // B3: server-side OTP store — SMS/Email MFA codes persisted as MfaOtpProps // (SHA-256 hashed, single-use under LockForUpdate). Singleton; resolves IRedbService // via IServiceScopeFactory per call (identical pattern to PropsSigningKeyStore / A1). services.TryAddSingleton(); // N-4 (Session C): server-side password-reset token store — single-use reset tokens // persisted as PasswordResetTokenProps (peppered SHA-256, single-use under // LockForUpdate). Singleton; mirrors PropsServerSideOtpStore. Reuses the existing // RecoveryCodePepperProvider for the server-wide pepper. services.TryAddSingleton(); // N-4 (Session C, N4-6): server-side e-mail-verification token store. Mirror of // RedbPasswordResetTokenStore with e-mail-snapshot binding for double-change race // protection. Registered unconditionally so the verify route can resolve it when // RedbIdentityOptions.EmailVerification.Enabled flips on at runtime. services.TryAddSingleton(); // N-4 (Session E, N4-7): server-side change-of-e-mail token store. Mirror of // RedbEmailVerificationTokenStore with extra fields (NewEmail + CurrentEmail) and // a pre-issue housekeeping pass that invalidates prior unconsumed tokens for the // same user when ChangeEmailOptions.InvalidatePreviousTokensOnRequest is true. services.TryAddSingleton(); // N-4 (Session C): default inline e-mail template registry. Hosts MAY replace // this with their own branded templates by registering an IEmailTemplateRegistry // singleton BEFORE calling AddRedbIdentityServer. The default ships English + // Russian copy for the "password-reset" template. services.TryAddSingleton(); // N-4: e-mail dispatch channel is INTENTIONALLY not registered by default. // Production hosts must register a concrete IEmailNotificationChannel (SMTP / // SendGrid / SES); test fixtures register InMemoryEmailNotificationChannel. // PasswordForgotProcessor gracefully degrades (logs + silently drops) when no // channel is registered. // // When Smtp.Enabled = true the redb.Route.Mail-backed channel is auto-registered // here (TryAdd — host opt-out by registering a different channel BEFORE calling // AddRedbIdentityServer). The matching SMTP route is wired by IdentityCoreRouteBuilder. if (options.Smtp.Enabled) { services.TryAddSingleton(); } // MFA-3: WebAuthn (FIDO2 / Passkey) wiring. Validates RpId/Origins fail-fast at // startup so a misconfigured deployment never reaches first-credential-registration // with broken settings (changing RpId after credentials exist invalidates every one). // Singleton challenge store mirrors the OTP-store pattern. if (options.WebAuthn.Enabled) { options.WebAuthn.Validate(); services.TryAddSingleton(); services.TryAddSingleton(options.WebAuthn); // IOptions for IOptions-aware consumers. services.AddSingleton>( Microsoft.Extensions.Options.Options.Create(options.WebAuthn)); // IFido2 — pure crypto verifier, singleton. Origins/RpId fixed at startup; // changing them after deployment requires app restart (and credentials may // be invalidated, see IdentityWebAuthnOptions docs). services.TryAddSingleton(_ => { var rpName = string.IsNullOrWhiteSpace(options.WebAuthn.RpName) ? options.WebAuthn.RpId! : options.WebAuthn.RpName!; var cfg = new Fido2NetLib.Fido2Configuration { RPID = options.WebAuthn.RpId!, RPName = rpName, Origins = new HashSet(options.WebAuthn.Origins, StringComparer.Ordinal), Timeout = (uint)options.WebAuthn.TimeoutMs, }; // metadataService = null when MDS3 is disabled \u2014 supported by Fido2NetLib. return new Fido2NetLib.Fido2(cfg, metadataService: null!); }); // Register WebAuthn as a "method" so MfaService.ResolveWebAuthnMethod() finds it. // It satisfies BOTH IMfaMethod (degenerate, throws if invoked through OTP path) // AND IWebAuthnMfaMethod (the real surface). services.TryAddEnumerable( ServiceDescriptor.Singleton()); services.TryAddSingleton(sp => { // Find the same singleton instance registered as IMfaMethod so resolution is // consistent (no two parallel instances with divergent caches). foreach (var m in sp.GetServices()) if (m is IWebAuthnMfaMethod web) return web; throw new InvalidOperationException( "WebAuthn IMfaMethod implementation was not registered."); }); // Wire MfaService.AttachWebAuthn at first scope activation. We can't pass the // dependency through the constructor without breaking every existing test that // constructs MfaService directly, so we replace the bare TryAddScoped // registration with a factory that activates the instance and then attaches the // WebAuthn collaborators before returning it. services.RemoveAll(); services.AddScoped(sp => { var instance = ActivatorUtilities.CreateInstance(sp); var store = sp.GetRequiredService(); var opts = sp.GetRequiredService(); instance.AttachWebAuthn(store, opts); return instance; }); } // Federation providers (OIDC redirect-based auth) if (options.Features.EnableFederation && options.FederationProviders.Count > 0) { services.AddHttpClient("redb-identity-federation"); // Skip providers that still carry placeholder credentials so users // never hit Google's "OAuth client was not found" 401 / Microsoft's // equivalent and mistake config for a server bug. The provider // reappears the moment the operator fills in real values (no // restart beyond config reload). static bool IsPlaceholder(string? v) => string.IsNullOrWhiteSpace(v) || v.Contains("REPLACE_ME", StringComparison.OrdinalIgnoreCase); foreach (var providerConfig in options.FederationProviders) { if (IsPlaceholder(providerConfig.ClientId) || IsPlaceholder(providerConfig.Authority)) continue; // H8: dispatch on Kind. Default ("oidc") preserves the v0 behavior so existing // appsettings keep working. "github" wires the OAuth2-only provider. services.AddSingleton(sp => { var kind = (providerConfig.Kind ?? "oidc").Trim().ToLowerInvariant(); var http = sp.GetRequiredService(); return kind switch { "github" => new GitHubFederatedAuthProvider(providerConfig, http), "oidc" or "" or null => new OidcFederatedAuthProvider(providerConfig, http), _ => throw new InvalidOperationException( $"Unknown federation provider kind '{kind}' for ProviderId='{providerConfig.ProviderId}'. Expected: oidc | github."), }; }); } } // C1: Rate-limit store. Picks the in-memory or Redis backend based on configuration. // The store is only registered when RateLimit.Enabled is true; otherwise the route // builder skips wiring the rate-limit processors entirely (Camel-style conditional // pipeline composition — see IdentityCoreRouteBuilder). // // For the Redis backend we reuse redb.Route.Redis's RedisConnectionFactory + the // RedisComponent registered in InitRoute — keeps connection management consistent // with the rest of the redb ecosystem (claim-check repository, redis: route URIs). if (options.RateLimit.Enabled) { switch (options.RateLimit.Backend?.ToLowerInvariant()) { case "redis": if (string.IsNullOrWhiteSpace(options.RateLimit.RedisConnectionString)) throw new InvalidOperationException( "RateLimit.Backend='redis' requires RateLimit.RedisConnectionString."); services.TryAddSingleton(sp => { var factory = new redb.Route.Redis.RedisConnectionFactory { ConnectionString = options.RateLimit.RedisConnectionString!, }; return new RedisRateLimitStore( factory, options.RateLimit.RedisKeyPrefix, sp.GetService() ?? TimeProvider.System); }); break; case "memory": case null: case "": services.TryAddSingleton(sp => new InMemoryRateLimitStore(sp.GetService() ?? TimeProvider.System)); break; default: throw new InvalidOperationException( $"RateLimit.Backend='{options.RateLimit.Backend}' is not recognised. " + "Use 'memory' or 'redis'."); } } return services; } /// /// Registers redb-backed OpenIddict stores for applications, authorizations, scopes, and tokens. /// Usage: services.AddOpenIddict().AddCore(options => options.UseRedbStores()); /// public static OpenIddictCoreBuilder UseRedbStores(this OpenIddictCoreBuilder builder) { ArgumentNullException.ThrowIfNull(builder); // Set entity types so OpenIddict managers know the concrete types builder.SetDefaultApplicationEntity>(); builder.SetDefaultAuthorizationEntity>(); builder.SetDefaultScopeEntity>(); builder.SetDefaultTokenEntity>(); // Register store implementations (default store resolvers discover these via DI) builder.Services.TryAddScoped( typeof(IOpenIddictApplicationStore>), typeof(RedbApplicationStore)); builder.Services.TryAddScoped( typeof(IOpenIddictAuthorizationStore>), typeof(RedbAuthorizationStore)); builder.Services.TryAddScoped( typeof(IOpenIddictScopeStore>), typeof(RedbScopeStore)); builder.Services.TryAddScoped( typeof(IOpenIddictTokenStore>), typeof(RedbTokenStore)); // A3: PROPS signing key store + OpenIddict credential post-configuration (opt-in via // RedbIdentityOptions.UsePropsSigningKeyStore). Registration is unconditional so the // store can be resolved by tooling / admin APIs; the OpenIddict integration itself // is gated by the option. builder.Services.TryAddSingleton(); builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton< IPostConfigureOptions, redb.Identity.Core.Keys.PropsSigningKeyStoreOpenIddictPostConfigure>()); // F3: Meter-based telemetry. Singleton; picked up by host-side OTEL pipeline via // AddMeter("RedbIdentity"). Safe to register unconditionally — zero cost if no // exporter is wired. builder.Services.TryAddSingleton(); // The enabled webhook subscriptions, cached for Delivery.SubscriptionCache (see WebhookSubscriptionCache). builder.Services.TryAddSingleton(sp => new redb.Identity.Core.Events.WebhookSubscriptionCache( sp.GetService() ?? TimeProvider.System, sp.GetRequiredService>().Value.Delivery.SubscriptionCache)); // The outbox backlog behind the health rule and the delivery gauges (see DeliveryBacklog). builder.Services.TryAddSingleton(sp => new redb.Identity.Core.Events.DeliveryBacklog( sp.GetRequiredService(), sp.GetService() ?? TimeProvider.System, sp.GetRequiredService().CreateLogger())); // C12: password hashing. Register a MultiFormatPasswordHasher that hashes new // passwords with the configured primary algorithm (Argon2id by default) and // transparently verifies legacy BCrypt / legacy SHA256+salt hashes. LoginService // and UserProviderBase resolve IPasswordHasher from DI; registering it here // replaces the default SimplePasswordHasher baked into PostgresUserProvider's // parameterless ctor path. builder.Services.TryAddSingleton(sp => { var opts = sp.GetRequiredService>().Value.PasswordHashing; var argon2 = new redb.Identity.Core.Security.Argon2idPasswordHasher( memoryKib: opts.Argon2id.MemoryKib, iterations: opts.Argon2id.Iterations, parallelism: opts.Argon2id.Parallelism, saltBytes: opts.Argon2id.SaltBytes, hashBytes: opts.Argon2id.HashBytes, logger: sp.GetService>()); var bcrypt = new BcryptPasswordHasher(workFactor: opts.Bcrypt.WorkFactor); if (opts.Algorithm == Configuration.PasswordHashAlgorithm.Bcrypt) { // BCrypt selected as primary: return plain bcrypt so new hashes use bcrypt. // Legacy Argon2id hashes written by a previous Argon2id-primary configuration // will not verify under this setting — expected, since operators picking // bcrypt have explicitly chosen that trade-off. return bcrypt; } return new redb.Identity.Core.Security.MultiFormatPasswordHasher(argon2, bcrypt); }); // Seed default password for the well-known 'admin' user from the base redb // SQL seed (_users.id=1, login='admin', password=''). Idempotent — only writes // when the stored password is empty. Configurable via RedbIdentityOptions.SeedAdmin. // Wired as transient — InitRoute.main resolves it and registers via // context.AddLifecycleListener (Tsak modules have no IHost, so IHostedService // would never run). builder.Services.AddTransient(); // Seed canonical OIDC client (default 'identity-web') so the bundled Web BFF // can complete /connect/authorize on a fresh install. Idempotent — skips when // a client with the same ClientId already exists. Configurable via // RedbIdentityOptions.SeedWebClient. Same lifecycle pattern as SeedAdmin. builder.Services.AddTransient(); // W6-0: backchannel client_credentials service account seeder. Opt-in via // RedbIdentityOptions.SeedBackchannelClient.Enabled=true. Web BFF uses this // account to publish/poll the revoked-sids list for cluster-wide BCL. builder.Services.AddTransient(); return builder; } // PersistKeysToRedb extension moved to redb.Identity.DataProtection (Phase 9a). // Use redb.Identity.DataProtection.RedbDataProtectionBuilderExtensions.PersistKeysToRedb. /// /// C10 — wires at-rest encryption for the DataProtection key-ring based on /// . Variants (priority order): /// custom KMS factory → certificate (PFX path > thumbprint) → AES-GCM master key. /// If is true /// and is false and none of /// the variants is configured, throws. /// public static IDataProtectionBuilder ProtectKeysWithRedbIdentity( this IDataProtectionBuilder builder, RedbIdentityOptions options) { ArgumentNullException.ThrowIfNull(builder); ArgumentNullException.ThrowIfNull(options); var dp = options.DataProtection; // Variant B — KMS / Vault hook. Highest priority because it's the most explicit // configuration the operator can supply. if (dp.CustomEncryptorFactory is not null) { var factory = dp.CustomEncryptorFactory; builder.Services.AddSingleton>( sp => new ConfigureNamedOptions(Options.DefaultName, o => o.XmlEncryptor = factory(sp))); return builder; } // Variant A — X.509 certificate. PFX-on-disk wins over thumbprint when both are set // (operator presumably picked PFX deliberately). if (dp.Certificate.IsConfigured) { var cert = CertificateLoader.Load(dp.Certificate); // ProtectKeysWithCertificate registers BOTH the encryptor and the decryptor — // decryption needs a cert with private key, which is why we pre-load it here // (the thumbprint overload only works against the local cert store). builder.ProtectKeysWithCertificate(cert); return builder; } // Variant C — AES-GCM master key. Smallest deployments / dev. if (!string.IsNullOrWhiteSpace(dp.MasterKey)) { byte[] keyBytes; try { keyBytes = Convert.FromBase64String(dp.MasterKey!); } catch (FormatException ex) { throw new InvalidOperationException( "DataProtection.MasterKey must be base64-encoded.", ex); } if (keyBytes.Length != 32) throw new InvalidOperationException( $"DataProtection.MasterKey must decode to exactly 32 bytes (AES-256); got {keyBytes.Length}."); var keyProvider = new RedbMasterKeyProvider(keyBytes); builder.Services.AddSingleton(keyProvider); builder.Services.AddSingleton>( sp => new ConfigureNamedOptions(Options.DefaultName, o => o.XmlEncryptor = new RedbAesGcmXmlEncryptor(keyProvider))); return builder; } // Production gate: nothing configured. if (dp.RequireAtRestEncryption && !options.AllowEphemeralKeys) { throw new InvalidOperationException( "DataProtection key-ring is unprotected at rest. Configure ONE of: " + "RedbIdentityOptions.DataProtection.MasterKey (32-byte base64), " + ".DataProtection.Certificate.Thumbprint, .DataProtection.Certificate.PfxPath, " + "or .DataProtection.CustomEncryptorFactory. " + "Disable this check only for local development by setting " + "DataProtection.RequireAtRestEncryption=false (or AllowEphemeralKeys=true)."); } // Permitted: dev / ephemeral. Key-ring stays in PROPS in plaintext. return builder; } } Path: redb-identity/src/redb.Identity.Core/Health/IdentityHealthContributor.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/Health/IdentityHealthContributor.cs ---- using Microsoft.AspNetCore.DataProtection.KeyManagement; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using OpenIddict.Server; using redb.Core; using redb.Tsak.Contracts; namespace redb.Identity.Core.Health; /// /// Per-module health probe for redb.Identity. Surfaces the module under /// module:identity in the aggregated /api/health/{startup,live,ready} /// endpoints exposed by redb.Tsak. /// /// Probes (worst status wins): /// /// db — returns a non-empty /// string. Failure → . /// signing-keys — at least one signing credential is registered with the /// OpenIddict server. Empty → (token issuance /// would fail). /// data-protection — the active key-ring exposes at least one key. /// Empty → (cookie / state protection still works /// on the in-memory bootstrap key, but nothing is persisted yet). /// /// /// /// Registered as a singleton in AddRedbIdentityServer. Resolves /// through a transient scope to honour its scoped lifetime. /// All exceptions are caught locally so a misbehaving probe cannot crash the health /// endpoint (Tsak additionally guards via fallback). /// /// public sealed class IdentityHealthContributor : IModuleHealthContributor { private readonly IServiceProvider _serviceProvider; private readonly ILogger _logger; public IdentityHealthContributor( IServiceProvider serviceProvider, ILogger logger) { _serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider)); _logger = logger ?? throw new ArgumentNullException(nameof(logger)); } /// public string ModuleName => "identity"; /// public async Task CheckHealthAsync(CancellationToken ct) { var dbOk = await CheckDatabaseAsync(ct).ConfigureAwait(false); var signingOk = CheckSigningKeys(); var dataProtectionOk = CheckDataProtection(); if (!dbOk || !signingOk) return HealthStatus.Unhealthy; if (!dataProtectionOk) return HealthStatus.Degraded; if (!await CheckDeliveryBacklogAsync(ct).ConfigureAwait(false)) return HealthStatus.Degraded; return HealthStatus.Healthy; } /// /// The oldest undelivered outbox row (webhooks, audit targets) is younger than /// Identity:Delivery:DegradedAfter. Older means the worker is not running or a destination has /// been failing that long: deliveries wait, nothing is lost, so Degraded and not Unhealthy. A table that /// cannot be read counts as fine here; the database probe reports that. /// private async Task CheckDeliveryBacklogAsync(CancellationToken ct) { var backlog = _serviceProvider.GetService(); var options = _serviceProvider.GetService>(); if (backlog is null || options is null) return true; var stats = await backlog.GetAsync(ct).ConfigureAwait(false); var limit = options.Value.Delivery.DegradedAfter; if (BacklogWithin(stats, limit)) return true; _logger.LogWarning( "Identity health: {Pending} outbox row(s) undelivered, the oldest for {Age:N0} s (limit {Limit:N0} s).", stats!.Pending, stats.OldestSeconds, limit.TotalSeconds); return false; } /// The health rule: no reading, nothing pending, or the oldest pending row within the limit. internal static bool BacklogWithin(redb.Identity.Core.Events.OutboxStats? stats, TimeSpan limit) => stats is null || stats.Pending == 0 || stats.OldestSeconds <= limit.TotalSeconds; private async Task CheckDatabaseAsync(CancellationToken ct) { try { using var scope = _serviceProvider.CreateScope(); var redb = scope.ServiceProvider.GetRequiredService(); var version = await redb.GetDbVersionAsync(ct).ConfigureAwait(false); return !string.IsNullOrWhiteSpace(version); } catch (Exception ex) when (ex is not OperationCanceledException) { _logger.LogWarning(ex, "Identity health: database probe failed"); return false; } } private bool CheckSigningKeys() { try { var monitor = _serviceProvider.GetService>(); if (monitor is null) return false; return monitor.CurrentValue.SigningCredentials.Count > 0; } catch (Exception ex) { _logger.LogWarning(ex, "Identity health: signing-key probe failed"); return false; } } private bool CheckDataProtection() { try { var keyManager = _serviceProvider.GetService(); if (keyManager is null) { // DataProtection not wired (atypical) — degraded rather than unhealthy: // session cookies / state protectors will fail later but other Identity // surfaces (token issuance) can still serve. return false; } // GetAllKeys is cached — single-digit ms even on hot key-rings. var keys = keyManager.GetAllKeys(); return keys.Count > 0; } catch (Exception ex) { _logger.LogWarning(ex, "Identity health: data-protection probe failed"); return false; } } } Path: redb-identity/src/redb.Identity.Core/Hosting/IdentitySchemaRegistry.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/Hosting/IdentitySchemaRegistry.cs ---- using redb.Identity.Core.Models; using redb.Identity.DataProtection; namespace redb.Identity.Core.Hosting; /// /// Authoritative list of all PROPS schemas managed by redb.Identity. /// Single source of truth for schema bootstrap () /// and test fixtures. External modules extending Identity with their own *Props can add /// types via BEFORE the route context starts. /// public static class IdentitySchemaRegistry { private static readonly List _types = [ typeof(UserProps), typeof(MfaProps), typeof(SessionProps), typeof(ApplicationProps), typeof(AuthorizationProps), typeof(ScopeProps), typeof(TokenProps), typeof(GroupProps), typeof(GroupMemberProps), typeof(IdempotencyRecordProps), typeof(DataProtectionKeyProps), // 4.4: when the key ring moved from the file system into redb (cutoff of the one-off import). typeof(DataProtectionKeyImportProps), typeof(SigningKeyProps), typeof(MfaOtpProps), typeof(WebAuthnConsumedChallengeProps), typeof(DpopConsumedJtiProps), // Session lifecycle: revoked-sid blacklist for OIDC back-channel logout + // single-logout enforcement. Cleanup processor queries by ExpiresAt < now() // — scheme MUST be registered or the Quartz cleanup tick throws every run. typeof(RevokedSidProps), // R1: AuditEventProps removed — audit moved to the flat relational // identity_audit_log table managed by IdentityAuditLogTableInitListener. typeof(PasswordHistoryProps), // H5 (DoD §5): declarative claim mapping rules + reusable Client Scopes + assignments. typeof(ClaimMapperProps), typeof(ClaimScopeProps), typeof(ClaimScopeAssignmentProps), // S2: claim schema (required/type/regex) with global + per-application scope. typeof(ClaimDefinitionProps), // B.3: first-class Roles registry — audience-scoped (organization / // application) buckets assignable to users directly + to groups // transitively. Effective role set resolved at token issuance. typeof(RoleProps), typeof(UserRoleAssignmentProps), typeof(GroupRoleAssignmentProps), typeof(RoleScopeAssignmentProps), // W1: outbound webhook subscriptions — fan-out for the events route. typeof(WebhookSubscriptionProps), // H8 (DoD §4): per-user federated identity links + PROPS-stored federation provider configs. typeof(FederatedIdentityProps), typeof(FederationProviderProps), // B1: bootstrap / system flag store (bare RedbObject — Props intentionally empty). typeof(IdentitySystemFlagProps), ]; /// /// All Props types to be synchronized with PROPS on Identity startup. /// public static IReadOnlyList Types { get { lock (_types) return _types.ToArray(); } } /// /// Registers an additional *Props type to be provisioned alongside the /// built-in Identity schemas. Must be called BEFORE the Identity route context starts /// (typically from a host-side AddRedbIdentityServer follow-up, or a sibling /// module's InitRoute.main that executes earlier in the load order). /// public static void Register() where TProps : class { lock (_types) { if (!_types.Contains(typeof(TProps))) _types.Add(typeof(TProps)); } } } Path: redb-identity/src/redb.Identity.Core/Keys/ISigningKeyStore.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/Keys/ISigningKeyStore.cs ---- using System.Collections.Immutable; using Microsoft.IdentityModel.Tokens; namespace redb.Identity.Core.Keys; /// /// In-memory representation of a signing / encryption key loaded from PROPS storage /// (). /// public sealed record SigningKeyMaterial( string Kid, string KeyKind, string Algorithm, SecurityKey SecurityKey, DateTimeOffset NotBefore, DateTimeOffset NotAfter, bool IsActive); /// /// Persistent store for OpenIddict signing / encryption keys backed by redb PROPS /// (). A3 replaces ephemeral in-memory keys so that /// cluster replicas share the same JWKS and tokens survive restarts. /// public interface ISigningKeyStore { /// Returns all keys currently in the store with NotAfter still in the future (active + still-valid rotated-out). Task> GetAllAsync(CancellationToken ct = default); /// /// Returns every key row in the store, regardless of whether /// is in the past (i.e. including retired keys). Used by the admin /signing-keys list endpoint to /// surface the full audit trail; the JWKS endpoint must still use so /// retired keys do not get advertised to RPs. /// Task> ListAllIncludingRetiredAsync(CancellationToken ct = default); /// /// Generates an initial active key for the given kind if the store contains no active key. /// Idempotent: once an active key of the requested kind exists, the call is a no-op. /// Task EnsureBootstrappedAsync(string keyKind, CancellationToken ct = default); /// /// Generates a fresh key of the given kind and marks every currently-active key of the same kind /// as inactive (so OpenIddict will pick the new one for future signing). The previously-active key /// is NOT retired — its is left untouched so RPs that /// cached the JWKS continue to validate any in-flight tokens that were signed with it. Call /// once the RP cache TTL (typically 1 h) has elapsed. /// /// The newly-created key material. Task RotateAsync(string keyKind, CancellationToken ct = default); /// /// Immediately ends the validity window of by setting NotAfter to "now". /// The key disappears from JWKS on the next request. Tokens previously signed with this key will /// fail signature validation against the live JWKS — call this only after the rotation grace /// window has elapsed. /// /// true when the key was found and retired; false when no key with that kid exists. Task RetireAsync(string kid, CancellationToken ct = default); } Path: redb-identity/src/redb.Identity.Core/Keys/JwksRefreshDiagnosticHandler.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/Keys/JwksRefreshDiagnosticHandler.cs ---- using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using OpenIddict.Server; using OpenIddict.Validation; using static OpenIddict.Validation.OpenIddictValidationEvents; namespace redb.Identity.Core.Keys; /// /// **Batch 12 diagnostic.** Fires on every rejected validation. Logs the key picture from /// both the server options and the validation options so we can see *which* layer hangs /// onto a stale snapshot after a JWKS rotate. Wired in the validation pipeline with /// max-priority order so it runs after the built-in rejection. /// internal sealed class JwksRefreshDiagnosticHandler : IOpenIddictValidationHandler { public static OpenIddictValidationHandlerDescriptor Descriptor { get; } = OpenIddictValidationHandlerDescriptor .CreateBuilder() .UseSingletonHandler() .SetOrder(int.MaxValue - 500) .Build(); private readonly IOptionsMonitor _serverOptions; private readonly IOptionsMonitor _validationOptions; private readonly ILogger _logger; public JwksRefreshDiagnosticHandler( IOptionsMonitor serverOptions, IOptionsMonitor validationOptions, ILogger logger) { _serverOptions = serverOptions; _validationOptions = validationOptions; _logger = logger; } public ValueTask HandleAsync(ProcessAuthenticationContext context) { if (!context.IsRejected) return default; try { string? tokenKid = null; if (!string.IsNullOrEmpty(context.AccessToken)) { var parts = context.AccessToken.Split('.'); if (parts.Length >= 2) { try { var s = parts[0].Replace('-','+').Replace('_','/'); var pad = s.Length % 4; s += pad == 2 ? "==" : pad == 3 ? "=" : ""; var hdrJson = System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(s)); using var doc = System.Text.Json.JsonDocument.Parse(hdrJson); if (doc.RootElement.TryGetProperty("kid", out var kidEl)) tokenKid = kidEl.GetString(); } catch { /* may be encrypted JWE */ } } } var srv = _serverOptions.CurrentValue; var val = _validationOptions.CurrentValue; var serverKids = srv.SigningCredentials.Select(c => c.Key?.KeyId ?? "(no-kid)").ToList(); var serverEncKids = srv.EncryptionCredentials.Select(c => c.Key?.KeyId ?? "(no-kid)").ToList(); var valIssuerKids = val.TokenValidationParameters?.IssuerSigningKeys? .Select(k => k.KeyId ?? "(no-kid)").ToList() ?? new List(); var valDecryptKids = val.TokenValidationParameters?.TokenDecryptionKeys? .Select(k => k.KeyId ?? "(no-kid)").ToList() ?? new List(); var serverNotInVal = serverKids.Except(valIssuerKids).ToList(); _logger.LogWarning( "JWKS-DIAG validation REJECTED. err={Err} desc={Desc} | token.kid={TokenKid} | " + "server.signing=[{ServerKids}] (n={SrvN}) | server.encryption=[{ServerEncKids}] | " + "val.issuerSigning=[{ValKids}] (n={ValN}) | val.decrypt=[{ValDecKids}] | " + "server_not_in_val=[{Delta}]", context.Error, context.ErrorDescription, tokenKid ?? "(none/JWE)", string.Join(",", serverKids), serverKids.Count, string.Join(",", serverEncKids), string.Join(",", valIssuerKids), valIssuerKids.Count, string.Join(",", valDecryptKids), string.Join(",", serverNotInVal)); } catch { /* diagnostic — never throw */ } return default; } } Path: redb-identity/src/redb.Identity.Core/Keys/PropsSigningKeyStore.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/Keys/PropsSigningKeyStore.cs ---- using System.Collections.Immutable; using System.Security.Cryptography; using System.Text; using Microsoft.AspNetCore.DataProtection; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Microsoft.IdentityModel.Tokens; using OpenIddict.Server; using OpenIddict.Validation; using redb.Core; using redb.Core.Models.Entities; using redb.Identity.Core.Models; namespace redb.Identity.Core.Keys; /// /// PROPS-backed implementation of . Singleton; resolves /// and through a fresh DI /// scope () per operation to avoid captive-scoped-into- /// singleton traps (identical lifetime pattern to RedbXmlRepository, A1). /// /// Private keys are stored as DataProtection-encrypted base64 PEM bytes with the purpose /// string redb.identity.signing-keys.v1. The DataProtection key ring is itself /// bootstrapped from PROPS (RedbXmlRepository), therefore RedbXmlRepositoryInitListener /// MUST execute before SigningKeyInitListener in InitRoute.main. /// /// public sealed class PropsSigningKeyStore : ISigningKeyStore { private const string ProtectorPurpose = "redb.identity.signing-keys.v1"; private readonly IServiceScopeFactory _scopeFactory; private readonly ILogger _logger; public PropsSigningKeyStore( IServiceScopeFactory scopeFactory, ILogger logger) { _scopeFactory = scopeFactory ?? throw new ArgumentNullException(nameof(scopeFactory)); _logger = logger ?? throw new ArgumentNullException(nameof(logger)); } public async Task> GetAllAsync(CancellationToken ct = default) { await using var scope = _scopeFactory.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); var protector = scope.ServiceProvider .GetRequiredService() .CreateProtector(ProtectorPurpose); // Server-side filter: only keys still inside their validity window. Expired // rotations stay in the table for audit but never enter the working set, so // we do not waste a DataProtection.Unprotect call on them. A fresh deployment // typically has 1–2 rows here per kind (active + grace overlap). var now = DateTimeOffset.UtcNow; var rows = await redb.Query() .Where(k => k.NotAfter > now) .OrderByDescendingRedb(o => o.DateCreate) .ToListAsync() .ConfigureAwait(false); var builder = ImmutableArray.CreateBuilder(rows.Count); foreach (var row in rows) { var p = row.Props; SecurityKey? key; try { var protectedBytes = Convert.FromBase64String(p.EncryptedPem); var pemBytes = protector.Unprotect(protectedBytes); key = ParsePem(pemBytes, p.Algorithm); } catch (Exception ex) { _logger.LogError(ex, "redb.Identity: failed to decrypt signing key kid={Kid} kind={Kind}; skipping", p.Kid, p.KeyKind); continue; } builder.Add(new SigningKeyMaterial( p.Kid, p.KeyKind, p.Algorithm, key, p.NotBefore, p.NotAfter, p.IsActive)); } return builder.ToImmutable(); } public async Task> ListAllIncludingRetiredAsync(CancellationToken ct = default) { await using var scope = _scopeFactory.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); var protector = scope.ServiceProvider .GetRequiredService() .CreateProtector(ProtectorPurpose); // List = every row, no NotAfter filter. The admin endpoint surfaces retired keys // for audit; the JWKS endpoint uses GetAllAsync so retired keys do not leak. var rows = await redb.Query() .OrderByDescendingRedb(o => o.DateCreate) .ToListAsync() .ConfigureAwait(false); var builder = ImmutableArray.CreateBuilder(rows.Count); foreach (var row in rows) { var p = row.Props; SecurityKey? key; try { var protectedBytes = Convert.FromBase64String(p.EncryptedPem); var pemBytes = protector.Unprotect(protectedBytes); key = ParsePem(pemBytes, p.Algorithm); } catch (Exception ex) { _logger.LogError(ex, "redb.Identity: failed to decrypt signing key kid={Kid} kind={Kind} during list; skipping", p.Kid, p.KeyKind); continue; } builder.Add(new SigningKeyMaterial( p.Kid, p.KeyKind, p.Algorithm, key, p.NotBefore, p.NotAfter, p.IsActive)); } return builder.ToImmutable(); } public async Task RotateAsync(string keyKind, CancellationToken ct = default) { ArgumentException.ThrowIfNullOrEmpty(keyKind); await using var scope = _scopeFactory.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); var protector = scope.ServiceProvider .GetRequiredService() .CreateProtector(ProtectorPurpose); // 1. Demote every currently-active key of this kind. The keys stay in the JWKS and in // OpenIddict's credentials until their own NotAfter passes — that's the entire point of // rotation: a smooth handover so RPs that cached the JWKS continue to validate tokens // signed under the old key. RetireAsync is the explicit "stop trusting it now" step: // it sets NotAfter to the present, and on the next options refresh the key is gone // from the JWKS, from minting and from validation alike. var activeRows = await redb.Query() .Where(k => k.KeyKind == keyKind && k.IsActive) .ToListAsync() .ConfigureAwait(false); foreach (var row in activeRows) { row.Props.IsActive = false; await redb.SaveAsync(row).ConfigureAwait(false); } // 2. Mint the new active key. var (algorithm, pemBytes) = GenerateKey(keyKind); var kid = "k_" + Guid.NewGuid().ToString("N"); var protectedPem = Convert.ToBase64String(protector.Protect(pemBytes)); var now = DateTimeOffset.UtcNow; var obj = new RedbObject(new SigningKeyProps { Kid = kid, KeyKind = keyKind, Algorithm = algorithm, EncryptedPem = protectedPem, NotBefore = now, NotAfter = now.AddDays(90), IsActive = true, }); obj.name = kid; await redb.SaveAsync(obj).ConfigureAwait(false); InvalidateOpenIddictOptionsCache(scope.ServiceProvider); _logger.LogDebug( "redb.Identity: rotated signing key kind={Kind} new_kid={Kid} demoted={Demoted} algorithm={Alg}", keyKind, kid, activeRows.Count, algorithm); var pemBytesForReturn = protector.Unprotect(Convert.FromBase64String(protectedPem)); var material = new SigningKeyMaterial( kid, keyKind, algorithm, ParsePem(pemBytesForReturn, algorithm), now, now.AddDays(90), true); return material; } public async Task RetireAsync(string kid, CancellationToken ct = default) { ArgumentException.ThrowIfNullOrEmpty(kid); await using var scope = _scopeFactory.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); // Identity stamps the row's `name` to the kid at creation time, so the // simple WHERE on Kid hits the same value either way. var row = await redb.Query() .Where(k => k.Kid == kid) .FirstOrDefaultAsync() .ConfigureAwait(false); if (row is null) return false; var now = DateTimeOffset.UtcNow; if (row.Props.NotAfter <= now) { // Already retired — idempotent no-op. return true; } row.Props.NotAfter = now; row.Props.IsActive = false; await redb.SaveAsync(row).ConfigureAwait(false); InvalidateOpenIddictOptionsCache(scope.ServiceProvider); _logger.LogDebug("redb.Identity: retired signing key kid={Kid} (NotAfter set to now)", kid); return true; } /// /// Batch 12 diagnostic mode: invalidates BOTH the server and validation /// IOptionsMonitor caches so the next options read re-runs every PostConfigure. /// private void InvalidateOpenIddictOptionsCache(IServiceProvider sp) { try { var serverCache = sp.GetService>(); serverCache?.TryRemove(Options.DefaultName); var validationCache = sp.GetService>(); validationCache?.TryRemove(Options.DefaultName); _logger.LogDebug( "redb.Identity: OpenIddict options cache invalidated (server={Server}, validation={Validation})", serverCache is not null, validationCache is not null); } catch (Exception ex) { _logger.LogWarning(ex, "redb.Identity: cache invalidation failed"); } } public async Task EnsureBootstrappedAsync(string keyKind, CancellationToken ct = default) { ArgumentException.ThrowIfNullOrEmpty(keyKind); await using var scope = _scopeFactory.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); var protector = scope.ServiceProvider .GetRequiredService() .CreateProtector(ProtectorPurpose); var hasActive = await redb.Query() .Where(k => k.KeyKind == keyKind && k.IsActive) .AnyAsync() .ConfigureAwait(false); if (hasActive) return; var (algorithm, pemBytes) = GenerateKey(keyKind); var kid = "k_" + Guid.NewGuid().ToString("N"); var protectedPem = Convert.ToBase64String(protector.Protect(pemBytes)); var now = DateTimeOffset.UtcNow; var obj = new RedbObject(new SigningKeyProps { Kid = kid, KeyKind = keyKind, Algorithm = algorithm, EncryptedPem = protectedPem, NotBefore = now, NotAfter = now.AddDays(90), IsActive = true, }); obj.name = kid; try { await redb.SaveAsync(obj).ConfigureAwait(false); _logger.LogInformation( "redb.Identity: bootstrapped signing key kind={Kind} kid={Kid} algorithm={Alg}", keyKind, kid, algorithm); } catch (Exception ex) { // Racy bootstrap: another replica may have written the first key concurrently. // Check-then-rethrow-if-nothing-there would be nice but we cannot distinguish // unique-violation cleanly without provider-specific plumbing; re-read and log. var collisionWinner = await redb.Query() .Where(k => k.KeyKind == keyKind && k.IsActive) .AnyAsync() .ConfigureAwait(false); if (collisionWinner) { _logger.LogInformation(ex, "redb.Identity: bootstrap write collided with another replica (kind={Kind}); continuing with the winning key", keyKind); return; } throw; } } private static (string Algorithm, byte[] PemBytes) GenerateKey(string keyKind) { if (string.Equals(keyKind, "signing", StringComparison.OrdinalIgnoreCase)) { using var rsa = RSA.Create(2048); var pem = rsa.ExportRSAPrivateKeyPem(); return ("RS256", Encoding.UTF8.GetBytes(pem)); } if (string.Equals(keyKind, "encryption", StringComparison.OrdinalIgnoreCase)) { using var rsa = RSA.Create(2048); var pem = rsa.ExportRSAPrivateKeyPem(); return ("RSA-OAEP", Encoding.UTF8.GetBytes(pem)); } throw new ArgumentOutOfRangeException(nameof(keyKind), keyKind, "Supported kinds are 'signing' and 'encryption'."); } private static SecurityKey ParsePem(byte[] pemBytes, string algorithm) { var pem = Encoding.UTF8.GetString(pemBytes); var rsa = RSA.Create(); rsa.ImportFromPem(pem); return new RsaSecurityKey(rsa); } } Path: redb-identity/src/redb.Identity.Core/Keys/PropsSigningKeyStoreOpenIddictPostConfigure.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/Keys/PropsSigningKeyStoreOpenIddictPostConfigure.cs ---- using System.Collections.Immutable; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Microsoft.IdentityModel.Tokens; using OpenIddict.Server; using redb.Identity.Core.Configuration; namespace redb.Identity.Core.Keys; /// /// A3: post-configures with the signing / encryption credentials /// held by the . Runs only when /// is true. /// /// **Re-runs on every options refresh.** and /// invalidate the /// entry, so the next IOptionsMonitor<OpenIddictServerOptions>.CurrentValue read builds a fresh /// options instance through the whole Configure → PostConfigure chain, and this method sees the store as it /// is now. It is additive within a build: it inserts, deduplicated by kid, and never clears a list another /// configurer filled. /// /// /// **One set of trusted keys.** The keys offered here are the store's working set — every key whose /// NotBefore..NotAfter window contains the present moment (). /// Rotation demotes a key and leaves its NotAfter alone, so it stays in this set and tokens it signed /// keep validating until that date: that is the handover window. Retirement sets NotAfter to now, so /// the key leaves this set on the next refresh, for minting and validation alike: trust in a retired key ends /// at retirement. The validation parameters are then a projection of the credential lists — exactly what /// OpenIddict's own post-configure writes — so the outcome does not depend on which post-configure runs /// last, and a credential another configurer added is trusted for validation as well. /// /// /// An earlier revision built a second, broader "validation pool" of every persisted key past /// NotBefore, retired ones included, and wrote it into the validation parameters so that tokens under /// retired keys would keep validating "during a grace window". A retired key's window ends at retirement, so /// that pool held retired keys for as long as their rows existed. It never reached a token only because /// OpenIddict's post-configure ran after this one and rebuilt the parameters from the credentials — an /// accident of registration order this component may not rely on, and does not any more. /// /// /// **Who mints.** OpenIddict's signing-credential selection picks the first algorithm-compatible entry from /// , and encryption the first encryption /// credential. Among the store's keys the active one is placed first, so newly rotated keys win while /// demoted keys remain behind them for validation. Relative to credentials another configurer added (the /// operator's own keys), decides: Store puts the /// store's keys first, Configured puts them after the configured ones. Both sets validate and are /// published either way. /// /// internal sealed class PropsSigningKeyStoreOpenIddictPostConfigure : IPostConfigureOptions { private readonly ISigningKeyStore _store; private readonly IOptions _options; private readonly ILogger _logger; public PropsSigningKeyStoreOpenIddictPostConfigure( ISigningKeyStore store, IOptions options, ILogger logger) { _store = store; _options = options; _logger = logger; } public void PostConfigure(string? name, OpenIddictServerOptions options) { if (!_options.Value.UsePropsSigningKeyStore) return; // The working set: NotAfter > now is the store's own server-side filter; NotBefore <= now keeps a key // scheduled for the future out until its time. Retired keys (NotAfter = the moment of retirement) // are not in this set, and nothing below reaches for them. var now = DateTimeOffset.UtcNow; var inWindow = _store.GetAllAsync().GetAwaiter().GetResult() .Where(m => m.NotBefore <= now) .ToImmutableArray(); if (!inWindow.Any(m => string.Equals(m.KeyKind, "signing", StringComparison.OrdinalIgnoreCase))) { _logger.LogWarning( "redb.Identity: PROPS signing-key store has no in-window signing key at OpenIddict post-configure time. " + "OpenIddict will reject token-mint requests. SigningKeyInitListener should mint a fresh one " + "on first context start; if you see this in steady state, every signing key has been retired " + "and rotate must be called before clients can authenticate."); } var existingSigningKids = new HashSet( options.SigningCredentials.Select(c => c.Key?.KeyId ?? string.Empty), StringComparer.Ordinal); var existingEncryptionKids = new HashSet( options.EncryptionCredentials.Select(c => c.Key?.KeyId ?? string.Empty), StringComparer.Ordinal); // Where the store's keys land in each list decides who mints: OpenIddict signs with the first // compatible signing credential and encrypts with the first encryption credential, while every // entry validates and is published. With credentials another configurer added (the operator's // SigningCredentials / EncryptionCredentials), MintingKeySource says which source comes first — // its absence with both sources present is refused at registration. With the store alone, the // store leads. Insert reverses order (the last inserted lands at the insertion point), so demoted // keys go in first, oldest first, and the active key last — it lands at the insertion point and // wins the minting pick among the store's keys. var storeLeads = _options.Value.MintingKeySource != MintingKeySource.Configured; var signingAt = storeLeads ? 0 : options.SigningCredentials.Count; var encryptionAt = storeLeads ? 0 : options.EncryptionCredentials.Count; var ordered = inWindow .OrderBy(m => m.IsActive) .ThenBy(m => m.NotBefore); foreach (var m in ordered) { if (string.Equals(m.KeyKind, "signing", StringComparison.OrdinalIgnoreCase)) { if (existingSigningKids.Contains(m.Kid)) continue; options.SigningCredentials.Insert(signingAt, new SigningCredentials(m.SecurityKey, m.Algorithm) { Key = { KeyId = m.Kid }, }); existingSigningKids.Add(m.Kid); } else if (string.Equals(m.KeyKind, "encryption", StringComparison.OrdinalIgnoreCase)) { if (existingEncryptionKids.Contains(m.Kid)) continue; options.EncryptionCredentials.Insert(encryptionAt, new EncryptingCredentials( m.SecurityKey, m.Algorithm, SecurityAlgorithms.Aes256CbcHmacSha512) { Key = { KeyId = m.Kid }, }); existingEncryptionKids.Add(m.Kid); } } // The validation parameters are the credentials, seen as keys. A deferred projection over the live // lists, not a copy: a credential a later configurer adds is trusted too, and there is no second list // that could drift from the first. OpenIddict's own post-configure writes these two lines as well; // writing them here makes the result the same whichever of the two runs last. options.TokenValidationParameters.IssuerSigningKeys = options.SigningCredentials.Select(c => c.Key); options.TokenValidationParameters.TokenDecryptionKeys = options.EncryptionCredentials.Select(c => c.Key); _logger.LogDebug( "redb.Identity: OpenIddict credentials reconciled from PROPS store ({Signing} signing, {Encryption} encryption, active_kid={ActiveKid})", options.SigningCredentials.Count, options.EncryptionCredentials.Count, inWindow.FirstOrDefault(x => x.IsActive && x.KeyKind == "signing")?.Kid ?? "(none)"); } } Path: redb-identity/src/redb.Identity.Core/Metrics/IdentityMetrics.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/Metrics/IdentityMetrics.cs ---- using System.Diagnostics.Metrics; namespace redb.Identity.Core.Metrics; /// /// F3: OpenTelemetry-compatible -based metrics for Identity. Exposed as a /// Singleton and consumed from route processors. Meter name RedbIdentity can be picked /// up by builder.Services.AddOpenTelemetry().WithMetrics(b => b.AddMeter("RedbIdentity")) /// in the host process (Tsak.Worker) without any Identity-side dependency on OTEL packages. /// /// Intentionally minimal: every counter / histogram represents an operational signal the /// Identity SRE needs on day-one (login success/fail, MFA success/fail, token issue/revoke, /// rate-limit rejections, password-verify latency). Call-sites use -local /// instruments directly — no abstraction layer so we do not pay boxing / dispatch cost in the /// auth hot path. /// /// public sealed class IdentityMetrics : IDisposable { public const string MeterName = "RedbIdentity"; private readonly Meter _meter; public IdentityMetrics() { _meter = new Meter(MeterName, version: "1.0.0"); LoginAttempts = _meter.CreateCounter( "identity.login.attempts", unit: "{attempt}", description: "Total password login attempts dispatched to the Identity core route."); LoginFailures = _meter.CreateCounter( "identity.login.failures", unit: "{failure}", description: "Failed password logins (bad password, unknown user, locked, mfa-required treated separately)."); MfaVerifications = _meter.CreateCounter( "identity.mfa.verifications", unit: "{verification}", description: "MFA verification attempts (totp / sms / email / recovery). Tag: method, result."); MfaLockouts = _meter.CreateCounter( "identity.mfa.lockouts", unit: "{lockout}", description: "MFA lockouts activated (FailedAttempts crossed the threshold). Tag: method."); TokensIssued = _meter.CreateCounter( "identity.tokens.issued", unit: "{token}", description: "Tokens minted by OpenIddict. Tag: grant_type, token_type."); TokenErrors = _meter.CreateCounter( "identity.tokens.errors", unit: "{error}", description: "Token endpoint errors (invalid_grant, invalid_client, etc.). Tag: error."); RateLimitRejections = _meter.CreateCounter( "identity.rate_limit.rejections", unit: "{rejection}", description: "Throttled requests. Tag: endpoint, key_dimension (ip/client/user)."); PasswordVerifyDuration = _meter.CreateHistogram( "identity.password.verify.duration", unit: "ms", description: "Wall-clock duration of a single password hash verification (BCrypt / PBKDF2 / Argon2)."); UniqueViolations = _meter.CreateCounter( "identity.unique_violation", unit: "{violation}", description: "DB unique-index violations surfaced to callers (TOCTOU guard). Tag: scheme, column."); AuditWriteFailures = _meter.CreateCounter( "identity.audit.write_failures", unit: "{failure}", description: "Audit events whose row could not be written to identity_audit_log; the event itself went on. Tag: event_type."); DeliveryAttempts = _meter.CreateCounter( "identity.delivery.attempts", unit: "{attempt}", description: "Outbox delivery attempts and their outcome. Tags: kind (webhook, audit), result (delivered, retry, failed, cancelled)."); DeliveryEnqueueFailures = _meter.CreateCounter( "identity.delivery.enqueue_failures", unit: "{failure}", description: "Events whose outbox rows could not be written; their deliveries are lost, the audit row is written. Tags: event_type, kind."); } private int _backlogObserved; /// /// Publishes the outbox backlog as the gauges identity.delivery.pending and /// identity.delivery.oldest_pending_age; the first call wins, later ones do nothing. /// public void ObserveDeliveryBacklog(Events.DeliveryBacklog backlog) { if (Interlocked.Exchange(ref _backlogObserved, 1) != 0) return; _meter.CreateObservableGauge( "identity.delivery.pending", () => backlog.Current?.Pending ?? 0L, unit: "{row}", description: "Outbox rows not yet delivered, failed or cancelled (webhooks and audit targets)."); _meter.CreateObservableGauge( "identity.delivery.oldest_pending_age", () => backlog.Current?.OldestSeconds ?? 0d, unit: "s", description: "Age of the oldest undelivered outbox row; it grows while the worker is down or a destination fails."); } public Counter LoginAttempts { get; } public Counter LoginFailures { get; } public Counter MfaVerifications { get; } public Counter MfaLockouts { get; } public Counter TokensIssued { get; } public Counter TokenErrors { get; } public Counter RateLimitRejections { get; } public Histogram PasswordVerifyDuration { get; } public Counter UniqueViolations { get; } public Counter AuditWriteFailures { get; } public Counter DeliveryAttempts { get; } public Counter DeliveryEnqueueFailures { get; } public void Dispose() => _meter.Dispose(); } Path: redb-identity/src/redb.Identity.Core/Mfa/IServerSideOtpStore.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/Mfa/IServerSideOtpStore.cs ---- using System; using System.Threading; using System.Threading.Tasks; namespace redb.Identity.Core.Mfa; /// /// B3: server-side OTP store — issues and consumes SMS/Email one-time codes so that the /// plaintext OTP lives only in transient memory (generator → delivery channel) and never /// appears in the encrypted mfa_state blob, URL query strings, access logs, or /// Referer headers. /// /// The resulting model is classic OTP-issuance: each challenge writes a single row /// containing the hash of the code, an absolute TTL, and a /// single-use flag. Verify loads the row under LockForUpdate, checks the hash in /// constant time, flips the flag, commits — so a second verify with the same code hits a /// already-consumed row and fails regardless of correctness. /// /// public interface IServerSideOtpStore { /// /// Issues a new OTP. Generates a CSPRNG 6-digit code, persists its SHA-256 hash, and /// returns the jti + plaintext code so the caller can deliver the plaintext via /// the SMS/Email channel and embed → ExpiresAt into /// the encrypted mfa_state via . /// /// User the challenge is bound to. /// sms or email. /// Masked destination (already sanitized for UI display). /// Time-to-live for this challenge. Typically 5 minutes. Task IssueAsync( long userId, string method, string destinationMasked, TimeSpan ttl, CancellationToken ct = default); /// /// Verifies and atomically consumes an OTP keyed by . On success /// the row is marked Consumed; on failure Attempts increments so downstream /// telemetry can flag guessing attempts. Already-consumed or expired rows return /// = false with the appropriate /// . /// /// Expected owner. Used as a defence-in-depth cross-check; a mismatch /// forces Success=false with Reason="user_mismatch". Task VerifyAndConsumeAsync( Guid jti, long userId, string code, CancellationToken ct = default); } /// Result of . /// Random per-issuance identifier. /// Plaintext code for channel delivery. Must NOT be persisted by the caller. /// Echoed masked destination for UI display. /// Absolute expiry passed to consumers. public readonly record struct OtpIssueResult( Guid Jti, string PlaintextCode, string DestinationMasked, DateTimeOffset ExpiresAt); /// Result of . /// Whether the code verified AND the row was successfully consumed. /// Diagnostic reason; values: ok, not_found, expired, /// already_consumed, user_mismatch, bad_code. /// Method string (sms/email) recorded on the row, if loaded. public readonly record struct OtpVerifyResult(bool Success, string Reason, string? Method = null); Path: redb-identity/src/redb.Identity.Core/Mfa/IWebAuthnChallengeStore.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/Mfa/IWebAuthnChallengeStore.cs ---- using System.Threading; using System.Threading.Tasks; namespace redb.Identity.Core.Mfa; /// /// MFA-3: server-side single-use marker for consumed WebAuthn challenges. /// /// Closes the replay window between challenge issuance and natural TTL expiry. The challenge /// itself is encrypted into the client-facing setup-token / mfa_state for convenience (no /// DB hit on issue), but completion of the ceremony writes a row here, and a second /// completion attempt with the same challenge fails fast with replay_detected. /// /// /// We persist only the SHA-256 hash of the challenge bytes — sufficient for equality on /// consume, no exposure of live challenges if the DB is leaked. Atomicity guaranteed by /// the calling transaction: WebAuthnMfaMethod.Complete*Async writes this row in the /// same TX as the credential persistence (registration) or sign-counter advance (assertion). /// /// public interface IWebAuthnChallengeStore { /// /// Atomically marks a challenge as consumed by the given user for the given operation. /// /// Returns on first consume. /// Returns if a row with the same hash already exists. /// /// /// Raw challenge bytes (32 random bytes per ceremony). /// Owner of the ceremony. /// register or assert. /// How long to keep the consumed marker before cleanup may delete it. Task ConsumeAsync( byte[] challenge, long userId, string operation, TimeSpan ttl, CancellationToken ct = default); } /// Result of . public enum WebAuthnConsumeResult { /// Challenge consumed for the first time — ceremony may proceed. Ok, /// Challenge has already been consumed — reject as replay. Replay, } Path: redb-identity/src/redb.Identity.Core/Mfa/PropsServerSideOtpStore.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/Mfa/PropsServerSideOtpStore.cs ---- using System; using System.Security.Cryptography; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Core; using redb.Core.Models.Entities; using redb.Identity.Core.Models; namespace redb.Identity.Core.Mfa; /// /// B3: PROPS-backed . Singleton; resolves /// through a fresh DI scope per operation (identical pattern to /// PropsSigningKeyStore / RedbXmlRepository) to avoid captive-scope-in-singleton. /// /// Codes are 6 ASCII digits generated via . Only the /// SHA-256 hex of the plaintext is persisted (); the /// plaintext is returned to the caller exactly once for channel delivery. /// /// /// Verify runs inside a redb transaction + LockForUpdateAsync on the OTP row so /// concurrent verify calls against the same jti serialize cleanly — the first /// successful call flips , subsequent calls see the flag /// under the lock and return with /// Reason = already_consumed. /// /// public sealed class PropsServerSideOtpStore : IServerSideOtpStore { private readonly IServiceScopeFactory _scopeFactory; private readonly ILogger _logger; private readonly TimeProvider _timeProvider; public PropsServerSideOtpStore( IServiceScopeFactory scopeFactory, ILogger logger, TimeProvider? timeProvider = null) { _scopeFactory = scopeFactory ?? throw new ArgumentNullException(nameof(scopeFactory)); _logger = logger ?? throw new ArgumentNullException(nameof(logger)); _timeProvider = timeProvider ?? TimeProvider.System; } /// public async Task IssueAsync( long userId, string method, string destinationMasked, TimeSpan ttl, CancellationToken ct = default) { if (userId <= 0) throw new ArgumentOutOfRangeException(nameof(userId)); ArgumentException.ThrowIfNullOrEmpty(method); if (ttl <= TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(ttl)); var jti = Guid.NewGuid(); var code = GenerateOtpCode(); var now = _timeProvider.GetUtcNow(); var expires = now + ttl; var hash = ComputeSha256Hex(code); await using var scope = _scopeFactory.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); var obj = new RedbObject(new MfaOtpProps { Jti = jti.ToString("N"), UserId = userId, Method = method, CodeHash = hash, DestinationMasked = destinationMasked ?? string.Empty, IssuedAt = now, ExpiresAt = expires, Consumed = false, Attempts = 0, }); obj.name = jti.ToString("N"); await redb.SaveAsync(obj).ConfigureAwait(false); return new OtpIssueResult(jti, code, destinationMasked ?? string.Empty, expires); } /// public async Task VerifyAndConsumeAsync( Guid jti, long userId, string code, CancellationToken ct = default) { if (jti == Guid.Empty) return new OtpVerifyResult(false, "not_found"); if (string.IsNullOrEmpty(code)) return new OtpVerifyResult(false, "bad_code"); await using var scope = _scopeFactory.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); var key = jti.ToString("N"); await using var tx = await redb.Context.BeginTransactionAsync().ConfigureAwait(false); var row = await redb.Query() .Where(o => o.Jti == key) .FirstOrDefaultAsync() .ConfigureAwait(false); if (row is null) { await tx.RollbackAsync().ConfigureAwait(false); return new OtpVerifyResult(false, "not_found"); } // Serialize concurrent verify attempts against the same row. if (row.key.HasValue) await redb.LockForUpdateAsync(row.key.Value).ConfigureAwait(false); var p = row.Props; if (p.UserId != userId) { p.Attempts++; try { await redb.SaveAsync(row).ConfigureAwait(false); await tx.CommitAsync().ConfigureAwait(false); } catch { await tx.RollbackAsync().ConfigureAwait(false); throw; } return new OtpVerifyResult(false, "user_mismatch", p.Method); } var now = _timeProvider.GetUtcNow(); if (p.Consumed) { await tx.CommitAsync().ConfigureAwait(false); return new OtpVerifyResult(false, "already_consumed", p.Method); } if (p.ExpiresAt < now) { await tx.CommitAsync().ConfigureAwait(false); return new OtpVerifyResult(false, "expired", p.Method); } var candidate = ComputeSha256Hex(code.Trim()); var ok = CryptographicOperations.FixedTimeEquals( Encoding.ASCII.GetBytes(candidate), Encoding.ASCII.GetBytes(p.CodeHash)); p.Attempts++; if (ok) { p.Consumed = true; } try { await redb.SaveAsync(row).ConfigureAwait(false); await tx.CommitAsync().ConfigureAwait(false); } catch { await tx.RollbackAsync().ConfigureAwait(false); throw; } return ok ? new OtpVerifyResult(true, "ok", p.Method) : new OtpVerifyResult(false, "bad_code", p.Method); } private static string GenerateOtpCode() { // 6-digit decimal code using rejection sampling to remove modulo bias. Span buf = stackalloc byte[4]; Span digits = stackalloc char[6]; for (var i = 0; i < 6; i++) { uint value; do { RandomNumberGenerator.Fill(buf); value = BitConverter.ToUInt32(buf); } while (value >= uint.MaxValue / 10 * 10); // drop the short last slice of the uint range digits[i] = (char)('0' + (int)(value % 10)); } return new string(digits); } private static string ComputeSha256Hex(string value) { var bytes = SHA256.HashData(Encoding.UTF8.GetBytes(value)); var sb = new StringBuilder(bytes.Length * 2); foreach (var b in bytes) sb.Append(b.ToString("x2")); return sb.ToString(); } } Path: redb-identity/src/redb.Identity.Core/Mfa/PropsWebAuthnChallengeStore.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/Mfa/PropsWebAuthnChallengeStore.cs ---- using System.Security.Cryptography; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Core; using redb.Core.Models.Entities; using redb.Core.Query; using redb.Identity.Core.Models; namespace redb.Identity.Core.Mfa; /// /// MFA-3: PROPS-backed mirroring /// . Singleton; resolves /// through a fresh DI scope per operation to avoid captive-scope-in-singleton. /// /// Anti-replay strategy: lookup-then-insert under transaction. The first /// with a given challenge writes a /// row; subsequent calls find the row and /// return . The lookup-then-insert is run in a /// transaction; if the underlying store were to allow concurrent inserts of the same /// hash, we'd still have last-writer-wins on the row but both completes would proceed — /// to make this race-tight, the calling code (e.g. WebAuthnMfaMethod.CompleteAssert) /// is expected to run inside its own outer transaction with LockForUpdateAsync on /// the user's row, so two concurrent ceremonies for the same user /// serialize on that lock before reaching here. Cross-user replay is ruled out by the /// UserId check in WebAuthnMfaMethod — if attacker submits user A's challenge /// against user B's account, the cross-check fails before we get here. /// /// public sealed class PropsWebAuthnChallengeStore : IWebAuthnChallengeStore { private readonly IServiceScopeFactory _scopeFactory; private readonly ILogger _logger; private readonly TimeProvider _timeProvider; public PropsWebAuthnChallengeStore( IServiceScopeFactory scopeFactory, ILogger logger, TimeProvider? timeProvider = null) { _scopeFactory = scopeFactory ?? throw new ArgumentNullException(nameof(scopeFactory)); _logger = logger ?? throw new ArgumentNullException(nameof(logger)); _timeProvider = timeProvider ?? TimeProvider.System; } /// public async Task ConsumeAsync( byte[] challenge, long userId, string operation, TimeSpan ttl, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(challenge); if (challenge.Length == 0) throw new ArgumentException("Challenge cannot be empty", nameof(challenge)); if (userId <= 0) throw new ArgumentOutOfRangeException(nameof(userId)); ArgumentException.ThrowIfNullOrEmpty(operation); if (ttl <= TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(ttl)); var hash = ComputeSha256Hex(challenge); var now = _timeProvider.GetUtcNow(); await using var scope = _scopeFactory.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); await using var tx = await redb.Context.BeginTransactionAsync().ConfigureAwait(false); var existing = await redb.Query() .Where(o => o.ChallengeHash == hash) .FirstOrDefaultAsync() .ConfigureAwait(false); if (existing is not null) { await tx.RollbackAsync().ConfigureAwait(false); _logger.LogWarning( "WebAuthn challenge replay detected: hash={Hash} userId={UserId} operation={Op}", hash, userId, operation); return WebAuthnConsumeResult.Replay; } var row = new RedbObject(new WebAuthnConsumedChallengeProps { ChallengeHash = hash, UserId = userId, Operation = operation, ConsumedAt = now, ExpiresAt = now + ttl, }); row.name = hash; await redb.SaveAsync(row).ConfigureAwait(false); await tx.CommitAsync().ConfigureAwait(false); return WebAuthnConsumeResult.Ok; } private static string ComputeSha256Hex(byte[] value) { var bytes = SHA256.HashData(value); var sb = new StringBuilder(bytes.Length * 2); foreach (var b in bytes) sb.Append(b.ToString("x2")); return sb.ToString(); } } Path: redb-identity/src/redb.Identity.Core/Models/AddressClaim.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/Models/AddressClaim.cs ---- namespace redb.Identity.Core.Models; /// /// OIDC structured address claim (§5.1.1). /// Stored as nested PROPS object inside . /// Serialized to JSON when emitted as the address claim. /// public class AddressClaim { /// Full street address (may include house number, street name, PO BOX, etc.). public string? StreetAddress { get; set; } /// City or locality. public string? Locality { get; set; } /// State, province, prefecture, or region. public string? Region { get; set; } /// Zip code or postal code. public string? PostalCode { get; set; } /// Country name or ISO 3166-1 alpha-2 code. public string? Country { get; set; } /// Full mailing address, formatted for display or use on a mailing label. public string? Formatted { get; set; } } Path: redb-identity/src/redb.Identity.Core/Models/ApplicationProps.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/Models/ApplicationProps.cs ---- using redb.Core.Attributes; namespace redb.Identity.Core.Models; /// /// PROPS Props for OAuth 2.0 / OpenID Connect client application. /// Base fields: name = display name, hash = concurrency token. /// [RedbScheme("identity.application")] public class ApplicationProps { /// /// OAuth client_id — unique per scheme, enforced by the database via [RedbUnique] /// (hash in _values._unique, partial unique index, all three providers). /// Point lookup: GetByUniqueAsync<ApplicationProps>(p => p.ClientId, id). /// V4-UNIQUE: replaced the [RedbIgnore] + _objects.value_string mirror /// (which SQL Server could not index); the mirror is no longer written — legacy rows /// are repaired by the boot backfill. /// [RedbUnique] public string? ClientId { get; set; } /// Hashed client_secret (confidential clients only). public string? ClientSecret { get; set; } /// "public" or "confidential". public string? ClientType { get; set; } /// "explicit", "implicit", or "external". public string? ConsentType { get; set; } /// "web" or "native". public string? ApplicationType { get; set; } /// Granted permissions: ["ept:token", "gt:authorization_code", "scp:openid"]. public string[]? Permissions { get; set; } /// Allowed redirect URIs (authorization_code flow). public string[]? RedirectUris { get; set; } /// Allowed post-logout redirect URIs. public string[]? PostLogoutRedirectUris { get; set; } /// /// N-4 (Session C): allowed password-reset landing URIs. The caller-supplied /// callerResetUrl on identity-password-forgot must exactly match one of /// these (string compare, no normalization). When null/empty, password recovery /// is disabled for this client. Acts as an open-redirect whitelist analogous to /// ; lives on the client (not OS-wide) so multi-tenant /// deployments can scope each BFF to its own reset page. /// public string[]? PasswordResetUris { get; set; } /// /// N-4 (Session C, sub-step N4-6): allowed e-mail-verification landing URIs. /// Mirrors for the verify-email flow — the /// callerVerifyUrl on identity-me-email-verify-send must exactly match /// one of these (string compare). When null/empty, e-mail verification is /// disabled for this client even when /// RedbIdentityOptions.EmailVerification.Enabled = true. /// public string[]? EmailVerifyUris { get; set; } /// /// N-4 (Session E, sub-step N4-7): allowed change-of-e-mail confirmation landing /// URIs. The callerConfirmUrl on identity-me-change-email-request must /// exactly match one of these (string compare). When null/empty, the strict /// change-of-e-mail flow is disabled for this client even when /// RedbIdentityOptions.ChangeEmail.Enabled = true. /// public string[]? ChangeEmailUris { get; set; } /// /// Optional OIDC Backchannel Logout endpoint (RFC: OIDC Back-Channel Logout 1.0). /// When set, on user logout the IdP POSTs a signed logout_token to this URL /// so the relying party can terminate its local session. Must be an absolute https URL /// in production. /// public string? BackchannelLogoutUri { get; set; } /// /// When true, the logout_token sent to /// will include the sid (session id) claim. RP can use it to terminate only the /// matching session instead of all sessions for the user. Mirrors the OIDC client metadata /// field backchannel_logout_session_required. /// public bool BackchannelLogoutSessionRequired { get; set; } /// Requirements: ["ft:pkce"]. public string[]? Requirements { get; set; } /// Localized display names: { "en": "My App", "de": "Meine App" }. public Dictionary? DisplayNames { get; set; } /// Extensible settings bag (OpenIddict Settings — string values). public Dictionary? Settings { get; set; } /// Extensible properties bag (OpenIddict Properties — JSON values stored as raw text). public Dictionary? Properties { get; set; } /// Serialized JSON Web Key Set (for client assertion). public string? JsonWebKeySet { get; set; } /// /// Z2 (RFC 7592): SHA-256 hex hash of the registration_access_token issued when /// the client was created via Dynamic Client Registration. null for clients created /// through the admin API. Consumed by ClientRegistrationManagementProcessor to /// authorize GET/PUT/DELETE /connect/register/{client_id}. /// public string? RegistrationAccessTokenHash { get; set; } /// /// RFC 9126 §5 — when true, the authorization server MUST reject any direct /// /connect/authorize request for this client that does not carry a valid /// request_uri (issued by /connect/par). Layered on top of the global /// RedbIdentityOptions.RequirePushedAuthorizationRequests flag so individual /// high-assurance clients (FAPI, financial APIs) can opt-in independently. /// public bool RequirePushedAuthorizationRequests { get; set; } /// /// Additional audiences attached to issued id_tokens as extra entries /// in the aud claim. The client's own client_id is always /// included by OpenIddict (matches OIDC core §2 default). When this array is /// non-empty, /// appends each entry as an additional aud value, allowing the same /// id_token to be consumed by federated downstream resource servers. /// public string[]? IdTokenAudiences { get; set; } /// /// Resource indicators attached to issued access_tokens as aud values /// (RFC 9068 §2.2), in addition to the Resources of the granted scopes. /// composes the final set; /// when neither source names a resource, the OP's own audience /// (RedbIdentityOptions.DefaultAccessTokenAudience) is used instead. /// public string[]? AccessTokenAudiences { get; set; } /// /// A.6: RFC 9101 (JAR) — JWT signing algorithm the client is expected to use /// when sending a signed authorization request as request / request_uri. /// Stored as an advisory hint today (no enforcement gate yet); reserved keys /// follow the JOSE registry: none, RS256, RS384, RS512, /// PS256, PS384, PS512, ES256, ES384, ES512, /// EdDSA. Server-side enforcement is queued for a follow-up /// (would need a ProcessAuthenticationContext handler that rejects when the /// inbound JWT's alg disagrees with the stored value). /// public string? RequestObjectSigningAlg { get; set; } /// /// OIDC Dynamic Client Registration 1.0 §2 request_uris: the addresses this client may pass as JAR /// request_uri. Matched exactly, whole value with query and fragment; the fragment is never fetched. /// With Jar.RequireRequestUriRegistration (default) a client without values cannot use request_uri. /// public string[]? RequestUris { get; set; } /// /// A.6: JWE algorithm for encrypting the request object (RFC 9101 §10.2). /// Advisory hint; same enforcement caveat as . /// public string? RequestObjectEncryptionAlg { get; set; } /// /// A.6: JWE encryption method for the request object (RFC 9101 §10.2). /// Advisory hint; same enforcement caveat as . /// public string? RequestObjectEncryptionEnc { get; set; } /// /// A.7: RFC 7591 §2 / RFC 7517 — client JWKS endpoint URL. When set and no inline /// is stored, the server fetches the key set from this address /// (guarded and cached, ClientKeys options) to verify the client's private_key_jwt /// assertions (RFC 7523) and its JAR request objects (RFC 9101). Mutually exclusive with the /// inline set: dynamic registration refuses both at once, and when both are stored the inline /// set is the only source. /// public string? JwksUri { get; set; } /// /// A.8: RFC 9449 (DPoP) — per-client opt-in to strict mode. When true, the /// token endpoint rejects access-token requests from this client that don't /// carry a valid DPoP proof header with invalid_dpop_proof. Server-wide /// still wins if it's true /// (it forces strict mode for every client). Default false (soft-mode — client /// may send a DPoP proof to upgrade to a sender-constrained access token). /// public bool RequireDpop { get; set; } /// /// A.10: skip the RP-initiated logout consent prompt for this application. /// When false (default), the user is shown a "Sign out of MyApp?" dialog /// before the session terminates; when true, the logout proceeds silently /// matching id_token_hint + post_logout_redirect_uri. /// public bool SkipLogoutConsent { get; set; } /// /// A.10: mark this application as a FIDO trusted relying party. When true, /// the WebAuthn assertion verification skips the extra "is this passkey /// from a trusted app?" check that we apply by default. Equivalent to /// WSO2 IS 7.x "Add as a FIDO trusted app". /// public bool IsFidoTrusted { get; set; } /// /// β: whitelist of group NAMES allowed to authenticate against this application. /// When null or empty (default) any authenticated user may use the app. When /// non-empty, /// rejects sign-in with access_denied unless the user is a member of at /// least one listed group. Independent of and OR'd against the per-scope /// RedbIdentityOptions.ScopeRequiredGroups server config — both gates /// must pass. /// /// Stored as group NAMES rather than ids so admin UI / operator can read it /// at a glance, matching the operator-mental-model that /// ScopeRequiredGroups already uses ("identity:manage" → "admins"). /// /// public string[]? AllowedGroups { get; set; } } Path: redb-identity/src/redb.Identity.Core/Models/AuthorizationProps.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/Models/AuthorizationProps.cs ---- using redb.Core.Attributes; namespace redb.Identity.Core.Models; /// /// PROPS Props for OAuth 2.0 authorization (grant / consent record). /// Base fields: key = userId (subject), date_create, date_complete = expiry. /// [RedbScheme("identity.authorization")] public class AuthorizationProps { /// FK → ApplicationProps object id. public long ApplicationObjectId { get; set; } /// "valid", "revoked", or "redeemed". public string? Status { get; set; } /// "permanent" or "ad-hoc". public string? Type { get; set; } /// Granted scopes: ["openid", "profile", "email"]. public string[]? Scopes { get; set; } /// Extensible properties bag. public Dictionary? Properties { get; set; } } Path: redb-identity/src/redb.Identity.Core/Models/ChangeEmailTokenProps.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/Models/ChangeEmailTokenProps.cs ---- using System; using redb.Core.Attributes; namespace redb.Identity.Core.Models; /// /// N-4 (Session E, sub-step N4-7): server-side material backing a single-use /// change-of-e-mail token. Carries both the requested and a /// snapshot of the user's e-mail at issue time () so the /// confirm step can detect a race where the address was modified through another path /// (admin update, /me/profile soft path, federation sync) between request and confirm. /// [RedbScheme("identity.change_email_token")] public class ChangeEmailTokenProps { /// Random per-issuance identifier. Travels on the confirm URL as ?jti=.... public string Jti { get; set; } = ""; /// Owner user id (joined to _users). Returned to the caller by verify. public long UserId { get; set; } /// /// Lower-cased copy of the address the user requested to switch to. Confirm /// writes this value into _users.email after passing the race-guards. /// public string NewEmail { get; set; } = ""; /// /// Lower-cased snapshot of the user's e-mail at issue time. Confirm rejects the /// token when _users.email != CurrentEmail — defends against the address /// being changed concurrently by another path (admin, federation, soft /me path). /// public string CurrentEmail { get; set; } = ""; /// /// sha256(pepper || tokenPlaintext), lowercase hex. Never store plaintext. /// Pepper is supplied by . /// public string TokenHash { get; set; } = ""; /// /// Id of the pepper was made with (). /// Null on rows written before 4.8.0: those are checked with the current pepper, then the previous ones. /// public string? PepperId { get; set; } /// Issue timestamp (UTC). public DateTimeOffset IssuedAt { get; set; } /// Absolute expiry — verify requests after this instant fail regardless of token. public DateTimeOffset ExpiresAt { get; set; } /// /// True once a successful verify has consumed the token, OR when the row was /// invalidated by a fresh request (see ChangeEmailOptions.InvalidatePreviousTokensOnRequest). /// public bool Consumed { get; set; } /// Count of verify attempts (success+fail). public int Attempts { get; set; } /// /// Caller-supplied landing URL captured at issue time (the page that will host the /// confirm form). Recorded for audit; whitelist enforcement happens at the issuing /// processor against ApplicationProps.ChangeEmailUris. /// public string CallerConfirmUrl { get; set; } = ""; } Path: redb-identity/src/redb.Identity.Core/Models/ClaimDefinitionProps.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/Models/ClaimDefinitionProps.cs ---- using redb.Core.Attributes; namespace redb.Identity.Core.Models; /// /// S2 — declarative claim schema. Defines a custom claim that may appear /// on with optional server-side /// validation (required / type / regex) and per-destination emit control. /// /// /// Three orthogonal mechanisms in the identity pipeline: /// /// Claim mappers () — translate /// user attributes / groups into emitted claims at token issuance time. /// UserProps.CustomClaims — per-user value storage; what a /// specific user actually has set. /// Claim definitions (this entity) — schema with required / /// type / pattern; validated at user create / update time. Optional /// auto-fills required claims that the /// caller omitted, so a fresh user can never end up below schema. /// /// /// /// /// Uniqueness: (, , ) /// is unique. A global definition for "external_user_id" is one row; an /// application-specific override for the same name is a separate row keyed /// by app id. /// /// [RedbScheme("identity.claim_definition")] public class ClaimDefinitionProps { /// /// Claim key as it appears in and in /// issued JWTs. Convention: namespaced with a colon prefix when the value /// is private (e.g. "redb:user_id", "myapp:tier"); bare for public OIDC /// extension claims. /// public string ClaimName { get; set; } = ""; /// Human-friendly label rendered next to the input on the user /// profile editor. Defaults to when null. public string? DisplayName { get; set; } /// Operator-facing description / help text rendered as a field /// hint on the user profile editor. public string? Description { get; set; } /// /// Value type — drives both the editor widget on the user profile UI and /// the server-side parse / validation. Allowed: "string" (default), /// "int", "long", "bool", "datetime", "url", "email". /// public string Type { get; set; } = "string"; /// /// When true, user create / update will be rejected with a 400 /// validation_error if the claim value is missing AND no /// is set. When false, the claim is optional — /// callers may omit it. /// public bool Required { get; set; } /// /// Default value applied when the caller omits a required claim. When /// the claim is optional and unset, no default is applied (the field /// simply stays absent from ). /// public string? DefaultValue { get; set; } /// /// Optional regex pattern. Applied to the value (string form) at user /// create / update; mismatches yield a 400 validation_error. Ignored for /// non-string types — those have type-specific parse instead. /// public string? ValidationPattern { get; set; } /// /// "global" — applies to every user. /// "application" — applies only when issuing a token for the specified /// application. Per-application definitions extend the global set /// additively. Defaults to "global". /// public string Scope { get; set; } = "global"; /// FK to the application (Object id) when = "application". Null for global. public long? ApplicationId { get; set; } /// /// When true (default), the claim is included on the issued id_token. /// Set false to keep the claim server-side / access_token only. /// public bool EmitOnIdToken { get; set; } = true; /// /// When true (default), the claim is included on the issued access_token. /// Set false to keep the claim id_token only (useful for short-lived /// id-token-only client-side decode scenarios). /// public bool EmitOnAccessToken { get; set; } = true; } Path: redb-identity/src/redb.Identity.Core/Models/ClaimMapperProps.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/Models/ClaimMapperProps.cs ---- using redb.Core.Attributes; namespace redb.Identity.Core.Models; /// /// H5 (v1.0 DoD §5): PROPS Props for a declarative claim-mapping rule emitted into OAuth/OIDC tokens. /// /// One rule produces one claim. A rule belongs to one of three scopes, expressed by /// parent_id on the underlying object: /// /// parent_id IS NULL — global rule, applied to every token. /// parent_id = ApplicationObjectId — per-application overlay rule, applied /// only to tokens issued for that client. /// parent_id = ClaimScopeObjectId — rule belongs to a reusable Client Scope /// (see ); applies to tokens issued for any Application /// that has the scope assigned (see ). /// /// /// /// Resolution model is similar to Keycloak Token Mappers (per-client + Client Scope mappers) /// and WSO2IS Claim Configuration (per-Service-Provider claim selection over a global Dialect). /// Per-rule destinations make application uniform across access_token, id_token /// and the userinfo endpoint. /// /// Base fields used: name = administrator-facing label (unique only within scope), /// parent_id = scope discriminator (see above). /// [RedbScheme("identity.claim_mapper")] public class ClaimMapperProps { /// /// Name of the claim emitted into the token (e.g. "department", "tenant_id"). /// MUST be a non-empty token-safe identifier — handlers reject empty / whitespace values /// at apply-time so tokens never contain a nameless claim. /// public string? ClaimType { get; set; } /// /// Source of the value. One of: /// /// UserProps — read from against the user's /// object. Supports nested dot-path /// (e.g. "GivenName", "Address.Country"). /// CustomClaim — read from dictionary; /// is the dictionary key. /// Constant — emit verbatim. Use for /// environment / audience tags. /// /// public string? SourceKind { get; set; } /// /// Path / key into the source. Dot-notation for UserProps, dictionary key for /// CustomClaim. Ignored for Constant. /// public string? SourcePath { get; set; } /// /// Value emitted when = Constant. Ignored otherwise. /// public string? ConstantValue { get; set; } /// /// Required OAuth scopes for this mapper to fire (subset semantics: ALL must be present /// in the requested scopes). Empty / null = no scope filter (mapper always runs). /// public string[]? RequiredScopes { get; set; } /// /// Token destinations for the emitted claim. Valid values per OpenIddict: /// access_token, id_token. Empty / null defaults to both. /// The userinfo endpoint independently re-emits all non-standard claims found in the /// principal (see ), /// so any mapper that targets id_token implicitly appears in userinfo as well. /// public string[]? Destinations { get; set; } /// /// When true, a missing / null source value causes token issuance to fail with /// invalid_request. When false (default), missing values cause silent skip. /// public bool Required { get; set; } /// /// Application order (ascending). When two mappers target the same , /// the LAST one wins (stable Last-Write semantics). Defaults to 0. /// public int Order { get; set; } /// /// When false, the mapper is loaded but skipped at apply-time. Allows soft-disable /// without DELETE for incident response. /// public bool Enabled { get; set; } = true; /// Free-form admin description. public string? Description { get; set; } } Path: redb-identity/src/redb.Identity.Core/Models/ClaimScopeAssignmentProps.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/Models/ClaimScopeAssignmentProps.cs ---- using redb.Core.Attributes; namespace redb.Identity.Core.Models; /// /// H5 (v1.0 DoD §5): Many-to-many link between an Application and a . /// /// Stored as a flat object (no tree relationship) so that adding / removing an assignment /// is a single atomic write that does not perturb the application or scope objects. /// Enforces uniqueness on (ApplicationId, ScopeId) through application-level check /// (no compound partial index — uniqueness is rare-write, frequent-read). /// /// Base fields used: key = ApplicationObjectId for fast indexed lookup of all /// assignments for an application. /// [RedbScheme("identity.claim_scope_assignment")] public class ClaimScopeAssignmentProps { /// /// Application the scope is assigned to. Stored ALSO in _objects.key for indexed /// lookup; the PROPS field is the authoritative copy. /// public long ApplicationId { get; set; } /// Object id of the assigned . public long ScopeId { get; set; } /// UTC timestamp the assignment was created. public DateTimeOffset AssignedAt { get; set; } /// Optional id of the admin user who created the assignment (for audit). public long? AssignedBy { get; set; } } Path: redb-identity/src/redb.Identity.Core/Models/ClaimScopeProps.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/Models/ClaimScopeProps.cs ---- using redb.Core.Attributes; namespace redb.Identity.Core.Models; /// /// H5 (v1.0 DoD §5): Reusable named bundle of rules. /// /// Conceptually equivalent to Keycloak's Client Scope: an admin defines a scope /// once (e.g. "tenant_metadata") with a set of claim mappers attached via /// parent_id, then assigns the scope to one or more applications via /// . A token issued for an application gets /// claims from: global mappers ∪ application-overlay mappers ∪ assigned-scopes mappers. /// /// Base fields used: name = display name; the unique identifier lives in /// under [RedbUnique]. /// [RedbScheme("identity.claim_scope")] public class ClaimScopeProps { /// /// Unique scope identifier (slug) — unique per scheme via [RedbUnique] on all /// three providers. V4-UNIQUE: replaced the [RedbIgnore] + value_string /// mirror, which was never actually backed by an index (the doc used to promise one /// that did not exist); duplicates were possible until this attribute. /// [RedbUnique] public string? ScopeName { get; set; } /// Free-form admin description. public string? Description { get; set; } /// /// When false, all assignments referencing this scope are inert — mappers under it /// are not applied. Allows soft-disable for incident response without unassigning. /// public bool Enabled { get; set; } = true; } Path: redb-identity/src/redb.Identity.Core/Models/DpopConsumedJtiProps.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/Models/DpopConsumedJtiProps.cs ---- using redb.Core.Attributes; namespace redb.Identity.Core.Models; /// /// Z4 (RFC 9449 §11.1): persisted marker for a consumed DPoP proof jti. /// Used by the redb replay-store backend to provide cluster-safe replay /// detection when in-process Memory store is insufficient. /// /// The composite primary lookup key is (Jkt, Jti) — the jkt scoping prevents /// distinct clients with colliding (cryptographically improbable but possible) jti /// values from being treated as replays of each other. Cleanup runs from /// timer://identity-dpop-replay-cleanup when is past. /// /// [RedbScheme("identity.dpop_consumed_jti")] public class DpopConsumedJtiProps { /// JWK SHA-256 thumbprint (RFC 7638) of the proof's public key, base64url. public string Jkt { get; set; } = ""; /// The jti claim from the DPoP proof JWT. public string Jti { get; set; } = ""; /// When the proof was consumed (UTC). public DateTimeOffset ConsumedAt { get; set; } /// Absolute expiry — eligible for cleanup when past. public DateTimeOffset ExpiresAt { get; set; } } Path: redb-identity/src/redb.Identity.Core/Models/EmailVerificationTokenProps.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/Models/EmailVerificationTokenProps.cs ---- using System; using redb.Core.Attributes; namespace redb.Identity.Core.Models; /// /// N-4 (Session C, sub-step N4-6): server-side material backing a single-use /// e-mail-verification token. Mirror of with one /// extra field — — that binds the token to a specific e-mail value /// captured at issue time. Confirm only flips UserProps.EmailVerified = true when /// the user's current e-mail still matches this snapshot (defends against the /// double-change race where a token issued for value A is consumed after the user has /// already pivoted to value B). /// [RedbScheme("identity.email_verification_token")] public class EmailVerificationTokenProps { /// Random per-issuance identifier. Travels on the verify URL as ?jti=.... public string Jti { get; set; } = ""; /// Owner user id (joined to _users). Returned to the caller by verify. public long UserId { get; set; } /// /// Lower-cased snapshot of the user's e-mail at issue time. Confirm rejects the token /// when _users.email != Email at consumption — this prevents a stale link from /// vouching for a new address the user has since adopted. /// public string Email { get; set; } = ""; /// /// sha256(pepper || tokenPlaintext), lowercase hex. Never store plaintext. /// Pepper is supplied by . /// public string TokenHash { get; set; } = ""; /// /// Id of the pepper was made with (). /// Null on rows written before 4.8.0: those are checked with the current pepper, then the previous ones. /// public string? PepperId { get; set; } /// Issue timestamp (UTC). public DateTimeOffset IssuedAt { get; set; } /// Absolute expiry — verify requests after this instant fail regardless of token. public DateTimeOffset ExpiresAt { get; set; } /// /// True once a successful verify has consumed the token. Mutated under LockForUpdate /// to enforce single-use semantics even under concurrent verify attempts. /// public bool Consumed { get; set; } /// /// Count of verify attempts (success+fail). Used by diagnostics and the cleanup route. /// public int Attempts { get; set; } /// /// The caller-supplied landing URL captured at issue time (the page that will host /// the verify-confirmation, e.g. https://app.example.com/verify-email). /// Recorded for audit; whitelist enforcement happens at issue time against /// ApplicationProps.EmailVerifyUris. /// public string CallerVerifyUrl { get; set; } = ""; } Path: redb-identity/src/redb.Identity.Core/Models/ExternalIdentity.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/Models/ExternalIdentity.cs ---- namespace redb.Identity.Core.Models; /// /// Federation identity linking a local user to an external provider (OIDC, LDAP, SAML). /// Stored as nested PROPS object inside dictionary. /// public class ExternalIdentity { /// Subject identifier in the external system (OIDC sub, LDAP DN, SAML NameID). public string? Sub { get; set; } /// When this identity was linked to the local user. public DateTimeOffset LinkedAt { get; set; } } Path: redb-identity/src/redb.Identity.Core/Models/FederatedIdentityProps.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/Models/FederatedIdentityProps.cs ---- using redb.Core.Attributes; namespace redb.Identity.Core.Models; /// /// H8 (v1.0 DoD §4): one federated identity link between a local user and an external IdP. /// One row per (user, provider) tuple. Stored in PROPS with: /// /// RedbObject.key = userId — fast filter for "all my federations". /// = "{providerId}:{externalSub}" — unique per scheme /// via [RedbUnique] (V4-UNIQUE), enables the O(1) reverse lookup at federated /// callback time. Historical note: the doc used to claim a partial unique index on /// value_string that no code ever created — duplicates were possible until F2; /// value_string is a transition mirror now. /// /// /// Replaces the legacy dictionary which only /// supported a single reverse-lookup key per user (the UserProps.value_string was /// overwritten by the most-recently-linked provider, breaking lookup for older links). /// is kept as a denormalized read-model mirror /// for backwards compatibility with code paths that already consumed it. /// /// [RedbScheme("identity.federated_identity")] public class FederatedIdentityProps { /// Provider id (e.g. google, azure-ad, github). Lowercase. public string ProviderId { get; set; } = string.Empty; /// External subject (the IdP's stable user identifier, e.g. sub for OIDC). public string ExternalSub { get; set; } = string.Empty; /// Email reported by the IdP at the time of the most recent login (may be null). public string? ExternalEmail { get; set; } /// Display name reported by the IdP at the time of the most recent login. public string? ExternalDisplayName { get; set; } /// UTC timestamp when the link was first established. public DateTimeOffset LinkedAt { get; set; } /// UTC timestamp of the last successful federated login through this link. public DateTimeOffset? LastLoginAt { get; set; } /// /// Reverse-lookup key "{ProviderId}:{ExternalSub}" — unique per scheme via /// [RedbUnique] on all three providers. Composed ONLY through /// so the writer and every reader agree on the format. /// Nullable on purpose: a pre-V4 row has no key until the transition backfill /// repairs it (NULL never participates in uniqueness). /// [RedbUnique] public string? LinkKey { get; set; } /// The one place the composite key format lives. public static string MakeLinkKey(string providerId, string externalSub) => $"{providerId}:{externalSub}"; } Path: redb-identity/src/redb.Identity.Core/Models/FederationProviderProps.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/Models/FederationProviderProps.cs ---- using redb.Core.Attributes; using redb.Identity.Contracts.Configuration; namespace redb.Identity.Core.Models; /// /// H8 (v1.0 DoD §4 gap (e)): PROPS-stored configuration for a single federated authentication /// provider. Mirrors /// loaded from appsettings.json, but allows runtime CRUD via the admin API /// (/api/v1/identity/federation-providers). /// /// Storage: /// /// — lowercase, unique per scheme via [RedbUnique] /// (V4-UNIQUE). Historical note: the doc used to claim a partial unique index on /// value_string that no code ever created — duplicates were possible until F2; /// value_string is a transition mirror now. /// is stored encrypted via DataProtection /// (identity.federation-provider-secret purpose) — admin API never returns the /// plaintext, only metadata (`HasSecret: bool`). /// /// /// [RedbScheme("identity.federation_provider")] public class FederationProviderProps { /// /// Provider id (slug), e.g. google — lowercase (the processor normalises), /// unique per scheme via [RedbUnique]. V4-UNIQUE: was a [RedbIgnore] /// phantom mirrored to value_string; the mirror is transition-only now. /// [RedbUnique] public string ProviderId { get; set; } = string.Empty; /// Discriminates wire protocol so the registry can pick the right /// factory. /// One of: oidc (generic OIDC discovery), github (OAuth2 + email API), /// future custom slugs (apple, vk, ...). /// public string Kind { get; set; } = "oidc"; /// Display name shown on the login page button. public string DisplayName { get; set; } = string.Empty; /// OIDC issuer / authority URI. Required for Kind=oidc; used as /// API base for non-OIDC providers (e.g. https://api.github.com). public string? Authority { get; set; } /// OAuth2 client_id. public string ClientId { get; set; } = string.Empty; /// OAuth2 client_secret, ALWAYS encrypted at rest via /// . public string? EncryptedClientSecret { get; set; } /// Scopes requested at challenge time. Default: ["openid","profile","email"] /// for OIDC; provider-specific defaults for non-OIDC kinds. public string[] Scopes { get; set; } = ["openid", "profile", "email"]; /// Create a local user on first federated login. Default: true. public bool AutoProvision { get; set; } = true; /// Whether this provider is available for end-user login. Allows soft-disable /// without deleting the PROPS row (preserves linked accounts). public bool Enabled { get; set; } = true; /// Display order on login page. Lower = shown first. public int Priority { get; set; } = 100; /// Optional claim mappings: external claim type → internal claim type. /// Note: the H5 system is the recommended way to do /// claim transformations; this is kept for back-compat with the existing /// /// field. public Dictionary? ClaimMappings { get; set; } } Path: redb-identity/src/redb.Identity.Core/Models/GroupMemberProps.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/Models/GroupMemberProps.cs ---- using redb.Core.Attributes; namespace redb.Identity.Core.Models; /// /// Flat membership link: key = userId, parent_id = groupId. /// Role discriminates permissions within the group. /// [RedbScheme("identity.group_member")] public class GroupMemberProps { /// "owner" | "admin" | "member" | "viewer" public string? Role { get; set; } /// When the user joined the group. public DateTimeOffset? JoinedAt { get; set; } /// Optional TTL-based membership expiry. public DateTimeOffset? ExpiresAt { get; set; } } Path: redb-identity/src/redb.Identity.Core/Models/GroupProps.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/Models/GroupProps.cs ---- using redb.Core.Attributes; namespace redb.Identity.Core.Models; /// /// PROPS entity for organizational groups with tree hierarchy. /// Base fields used: name = display name, parent_id = parent group (tree), note = optional notes. /// GroupType discriminates: "organization", "department", "team", "role". /// [RedbScheme("identity.group")] public class GroupProps { /// Group description. public string? Description { get; set; } /// "organization" | "department" | "team" | "role" public string? GroupType { get; set; } /// External identifier provided by SCIM clients (IdP-assigned). public string? ExternalId { get; set; } } Path: redb-identity/src/redb.Identity.Core/Models/GroupRoleAssignmentProps.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/Models/GroupRoleAssignmentProps.cs ---- using redb.Core.Attributes; namespace redb.Identity.Core.Models; /// /// B.3 — group → role assignment. Every member of the group inherits the /// role at token-issuance time; tree ancestors of the group don't /// (assignments are NOT walked up the group hierarchy on purpose — the /// group is the assignment scope, not the subtree). /// /// /// Stored shape: parent_id = role's _objects.id, value_long = /// group id, key = group id. Same uniqueness guarantees as /// . /// /// [RedbScheme("identity.group_role_assignment")] public class GroupRoleAssignmentProps { public DateTimeOffset AssignedAt { get; set; } = DateTimeOffset.UtcNow; /// Optional — id of the operator who assigned the role. public long? AssignedByUserId { get; set; } } Path: redb-identity/src/redb.Identity.Core/Models/IdempotencyRecordProps.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/Models/IdempotencyRecordProps.cs ---- using redb.Core.Attributes; namespace redb.Identity.Core.Models; /// /// E2 — PROPS record for cached responses of Idempotency-Key-bearing requests. /// /// Lookup is keyed by the indexed name column (composite /// idem:{scope}:{operation}:{caller}:{key}). The TTL is the standard /// date_complete field: the cache ignores a record past it, and /// deletes such records on its timer /// (). /// /// [RedbScheme("identity.idempotency_record")] public class IdempotencyRecordProps { /// HTTP method of the original request, e.g. POST / PUT. Audit-only. public string? Method { get; set; } /// /// Logical scope this record belongs to (route id of the direct-vm route that produced /// the response, e.g. identity-manage-apps). Used in the composite name. /// public string? Scope { get; set; } /// /// Operation header value of the original request, e.g. create / update. /// Distinguishes different operations under the same scope so two unrelated calls that /// happen to share an Idempotency-Key never alias each other. /// public string? Operation { get; set; } /// /// Sub-claim of the caller (or "anon" when no authenticated principal is on the /// outer exchange). Idempotency is per-caller by design: different callers using the /// same key produce independent records, so a client cannot be served someone else's /// cached response. /// public string? CallerSubject { get; set; } /// The verbatim Idempotency-Key header value (defensive equality check). public string? IdempotencyKey { get; set; } /// HTTP status code captured for replay (e.g. 200, 201, 204). public int StatusCode { get; set; } /// /// JSON-serialized response body captured at completion. May be null when the /// original response had no body (e.g. 204 No Content). Stored verbatim — replay /// deserializes it back to a so the HTTP /// serializer round-trips an identical wire payload. Always null when is set. /// public string? ResponseBody { get; set; } /// /// The answer carried a one-time secret (a member marked [OneTimeSecret] in redb.Identity.Contracts), so /// it was not stored. A replay does not run the operation again and answers that the secret is not shown again. /// public bool SecretWithheld { get; set; } } Path: redb-identity/src/redb.Identity.Core/Models/IdentitySystemFlagProps.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/Models/IdentitySystemFlagProps.cs ---- using redb.Core.Attributes; namespace redb.Identity.Core.Models; /// /// B1 — System-wide one-shot flag stored as a bare RedbObject<IdentitySystemFlagProps> /// whose data lives entirely in the root _objects table — no PROPS row is written. /// /// All payload fields use built-in base columns: /// /// name = flag identifier (e.g. "bootstrap_completed"), mirrored into /// value_unique — UNIQUE per scheme via the core index (V4-UNIQUE). /// value_bool = set / unset state. /// value_datetime = when the flag was set. /// value_string = optional context payload (e.g. client_id of the bootstrapped app). /// note = optional human-readable comment. /// date_create + owner_id = audit, free. /// /// /// /// The Props body is intentionally empty: this class exists only so a typed /// Query<IdentitySystemFlagProps>() binds to a known scheme. Bootstrap races /// are closed by the core's ValueUnique per-scheme unique index (V4-UNIQUE, /// first-wins: the loser catches RedbUniqueViolationException and /// treats it as "already completed"); the pre-V4 artificial (scheme_id, _name) /// index from is being retired. /// /// [RedbScheme("identity.system_flag")] public sealed class IdentitySystemFlagProps { // intentionally empty — see class XML doc. } Path: redb-identity/src/redb.Identity.Core/Models/MfaArchivedRecoveryCodeBatch.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/Models/MfaArchivedRecoveryCodeBatch.cs ---- namespace redb.Identity.Core.Models; /// /// A snapshot of recovery-code hashes that were active before being retired /// (for example because MFA was disabled or because the user regenerated the set). /// /// Stored append-only on . The hashes here /// are NOT consulted by MfaService.VerifyRecoveryCodeAsync and cannot be used /// to log in — keeping them is purely audit/forensic so that an admin can answer /// «which codes were active for this user when MFA was disabled at ArchivedAt?» /// without weakening the security promise that Disable revokes the codes. /// /// B9 / BUG-8. /// public sealed class MfaArchivedRecoveryCodeBatch { /// UTC timestamp at which the batch was retired. public DateTimeOffset ArchivedAt { get; set; } /// /// Reason the batch was retired ("disable", "regenerate", etc.). Free-form short tag, /// not surfaced to end users. /// public string? Reason { get; set; } /// The hashed codes (same wire format as ). public List HashedCodes { get; set; } = new(); } Path: redb-identity/src/redb.Identity.Core/Models/MfaChallengeResult.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/Models/MfaChallengeResult.cs ---- namespace redb.Identity.Core.Models; /// /// Result of . /// On success: returns the new encrypted state (with embedded OTP) and masked destination for UI. /// On failure: returns error code (e.g. "rate_limited", "delivery_failed", "method_not_configured"). /// public sealed class MfaChallengeResult { public bool Success { get; init; } /// New encrypted MFA state to use for the verify step. Null on failure. public string? MfaState { get; init; } /// Masked destination for UI (e.g. "+7***1234"). Null on failure. public string? MaskedDestination { get; init; } /// Method that issued the challenge ("sms" or "email"). Null on failure. public string? Method { get; init; } /// Seconds until next challenge can be requested (rate limit). public int? RetryAfterSeconds { get; init; } /// Error code on failure: "rate_limited", "delivery_failed", "method_not_configured", "no_channel". public string? Error { get; init; } public static MfaChallengeResult Failed(string error, int? retryAfter = null) => new() { Success = false, Error = error, RetryAfterSeconds = retryAfter }; public static MfaChallengeResult Ok(string method, string mfaState, string maskedDestination) => new() { Success = true, Method = method, MfaState = mfaState, MaskedDestination = maskedDestination }; } Path: redb-identity/src/redb.Identity.Core/Models/MfaOtpProps.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/Models/MfaOtpProps.cs ---- using redb.Core.Attributes; namespace redb.Identity.Core.Models; /// /// B3: server-side OTP material for SMS / Email MFA methods. /// /// The plaintext OTP lives only in memory between generation and delivery; what we /// persist is the SHA-256 hash of the plaintext (so a database leak does not disclose /// live codes). is a per-issuance random identifier; the client-side /// state (see ) carries it instead of the plaintext code, so the /// code never appears in URLs / HTTP logs / referer headers. /// /// /// Consumption is single-use: flips to true atomically under /// LockForUpdate during verify, and subsequent attempts against the same /// are rejected regardless of code correctness. Expired /// ( < now) or consumed rows are soft-deleted by the /// timer://identity-mfa-otp-cleanup route. /// /// [RedbScheme("identity.mfa_otp")] public class MfaOtpProps { /// Random per-issuance identifier. Matches . public string Jti { get; set; } = ""; /// Owner user id (joined to _users). public long UserId { get; set; } /// Delivery method that issued this OTP: sms or email. public string Method { get; set; } = ""; /// SHA-256 of the plaintext OTP, lowercase hex. Never store plaintext. public string CodeHash { get; set; } = ""; /// Masked destination for UI display (e.g. +7***1234, u***@example.com). public string DestinationMasked { get; set; } = ""; /// Issue timestamp (UTC). public DateTimeOffset IssuedAt { get; set; } /// Absolute expiry — verify requests after this instant fail regardless of code. public DateTimeOffset ExpiresAt { get; set; } /// /// True once a successful verify has consumed the code. Mutated under LockForUpdate /// to enforce single-use semantics even under concurrent verify attempts. /// public bool Consumed { get; set; } /// /// Count of verify attempts (success+fail). Used by the cleanup route to highlight abuse /// and by diagnostics; not directly consulted for rate-limiting (that lives on /// MfaProps.OtpAttemptsSinceLastSent). /// public int Attempts { get; set; } } Path: redb-identity/src/redb.Identity.Core/Models/MfaProps.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/Models/MfaProps.cs ---- using redb.Core.Attributes; namespace redb.Identity.Core.Models; /// /// PROPS entity storing MFA configuration and secrets for a user. /// Key = userId (_users._id). Separate from UserProps: different concern (security vs profile), /// loaded only during login + MFA setup (not on every request). /// [RedbScheme("identity.mfa")] public class MfaProps { /// /// The owning user's _users._id — unique per scheme via [RedbUnique] /// (V4-UNIQUE: replaces the artificial UX_identity_mfa_user_id index /// on _objects._key). Written alongside RedbObject.key in /// MfaService.LoadOrCreateMfaPropsAsync — the single creation site; key /// stays for the existing Key == queries. Nullable so a pre-V4 row stays outside /// the index until the transition backfill copies the key in. /// [RedbUnique] public long? UserId { get; set; } /// Whether MFA is globally enabled for this user. public bool Enabled { get; set; } /// Default MFA method ID ("totp"). Used when multiple methods available. public string? DefaultMethod { get; set; } /// /// TOTP shared secret, encrypted at rest via . /// Null if TOTP not configured. /// public string? TotpSecret { get; set; } /// Whether TOTP has been confirmed (user entered first valid code after setup). public bool TotpConfirmed { get; set; } /// /// SHA256-hashed recovery codes. Each code is one-time use. /// Null until MFA is first confirmed. /// public List? RecoveryCodes { get; set; } /// /// Id of the pepper were hashed with /// (); one id per set, since a set is always issued /// whole. Null on sets issued before 4.8.0: those are checked with the current pepper, then the previous ones. /// The hash format itself is unchanged, so an earlier version still verifies the codes with the same pepper. /// public string? RecoveryCodesPepperId { get; set; } /// /// Archive of recovery-code batches that were retired (e.g. when MFA was disabled or /// regenerated). Holding the previous hashes lets an admin audit /// «which codes were active before the wipe» without making them usable for login — /// they are NEVER consulted by VerifyRecoveryCodeAsync. Append-only; /// pruning policy belongs to a future admin-tools sprint. Null on rows that have never /// been archived (B9 / BUG-8). /// public List? ArchivedRecoveryCodes { get; set; } /// Consecutive failed MFA verification attempts (for lockout). public int FailedAttempts { get; set; } /// Account locked until this time after too many failed attempts. Null if not locked. public DateTimeOffset? LockedUntil { get; set; } /// Timestamp of last successful MFA verification. public DateTimeOffset? LastVerifiedAt { get; set; } /// /// Last accepted TOTP time-step (Unix-seconds / 30) — RFC 6238 §5.2 replay protection. /// A login attempt with a step ≤ this value is rejected even if the 6-digit code is /// otherwise valid within the verification window. Null until the first successful /// TOTP verify (legacy rows). /// public long? LastTotpStep { get; set; } // ── SMS OTP ── /// Phone number for SMS OTP (E.164 format, e.g. "+79991234567"). Null if SMS not configured. public string? SmsPhone { get; set; } /// Whether SMS OTP has been confirmed (user entered first valid code). public bool SmsConfirmed { get; set; } // ── Email OTP ── /// Email address for OTP delivery (may differ from profile email). Null if not configured. public string? OtpEmail { get; set; } /// Whether Email OTP has been confirmed (user entered first valid code). public bool EmailConfirmed { get; set; } // ── WebAuthn (FIDO2) — skeleton only, full implementation deferred to MFA-3 ── /// /// WebAuthn credentials keyed by base64url credential ID. /// Skeleton field: shape only — no register/verify implementation yet. /// public Dictionary? WebAuthnCredentials { get; set; } // ── Rate limiting (SMS/Email send throttle) ── /// Timestamp of last OTP send (for cooldown enforcement). public DateTimeOffset? LastOtpSentAt { get; set; } /// /// Sliding-window record of recent OTP send timestamps (Unix seconds). /// On each send the list is pruned (entries older than 1 hour are dropped) and the /// current timestamp is appended; capped at 50 entries to bound storage. Used to enforce /// over a true rolling window /// (B6) instead of a calendar-hour bucket (which would let an attacker burst OTPs at the /// hour boundary). /// public List? RecentOtpTimestamps { get; set; } } Path: redb-identity/src/redb.Identity.Core/Models/MfaSetupResult.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/Models/MfaSetupResult.cs ---- namespace redb.Identity.Core.Models; /// /// Result of : contains data the user needs /// to complete MFA enrollment (secret, QR code URI, etc.). /// public sealed record MfaSetupResult { /// MFA method that generated this result (e.g. "totp"). public required string MethodId { get; init; } /// For TOTP: base32-encoded shared secret (shown once during setup). public string? SecretBase32 { get; init; } /// For TOTP: otpauth:// URI for QR code generation. public string? QrUri { get; init; } /// /// Opaque, encrypted setup token (B5). The client MUST submit it back to the confirm /// endpoint together with the first verification code so that the candidate secret/ /// destination can be applied atomically. Null only when carries an /// error (initiation failed before any token was issued). /// public string? SetupToken { get; init; } /// Extensibility for future methods (e.g. WebAuthn challenge). public Dictionary? Extra { get; init; } } Path: redb-identity/src/redb.Identity.Core/Models/MfaSetupTokenPayload.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/Models/MfaSetupTokenPayload.cs ---- namespace redb.Identity.Core.Models; /// /// Encrypted payload of an MFA setup token (B5). Bound to a single user + setup attempt /// via ; protected with DataProtection purpose /// "redb.identity.mfa-setup.v1" and capped by a 10-minute TTL. /// Not exposed publicly — round-trips between client and server as an opaque string. /// public sealed class MfaSetupTokenPayload { public long UserId { get; set; } public string MethodId { get; set; } = string.Empty; public string? EncryptedSecret { get; set; } public string? Destination { get; set; } public DateTimeOffset IssuedAt { get; set; } public Guid Jti { get; set; } /// /// MFA-3: 32 random challenge bytes for an in-progress WebAuthn registration ceremony. /// Echoed by the browser inside clientDataJSON.challenge; verified byte-equal at /// confirm time by Fido2NetLib. Once the registration completes, the SHA-256 hash of /// these bytes is written to so a captured /// setup-token cannot be replayed within the 10-min TTL. Null for non-WebAuthn flows. /// public byte[]? WebAuthnChallenge { get; set; } /// /// MFA-3: serialized CredentialCreateOptions JSON for the in-progress registration. /// Fido2NetLib's MakeNewCredentialAsync needs the *exact same* options instance back /// at confirm time — we round-trip it via the encrypted setup token so no server-side /// session state is needed. Null for non-WebAuthn flows. /// public string? WebAuthnOptionsJson { get; set; } } Path: redb-identity/src/redb.Identity.Core/Models/MfaState.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/Models/MfaState.cs ---- namespace redb.Identity.Core.Models; /// /// Temporary state between password verification and MFA code entry. /// Encrypted via with TTL enforcement. /// public sealed class MfaState { /// /// Replay-protection identifier. Unique per issued state token. /// Used by MfaVerify route's IdempotentConsumer to dedupe retransmits/replays /// (key = mfa-verify:{Jti}:{code}) — legitimate retry with a different code still passes through. /// public Guid Jti { get; set; } /// Authenticated user ID (password already verified). public long UserId { get; set; } /// Username for display on MFA page. public string? Username { get; set; } /// Available MFA methods for this user (e.g. ["totp"]). public string[] Methods { get; set; } = []; /// Original return URL from the authorization request. public string? ReturnUrl { get; set; } /// When this state was issued. Used for TTL enforcement. public DateTimeOffset? IssuedAt { get; set; } /// /// B3: server-side OTP identifier (see ). The actual /// plaintext code is NOT carried in the state blob — it lives in _objects under /// MfaOtpProps keyed by this jti, hashed. Null for TOTP. /// public Guid? OtpJti { get; set; } /// Masked destination for UI display (e.g. "+7***1234", "u***@example.com"). Safe to carry client-side. public string? OtpDestination { get; set; } /// Method that issued the OTP code: "sms" or "email". Null for TOTP states. public string? OtpMethod { get; set; } /// B3: absolute OTP expiry copied from for cheap pre-check. public DateTimeOffset? OtpExpiresAt { get; set; } /// /// The jti of the setup token this OTP was sent for, when it was sent to a candidate destination at /// enrollment. Confirm accepts the OTP only for that setup token, so a code sent for sign-in (to the /// confirmed destination) cannot confirm a new one. Null for sign-in challenges. /// public Guid? SetupJti { get; set; } // ── MFA-3: WebAuthn (FIDO2) challenge plumbing ── /// /// MFA-3: 32 random bytes issued at webauthn/{register|assert}/begin. The browser /// signs (or wraps in attestation) this exact value via navigator.credentials.create /// or navigator.credentials.get; on complete we verify byte-equality against /// the value the authenticator hashed into clientDataJSON.challenge. The challenge /// is also persisted (hashed) to at completion /// to enforce single-use semantics, so a captured token cannot be replayed within its /// 5-min TTL window. Null for non-WebAuthn flows. /// public byte[]? WebAuthnChallenge { get; set; } /// /// MFA-3: which WebAuthn ceremony this state belongs to: register (attestation, /// new credential being created) or assert (assertion, existing credential being /// used to authenticate). Mismatched flow at complete is rejected with /// flow_mismatch. Null for non-WebAuthn flows. /// public string? WebAuthnFlow { get; set; } /// /// MFA-3: serialized AssertionOptions JSON (or CredentialCreateOptions) issued /// at begin. / /// require the *exact same* options /// instance at completion time — round-tripping the JSON via the encrypted state token /// avoids server-side session storage while remaining tamper-proof (DataProtection signs /// the entire blob). Null for non-WebAuthn flows. /// public string? WebAuthnOptionsJson { get; set; } } Path: redb-identity/src/redb.Identity.Core/Models/MfaStatusResult.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/Models/MfaStatusResult.cs ---- namespace redb.Identity.Core.Models; /// /// MFA status for a user, returned by management API. /// public sealed class MfaStatusResult { public bool Enabled { get; set; } public string[] Methods { get; set; } = []; public int RecoveryCodesRemaining { get; set; } } Path: redb-identity/src/redb.Identity.Core/Models/PasswordHistoryProps.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/Models/PasswordHistoryProps.cs ---- using redb.Core.Attributes; namespace redb.Identity.Core.Models; /// /// H10 — per-user password history entry. Stores a verifier-hash (Argon2id by default, /// produced via the same that hashes /// live credentials) of a previously-used password so that /// recent passwords can be /// rejected on reuse. Plain-text passwords are NEVER persisted. /// /// Each row is owned by the user whose password it tracks; soft-delete cascades on user /// removal happen via the standard IdentityDeletionHelper flow (rows are soft- /// deleted alongside ). /// /// [RedbScheme("identity.password_history")] public class PasswordHistoryProps { /// Owner user id (foreign key to _users._id). public long UserId { get; set; } /// Argon2id (or legacy) verifier-hash of the previously-used password. public string HashedPassword { get; set; } = ""; /// UTC timestamp when this password became the user's active credential. public DateTimeOffset CreatedAt { get; set; } } Path: redb-identity/src/redb.Identity.Core/Models/PasswordResetTokenProps.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/Models/PasswordResetTokenProps.cs ---- using System; using redb.Core.Attributes; namespace redb.Identity.Core.Models; /// /// N-4 (Session C): server-side material backing a single-use password-reset token. /// /// The token plaintext (32 bytes of CSPRNG, base64url-encoded) is returned exactly once /// from IPasswordResetTokenStore.IssueAsync for delivery via the e-mail channel; /// what we persist is sha256(pepper || token) (lowercase hex) so a database leak /// does not disclose live reset links. is a per-issuance random /// identifier carried on the reset URL alongside the plaintext so verify can locate the /// row in O(1). /// /// /// Consumption is single-use: flips to true atomically /// under LockForUpdate during verify, and subsequent attempts against the same /// are rejected regardless of token correctness. Expired /// ( < now) or consumed rows are reaped by a periodic /// cleanup route (analogous to timer://identity-mfa-otp-cleanup). /// /// [RedbScheme("identity.password_reset_token")] public class PasswordResetTokenProps { /// Random per-issuance identifier. Travels on the reset URL as ?jti=.... public string Jti { get; set; } = ""; /// Owner user id (joined to _users). Returned to the caller by verify. public long UserId { get; set; } /// /// sha256(pepper || tokenPlaintext), lowercase hex. Never store plaintext. /// Pepper is supplied by . /// public string TokenHash { get; set; } = ""; /// /// Id of the pepper was made with (). /// Null on rows written before 4.8.0: those are checked with the current pepper, then the previous ones. /// public string? PepperId { get; set; } /// Issue timestamp (UTC). public DateTimeOffset IssuedAt { get; set; } /// Absolute expiry — verify requests after this instant fail regardless of token. public DateTimeOffset ExpiresAt { get; set; } /// /// True once a successful verify has consumed the token. Mutated under LockForUpdate /// to enforce single-use semantics even under concurrent verify attempts. /// public bool Consumed { get; set; } /// /// Count of verify attempts (success+fail). Used by diagnostics and the cleanup route to /// surface abuse; not consulted directly for rate-limiting (that lives on the HTTP facade). /// public int Attempts { get; set; } /// /// The caller-supplied reset URL captured at issue time (the page that will host the /// reset form, e.g. https://app.example.com/reset-password). Recorded for audit /// and to enable optional cross-checks at verify time; the open-redirect / whitelist /// check itself is enforced at the HTTP facade against the configured allow-list. /// public string CallerResetUrl { get; set; } = ""; } Path: redb-identity/src/redb.Identity.Core/Models/RevokedSidProps.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/Models/RevokedSidProps.cs ---- using redb.Core.Attributes; namespace redb.Identity.Core.Models; /// /// W6-0: One revocation entry in the backchannel revoked-sids list. /// /// At least one of / is set: /// /// only \u2014 single OIDC session was revoked. /// only \u2014 every session of that subject is revoked /// ("logout everywhere" / admin RevokeAll). /// Both \u2014 explicit single-session revoke that also carries the subject. /// /// /// /// Polling Relying Parties (RPs) call GET /api/internal/revoked-sids/since to fetch /// new entries; their local cache evicts past . The /// identity-revoked-sids-cleanup route soft-deletes rows past /// on a leader-only timer (.Cluster(true)). /// /// [RedbScheme("identity.revoked_sid")] public class RevokedSidProps { /// OIDC sid claim of the revoked session, or null when only is set. public string? Sid { get; set; } /// OIDC sub claim. Set for sub-only ("revoke all sessions of subject") entries. public string? Sub { get; set; } /// Optional OAuth client_id this revocation applies to. Null = applies to all clients. public string? ClientId { get; set; } /// UTC timestamp the entry was created. RPs use this as the polling cursor. public DateTimeOffset RevokedAt { get; set; } /// UTC timestamp after which this entry can be evicted (typically max cookie lifetime). public DateTimeOffset ExpiresAt { get; set; } } Path: redb-identity/src/redb.Identity.Core/Models/RoleProps.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/Models/RoleProps.cs ---- using redb.Core.Attributes; namespace redb.Identity.Core.Models; /// /// B.3 — first-class role entity. Roles exist independently of groups and /// claim mappers: they're a named bucket of access an operator can assign /// to a user (directly) or to a group (transitively to every member). /// /// /// Three layers in our token-issuance pipeline now compose orthogonally: /// /// Claim mappers () — declarative /// rules that translate user attributes / group membership into JWT /// claims at sign-in time. Mappers are the WIRING layer. /// Groups () — hierarchical user /// organisation; can carry per-membership role labels via /// . Groups are the MEMBERSHIP layer. /// Roles (this entity) — first-class named access buckets, /// audience-scoped (organization-wide OR per-application). Assigned /// directly to users via or /// transitively via groups via . /// Roles are the ACCESS layer that operators reason about. /// /// /// /// /// Token issuance walks the user's EFFECTIVE role set = direct user /// assignments ∪ transitive assignments via every group the user belongs to /// (including ancestor groups when claim mappers expand the tree). For /// audience='application' roles the set is FILTERED to the client_id of the /// token being issued — an "engineering-admin" role on app A doesn't leak /// into a token issued for app B. /// /// /// /// Uniqueness: (Name, Audience, ApplicationId) is unique. Built-in roles /// (system / everyone / admin / impersonator) are seeded with /// =true and can't be deleted via the admin API. /// /// [RedbScheme("identity.role")] public class RoleProps { /// /// Identifier-safe name; appears verbatim in the emitted roles /// claim. Convention: lowercase / hyphenated. /// public string Name { get; set; } = ""; /// Operator-facing label rendered in the admin UI. public string? DisplayName { get; set; } public string? Description { get; set; } /// /// "organization" — visible to every application in this Identity /// instance; emitted on every token for which the user holds the role. /// "application" — scoped to a single application; emitted only on /// tokens issued for the matching . /// public string Audience { get; set; } = "organization"; /// FK to the Application object id when = "application". Null for organization. public long? ApplicationId { get; set; } /// /// True for system-seeded roles (system / everyone / admin / impersonator) /// — the admin API rejects delete on these. Set on the seed insert only; /// operator-created roles always have IsSystem=false. /// public bool IsSystem { get; set; } } Path: redb-identity/src/redb.Identity.Core/Models/RoleScopeAssignmentProps.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/Models/RoleScopeAssignmentProps.cs ---- using redb.Core.Attributes; namespace redb.Identity.Core.Models; /// /// B.3 (permission picker) — role → OAuth scope binding. One row per /// (role, scope) pair. Drives the per-role permission set: every effective /// role's attached scopes are unioned into the principal scope set at /// token issuance, so a user inheriting role X automatically requests /// scope orders.read when their token is minted. /// /// /// Stored shape: parent_id = role's _objects.id (lets us list /// every scope of a role in a single indexed scan), value_long + /// key = scope's _objects.id. Same uniqueness pattern as /// UserRoleAssignmentProps: idempotent attach (server-side dedupe by /// (parent_id, key)) without a separate UNIQUE check. /// /// [RedbScheme("identity.role_scope_assignment")] public class RoleScopeAssignmentProps { public DateTimeOffset AttachedAt { get; set; } = DateTimeOffset.UtcNow; /// Optional — id of the operator who attached the scope. public long? AttachedByUserId { get; set; } } Path: redb-identity/src/redb.Identity.Core/Models/ScopeProps.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/Models/ScopeProps.cs ---- using redb.Core.Attributes; namespace redb.Identity.Core.Models; /// /// PROPS Props for OAuth 2.0 scope definition. /// Base fields: name = scope display name. /// [RedbScheme("identity.scope")] public class ScopeProps { /// /// Unique scope identifier (e.g. "openid", "profile", "api") — unique per scheme via /// [RedbUnique] (all three providers). Point lookup: /// GetByUniqueAsync<ScopeProps>(p => p.ScopeName, name). /// V4-UNIQUE: replaced the [RedbIgnore] + value_string mirror; the mirror /// is no longer written — legacy rows are repaired by the boot backfill. /// [RedbUnique] public string? ScopeName { get; set; } /// Human-readable description. public string? Description { get; set; } /// Resource servers this scope grants access to. public string[]? Resources { get; set; } /// Localized display names: { "en": "Profile", "de": "Profil" }. public Dictionary? DisplayNames { get; set; } /// Localized descriptions. public Dictionary? Descriptions { get; set; } /// Extensible properties bag. public Dictionary? Properties { get; set; } } Path: redb-identity/src/redb.Identity.Core/Models/SessionProps.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/Models/SessionProps.cs ---- using redb.Core.Attributes; namespace redb.Identity.Core.Models; /// /// PROPS entity tracking user login sessions. /// Key = userId (subject). Each record represents one login event. /// Revoking a session cascades to revoking all authorizations and tokens for that user. /// [RedbScheme("identity.session")] public class SessionProps { /// FK to the application (client) the user logged into. public long ApplicationObjectId { get; set; } /// /// The applications (object ids) that obtained tokens through this session at the authorization /// endpoint, in the order they first did. Back-channel logout for this session goes to exactly these /// relying parties, with this session's id as sid (OIDC Back-Channel Logout 1.0 §2.1: the OP /// notifies the RPs the End-User logged in to through the session being ended). Appended by /// ; null for a session no relying party has /// used yet. /// public long[]? ClientApplicationIds { get; set; } /// "active" or "revoked". public string? Status { get; set; } /// Whether session was established with MFA verification. public bool MfaVerified { get; set; } /// MFA method used (totp, recovery). Null if no MFA. public string? MfaMethod { get; set; } /// /// Client IP address captured from the authenticating request (redbHttp.RemoteAddress, /// sanitized through TrustedProxyResolverProcessor when the hop is whitelisted). /// Surfaced in GET /me/sessions so the user can recognize their devices. /// public string? IpAddress { get; set; } /// Raw User-Agent header captured at login time. May be null for non-HTTP transports. public string? UserAgent { get; set; } /// /// Human-friendly device label derived from (e.g. "Chrome 135 on Windows 10"), /// parsed at login time. Displayed in the self-service sessions list UI. /// public string? DeviceLabel { get; set; } /// /// S-track: last time this session was used. Updated on every activity that /// proves the session is still in use — refresh_token grant, cookie /// validation, /connect/userinfo call. Drives idle-timeout expiration: /// (now - LastAccessedAt) > RedbIdentityOptions.SessionIdleTimeout → /// auto-revoked. Mirrors industry pattern (Keycloak, Auth0, Okta). /// Null on legacy rows created before this field landed. /// public DateTimeOffset? LastAccessedAt { get; set; } /// /// S-track: label of the most recent activity that bumped /// — "refresh_token", "cookie", "userinfo", /// "introspect". Diagnostic only; the timeout calculation cares only about /// the timestamp. /// public string? LastAccessedBy { get; set; } } Path: redb-identity/src/redb.Identity.Core/Models/SigningKeyProps.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/Models/SigningKeyProps.cs ---- using redb.Core.Attributes; namespace redb.Identity.Core.Models; /// /// PROPS Props for persistent OpenIddict signing / encryption keys (A3). /// One row per key; the active key for signing new tokens is the row with /// = true and = "signing"; older keys remain in /// the JWKS (and in OpenIddict's credential list) until so that /// tokens signed by them continue to validate through the rotation-overlap window. /// /// is produced by IDataProtector.Protect over the raw PEM /// bytes with purpose redb.identity.signing-keys.v1. This reuses the /// RedbXmlRepository DataProtection key ring that is loaded earlier in the route /// lifecycle, which means the key ring MUST be seeded first /// (RedbXmlRepositoryInitListener runs before SigningKeyInitListener in /// InitRoute.main). /// /// [RedbScheme("identity.signing_key")] public class SigningKeyProps { /// Unique key id (URL-safe). public string Kid { get; set; } = ""; /// "signing" or "encryption". public string KeyKind { get; set; } = ""; /// JWS/JWE algorithm identifier (e.g. RS256, RSA-OAEP). public string Algorithm { get; set; } = ""; /// DataProtection-protected PEM-encoded private key (base64). public string EncryptedPem { get; set; } = ""; /// Earliest UTC time the key may be used to sign / encrypt. public DateTimeOffset NotBefore { get; set; } /// Latest UTC time the key may be used to validate / decrypt. Past this, drop from JWKS. public DateTimeOffset NotAfter { get; set; } /// /// True for the single current key used to sign / encrypt new tokens. Older keys remain /// = false but are still exposed in the JWKS / credentials list /// until . /// public bool IsActive { get; set; } } Path: redb-identity/src/redb.Identity.Core/Models/TokenProps.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/Models/TokenProps.cs ---- using redb.Core.Attributes; namespace redb.Identity.Core.Models; /// /// PROPS Props for OAuth 2.0 / OIDC token (access, refresh, id, authorization_code). /// Base fields: key = userId (subject), date_create, date_complete = expiry, date_begin = redemption. /// [RedbScheme("identity.token")] public class TokenProps { /// FK → ApplicationProps object id. public long ApplicationObjectId { get; set; } /// FK → AuthorizationProps object id. public long AuthorizationObjectId { get; set; } /// "valid", "revoked", "redeemed", or "inactive". public string? Status { get; set; } /// /// Token type as OpenIddict writes it. From OpenIddict 7 a URI-style identifier /// (urn:ietf:params:oauth:token-type:refresh_token, urn:openiddict:params:oauth:token-type:authorization_code, ...); /// rows written by OpenIddict 6 keep the short form (refresh_token, authorization_code, ...), /// which OpenIddictTokenManager.GetTypeAsync maps to the URI form on read. /// public string? Type { get; set; } /// /// Opaque reference id (for reference tokens) — unique per scheme via [RedbUnique] /// on all three providers; NULL (non-reference tokens) never participates. /// V4-UNIQUE note: this property was always stored, but the store wrote the id only into /// the value_string mirror, so _values could be empty for store-created /// tokens — the transition backfill repairs that. /// [RedbUnique] public string? ReferenceId { get; set; } /// /// Serialized token payload content. /// Stored in root _objects.note field (not PROPS) to avoid btree index size limits. /// [RedbIgnore] public string? Payload { get; set; } /// Extensible properties bag. public Dictionary? Properties { get; set; } /// /// Subject of the actor in a delegation token exchange (RFC 8693). /// Stored for audit/query — the full act claim chain is in the token payload. /// public string? ActorSubject { get; set; } } Path: redb-identity/src/redb.Identity.Core/Models/UserProps.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/Models/UserProps.cs ---- using redb.Core.Attributes; namespace redb.Identity.Core.Models; /// /// OIDC profile extension for a user stored in _users. /// Credentials (login, password), email, phone and status live in the relational /// _users table. This PROPS extension stores OIDC-specific profile claims. /// Linked via RedbObject.key = _users._id. /// [RedbScheme("identity.user")] public class UserProps { /// /// The owning user's _users._id — unique per scheme via [RedbUnique] /// (V4-UNIQUE: replaces the artificial UX_identity_user_ext_user_id /// index on _objects._key). Written alongside RedbObject.key at every /// creation site; key stays for the many Key == queries. Nullable so a /// pre-V4 row stays outside the index until the transition backfill copies the key in. /// [RedbUnique] public long? UserId { get; set; } // --- OIDC Standard Claims (profile scope) --- // // The full set OIDC Core §5.1 defines for `scope=profile`. The OIDF conformance suite // (oidcc-scope-profile / oidcc-scope-all) checks userinfo against exactly this list and warns // for every one the OP fails to return. They are plain PROPS fields — adding them needed no // migration and no schema deploy; the next request simply saw them. /// Given name (first name). OIDC: given_name. public string? GivenName { get; set; } /// Family name (last name). OIDC: family_name. public string? FamilyName { get; set; } /// Middle name. OIDC: middle_name. public string? MiddleName { get; set; } /// Casual name the user prefers to be called (e.g. "Mike" for Michael). OIDC: nickname. public string? Nickname { get; set; } /// Shorthand name the RP may use to identify the user in its UI. Defaults to the /// login when unset (emitted by IdentityPrincipalBuilder). OIDC: preferred_username. public string? PreferredUsername { get; set; } /// URL of the user's profile page. OIDC: profile. public string? Profile { get; set; } /// URL of the user's profile picture. OIDC: picture. public string? Picture { get; set; } /// URL of the user's web page or blog. OIDC: website. public string? Website { get; set; } /// Gender. OIDC: gender ("female" / "male" / other values are allowed). public string? Gender { get; set; } /// Birthday as ISO 8601 YYYY-MM-DD (year alone is allowed). OIDC: birthdate. public string? Birthdate { get; set; } /// IANA time-zone name, e.g. "Europe/Moscow". OIDC: zoneinfo. public string? ZoneInfo { get; set; } /// BCP 47 language tag, e.g. "ru-RU". OIDC: locale. public string? Locale { get; set; } /// When the profile was last changed. Emitted as the OIDC updated_at claim /// (a JSON number — seconds since the epoch). Falls back to the user's registration date. public DateTimeOffset? UpdatedAt { get; set; } // --- OIDC Standard Claims (email scope) --- /// Whether the email has been verified. OIDC: email_verified. public bool EmailVerified { get; set; } // --- OIDC Standard Claims (phone scope) --- /// Whether the phone number has been verified. OIDC: phone_number_verified. public bool PhoneNumberVerified { get; set; } // --- OIDC Standard Claims (address scope) --- /// Structured address claim (OIDC §5.1.1). Stored as nested PROPS object. public AddressClaim? Address { get; set; } // --- Custom claims --- /// Arbitrary key-value claims emitted into tokens. Keys become claim types, values become claim values. public Dictionary? CustomClaims { get; set; } // --- SCIM provisioning --- /// SCIM externalId (RFC 7643 §3.1) — identifier assigned by the provisioning client. NOT related to federation. public string? ScimExternalId { get; set; } // --- SCIM Enterprise User extension (RFC 7643 §4.3) --- // // What corporate provisioning (Okta / Entra ID / Workday) pushes on the first sync. Props, so // adding them costs no migration: an existing user simply has them null until someone writes one. /// RFC 7643 §4.3 — employeeNumber. public string? EmployeeNumber { get; set; } /// RFC 7643 §4.3 — costCenter. public string? CostCenter { get; set; } /// RFC 7643 §4.3 — organization. public string? Organization { get; set; } /// RFC 7643 §4.3 — division. public string? Division { get; set; } /// RFC 7643 §4.3 — department. public string? Department { get; set; } /// /// RFC 7643 §4.3 — manager.value: the _users._id of this user's manager, as a /// string because SCIM ids are strings on the wire. $ref and displayName are NOT /// stored: the spec marks displayName read-only (the provider resolves it) and $ref is derived /// from the id plus the request's base URL. Storing either would let them rot out of sync with /// the manager's actual record. /// public string? ManagerId { get; set; } // --- Federation linking (multi-provider) --- /// /// Federation identities keyed by provider ID (e.g. "google", "corp-ldap"). /// Stored natively in PROPS as separate rows (not JSON). /// Hot-path reverse lookup uses RedbObject.value_string = "{providerId}:{sub}". /// public Dictionary? ExternalIdentities { get; set; } // --- H10: password policy state --- /// /// UTC timestamp of the last password change for this user. Updated by every successful /// admin Create / admin Change / self-service Change / SCIM Create / SCIM PATCH path /// (see IdentityProcessorHelpers.RecordPasswordChangedAsync). When /// is greater than zero, login /// compares now - PasswordChangedAt against MaxAge and forces a change when /// expired. Null means the value was never recorded — treated as "not expired" for /// backward compatibility with users created before H10. /// public DateTimeOffset? PasswordChangedAt { get; set; } /// /// H8 (v1.0 DoD §4 gap (d)): true iff the user has set their own password through any /// of the password-change paths (admin SetPassword, self-service /// /me/password, SCIM PATCH, registration with explicit password). Federated /// auto-provisioning leaves this false even though _users.password_hash is filled /// with a random value (so the local row is internally consistent). Used by the /// MeFederatedIdentitiesProcessor "unlink last social" safeguard: a user whose /// only authentication factor is a federated link cannot remove that link without /// first setting a local password. /// public bool HasUserPassword { get; set; } } Path: redb-identity/src/redb.Identity.Core/Models/UserRoleAssignmentProps.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/Models/UserRoleAssignmentProps.cs ---- using redb.Core.Attributes; namespace redb.Identity.Core.Models; /// /// B.3 — direct user → role assignment. One row per (user, role) pair. /// /// /// Stored shape: parent_id points at the role's _objects.id (so we /// can fetch every member of a role with a single Query.WhereRedb on /// parent_id without joining); value_long mirrors the user id so the /// reverse query (every role of a user) also runs as a single indexed /// scan. The key field is also set to the user id, enabling a /// per-scheme unique index on (parent_id, key) to enforce idempotent /// assignment without a separate uniqueness check. /// /// [RedbScheme("identity.user_role_assignment")] public class UserRoleAssignmentProps { public DateTimeOffset AssignedAt { get; set; } = DateTimeOffset.UtcNow; /// Optional — id of the operator who assigned the role. public long? AssignedByUserId { get; set; } } Path: redb-identity/src/redb.Identity.Core/Models/WebAuthnConsumedChallengeProps.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/Models/WebAuthnConsumedChallengeProps.cs ---- using redb.Core.Attributes; namespace redb.Identity.Core.Models; /// /// MFA-3: server-side single-use marker for consumed WebAuthn challenges. /// /// The 32-byte challenge issued at register/begin or assert/begin is encrypted /// into the client-facing setup-token / mfa_state for convenience (no DB hit on issue), but /// completion of the ceremony writes a row here and rejects retries with the same challenge. /// This closes the replay window between issue and natural TTL expiry — without it, a captured /// `setup_token` containing a still-fresh challenge could be replayed within the 5-min TTL. /// /// /// We persist (SHA-256 hex of challenge bytes) — not the raw /// challenge — so a database leak does not expose live challenges to an attacker who would /// otherwise need a stolen DataProtector key to forge them. The hash is sufficient for /// equality-detection on consume. /// /// /// Atomicity: writes this row inside the same transaction as /// the credential persistence (registration) or sign-counter advance (assertion); a unique /// index on makes second-consume race-safe — duplicate insert /// fails fast with replay_detected. Cleanup runs via /// timer://identity-mfa-webauthn-challenge-cleanup once is past. /// /// [RedbScheme("identity.webauthn_consumed_challenge")] public class WebAuthnConsumedChallengeProps { /// SHA-256 hex (lowercase) of the raw challenge bytes. Indexed for replay detection. public string ChallengeHash { get; set; } = ""; /// Owner user id; cross-checked at consume time to reject cross-user replay. public long UserId { get; set; } /// Operation that consumed the challenge: register or assert. public string Operation { get; set; } = ""; /// When the consumed marker was written (UTC). Equal to ceremony-completion time. public DateTimeOffset ConsumedAt { get; set; } /// /// Absolute expiry of the original challenge — after this point the marker can be cleaned /// up because no fresh assertion can carry the same challenge (TTL on the encrypted token /// matches this). Cleanup processor checks ExpiresAt < now. /// public DateTimeOffset ExpiresAt { get; set; } } Path: redb-identity/src/redb.Identity.Core/Models/WebAuthnCredential.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/Models/WebAuthnCredential.cs ---- namespace redb.Identity.Core.Models; /// /// WebAuthn (FIDO2) credential descriptor stored per user in . /// One row per registered authenticator (Yubikey, TouchID, sync-passkey, …); multiple rows per /// user are normal and required (passkey-providers register one credential per device-cluster). /// /// All cryptographic verification is delegated to Fido2NetLib (Fido2.MakeAssertionAsync) — /// this DTO is just the persisted shape. Equality of is the credential's /// primary key; the COSE-encoded never changes, but /// does (see field doc) and is updated atomically with each successful /// assertion under LockForUpdateAsync so concurrent assertions cannot lose the counter /// advance (CTAP2 spec — counter rollback is treated as cloning evidence). /// /// public sealed class WebAuthnCredential { /// Raw credential ID bytes. Base64url-encoded by callers when used as a dictionary key. public byte[] CredentialId { get; set; } = []; /// COSE-encoded public key bytes. Immutable for the lifetime of the credential. public byte[] PublicKey { get; set; } = []; /// /// Authenticator-reported signature counter. Per CTAP2 §6.1.4 it MUST be monotonically /// non-decreasing across assertions; a decrease (or zero from a non-zero baseline) is /// treated as evidence the credential was cloned and the assertion is rejected. Some /// modern authenticators (TouchID, Windows Hello platform authenticator, sync-passkeys) /// always report 0 — for those stays 0 forever and the rollback /// check degenerates to "0 ≥ 0" (safe). /// public long SignCount { get; set; } /// User-friendly device label (e.g. "YubiKey 5 NFC", "iPhone Touch ID"). public string? DisplayName { get; set; } /// Authenticator AAGUID (FIDO2 attestation metadata; 16-byte GUID, base64url-encoded here). public string? Aaguid { get; set; } /// When the credential was registered. public DateTimeOffset RegisteredAt { get; set; } /// Last successful assertion timestamp. public DateTimeOffset? LastUsedAt { get; set; } /// /// Whether user-verification (PIN / biometric) was asserted at registration time /// (clientDataJSON.uv flag). MFA-3 invariant: if a credential was registered with UV, /// every subsequent assertion MUST also carry uv=true — downgrading from /// PIN/biometric-protected to mere-presence is treated as a downgrade attack and the /// assertion is rejected. NIST SP 800-63B AAL2-strict. /// public bool UserVerified { get; set; } /// /// FIDO2 backup-eligibility flag from the authenticator data (BE bit, byte[0] bit 3). /// True for sync-passkeys (iCloud Keychain, Google Password Manager, 1Password, …) /// which can be replicated across the user's device-cluster; false for platform-bound /// or single-device authenticators (Yubikey, single-Windows-device passkey). /// public bool BackupEligible { get; set; } /// /// FIDO2 current backup-state flag from the authenticator data (BS bit, byte[0] bit 4). /// True iff the credential is currently synced/backed-up; transitions to true once the /// user-cluster has at least one backup. Combined with this /// lets RPs warn "your passkey is not backed up — you may lose access if you lose this /// device". Updated on every assertion (Fido2NetLib re-emits the flag). /// public bool BackupState { get; set; } } Path: redb-identity/src/redb.Identity.Core/Models/WebhookSubscriptionProps.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/Models/WebhookSubscriptionProps.cs ---- using redb.Core.Attributes; namespace redb.Identity.Core.Models; /// /// W1 — outbound webhook subscription. One row per HTTP endpoint that /// receives identity events as POST bodies, signed with HMAC-SHA256. /// /// /// Delivery semantics: /// * Fire-and-forget from the originating mutation's perspective: /// WebhookDeliveryRouteConsumer picks events off a /// WireTap of the identity-events route and dispatches them /// async, so a slow webhook receiver never back-pressures the /// token endpoint or admin API. /// * Per-subscription exponential backoff with retry limit. Failures /// after retries are logged + audited as WebhookDeliveryFailed /// so operators can wire alerting without leaving the audit log. /// /// /// /// Filtering: /// * = "*" — receive every event. /// * Comma-separated list of CamelCase IDs from /// IdentityAuditEventIds (e.g. "UserCreated,UserDeleted"). /// * Prefix cat: matches by category instead — e.g. /// "cat:admin,cat:authentication" delivers every admin + auth event. /// /// /// /// Signing: /// * Body is canonical JSON of the IdentityEvent envelope. /// * Header X-RedbIdentity-Signature = sha256=<hex> of /// HMAC-SHA256(secret, body). GitHub-style — covers raw body /// bytes only, so receivers verify with the standard HMAC-SHA256 /// recipe without canonical-payload-recomposition pitfalls. /// * Header X-RedbIdentity-Timestamp = ISO-8601 UTC. /// * Header X-RedbIdentity-Delivery = per-attempt GUID /// (idempotency key the receiver can dedupe on). /// * Header X-RedbIdentity-EventType = canonical event id. /// Receivers verify by recomputing HMAC over timestamp + "." + body /// using the shared secret. Reject the signature window beyond ±5min to /// dampen replay; the timestamp + delivery id make replay detection /// trivial. /// /// [RedbScheme("identity.webhook_subscription")] public class WebhookSubscriptionProps { /// Operator-facing label rendered in the admin UI. public string? DisplayName { get; set; } public string? Description { get; set; } /// /// Absolute HTTP(S) URL the event is POSTed to. Validated at create /// time — wildcards and fragments are rejected per common-sense /// webhook security. /// public string Url { get; set; } = ""; /// /// Filter expression — "*" (everything), comma-separated event ids, /// or "cat:<category>" tokens (also comma-separable). Defaults /// to "*" so a new subscription works without a follow-up edit. /// public string EventTypeFilter { get; set; } = "*"; /// /// HMAC-SHA256 secret. Generated server-side on create (returned /// once in the response) and rotated through the secret-rotate /// endpoint. Receiver verifies signatures with this value. /// public string HmacSecret { get; set; } = ""; /// Master enable switch — disabled subscriptions are skipped. public bool Enabled { get; set; } = true; /// Per-attempt timeout in milliseconds. Default 5000. public int TimeoutMs { get; set; } = 5000; /// /// Max delivery attempts (including the first). Exponential backoff /// between retries: base * (2 ^ attempt). Default 3. /// public int MaxAttempts { get; set; } = 3; /// Backoff base in milliseconds. Default 500. public int RetryBackoffMs { get; set; } = 500; /// /// Extra HTTP headers attached to every delivery (e.g. an /// operator-managed shared auth header). Reserved redb-internal /// headers (`X-RedbIdentity-*`) override any clash. /// public Dictionary? ExtraHeaders { get; set; } /// /// Optional self-rolled concurrency token surfaced on update so a /// stale admin tab can't silently overwrite a fresher mutation. /// public string? ConcurrencyToken { get; set; } } Path: redb-identity/src/redb.Identity.Core/Module/BootstrapAdminBackfillListener.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/BootstrapAdminBackfillListener.cs ---- using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Core; using redb.Core.Query; using redb.Identity.Core.Models; using redb.Identity.Core.Services; using redb.Route.Abstractions; namespace redb.Identity.Core.Module; /// /// B.3 backfill — ensure the bootstrap admin user is also a member of the /// "admin" system role, not just the "admins" group. Bootstrap installs /// created before the B.3 system-roles listener landed have the admin user /// in the group (carrying scope identity:admin) but NOT in the role, /// so role-centric UI surfaces ("Users with this role" on /// /admin/roles/{id}) misleadingly render "no users". /// /// This listener walks every group whose name ends in "-admin" or matches /// the bootstrap admin group (best-effort recovery), finds every member /// flagged with role="admin", and idempotently assigns each one to the /// system admin role. Runs every startup after SeedSystemRolesListener /// (registered in InitRoute right after it), so a fresh bootstrap during /// the same process boot is also covered. /// /// Failure is logged at warning level; the group-scope auth path stays /// functional regardless, so we never block startup. /// internal sealed class BootstrapAdminBackfillListener : IRouteLifecycleListener { private readonly IServiceProvider _sp; public BootstrapAdminBackfillListener(IServiceProvider sp) => _sp = sp; public async Task OnContextStarting(IRouteContext context, CancellationToken ct) { await using var scope = _sp.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); var logger = scope.ServiceProvider .GetRequiredService() .CreateLogger(); try { // 1. Find the system "admin" role. var adminRole = await redb.Query() .Where(p => p.Name == "admin") .Where(p => p.Audience == "organization") .FirstOrDefaultAsync() .ConfigureAwait(false); if (adminRole is null) { logger.LogDebug("BootstrapAdminBackfillListener: admin role not seeded yet — skip."); return; } // 2. Find candidate "admins" groups. Bootstrap defaults the name // to "admins"; operators may have renamed it, so we also // sweep any group whose membership row says role=admin. var adminGroups = await redb.Query() .WhereRedb(o => o.Name == "admins") .ToListAsync() .ConfigureAwait(false); if (adminGroups.Count == 0) { logger.LogDebug("BootstrapAdminBackfillListener: no 'admins' group found — bootstrap likely not run yet."); return; } // 3. For every admin group, walk members flagged role=admin, // idempotently assign each to the admin role. var groupSvc = scope.ServiceProvider.GetRequiredService(); var roleSvc = new RoleService(redb); var (existingUserIds, _) = await roleSvc.ListAssigneesAsync(adminRole.Id, ct).ConfigureAwait(false); var existingSet = new HashSet(existingUserIds); var added = 0; foreach (var g in adminGroups) { var members = await groupSvc.GetMembersAsync(g.Id, ct).ConfigureAwait(false); foreach (var m in members) { if (m.Role != "admin") continue; if (existingSet.Contains(m.UserId)) continue; try { await roleSvc.AssignUserAsync(adminRole.Id, m.UserId, actingUserId: null, ct).ConfigureAwait(false); existingSet.Add(m.UserId); added++; } catch (Exception ex) { logger.LogWarning(ex, "BootstrapAdminBackfillListener: failed to mirror user {UserId} from group {GroupId} into admin role", m.UserId, g.Id); } } } if (added > 0) { logger.LogInformation( "redb.Identity: backfilled {Count} admin-group members into the admin role.", added); } } catch (Exception ex) { logger.LogWarning(ex, "BootstrapAdminBackfillListener: unexpected failure — group-scope auth remains intact, but role-centric UI may show empty 'admin' role until next restart."); } } } Path: redb-identity/src/redb.Identity.Core/Module/GroupNameKeyListener.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/GroupNameKeyListener.cs ---- using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Core; using redb.Core.Exceptions; using redb.Identity.Core.Models; using redb.Identity.Core.Services; using redb.Route.Abstractions; namespace redb.Identity.Core.Module; /// /// Gives every group that has no name key yet its key ( in /// ValueUnique), at every start. Groups created before names were unique have none. /// /// Groups are taken oldest first and saved one by one, each on its own, so the oldest group keeps a /// contested name. A group whose name is already the key of another group keeps no key, stays /// usable, and is logged as an error with both ids at every start until an operator renames or /// removes one of them; the next start then gives it its key. Nothing stops the start. /// /// internal sealed class GroupNameKeyListener : IRouteLifecycleListener { private readonly IServiceProvider _sp; public GroupNameKeyListener(IServiceProvider sp) => _sp = sp; public async Task OnContextStarting(IRouteContext context, CancellationToken ct) { await using var scope = _sp.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); var logger = scope.ServiceProvider.GetRequiredService() .CreateLogger(); await RunAsync(redb, new GroupService(redb), logger, ct).ConfigureAwait(false); } /// One pass; returns the number of groups left without a key because their name is taken. internal static async Task RunAsync( IRedbService redb, IGroupService groups, ILogger logger, CancellationToken ct) { List> unkeyed; try { unkeyed = await redb.Query() .WhereRedb(o => o.ValueUnique == null) .ToListAsync() .ConfigureAwait(false); } catch (Exception ex) { logger.LogError(ex, "redb.Identity: could not read the groups that have no name key; group names are not checked at this start."); return 0; } var conflicts = 0; foreach (var group in unkeyed.OrderBy(g => g.Id)) { ct.ThrowIfCancellationRequested(); if (string.IsNullOrWhiteSpace(group.name)) continue; group.ValueUnique = GroupNames.Key(group.name); try { await redb.SaveAsync(group).ConfigureAwait(false); } catch (RedbUniqueViolationException ex) when (ex.Kind == RedbUniqueViolationKind.ObjectKey) { conflicts++; var holder = await groups.FindGroupByNameAsync(group.name, ct).ConfigureAwait(false); logger.LogError( "redb.Identity: group {Id} '{Name}' has the same name as group {HolderId} '{HolderName}' " + "(names are compared without case and surrounding whitespace). It keeps working but has no " + "name key; rename or remove one of the two, the next start gives it its key.", group.Id, group.name, holder?.Id, holder?.name); } } if (conflicts > 0) logger.LogWarning( "redb.Identity: {Count} group(s) share a name with another group; see the errors above.", conflicts); return conflicts; } } Path: redb-identity/src/redb.Identity.Core/Module/IdentityAuditLogTableInitListener.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/IdentityAuditLogTableInitListener.cs ---- using System.Reflection; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Core; using redb.Core.Query; using redb.Route.Abstractions; using redb.Route.RedbCore.Models; namespace redb.Identity.Core.Module; /// /// Creates / migrates the flat identity_audit_log relational table that /// backs GET /api/v1/identity/audit and the user-detail Audit tab. /// /// /// Architectural note. The audit pipeline used to persist events as /// AuditEventProps rows in _objects + _values. That worked /// but bloated the redb store with append-only flat data and turned trivial /// "events for user X" queries into PVT scans. The relational table reverses /// the trade-off: one row per event, indexed by (timestamp, event_type, /// category, user_id, login). We still go through redb's /// for connection / dialect / transaction management — only the storage shape /// is plain SQL. /// /// /// /// DDL ships as an embedded resource per dialect /// (sql/audit/{pg,mssql,sqlite}_create_table.sql) so the .tpkg carries /// the schema and operators don't need a side-channel migration script. All /// scripts are idempotent: CREATE TABLE IF NOT EXISTS + per-index /// IF NOT EXISTS guards. /// /// /// /// Order: registered AFTER so /// the base redb schema and per-scheme unique indexes are already live. /// /// internal sealed class IdentityAuditLogTableInitListener : IRouteLifecycleListener { private readonly IServiceProvider _sp; public IdentityAuditLogTableInitListener(IServiceProvider sp) => _sp = sp; public async Task OnContextStarting(IRouteContext context, CancellationToken ct) { await using var scope = _sp.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); var dialect = scope.ServiceProvider.GetRequiredService(); var logger = scope.ServiceProvider .GetRequiredService() .CreateLogger(); var provider = dialect.ProviderName ?? ""; var resourceName = provider switch { var p when string.Equals(p, "PostgreSQL", StringComparison.OrdinalIgnoreCase) => "redb.Identity.Core.sql.audit.pg_create_table.sql", var p when string.Equals(p, "MSSql", StringComparison.OrdinalIgnoreCase) || string.Equals(p, "SqlServer", StringComparison.OrdinalIgnoreCase) => "redb.Identity.Core.sql.audit.mssql_create_table.sql", var p when string.Equals(p, "Sqlite", StringComparison.OrdinalIgnoreCase) || string.Equals(p, "SQLite", StringComparison.OrdinalIgnoreCase) => "redb.Identity.Core.sql.audit.sqlite_create_table.sql", _ => null }; if (resourceName is null) { logger.LogWarning( "redb.Identity: audit log table init skipped — unsupported dialect '{Provider}'", provider); return; } var sql = ReadEmbedded(resourceName); if (string.IsNullOrEmpty(sql)) { logger.LogError( "redb.Identity: failed to read embedded DDL '{Resource}' — audit table NOT created.", resourceName); return; } try { await redb.Context.ExecuteAsync(sql).ConfigureAwait(false); if (resourceName.EndsWith("sqlite_create_table.sql", StringComparison.Ordinal)) await AddSqliteColumnAsync(redb, "identity_audit_log", "actor_subject", "TEXT").ConfigureAwait(false); logger.LogInformation( "redb.Identity: identity_audit_log ensured ({Provider}).", provider); } catch (Exception ex) { // Audit table absence is degraded mode, NOT a startup blocker — // the sink will fail per-event and log, but the rest of identity // is still serviceable. logger.LogError(ex, "redb.Identity: failed to ensure identity_audit_log on {Provider}. " + "Audit persistence will fail until the table is created manually.", provider); } } /// /// SQLite has no ADD COLUMN IF NOT EXISTS: a table created by an earlier version gains the column here. /// A second process that added it first makes this ALTER fail with "duplicate column name", which means the /// column is there; anything else propagates. /// internal static async Task AddSqliteColumnAsync(IRedbService redb, string table, string column, string type) { var present = await redb.Context.ExecuteScalarAsync( $"SELECT COUNT(*) FROM pragma_table_info('{table}') WHERE name = '{column}'").ConfigureAwait(false); if (present > 0) return; try { await redb.Context.ExecuteAsync($"ALTER TABLE {table} ADD COLUMN {column} {type}").ConfigureAwait(false); } catch (Exception e) when (e.Message.Contains("duplicate column name", StringComparison.OrdinalIgnoreCase)) { } } internal static string? ReadEmbedded(string resourceName) { var asm = typeof(IdentityAuditLogTableInitListener).Assembly; using var stream = asm.GetManifestResourceStream(resourceName); if (stream is null) return null; using var reader = new StreamReader(stream); return reader.ReadToEnd(); } } Path: redb-identity/src/redb.Identity.Core/Module/IdentityDeliveryOutboxInitListener.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/IdentityDeliveryOutboxInitListener.cs ---- using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Core; using redb.Core.Query; using redb.Identity.Core.Events; using redb.Route.Abstractions; namespace redb.Identity.Core.Module; /// /// Creates the delivery outbox table identity_delivery_outbox and its indexes when they are /// missing (idempotent DDL per dialect, sql/events/*.sql, section create_outbox). A failure /// is logged and does not stop the start: events are still audited, their webhook deliveries fail to /// enqueue and are counted until the table exists. /// internal sealed class IdentityDeliveryOutboxInitListener : IRouteLifecycleListener { private readonly IServiceProvider _sp; public IdentityDeliveryOutboxInitListener(IServiceProvider sp) => _sp = sp; public async Task OnContextStarting(IRouteContext context, CancellationToken ct) { await using var scope = _sp.CreateAsyncScope(); var logger = scope.ServiceProvider.GetRequiredService() .CreateLogger(); try { var store = new IdentityEventStore( scope.ServiceProvider.GetRequiredService(), scope.ServiceProvider.GetRequiredService()); await store.EnsureOutboxAsync(ct).ConfigureAwait(false); } catch (Exception ex) { logger.LogError(ex, "redb.Identity: could not ensure identity_delivery_outbox; webhook deliveries cannot be enqueued until it exists."); } } } Path: redb-identity/src/redb.Identity.Core/Module/IdentityExchangeAccessor.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/IdentityExchangeAccessor.cs ---- using redb.Route.Abstractions; namespace redb.Identity.Core.Module; /// /// Carries the that a per-exchange Identity DI scope was opened for. /// /// This is the missing link that lets everything inside the isolated Identity child container — /// most importantly the OpenIddict stores (RedbTokenStore, RedbAuthorizationStore, …) — /// write on the same IRedbService, and therefore the same DB connection, that a /// route-level redb transaction was opened on. /// /// /// Why it is needed at all. In the .tpkg topology the route-context host provider does /// not carry Identity's registrations (that is the point of module isolation), so Identity resolves /// its services from a child container. Until now every child scope also opened its own host /// scope for — a second connection. A route-level /// transaction runs on the exchange-cached connection, so the stores were writing outside it: no /// atomicity, and — because the second connection blocks on the row locks the first one holds while /// the first awaits the call that opened the second — a deadlock that only cleared on the 30s /// transaction timeout. /// /// /// Scoped. Set once by whoever opens the scope (see IdentityRouteContextExtensions), read by /// HostRedbScope. Deliberately not an AsyncLocal: the scope is created /// explicitly and lives for exactly one exchange, so an explicit holder is simpler, deterministic, /// and cannot leak across tasks. /// /// internal sealed class IdentityExchangeAccessor { /// /// The exchange this scope belongs to, or null when the scope was opened outside a route /// (hosted services, cleanup timers, schema init, diagnostics). In that case there is no /// ambient transaction to join and the caller falls back to its own host scope. /// public IExchange? Exchange { get; set; } } Path: redb-identity/src/redb.Identity.Core/Module/IdentityModuleConfigBinder.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/IdentityModuleConfigBinder.cs ---- using System.Net; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration.Memory; using redb.Identity.Core.Configuration; using redb.Route.Abstractions; using redb.Identity.Contracts.Configuration; namespace redb.Identity.Core.Module; /// /// Binds the Tsak-merged context configuration (5-layer pipeline: /// appsettings → context.json → {Module}.config.json → Override) into a strongly typed /// instance. /// /// /// Tsak hands us configuration as a nested IDictionary<string, object?> /// stored on via SetProperty. To reuse the existing /// .NET IConfiguration.Bind(...) machinery (with all its convention parsing, /// TimeSpan handling, list expansion, etc.) we flatten the dictionary into /// entries and rebuild a transient /// . /// /// Two property classes that IConfiguration.Bind cannot construct from strings — /// () and /// () — are /// post-processed manually after the bind. /// /// /// Cryptographic credentials ( / /// ) are NOT loaded from JSON. /// They are produced by the key-provisioning step that runs separately /// (e.g. ephemeral fallback for dev, redb-backed RSA store for production). /// /// internal static class IdentityModuleConfigBinder { /// Top-level config section consumed by Identity. public const string SectionName = "Identity"; /// /// Builds from 's /// "Identity" property. Returns defaults when the property is missing or /// empty so the module can run in development without explicit configuration. /// public static RedbIdentityOptions Bind(IRouteContext context) { ArgumentNullException.ThrowIfNull(context); var options = new RedbIdentityOptions(); if (Configuration(context) is not { } cfg) return options; cfg.Bind(options, opt => opt.BindNonPublicProperties = false); // IConfiguration.Bind merges arrays/lists by index instead of replacing them, so a // user-supplied list with fewer elements than the default leaves the tail of the // default visible. For a config-driven server that's the wrong default — operators // expect "set the list to exactly this". Re-bind list-shaped properties manually // when the operator provided one. ReplaceListIfPresent(cfg, "DynamicRegistrationAllowedGrantTypes", arr => options.DynamicRegistrationAllowedGrantTypes = arr); ReplaceListIfPresent(cfg, "DynamicRegistrationAllowedScopes", arr => options.DynamicRegistrationAllowedScopes = arr); var federationSection = cfg.GetSection("FederationProviders"); if (federationSection.Exists()) { var providers = federationSection.Get>(); if (providers is not null) options.FederationProviders = providers; } // Post-process types Bind cannot parse from strings. BindReverseProxyIpAddresses(cfg, options); return options; } /// Sub-section of read by . public const string AuditSection = "Audit"; /// /// Builds from Identity:Audit of /// : the master switch, the event filter, the relational sink and the /// external targets the events are multicast to. Defaults when the section is missing. /// Targets replaces the default list rather than merging by index. /// public static IdentityAuditOptions BindAudit(IRouteContext context) { ArgumentNullException.ThrowIfNull(context); var audit = new IdentityAuditOptions(); var section = Configuration(context)?.GetSection(AuditSection); if (section is null || !section.Exists()) return audit; section.Bind(audit, opt => opt.BindNonPublicProperties = false); var targets = section.GetSection(nameof(IdentityAuditOptions.Targets)); if (targets.Exists()) audit.Targets = targets.Get>() ?? []; return audit; } // The context's "Identity" property flattened into IConfiguration key-value form // (Section:Key:Index syntax), so the standard IConfiguration.Bind reflection path can hydrate // the POCOs; null when the property is missing or empty. private static IConfiguration? Configuration(IRouteContext context) { var raw = context.GetProperty>(SectionName); if (raw is null || raw.Count == 0) return null; var flat = new Dictionary(StringComparer.OrdinalIgnoreCase); Flatten(raw, prefix: string.Empty, sink: flat); return new ConfigurationBuilder() .Add(new MemoryConfigurationSource { InitialData = flat }) .Build(); } private static void ReplaceListIfPresent(IConfiguration cfg, string key, Action setter) { var section = cfg.GetSection(key); if (!section.Exists()) return; var arr = section.Get(); if (arr is not null) setter(arr); } 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; } } } /// /// IConfiguration.Bind cannot construct / /// from strings — parse them manually. /// private static void BindReverseProxyIpAddresses(IConfiguration cfg, RedbIdentityOptions options) { var proxies = cfg.GetSection("ReverseProxies:KnownProxies").Get(); if (proxies is { Length: > 0 }) { options.ReverseProxies.KnownProxies.Clear(); foreach (var p in proxies) { if (IPAddress.TryParse(p, out var ip)) options.ReverseProxies.KnownProxies.Add(ip); } } var nets = cfg.GetSection("ReverseProxies:KnownNetworks").Get(); if (nets is { Length: > 0 }) { options.ReverseProxies.KnownNetworks.Clear(); foreach (var n in nets) { if (IPNetwork.TryParse(n, out var net)) options.ReverseProxies.KnownNetworks.Add(net); } } } } Path: redb-identity/src/redb.Identity.Core/Module/IdentityModuleHost.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/IdentityModuleHost.cs ---- using Microsoft.AspNetCore.DataProtection; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using redb.Core; using redb.Core.Query; using redb.Identity.Core.Configuration; using redb.Identity.DataProtection; using redb.Route.Abstractions; using redb.Route.RedbCore.Extensions; namespace redb.Identity.Core.Module; /// /// Builds a self-contained child for the redb.Identity /// .tpkg module. The Tsak.Worker root container is built BEFORE modules are loaded /// (modules ship as plug-ins), so an Identity-internal DI graph is built lazily here /// from the Tsak-resolved . /// /// /// /// Bridge services from the host root container: /// /// — shared logging plumbing. /// — testable clock (defaults to system). /// — host configuration root. /// — resolved by name from the route context registry /// so each Identity instance binds to the correct redb data source per /// . /// /// /// /// Identity-owned registrations (built fresh in the child container): /// /// AddRedbIdentityServer(options) — OpenIddict + Mfa + Login + Token + Federation + RateLimit. /// AddDataProtection().PersistKeysToRedb() — DataProtection key-ring stored in redb. /// AddHttpClient() — base infrastructure for federated OIDC HTTP calls. /// /// /// /// The returned is owned by the caller and must be /// disposed when the route context stops (see ). /// /// internal static class IdentityModuleHost { public static ServiceProvider Build( IRouteContext routeContext, RedbIdentityOptions options, Action? extraRegistrations = null) { ArgumentNullException.ThrowIfNull(routeContext); ArgumentNullException.ThrowIfNull(options); var rootSp = routeContext.GetServiceProvider() ?? throw new InvalidOperationException( "IRouteContext is missing a backing IServiceProvider — cannot bridge host services."); var services = new ServiceCollection(); // 1. Bridge core host services. var loggerFactory = rootSp.GetRequiredService(); services.AddSingleton(loggerFactory); services.AddLogging(); // wires Microsoft.Extensions.Logging.ILogger against the bridged factory. services.AddSingleton(rootSp.GetService() ?? TimeProvider.System); var hostConfiguration = rootSp.GetService(); if (hostConfiguration is not null) services.AddSingleton(hostConfiguration); // Bridge the host's IRouteContext into the child SP. The runtime that owns the // Identity routes (incl. direct-vm://identity-email-send) is the host context — child // services that publish into it (e.g. SmtpEmailNotificationChannel) need to resolve // IRouteContext from this child container, not from the host's. We bridge instead of // re-registering because the route context is a singleton per Tsak context, and // publishing into a *different* context would silently bypass the SMTP route entirely. services.AddSingleton(routeContext); // 2. IRedbService — bridged from the host as a SCOPED service. // // Why scoped (E7 follow-up): in the .tpkg topology redb.Route opens a per-exchange // child scope (exposed as IExchange.ServiceProvider) and OpenIddict resolves its // Scoped stores (RedbTokenStore, RedbAuthorizationStore, …) through that scope. // Production `AddRedbPro` registers IRedbService as Scoped — one per request, // backed by a fresh Npgsql connection from the pool. A Singleton bridge would // captive-capture one IRedbService for ALL concurrent requests, serialising the // whole Identity surface on a single connection. We instead bridge the host's // IServiceScopeFactory (or the named-instance factory registered by // TsakContextManager under `redb-factory:{name}`) and register a Scoped wrapper // that opens a host-side scope per child scope and disposes it deterministically. var redbInstanceName = options.RedbInstanceName?.TrimStart('#'); IServiceScopeFactory hostRedbScopeFactory; if (!string.IsNullOrEmpty(redbInstanceName)) { // Named instance — Tsak put a scope factory in the registry alongside the // singleton fallback. Use the factory so each child scope gets its own // IRedbService (and its own connection). hostRedbScopeFactory = routeContext.GetFromRegistry("redb-factory:" + redbInstanceName) ?? throw new InvalidOperationException( $"Named IRedbService '{options.RedbInstanceName}' has no scope factory registered " + $"in the route context (key 'redb-factory:{redbInstanceName}'). Did Tsak's " + "RegisterNamedRedbServices run before module initialisation?"); } else { // Default unnamed — bridge the host root provider's scope factory directly. hostRedbScopeFactory = rootSp.GetRequiredService(); } // Wrap the host scope factory in a marker singleton so we DO NOT shadow the // child container's own IServiceScopeFactory registration (doing so would make // childSp.CreateScope() open scopes against the host container instead). var hostScopeFactoryHolder = new HostRedbScopeFactoryHolder(hostRedbScopeFactory, redbInstanceName); services.AddSingleton(hostScopeFactoryHolder); // Carries the exchange this child scope was opened for. Seeded by whoever opens the scope // (IdentityRouteContextExtensions / RedbRouteOpenIddictServerHandler); read by HostRedbScope, // which uses it to bind IRedbService to the exchange's connection instead of opening a // second one. Without this, nothing inside the child container can join a route-level redb // transaction — see HostRedbScope's remarks. services.AddScoped(); services.AddScoped(); services.AddScoped(sp => sp.GetRequiredService().Service); // 9f: bridge ISqlDialect from the host scope alongside IRedbService so listeners // (e.g. IdentityUniqueIndexesInitListener) can resolve the dialect against the // child container without falling back to host-only registrations. services.AddScoped(sp => sp.GetRequiredService().Dialect); // 3. Options snapshot. services.AddSingleton(Options.Create(options)); services.AddOptions(); // 4. HttpClient factory base — required by federation and any Identity HTTP egress. services.AddHttpClient(); // 5. Identity itself. services.AddRedbIdentityServer(options); // 6. DataProtection persisted to redb (keys live in redb so all replicas share them). services.AddDataProtection() .SetApplicationName("redb.identity") .PersistKeysToRedb() .ProtectKeysWithRedbIdentity(options); // 7. Optional caller-supplied registrations (Variant B integrations such as LDAP // that live in sibling assemblies and cannot be referenced from Core directly). extraRegistrations?.Invoke(services); // E7: enforce captive-dependency detection at build time. ValidateScopes catches // singletons capturing scoped services AND scoped services resolved from the root // provider; ValidateOnBuild fails fast on misconfigured DI instead of leaving a // latent bug for the first request to discover. return services.BuildServiceProvider(new ServiceProviderOptions { ValidateScopes = true, ValidateOnBuild = true, }); } } /// /// Disposes the Identity child when the surrounding route /// context stops. Without this the child container would leak across Tsak hot-reloads. /// internal sealed class ChildHostDisposeListener : IRouteLifecycleListener { private readonly ServiceProvider _childSp; public ChildHostDisposeListener(ServiceProvider childSp) => _childSp = childSp; public Task OnContextStopped(IRouteContext context, CancellationToken ct) { _childSp.Dispose(); return Task.CompletedTask; } } /// /// Bridges from Tsak's host container into Identity's child container, /// and — critically — makes sure that inside a route it is the same instance, and therefore /// the same DB connection, that any route-level redb transaction was opened on. /// /// /// /// Two independent DI universes: Tsak's host container (where is Scoped /// via AddRedbPro, or named via RedbInstanceFactory) and Identity's child container, /// from which OpenIddict resolves its stores. This class is the bridge. /// /// /// The bug this fixes. It used to open its own host scope in the constructor — /// unconditionally, eagerly. That is a second connection. A route-level transaction (the /// ambient scope .Transacted() opens) runs on the connection redb.Route caches on the exchange, so the /// OpenIddict stores were writing on a different one: no atomicity at all, and worse — the second /// connection blocks on row locks the first one holds, while the first is awaiting the very call /// that opened the second. Deadlock, cleared only by the 30s transaction timeout. Hence the rule: /// do not open a fresh DI scope inside a route processor that runs under a transaction; and it is why WithRedbTx had to be stripped from the token /// route. It is not a SQLite quirk: the rule is written about Npgsql. SQLite (single writer) only /// makes the symptom louder. /// /// /// The fix. When the scope belongs to an exchange, ask redb.Route for the exchange's /// — the very instance it caches in IExchange.Properties, which /// enlists into the route's ambient transaction. One connection, one transaction, everybody enlisted. Only when /// there is no exchange (hosted services, cleanup timers, schema init) do we fall back to opening a /// host scope of our own, which is correct: there is no ambient transaction to join. /// /// /// Resolution is lazy. A scope that never touches the DB no longer pays for a connection. /// /// internal sealed class HostRedbScope : IDisposable, IAsyncDisposable { private readonly HostRedbScopeFactoryHolder _holder; private readonly IdentityExchangeAccessor _accessor; private readonly IRouteContext _routeContext; private readonly string? _redbName; private IServiceScope? _ownScope; // opened ONLY on the no-exchange path private IRedbService? _service; private ISqlDialect? _dialect; public HostRedbScope( HostRedbScopeFactoryHolder holder, IdentityExchangeAccessor accessor, IRouteContext routeContext) { _holder = holder; _accessor = accessor; _routeContext = routeContext; _redbName = holder.RedbInstanceName; } public IRedbService Service => _service ??= ResolveService(); public ISqlDialect Dialect => _dialect ??= ResolveDialect(); private IRedbService ResolveService() { // In-route: take the exchange's instance. This is the whole point — it is the connection // enlisted into the route's ambient transaction, so our writes land inside it. if (_accessor.Exchange is { } exchange) return _routeContext.GetRedbService(_redbName ?? string.Empty, exchange); // Out-of-route (timers, hosted services, init): no ambient transaction exists, so an own // scope is both safe and necessary. return EnsureOwnScope().ServiceProvider.GetRequiredService(); } private ISqlDialect ResolveDialect() { // The dialect is a stateless SQL-shape helper, not a connection — but resolve it from the // exchange's provider when we can, rather than opening a scope purely to reach it. if (_accessor.Exchange?.ServiceProvider?.GetService() is { } fromExchange) return fromExchange; return EnsureOwnScope().ServiceProvider.GetRequiredService(); } private IServiceScope EnsureOwnScope() => _ownScope ??= _holder.Factory.CreateScope(); public void Dispose() => _ownScope?.Dispose(); public ValueTask DisposeAsync() { if (_ownScope is null) return ValueTask.CompletedTask; var scope = _ownScope; _ownScope = null; return scope is IAsyncDisposable a ? a.DisposeAsync() : new ValueTask(Task.Run(scope.Dispose)); } } /// /// Marker holder for the host's . Registered as a /// distinct type (NOT as IServiceScopeFactory directly) so the child container /// keeps its own scope factory intact while still being able to reach the host one /// when bridging . /// internal sealed class HostRedbScopeFactoryHolder { public IServiceScopeFactory Factory { get; } /// /// The named redb instance this module runs on (already trimmed of the leading '#'), or null /// for the default unnamed one. needs it to ask redb.Route for the /// exchange's instance under the same name the route transaction was opened on. /// public string? RedbInstanceName { get; } public HostRedbScopeFactoryHolder(IServiceScopeFactory factory, string? redbInstanceName = null) { Factory = factory; RedbInstanceName = redbInstanceName; } } Path: redb-identity/src/redb.Identity.Core/Module/IdentityRouteContextExtensions.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/IdentityRouteContextExtensions.cs ---- using Microsoft.Extensions.DependencyInjection; using redb.Route.Abstractions; namespace redb.Identity.Core.Module; /// /// Bridges Identity-owned services (OpenIddict managers, deletion service, options snapshot, …) /// from the Identity child into route processors that run inside /// the host route context. Mirrors the named-instance pattern that RedbRouteExtensions /// uses for IRedbService: /// /// Tsak/InitRoute publishes the Identity child SP's /// in the route-context registry under "identity-sp:{name}". /// Per-exchange consumers ask which creates a fresh /// scope on first call within an exchange and caches it under "__redb_scope:identity-sp:{name}" /// in . The scope is auto-disposed by /// Exchange.ReleaseScopes() alongside named redb scopes (same __redb_scope: prefix /// is intentional — it co-opts the framework's existing scope-disposal hook so Identity /// scopes get deterministic cleanup without touching redb.Route). /// /// /// /// /// Why this exists: under .tpkg deployment the host root has no /// Identity registrations — those live in a child container built by /// . is a /// per-exchange scope of the host root, not of the child container, so processors that /// reach for exchange.ServiceProvider.GetRequiredService<IOpenIddictApplicationManager>() /// silently work in single-SP test fixtures (Path 1 in InitRoute) yet throw at runtime /// under tpkg loading (Path 2). Going through this helper unifies both paths. /// /// /// The host SP fallback exists so unit tests that drive a processor without a route context can /// still resolve services from the host container; production code always hits the registry. /// /// public static class IdentityRouteContextExtensions { private const string FactoryPrefix = "identity-sp:"; // Reuse redb.Route's __redb_scope: prefix so Exchange.ReleaseScopes() auto-disposes // Identity scopes — see Exchange.cs:217-233 (named scopes are matched purely by prefix). private const string ScopeCachePrefix = "__redb_scope:identity-sp:"; private const string DefaultName = "default"; /// /// Publishes the Identity child SP's in the route-context /// registry. Call once during module init, after the child SP is built. /// public static IRouteContext RegisterIdentityScopeFactory( this IRouteContext context, string? name, IServiceScopeFactory factory) { ArgumentNullException.ThrowIfNull(context); ArgumentNullException.ThrowIfNull(factory); context.AddToRegistry(FactoryPrefix + Clean(name), factory); return context; } /// /// Resolves from the Identity child container against a per-exchange /// scope. Throws if neither the registry factory nor a host SP fallback can satisfy the lookup. /// public static T GetIdentityService( this IRouteContext context, IExchange? exchange, string? name = null) where T : notnull { ArgumentNullException.ThrowIfNull(context); var sp = ResolveServiceProvider(context, exchange, name); return sp.GetRequiredService(); } /// /// Same as but returns null when the requested /// service is not registered. Use for opt-in services like IBackgroundDeletionService /// or IRegisteredClientOriginRegistry. /// public static T? GetIdentityServiceOrDefault( this IRouteContext context, IExchange? exchange, string? name = null) where T : class { ArgumentNullException.ThrowIfNull(context); var sp = TryResolveServiceProvider(context, exchange, name); return sp?.GetService(); } private static IServiceProvider ResolveServiceProvider(IRouteContext context, IExchange? exchange, string? name) { return TryResolveServiceProvider(context, exchange, name) ?? throw new InvalidOperationException( $"Identity scope factory '{FactoryPrefix}{Clean(name)}' is not registered, and the route " + "context has no fallback IServiceProvider. Ensure InitRoute called " + "context.RegisterIdentityScopeFactory(...) during module bootstrap."); } /// /// Tells a freshly opened Identity child scope which exchange it belongs to. /// /// HostRedbScope reads this to bind IRedbService to the exchange's connection — /// the one enlisted into the route-level ambient transaction (.Transacted()) — instead of /// opening a second connection of its own. Without the seed, everything inside the child /// container (including every OpenIddict store) writes outside the route transaction, and, worse, /// deadlocks against it. /// /// /// Best-effort by design: fixtures and single-SP hosts may not register the accessor at all, and /// they have no route transaction to join either — so a miss is not an error. /// /// private static void SeedExchange(IServiceProvider scopeSp, IExchange exchange) { if (scopeSp.GetService() is { } accessor) accessor.Exchange = exchange; } private static IServiceProvider? TryResolveServiceProvider(IRouteContext context, IExchange? exchange, string? name) { var clean = Clean(name); if (exchange != null) { var cacheKey = ScopeCachePrefix + clean; // Reuse a scope already opened for this exchange (multiple processors in the same // pipeline share one Identity scope, mirroring per-exchange IRedbService caching). if (exchange.Properties.TryGetValue(cacheKey, out var cached) && cached is IServiceScope cachedScope) return cachedScope.ServiceProvider; if (context.GetFromRegistry(FactoryPrefix + clean) is { } factory) { var scope = factory.CreateScope(); exchange.Properties[cacheKey] = scope; SeedExchange(scope.ServiceProvider, exchange); return scope.ServiceProvider; } // Single-SP fallback (unit-test fixtures, legacy hosts that didn't call // RegisterIdentityScopeFactory). Still build a per-exchange scope from the host // root via the SP's own scope factory, otherwise Scoped services // (IOpenIddictApplicationStore = RedbApplicationStore, IRedbService, etc.) get // captured at root lifetime and behave as singletons — the per-instance // _clientIdCache then persists across all requests and silently shadows DB // mutations made through other scopes (see BootstrapAdminEndpointTests where // cleanup-scope deletes never reached the captive store's cache, so the // bootstrap processor kept finding a stale id=44105488 ghost). Caching the // scope on the exchange keeps "same exchange → same scope" for processors that // expect shared IRedbService state, matching the factory path above. var rootSp = context.GetServiceProvider(); if (rootSp is not null) { var rootFactory = rootSp.GetService(); if (rootFactory is not null) { var scope = rootFactory.CreateScope(); exchange.Properties[cacheKey] = scope; SeedExchange(scope.ServiceProvider, exchange); return scope.ServiceProvider; } return rootSp; } return null; } // No-exchange path (diagnostic tooling that calls into a processor without going // through the route system) — return the host root SP as-is. There's no exchange to // hang a scope off of, so the caller owns the lifetime. return context.GetServiceProvider(); } private static string Clean(string? name) => string.IsNullOrEmpty(name) ? DefaultName : name.TrimStart('#'); } Path: redb-identity/src/redb.Identity.Core/Module/IdentitySchemaInitListener.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/IdentitySchemaInitListener.cs ---- using System.Reflection; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Core; using redb.Core.Attributes; using redb.Core.Providers; using redb.Identity.Core.Hosting; using redb.Route.Abstractions; namespace redb.Identity.Core.Module; /// /// Initializes redb base infrastructure (_objects/_schemes/_values/etc.) and synchronises all /// Identity PROPS schemas () before any Identity route /// starts. Registered from redb.Identity.Core.Module.InitRoute.main via /// context.AddLifecycleListener(...). Runs in — /// guaranteed to complete BEFORE any route (including the HTTP facade) processes its first /// exchange, so downstream processors can assume every *Props scheme exists. /// /// A6 cluster coordination (opt-in): when IDistributedLock is registered in the /// root service provider (i.e. when Tsak:Cluster:Enabled=true and the Pro cluster /// primitives are available), acquires an exclusive short-TTL lock /// (identity:schema-init) before running DDL so that concurrent cold-starts on /// multiple replicas do not race each other on CREATE TABLE IF NOT EXISTS. In /// standalone (the DI service is absent) the coordination block is a no-op. /// /// internal sealed class IdentitySchemaInitListener : IRouteLifecycleListener { private readonly IServiceProvider _sp; public IdentitySchemaInitListener(IServiceProvider sp) => _sp = sp; public async Task OnContextStarting(IRouteContext context, CancellationToken ct) { await using var scope = _sp.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); var logger = scope.ServiceProvider .GetRequiredService() .CreateLogger(); // A6 cluster lock — only when Tsak cluster primitives are registered. // Duck-typed via reflection to avoid a hard reference to redb.Tsak.Core.Pro from // redb.Identity.Core. Presence of the lock service indicates Tsak:Cluster:Enabled=true. var lockService = TryResolveDistributedLock(_sp); var nodeId = Environment.MachineName; object? acquired = null; if (lockService is not null) { acquired = await TryAcquireDistributedLockAsync(lockService, "identity:schema-init", nodeId, ttlSeconds: 120, ct) .ConfigureAwait(false); if (acquired is null) { logger.LogInformation("redb.Identity: schema init — follower; another node holds the lock, proceeding idempotently"); } else { logger.LogInformation("redb.Identity: schema init — leader under cluster lock"); } } try { logger.LogInformation("redb.Identity: initializing redb base schema"); await redb.InitializeAsync(ensureCreated: true).ConfigureAwait(false); // Eagerly synchronise every registered Identity Props type so downstream code // (processors, listeners) never triggers a lazy DDL from inside a hot path. var syncMethod = typeof(ISchemeSyncProvider) .GetMethod(nameof(ISchemeSyncProvider.SyncSchemeAsync)) ?? throw new InvalidOperationException("ISchemeSyncProvider.SyncSchemeAsync not found."); // The call below is by reflection because the type is only known at runtime, and that makes // it invisible to the compiler: when SyncSchemeAsync gained its CancellationToken, this site // kept building without a word and threw "Parameter count mismatch" on the first type at // startup. The loop then never ran, no scheme was synchronised, and every listener after it // failed with "Scheme for type 'X' not found" — a dozen symptoms with nothing pointing here. // So the arity is checked once, up front, and says what actually broke. var syncParameters = syncMethod.GetParameters(); if (syncParameters.Length != 1 || syncParameters[0].ParameterType != typeof(CancellationToken)) { throw new InvalidOperationException( "ISchemeSyncProvider.SyncSchemeAsync no longer takes exactly one CancellationToken " + $"(now: {string.Join(", ", syncParameters.Select(p => p.ParameterType.Name))}). " + "This reflection call site in IdentitySchemaInitListener must be updated to match, " + "otherwise no Identity scheme is synchronised and the whole module fails to start."); } foreach (var t in IdentitySchemaRegistry.Types) { var generic = syncMethod.MakeGenericMethod(t); var task = (Task?)generic.Invoke(redb, [ct]); if (task is not null) await task.ConfigureAwait(false); // CRITICAL: explicitly register each (scheme_id ↔ CLR Type) // pair in GlobalMetadataCache. Without this every polymorphic // load path — TreeQueryProviderBase.LoadObjectsByIdsAsync // (non-generic, which the tree ancestor walk uses to load // parent objects whose scheme is only known at runtime) — // throws "Type not found for scheme_id=N" and the catch // upstack silently degrades the `groups` claim to // direct-membership-only. // // The library's auto-scan (InitializeTypeRegistryAsync) walks // AppDomain assemblies looking for [RedbScheme] types, but // Tsak loads Identity's types into a child ALC + the scan // catches ReflectionTypeLoadException silently — so the // registry comes up empty in production. Explicit registration // by the schema initializer eliminates that race entirely. var attr = t.GetCustomAttribute(); if (attr is not null) { var schemeName = attr.GetSchemeName(t); var scheme = await redb.GetSchemeByNameAsync(schemeName).ConfigureAwait(false); if (scheme is not null) { redb.Cache.RegisterClrType(schemeName, scheme.Id, t); } } } logger.LogInformation( "redb.Identity: redb base schema ready ({Count} scheme types synced + CLR type registry populated)", IdentitySchemaRegistry.Types.Count); } finally { if (lockService is not null && acquired is not null) { await ReleaseDistributedLockAsync(lockService, "identity:schema-init", nodeId, ct) .ConfigureAwait(false); } } } private static object? TryResolveDistributedLock(IServiceProvider sp) { // Resolve redb.Tsak.Core.Pro.Cluster.Contracts.IDistributedLock without a compile-time // reference — Identity.Core must build regardless of Pro presence. var type = Type.GetType("redb.Tsak.Core.Pro.Cluster.Contracts.IDistributedLock, redb.Tsak.Core.Pro", throwOnError: false); return type is null ? null : sp.GetService(type); } private static async Task TryAcquireDistributedLockAsync(object lockService, string name, string nodeId, int ttlSeconds, CancellationToken ct) { var method = lockService.GetType().GetMethod("TryAcquireAsync") ?? throw new InvalidOperationException("IDistributedLock.TryAcquireAsync not found."); var task = (Task?)method.Invoke(lockService, [name, nodeId, "identity", ttlSeconds, ct]) ?? throw new InvalidOperationException("IDistributedLock.TryAcquireAsync returned null."); await task.ConfigureAwait(false); var result = task.GetType().GetProperty("Result")?.GetValue(task); var acquired = (bool?)(result?.GetType().GetProperty("Acquired")?.GetValue(result)) ?? false; return acquired ? result : null; } private static async Task ReleaseDistributedLockAsync(object lockService, string name, string nodeId, CancellationToken ct) { var method = lockService.GetType().GetMethod("ReleaseAsync") ?? throw new InvalidOperationException("IDistributedLock.ReleaseAsync not found."); var task = (Task?)method.Invoke(lockService, [name, nodeId, "identity", ct]); if (task is not null) await task.ConfigureAwait(false); } } Path: redb-identity/src/redb.Identity.Core/Module/IdentityUniqueIndexesInitListener.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/IdentityUniqueIndexesInitListener.cs ---- using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Core; using redb.Core.Query; using redb.Route.Abstractions; namespace redb.Identity.Core.Module; /// /// V4-UNIQUE remainder of the pre-V4 artificial-index bootstrap. The eight /// per-scheme partial indexes on _objects moved to the core's [RedbUnique] / /// ValueUnique machinery and are DROPPED by /// once the transition backfill has run clean. ONE index stays: /// /// /// UX_users_email — a partial unique index straight on the core _users(_email) /// table, the only place email lives; V4 primitives cannot express it. Closes the /// register/create email TOCTOU the same way _login's UNIQUE closes login. NOTE for /// shared databases: this one is NOT scheme-scoped — it imposes email uniqueness on every /// application sharing _users (accepted by the owner). /// /// /// The R2 interim index on redb.Route's IdempotentEntryProps was retired on /// 2026-09-02: Route's own fix (commit 816a3d2a, `RedbIdempotentRepository` writes /// ValueUnique and catches the typed violation) made it redundant, and /// now drops it with the other retired indexes. /// /// DDL is idempotent; a failure degrades to the optimistic in-code checks rather than /// aborting the bootstrap. The class name is wider than its remaining content on purpose — /// it is the historical anchor every doc points at. /// internal sealed class IdentityUniqueIndexesInitListener : IRouteLifecycleListener { private readonly IServiceProvider _sp; public IdentityUniqueIndexesInitListener(IServiceProvider sp) => _sp = sp; public async Task OnContextStarting(IRouteContext context, CancellationToken ct) { await using var scope = _sp.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); var dialect = scope.ServiceProvider.GetRequiredService(); var logger = scope.ServiceProvider .GetRequiredService() .CreateLogger(); var provider = dialect.ProviderName; var isPostgres = string.Equals(provider, "PostgreSQL", StringComparison.OrdinalIgnoreCase); var isMsSql = string.Equals(provider, "MSSql", StringComparison.OrdinalIgnoreCase) || string.Equals(provider, "SqlServer", StringComparison.OrdinalIgnoreCase); var isSqlite = string.Equals(provider, "SQLite", StringComparison.OrdinalIgnoreCase); if (!isPostgres && !isMsSql && !isSqlite) { logger.LogWarning( "redb.Identity: unique-index init skipped — unsupported SQL dialect '{Provider}'", provider); return; } // ── UX_users_email (stays) ────────────────────────────────────────────────────────── // Partial (WHERE _email IS NOT NULL) so the many null-email users don't collide — // also what lets it work on SQL Server, whose plain UNIQUE allows a single NULL. // Case-folding is the processors' job (lower-invariant before insert). try { var emailSql = isMsSql ? "IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = 'UX_users_email') " + "CREATE UNIQUE INDEX [UX_users_email] ON [_users]([_email]) WHERE [_email] IS NOT NULL" : "CREATE UNIQUE INDEX IF NOT EXISTS \"UX_users_email\" ON _users (_email) WHERE _email IS NOT NULL"; await redb.Context.ExecuteAsync(emailSql).ConfigureAwait(false); logger.LogDebug("redb.Identity: unique index 'UX_users_email' ensured on _users(_email)."); } catch (Exception ex) { logger.LogError(ex, "redb.Identity: failed to create unique index 'UX_users_email' on _users(_email)."); } } } Path: redb-identity/src/redb.Identity.Core/Module/RedbXmlRepositoryInitListener.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/RedbXmlRepositoryInitListener.cs ---- using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using redb.Core; using redb.Identity.Core.Configuration; using redb.Identity.DataProtection; using redb.Route.Abstractions; namespace redb.Identity.Core.Module; /// /// Loads the DataProtection XML key snapshot into before any /// route (including the HTTP facade) processes its first exchange. /// /// Without this listener the very first Protect/Unprotect call would face an /// empty key ring and force KeyManager to generate a fresh key — invalidating any /// existing session/refresh-token cookies issued by other replicas. Seeding the snapshot at /// guarantees consistency across cold starts and restarts. /// /// /// Before loading, file key rings the process wrote up to 4.3 (the ASP.NET Core default directory, /// plus ) are imported into redb, so data /// protected with them stays readable (). /// /// internal sealed class RedbXmlRepositoryInitListener : IRouteLifecycleListener { private readonly IServiceProvider _sp; public RedbXmlRepositoryInitListener(IServiceProvider sp) => _sp = sp; public async Task OnContextStarting(IRouteContext context, CancellationToken ct) { await using var scope = _sp.CreateAsyncScope(); var repo = scope.ServiceProvider.GetRequiredService(); var redb = scope.ServiceProvider.GetRequiredService(); var logger = scope.ServiceProvider .GetRequiredService() .CreateLogger(); var directories = DefaultFileKeyRing.Directories().ToList(); var explicitPath = scope.ServiceProvider.GetService>()? .Value.DataProtection.ImportKeysFromPath; if (!string.IsNullOrWhiteSpace(explicitPath)) directories.Add(explicitPath); await RedbXmlRepository.ImportFileKeyRingsAsync(redb, directories, logger, ct).ConfigureAwait(false); var count = await repo.ReloadAsync(redb, ct).ConfigureAwait(false); logger.LogInformation( "redb.Identity: DataProtection key-ring snapshot loaded ({Count} keys)", count); } } Path: redb-identity/src/redb.Identity.Core/Module/SeedAdminRoleAssignmentListener.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/SeedAdminRoleAssignmentListener.cs ---- using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using redb.Core; using redb.Core.Query; using redb.Identity.Core.Configuration; using redb.Identity.Core.Models; using redb.Identity.Core.Services; using redb.Route.Abstractions; namespace redb.Identity.Core.Module; /// /// Bridge the canonical SeedAdmin user (the admin account from the redb SQL /// seed + ) to the canonical B.3 admin /// role (the admin system role from ). /// /// Without this listener the two seeders run in isolation and the admin user /// never appears in /admin/roles/{adminRoleId}/assignees — operators see /// the admin role on /admin/roles with zero users next to it and can't tell /// whether authorisation is actually flowing through the role-based path. The /// existing covers a /// SEPARATE flow (POST /internal/bootstrap-admin) that creates its own /// admin user + group; installs that never call that endpoint (the common /// case for the seeded admin account) get the role left empty. /// /// Runs on every startup AFTER both seeders. Idempotent: looks up the admin /// user by , the admin role by /// name=admin / audience=organization, and skips when the assignment /// already exists. Failure is logged at warning level and never blocks /// startup — the group-scope path remains a safety net. /// internal sealed class SeedAdminRoleAssignmentListener : IRouteLifecycleListener { private readonly IServiceProvider _sp; private readonly IOptions _options; public SeedAdminRoleAssignmentListener(IServiceProvider sp, IOptions options) { _sp = sp; _options = options; } public async Task OnContextStarting(IRouteContext context, CancellationToken ct) { await using var scope = _sp.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); var logger = scope.ServiceProvider .GetRequiredService() .CreateLogger(); var seedAdmin = _options.Value.SeedAdmin; if (!seedAdmin.Enabled || string.IsNullOrWhiteSpace(seedAdmin.Login)) { logger.LogDebug("SeedAdminRoleAssignmentListener: SeedAdmin disabled or no login configured — skip."); return; } try { // 1. Resolve admin user by login. Returns null when the SQL seed // hasn't created the row yet (extremely fresh DB) — log + skip; // next startup will catch it. var adminUser = await redb.UserProvider.GetUserByLoginAsync(seedAdmin.Login).ConfigureAwait(false); if (adminUser is null) { logger.LogDebug( "SeedAdminRoleAssignmentListener: user with login '{Login}' not found — skip (SQL seed may not have run).", seedAdmin.Login); return; } // 2. Resolve admin role. SeedSystemRolesListener creates it earlier // in the lifecycle chain. var adminRole = await redb.Query() .WhereRedb(o => o.Name == "admin") .Where(p => p.Audience == "organization") .FirstOrDefaultAsync() .ConfigureAwait(false); if (adminRole is null) { logger.LogWarning( "SeedAdminRoleAssignmentListener: admin role not seeded — SeedSystemRolesListener must run first."); return; } // 3. Idempotent assign. RoleService.AssignUserAsync no-ops on duplicate. var roleSvc = new RoleService(redb); var (existingUserIds, _) = await roleSvc.ListAssigneesAsync(adminRole.Id, ct).ConfigureAwait(false); if (existingUserIds.Contains(adminUser.Id)) { logger.LogDebug( "SeedAdminRoleAssignmentListener: user {UserId} ({Login}) already in admin role — skip.", adminUser.Id, seedAdmin.Login); return; } await roleSvc.AssignUserAsync(adminRole.Id, adminUser.Id, actingUserId: null, ct).ConfigureAwait(false); logger.LogInformation( "redb.Identity: seed admin '{Login}' (user id {UserId}) assigned to system admin role (id {RoleId}).", seedAdmin.Login, adminUser.Id, adminRole.Id); } catch (Exception ex) { logger.LogWarning(ex, "SeedAdminRoleAssignmentListener: failed to mirror seed admin into admin role — UI will show role as empty until next startup."); } } } Path: redb-identity/src/redb.Identity.Core/Module/SeedAdminRoleScopesListener.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/SeedAdminRoleScopesListener.cs ---- using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using redb.Core; using redb.Core.Query; using redb.Identity.Core.Configuration; using redb.Identity.Core.Models; using redb.Identity.Core.Services; using redb.Route.Abstractions; namespace redb.Identity.Core.Module; /// /// Give the system admin role the management scope it is named after. /// /// issues an administrative scope /// only when the user's roles carry it. Before that gate existed nothing ever attached a scope to a /// role — the console worked because every signed-in account received identity:manage outright — /// so upgrading an existing installation would find the admin role empty and lock the only /// administrator out of their own console. This listener closes that gap: on startup, if the system /// admin role has no scopes attached at all, it attaches the management scope. /// /// /// Deliberately narrow. It fires only when the role's scope list is empty, so an operator who has /// curated that list — attached three granular scopes, or detached the master one on purpose — is /// never overruled. It attaches exactly one scope, the master one, because that is what the role /// already meant in every install that predates the gate; anything finer is the operator's call in /// Administration → Roles. And it touches only the admin role: everyone, /// impersonator and system keep whatever they were given. /// /// /// Runs after (which creates the role) and is idempotent: /// once the role has a scope, every later startup skips. Failure is logged and never blocks startup — /// but it is logged at warning level, because a failure here means an administrator may find the /// console refusing them. /// /// internal sealed class SeedAdminRoleScopesListener : IRouteLifecycleListener { private const string AdminRoleName = "admin"; private const string OrganizationAudience = "organization"; private readonly IServiceProvider _sp; private readonly IOptions _options; public SeedAdminRoleScopesListener(IServiceProvider sp, IOptions options) { _sp = sp; _options = options; } public async Task OnContextStarting(IRouteContext context, CancellationToken ct) { await using var scope = _sp.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); var logger = scope.ServiceProvider .GetRequiredService() .CreateLogger(); var managementScope = _options.Value.ManagementScope; if (string.IsNullOrWhiteSpace(managementScope)) { logger.LogWarning("SeedAdminRoleScopesListener: ManagementScope is not configured — skip."); return; } try { var adminRole = await redb.Query() .WhereRedb(o => o.Name == AdminRoleName) .Where(p => p.Audience == OrganizationAudience) .FirstOrDefaultAsync() .ConfigureAwait(false); if (adminRole is null) { logger.LogWarning( "SeedAdminRoleScopesListener: admin role not seeded — SeedSystemRolesListener must run first."); return; } var roleSvc = new RoleService(redb); var attached = await roleSvc.ListScopeIdsForRoleAsync(adminRole.Id, ct).ConfigureAwait(false); if (attached.Count > 0) { logger.LogDebug( "SeedAdminRoleScopesListener: admin role (id {RoleId}) already carries {Count} scope(s) — leaving it alone.", adminRole.Id, attached.Count); return; } // The scope registry holds one object per scope name; V4-UNIQUE keeps ScopeName unique, // and value_string carries the same name on rows written before that. var scopeObj = await redb.Query() .WhereRedb(o => o.Name == managementScope) .FirstOrDefaultAsync() .ConfigureAwait(false) ?? await redb.Query() .Where(p => p.ScopeName == managementScope) .FirstOrDefaultAsync() .ConfigureAwait(false); if (scopeObj is null) { logger.LogWarning( "SeedAdminRoleScopesListener: scope '{Scope}' is not in the registry — the admin role stays without scopes, " + "and administrators will be refused administrative scopes until it is attached in Administration -> Roles.", managementScope); return; } await roleSvc.AttachScopeAsync(adminRole.Id, scopeObj.Id, actingUserId: null, ct).ConfigureAwait(false); logger.LogWarning( "redb.Identity: attached '{Scope}' to the system admin role (role id {RoleId}, scope id {ScopeId}). " + "Administrative scopes are now issued only to users whose roles carry them; adjust the set in Administration -> Roles.", managementScope, adminRole.Id, scopeObj.Id); } catch (Exception ex) { logger.LogWarning(ex, "SeedAdminRoleScopesListener: failed to attach '{Scope}' to the admin role — administrators may be refused " + "administrative scopes until it is attached manually in Administration -> Roles.", managementScope); } } } Path: redb-identity/src/redb.Identity.Core/Module/SeedSystemRolesListener.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/SeedSystemRolesListener.cs ---- using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Core; using redb.Identity.Core.Models; using redb.Identity.Core.Services; using redb.Route.Abstractions; namespace redb.Identity.Core.Module; /// /// B.3 — seed the four canonical built-in roles (system / everyone / admin / /// impersonator) on every Identity startup. Idempotent: skips any role that /// already exists by name + audience. Operators can rename DisplayName or /// Description through the admin API, but the API blocks delete on /// IsSystem=true (RoleService.DeleteRoleAsync), so the seed stays /// authoritative for the "what roles ship with Identity" answer. /// internal sealed class SeedSystemRolesListener : IRouteLifecycleListener { private readonly IServiceProvider _sp; public SeedSystemRolesListener(IServiceProvider sp) => _sp = sp; public async Task OnContextStarting(IRouteContext context, CancellationToken ct) { await using var scope = _sp.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); var logger = scope.ServiceProvider .GetRequiredService() .CreateLogger(); var svc = new RoleService(redb); var defaults = new (string Name, string DisplayName, string Description)[] { ("system", "System", "Process-level identity used by background jobs and bootstrap. Never assigned to end users."), ("everyone", "Everyone", "Implicit role every authenticated user holds. Used as a default audience for org-wide claim emission."), ("admin", "Administrator", "Full administrative access to the Identity surface — manage users, applications, scopes, claim definitions, roles."), ("impersonator", "Impersonator", "Holders can mint act-as tokens for other users via the impersonation flow. Audit-tracked."), }; var created = 0; var skipped = 0; foreach (var (name, displayName, description) in defaults) { try { var existing = await redb.Query() .Where(p => p.Name == name) .Where(p => p.Audience == "organization") .FirstOrDefaultAsync() .ConfigureAwait(false); if (existing is not null) { skipped++; continue; } await svc.CreateRoleAsync( name, "organization", applicationId: null, displayName: displayName, description: description, isSystem: true, ct).ConfigureAwait(false); created++; } catch (Exception ex) { logger.LogWarning(ex, "SeedSystemRolesListener: failed to seed system role '{Name}' — operator can recreate via admin API", name); } } logger.LogInformation( "redb.Identity: system roles seed complete (created={Created} skipped={Skipped})", created, skipped); } } Path: redb-identity/src/redb.Identity.Core/Module/SeedSystemScopesListener.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/SeedSystemScopesListener.cs ---- using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Core; using redb.Core.Models.Entities; using redb.Core.Query; using redb.Identity.Contracts.Configuration; using redb.Identity.Core.Models; using redb.Route.Abstractions; namespace redb.Identity.Core.Module; /// /// Seed the static catalogue into the /// identity.scope store on every startup. Without this the role- /// permission picker on /admin/roles/{id} can only attach scopes /// that some demo or operator explicitly created via the admin API. /// Idempotent: skips any scope already present — one probe of the /// [RedbUnique] ScopeName index (V4-UNIQUE). /// /// Descriptions read like operator-facing UI labels because the picker /// surfaces them verbatim. Order in the seed array dictates picker /// ordering within a resource group. /// internal sealed class SeedSystemScopesListener : IRouteLifecycleListener { private readonly IServiceProvider _sp; public SeedSystemScopesListener(IServiceProvider sp) => _sp = sp; public async Task OnContextStarting(IRouteContext context, CancellationToken ct) { await using var scope = _sp.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); var logger = scope.ServiceProvider .GetRequiredService() .CreateLogger(); var defaults = new (string Name, string Description)[] { // Universal (IdentityScopes.Manage, "Full administrative access — implies every granular scope below."), (IdentityScopes.Account, "Self-service — token may target only the owning user's /me endpoints."), (IdentityScopes.ReadOnly, "Read-only admin — GET on any management endpoint, mutations rejected."), // Users surface (IdentityScopes.UsersRead, "Read users and group memberships."), (IdentityScopes.UsersWrite, "Create, update, delete users; manage group memberships."), (IdentityScopes.GroupsRead, "Read groups and their hierarchy."), (IdentityScopes.GroupsWrite, "Create, update, delete groups and members."), (IdentityScopes.ConsentsRead, "Read users' OAuth consents."), (IdentityScopes.ConsentsWrite, "Revoke users' OAuth consents on their behalf."), (IdentityScopes.MfaRead, "Read users' MFA enrolment status."), (IdentityScopes.MfaWrite, "Reset, replace, disable users' MFA enrolments."), // Application / OIDC config surface (IdentityScopes.ApplicationsRead, "Read OAuth/OIDC applications and clients."), (IdentityScopes.ApplicationsWrite, "Create, update, delete applications; rotate client secrets."), (IdentityScopes.ScopesRead, "Read OAuth scope definitions."), (IdentityScopes.ScopesWrite, "Create, update, delete OAuth scopes."), (IdentityScopes.RolesRead, "Read roles, assignees, and attached scopes."), (IdentityScopes.RolesWrite, "Create, update, delete roles; assign users/groups; attach scopes."), (IdentityScopes.ClaimsRead, "Read claim mappers, definitions, and scope assignments."), (IdentityScopes.ClaimsWrite, "Create, update, delete claim mappers, definitions, and scope assignments."), (IdentityScopes.FederationRead, "Read external identity providers (Google, Microsoft, OIDC, SAML)."), (IdentityScopes.FederationWrite, "Create, update, delete external identity provider configurations."), (IdentityScopes.WebhooksRead, "Read outbound webhook subscriptions."), (IdentityScopes.WebhooksWrite, "Create, update, delete webhook subscriptions; rotate HMAC secrets."), (IdentityScopes.SigningKeysRead, "Read the JWKS catalogue and key metadata."), (IdentityScopes.SigningKeysWrite, "Rotate, retire, deactivate signing keys."), // Runtime surface (IdentityScopes.SessionsRead, "Read user sessions across all subjects."), (IdentityScopes.SessionsWrite, "Revoke sessions and manage the revoked-sid blacklist."), (IdentityScopes.TokensRead, "Read issued OAuth tokens (admin browse)."), (IdentityScopes.TokensWrite, "Revoke and prune issued OAuth tokens."), (IdentityScopes.AuditRead, "Read the immutable identity audit log."), (IdentityScopes.Impersonate, "Mint impersonate-as tokens (RFC 8693 token exchange with act claim)."), }; var created = 0; var skipped = 0; foreach (var (name, description) in defaults) { try { var existing = await redb.GetByUniqueAsync(p => p.ScopeName, name) .ConfigureAwait(false); if (existing is not null) { skipped++; continue; } var obj = new RedbObject(new ScopeProps { ScopeName = name, Description = description, }); obj.Name = name; await redb.SaveAsync(obj).ConfigureAwait(false); created++; } catch (Exception ex) { logger.LogWarning(ex, "SeedSystemScopesListener: failed to seed system scope '{Name}' — picker UX will be missing it.", name); } } logger.LogInformation( "redb.Identity: system scopes seed complete (created={Created} skipped={Skipped})", created, skipped); } } Path: redb-identity/src/redb.Identity.Core/Module/SigningKeyInitListener.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/SigningKeyInitListener.cs ---- using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Identity.Core.Configuration; using redb.Identity.Core.Keys; using redb.Route.Abstractions; namespace redb.Identity.Core.Module; /// /// A3: seeds the PROPS signing / encryption key store () /// before the HTTP facade serves the first token request. Required so that the first /// /connect/token call does not force OpenIddict to fall back to an ephemeral in-memory /// key (which would split the JWKS across cluster replicas and invalidate tokens on restart). /// /// Must run AFTER RedbXmlRepositoryInitListener because the PROPS store encrypts private /// PEM material with the DataProtection key ring that RedbXmlRepository loads — if the /// ring is empty, DataProtection will lazily generate its first key here, which is fine. /// /// /// Cluster coordination (A3 + A6 gap — G12 "distributed-lock on kid"): when /// IDistributedLock is registered in the root service provider (i.e. when /// Tsak:Cluster:Enabled=true and Pro cluster primitives are available), acquires an /// exclusive short-TTL lock (identity:keys-init) before invoking /// so that a cold-start of N replicas /// against an empty key store does not result in N concurrent check-then-write paths each /// generating its own kid → N active keys per kind → JWKS key-set bloat + 90-day rotation /// cliff when all N expire together. Mirrors (A6). /// In standalone (the DI service is absent) the coordination block is a no-op — within a /// single process only one lifecycle callback runs, so no in-process race is possible. /// /// internal sealed class SigningKeyInitListener : IRouteLifecycleListener { private readonly IServiceProvider _sp; public SigningKeyInitListener(IServiceProvider sp) => _sp = sp; public async Task OnContextStarting(IRouteContext context, CancellationToken ct) { await using var scope = _sp.CreateAsyncScope(); var options = scope.ServiceProvider .GetRequiredService>() .Value; if (!options.UsePropsSigningKeyStore) return; var store = scope.ServiceProvider.GetRequiredService(); var logger = scope.ServiceProvider .GetRequiredService() .CreateLogger(); // Cluster lock — duck-typed via reflection so redb.Identity.Core stays clean of a // compile-time reference to redb.Tsak.Core.Pro. Presence of the service indicates // Tsak:Cluster:Enabled=true. See IdentitySchemaInitListener (A6) for the reference // pattern; both listeners must use identical acquire/release plumbing because a drift // would silently break cluster coordination on one of them. var lockService = TryResolveDistributedLock(_sp); var nodeId = Environment.MachineName; object? acquired = null; if (lockService is not null) { acquired = await TryAcquireDistributedLockAsync(lockService, "identity:keys-init", nodeId, ttlSeconds: 120, ct) .ConfigureAwait(false); logger.LogInformation( acquired is null ? "redb.Identity: signing-key init — follower; another replica is bootstrapping, will no-op via idempotent check" : "redb.Identity: signing-key init — leader under cluster lock identity:keys-init"); } try { await store.EnsureBootstrappedAsync("signing", ct).ConfigureAwait(false); // Both kinds, always. DisableAccessTokenEncryption leaves only access tokens as plain JWS; // authorization codes, refresh tokens, device and user codes and OpenIddict's state tokens are // encrypted whatever it says, and OpenIddict refuses to build its options without an encryption // credential. A store with a signing key and no encryption key is a server that cannot start. await store.EnsureBootstrappedAsync("encryption", ct).ConfigureAwait(false); var materials = await store.GetAllAsync(ct).ConfigureAwait(false); logger.LogInformation( "redb.Identity: PROPS signing-key store ready ({Count} key(s) loaded)", materials.Length); } finally { if (lockService is not null && acquired is not null) { await ReleaseDistributedLockAsync(lockService, "identity:keys-init", nodeId, ct) .ConfigureAwait(false); } } } private static object? TryResolveDistributedLock(IServiceProvider sp) { // Resolve redb.Tsak.Core.Pro.Cluster.Contracts.IDistributedLock without a compile-time // reference — Identity.Core must build regardless of Pro presence. var type = Type.GetType( "redb.Tsak.Core.Pro.Cluster.Contracts.IDistributedLock, redb.Tsak.Core.Pro", throwOnError: false); return type is null ? null : sp.GetService(type); } private static async Task TryAcquireDistributedLockAsync( object lockService, string name, string nodeId, int ttlSeconds, CancellationToken ct) { var method = lockService.GetType().GetMethod("TryAcquireAsync") ?? throw new InvalidOperationException("IDistributedLock.TryAcquireAsync not found."); var task = (Task?)method.Invoke(lockService, [name, nodeId, "identity", ttlSeconds, ct]) ?? throw new InvalidOperationException("IDistributedLock.TryAcquireAsync returned null."); await task.ConfigureAwait(false); var result = task.GetType().GetProperty("Result")?.GetValue(task); var isAcquired = (bool?)(result?.GetType().GetProperty("Acquired")?.GetValue(result)) ?? false; return isAcquired ? result : null; } private static async Task ReleaseDistributedLockAsync( object lockService, string name, string nodeId, CancellationToken ct) { var method = lockService.GetType().GetMethod("ReleaseAsync") ?? throw new InvalidOperationException("IDistributedLock.ReleaseAsync not found."); var task = (Task?)method.Invoke(lockService, [name, nodeId, "identity", ct]); if (task is not null) await task.ConfigureAwait(false); } } Path: redb-identity/src/redb.Identity.Core/Module/V4UniqueBackfillListener.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/V4UniqueBackfillListener.cs ---- using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Core; using redb.Core.Exceptions; using redb.Core.Models.Entities; using redb.Core.Query; using redb.Identity.Core.Models; using redb.Route.Abstractions; namespace redb.Identity.Core.Module; /// /// V4-UNIQUE transition backfill. Pre-V4 the unique keys of Identity schemes /// lived only in the _objects.value_string mirror while the Props property was a /// [RedbIgnore] phantom — so existing rows have NO _values value and therefore /// no _unique hash, and the new GetByUniqueAsync lookups cannot see them. /// This listener copies the mirror into Props and re-saves, which computes the unique key. /// /// /// Idempotent by construction, no completion flag: a repaired row drops out of the candidate /// set (Props value equals the mirror), so a re-run converges to a no-op. Candidates are rows /// with a non-NULL mirror; after teardown new rows stop carrying the mirror, /// so the set shrinks to legacy rows only and empties as they are re-saved or TTL-reaped. /// /// /// /// A duplicate discovered during backfill (possible for the schemes that never actually had /// an index — ClaimScope, FederatedIdentity, FederationProvider) surfaces as /// : it is logged with both /// ids and the loser keeps a NULL key (outside the index) for manual review. Federated-link /// duplicates are logged as errors — two users holding one external identity is a potential /// account-takeover and must reach the operator. /// /// /// Registered in redb.Identity.Core.Module.InitRoute after /// (schemes exist) and BEFORE the seed listeners — the seeds look up by unique key now, and /// must see legacy seeded rows as repaired, not recreate them. /// internal sealed class V4UniqueBackfillListener : IRouteLifecycleListener { /// /// Convergence flag: without it every boot /// re-loads every candidate row of every scheme — all user-ext rows included — for ever. /// Once one boot has backfilled every scheme clean and dropped the retired indexes, this /// SystemFlag row short-circuits all later boots. Versioned name: bump the suffix if /// schemes are ever added to this listener. Delete the row to force a re-run. /// internal const string ConvergedFlagName = "v4_unique_backfill_done:v1"; private readonly IServiceProvider _sp; public V4UniqueBackfillListener(IServiceProvider sp) => _sp = sp; public async Task OnContextStarting(IRouteContext context, CancellationToken ct) { await using var scope = _sp.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); var logger = scope.ServiceProvider .GetRequiredService() .CreateLogger(); try { var converged = await redb.Query() .WhereRedb(o => o.ValueUnique == ConvergedFlagName) .FirstOrDefaultAsync() .ConfigureAwait(false); if (converged is not null) { logger.LogDebug("V4-UNIQUE backfill: already converged, skipping."); return; } } catch (Exception ex) { // A failed probe (fresh database, scheme not there yet) just means running the // idempotent pass below. logger.LogDebug(ex, "V4-UNIQUE backfill: convergence probe failed; running the pass."); } await RunPassIgnoringConvergenceAsync(scope.ServiceProvider, redb, logger, ct).ConfigureAwait(false); } // ── Test seams (V4Unique backfill tests): repair EXACTLY ONE scheme ───────────── // On the process-shared SQLite database the test classes run in parallel; a full // gate-free pass from one class also repairs the other classes' freshly-created // legacy rows, and two concurrent full passes over the same row produced // false-duplicate unique collisions and stale-snapshot overwrites (the // ordering-dependent failures of 2026-09-08). A single-scheme pass touches only the // calling test's rows; the full pass stays private to the production gate above. internal Task RunMirrorSchemeAsync( Func getKey, Action setKey, CancellationToken ct) where TProps : class, new() => RunOneAsync((redb, logger) => BackfillMirrorAsync(redb, logger, getKey, setKey, ct)); internal Task RunUserKeySchemeAsync( Func getKey, Action setKey, CancellationToken ct) where TProps : class, new() => RunOneAsync((redb, logger) => BackfillUserKeyAsync(redb, logger, getKey, setKey, ct)); internal Task RunValueUniqueSchemeAsync( Func transform, CancellationToken ct) where TProps : class, new() => RunOneAsync((redb, logger) => BackfillValueUniqueAsync(redb, logger, transform, ct)); private async Task RunOneAsync(Func> pass) { await using var scope = _sp.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); var logger = scope.ServiceProvider .GetRequiredService() .CreateLogger(); return await pass(redb, logger).ConfigureAwait(false); } private async Task RunPassIgnoringConvergenceAsync( IServiceProvider scopedSp, IRedbService redb, ILogger logger, CancellationToken ct) { var clean = true; // F1 schemes: key was mirrored in value_string, Props was the [RedbIgnore] phantom. clean &= await BackfillMirrorAsync(redb, logger, p => p.ClientId, (p, v) => p.ClientId = v, ct).ConfigureAwait(false); clean &= await BackfillMirrorAsync(redb, logger, p => p.ScopeName, (p, v) => p.ScopeName = v, ct).ConfigureAwait(false); clean &= await BackfillMirrorAsync(redb, logger, p => p.ScopeName, (p, v) => p.ScopeName = v, ct).ConfigureAwait(false); clean &= await BackfillMirrorAsync(redb, logger, p => p.ReferenceId, (p, v) => p.ReferenceId = v, ct).ConfigureAwait(false); // F2 schemes: these two never actually had an index, so this is the // first time their keys become enforceable — duplicates are EXPECTED to be possible // here and every one is a finding for the operator (a duplicated federated link is // a potential account-takeover vector, see the class doc). clean &= await BackfillMirrorAsync(redb, logger, p => p.LinkKey, (p, v) => p.LinkKey = v, ct).ConfigureAwait(false); clean &= await BackfillMirrorAsync(redb, logger, p => p.ProviderId is { Length: > 0 } pid ? pid : null, (p, v) => p.ProviderId = v ?? string.Empty, ct).ConfigureAwait(false); // F3 key-mirror schemes: the key is the numeric _objects._key, copied // into the [RedbUnique] UserId prop. clean &= await BackfillUserKeyAsync(redb, logger, p => p.UserId, (p, v) => p.UserId = v, ct).ConfigureAwait(false); clean &= await BackfillUserKeyAsync(redb, logger, p => p.UserId, (p, v) => p.UserId = v, ct).ConfigureAwait(false); // F3 ValueUnique schemes: the key is the root _name (SystemFlag) or its // SHA-256 (IdempotencyRecord); Props are not touched. clean &= await BackfillValueUniqueAsync(redb, logger, name => name, ct).ConfigureAwait(false); clean &= await BackfillValueUniqueAsync(redb, logger, Routes.Processors.IdempotencyKeyHash.Sha256Hex, ct).ConfigureAwait(false); // ── Teardown: drop the retired pre-V4 indexes — but only // after EVERY scheme backfilled without a scheme-level failure. A failed scheme // keeps the old indexes one more boot (idempotent retry) so its rows are never // left without either enforcement. Duplicate findings do NOT block the drop: // dropping an index that never guarded those schemes changes nothing for them. if (clean) { await DropRetiredIndexesAsync(scopedSp, redb, logger).ConfigureAwait(false); // Mark convergence — first-wins across racing nodes. try { var flag = new RedbObject(new IdentitySystemFlagProps()); flag.Name = ConvergedFlagName; flag.ValueUnique = ConvergedFlagName; flag.value_bool = true; flag.value_datetime = DateTime.UtcNow; flag.note = "V4-UNIQUE transition backfill converged; the listener now no-ops. " + "Delete this row to force a re-run."; await redb.SaveAsync(flag).ConfigureAwait(false); } catch (RedbUniqueViolationException) { // Another node converged concurrently — same outcome. } catch (Exception ex) { logger.LogWarning(ex, "V4-UNIQUE: converged, but the flag row could not be written; the (idempotent) " + "pass will re-run on the next boot."); } } else { logger.LogWarning( "V4-UNIQUE: at least one scheme's backfill failed — the retired pre-V4 indexes are " + "kept for this boot and the whole pass retries on the next start."); } } /// The pre-V4 indexes replaced by core primitives. Only /// UX_users_email stays. UX_route_idempotent_entry_name joined the /// retired set on 2026-09-02, when Route's own fix (816a3d2a) shipped ValueUnique + the /// typed catch in RedbIdempotentRepository. private static readonly string[] RetiredIndexes = [ "UX_identity_application_client_id", "UX_identity_scope_name", "UX_identity_token_reference_id", "UX_identity_mfa_user_id", "UX_identity_user_ext_user_id", "UX_identity_idempotency_record_name", "UX_identity_system_flag_name", "UX_route_idempotent_entry_name", ]; private static async Task DropRetiredIndexesAsync( IServiceProvider scopedSp, IRedbService redb, ILogger logger) { var dialect = scopedSp.GetRequiredService(); var isMsSql = string.Equals(dialect.ProviderName, "MSSql", StringComparison.OrdinalIgnoreCase) || string.Equals(dialect.ProviderName, "SqlServer", StringComparison.OrdinalIgnoreCase); foreach (var name in RetiredIndexes) { var sql = isMsSql ? $"IF EXISTS (SELECT 1 FROM sys.indexes WHERE name = '{name}') DROP INDEX [{name}] ON [_objects]" : $"DROP INDEX IF EXISTS \"{name}\""; try { await redb.Context.ExecuteAsync(sql).ConfigureAwait(false); } catch (Exception ex) { // A role without DDL rights degrades to a leftover (harmless) index; hand the // operator the exact statement instead of failing the boot — same contract the // index CREATION always had. logger.LogError(ex, "V4-UNIQUE: could not drop retired index '{Index}'. Run manually: {Sql}", name, sql); } } logger.LogInformation("V4-UNIQUE: retired pre-V4 unique indexes dropped (idempotent)."); } /// /// F3 variant of : the pre-V4 key lives in the /// numeric _objects._key (MfaProps, UserProps ext), copied into the /// [RedbUnique] UserId prop. Same idempotence-by-construction: a repaired row /// (Props.UserId == key) drops out. /// private static async Task BackfillUserKeyAsync( IRedbService redb, ILogger logger, Func getKey, Action setKey, CancellationToken ct) where TProps : class, new() { try { await redb.SyncSchemeAsync().ConfigureAwait(false); var candidates = await redb.Query() .WhereRedb(o => o.Key != null) .ToListAsync() .ConfigureAwait(false); var repaired = 0; var duplicates = 0; foreach (var obj in candidates) { ct.ThrowIfCancellationRequested(); if (obj.key is not { } key || getKey(obj.Props) == key) continue; setKey(obj.Props, key); try { await redb.SaveAsync(obj).ConfigureAwait(false); repaired++; } catch (RedbUniqueViolationException ex) { duplicates++; logger.LogError(ex, "V4-UNIQUE backfill: DUPLICATE user key {Key} in {Scheme} — object {Id} keeps a NULL " + "unique key (outside the index) and needs manual review.", key, typeof(TProps).Name, obj.id); } } if (repaired > 0 || duplicates > 0) logger.LogInformation( "V4-UNIQUE backfill {Scheme}: candidates={Candidates} repaired={Repaired} duplicates={Duplicates}", typeof(TProps).Name, candidates.Count, repaired, duplicates); return true; } catch (Exception ex) { logger.LogError(ex, "V4-UNIQUE backfill failed for {Scheme}.", typeof(TProps).Name); return false; } } /// /// F3 variant for root-only schemes: the pre-V4 key lives in _objects._name and the /// enforced key is ValueUnique = transform(_name) (identity for SystemFlag, SHA-256 /// for IdempotencyRecord). Props are never touched — SystemFlag has none by design. /// private static async Task BackfillValueUniqueAsync( IRedbService redb, ILogger logger, Func transform, CancellationToken ct) where TProps : class, new() { try { await redb.SyncSchemeAsync().ConfigureAwait(false); var candidates = await redb.Query() .WhereRedb(o => o.Name != null) .ToListAsync() .ConfigureAwait(false); var repaired = 0; var duplicates = 0; foreach (var obj in candidates) { ct.ThrowIfCancellationRequested(); if (obj.name is not { } name || obj.ValueUnique is not null) continue; obj.ValueUnique = transform(name); try { await redb.SaveAsync(obj).ConfigureAwait(false); repaired++; } catch (RedbUniqueViolationException ex) { duplicates++; logger.LogError(ex, "V4-UNIQUE backfill: DUPLICATE root key '{Name}' in {Scheme} — object {Id} keeps a NULL " + "ValueUnique (outside the index) and needs manual review.", name, typeof(TProps).Name, obj.id); } } if (repaired > 0 || duplicates > 0) logger.LogInformation( "V4-UNIQUE backfill {Scheme}: candidates={Candidates} repaired={Repaired} duplicates={Duplicates}", typeof(TProps).Name, candidates.Count, repaired, duplicates); return true; } catch (Exception ex) { logger.LogError(ex, "V4-UNIQUE backfill failed for {Scheme}.", typeof(TProps).Name); return false; } } /// /// Repairs one scheme: every row whose value_string mirror is set but whose Props /// key does not match gets the mirror copied into Props and is re-saved (the save computes /// the _unique hash). The candidate query is by the indexed base field; the /// props-vs-mirror comparison is in memory on purpose — a legacy row has no /// _values row at all, and a server-side Props == null filter would have to /// distinguish "value IS NULL" from "no row", which this code must not depend on. /// private static async Task BackfillMirrorAsync( IRedbService redb, ILogger logger, Func getKey, Action setKey, CancellationToken ct) where TProps : class, new() { try { await redb.SyncSchemeAsync().ConfigureAwait(false); var candidates = await redb.Query() .WhereRedb(o => o.ValueString != null) .ToListAsync() .ConfigureAwait(false); var repaired = 0; var duplicates = 0; foreach (var obj in candidates) { ct.ThrowIfCancellationRequested(); var mirror = obj.value_string; if (mirror is null || getKey(obj.Props) == mirror) continue; // already repaired (or a fresh dual-write row) setKey(obj.Props, mirror); try { await redb.SaveAsync(obj).ConfigureAwait(false); repaired++; } catch (RedbUniqueViolationException ex) { duplicates++; // R4(a): report, leave the loser outside the index, keep going. // The prop value at the moment of failure is logged next to the mirror: when the two // agree the value was intact and the rejected key was computed wrongly; when they // differ the object carried another object's value (2026-09-10 MSSQL full-run triage). logger.LogError(ex, "V4-UNIQUE backfill: DUPLICATE key '{Key}' in {Scheme} — object {Id} keeps a NULL " + "unique key (outside the index) and needs manual review. Prop value at failure: '{PropValue}'.", mirror, typeof(TProps).Name, obj.id, getKey(obj.Props)); } } if (repaired > 0 || duplicates > 0) logger.LogInformation( "V4-UNIQUE backfill {Scheme}: candidates={Candidates} repaired={Repaired} duplicates={Duplicates}", typeof(TProps).Name, candidates.Count, repaired, duplicates); return true; } catch (Exception ex) { // Do not abort the bootstrap: an unfilled scheme degrades to "legacy rows invisible // to unique lookups" — visible and diagnosable — rather than a dead host. logger.LogError(ex, "V4-UNIQUE backfill failed for {Scheme}.", typeof(TProps).Name); return false; } } } Path: redb-identity/src/redb.Identity.Core/OpenIddict/Handlers/ApplyAuthorizationResponseHandler.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/OpenIddict/Handlers/ApplyAuthorizationResponseHandler.cs ---- using System.Net; using System.Text; using OpenIddict.Abstractions; using OpenIddict.Server; using redb.Route.Http; using static OpenIddict.Server.OpenIddictServerEvents; namespace redb.Identity.Core.OpenIddict.Handlers; /// /// Writes the authorization response to . /// Handles OIDC response_mode dispatch: /// /// query → 302 redirect with parameters in URL query string. /// fragment → 302 redirect with parameters in URL fragment. /// form_post → 200 HTML page with auto-submit form (OIDC FAPI form_post §1). /// /// When RedirectUri is absent (e.g. validation errors before redirect resolution), /// the response is emitted as JSON for the OAuth wire profile. /// internal sealed class ApplyAuthorizationResponseHandler : IOpenIddictServerHandler { public static OpenIddictServerHandlerDescriptor Descriptor { get; } = OpenIddictServerHandlerDescriptor.CreateBuilder() .UseSingletonHandler() .SetOrder(int.MaxValue - 50_000) .Build(); public ValueTask HandleAsync(ApplyAuthorizationResponseContext context) { var exchange = context.Transaction.GetRouteExchange(); if (exchange is null) return default; var redirectUri = context.RedirectUri; // OpenIddict does not auto-populate context.RedirectUri when a Reject() fires from // the HandleAuthorizationRequest stage (e.g. prompt=none → login_required, consent_required). // RFC 6749 §4.1.2.1 requires errors to be reported via the validated redirect_uri whenever // possible — so when we have an error AND the request carried a validated redirect_uri, // promote it as the response target. We only do this when the response actually carries // an error code, so success paths still rely on OpenIddict's canonical population. if (string.IsNullOrEmpty(redirectUri) && !string.IsNullOrEmpty(context.Response.Error)) { redirectUri = context.Request?.RedirectUri; } if (string.IsNullOrEmpty(redirectUri)) { // No redirect target — emit JSON (e.g. invalid_request before client/redirect resolution). RedbRouteOpenIddictServerHelpers.WriteResponseToExchange(exchange, context.Response); context.HandleRequest(); return default; } // For non-HTTP callers (direct-vm, tests) there is no browser to follow a redirect. // Return the response parameters as a JSON dict so callers can read code/state directly. // Browser requests always carry redbHttp.Method (set by the HTTP consumer). if (!exchange.In.Headers.ContainsKey(HttpHeaders.Method)) { RedbRouteOpenIddictServerHelpers.WriteResponseToExchange(exchange, context.Response); context.HandleRequest(); return default; } // Default response_mode per OIDC §3.1.2.1: query for code flow, fragment for implicit/hybrid. var mode = context.ResponseMode; if (string.IsNullOrEmpty(mode)) mode = "query"; switch (mode) { case "form_post": EmitFormPost(exchange, redirectUri, context.Response); break; case "fragment": EmitRedirect(exchange, redirectUri, context.Response, useFragment: true); break; default: // "query" EmitRedirect(exchange, redirectUri, context.Response, useFragment: false); break; } context.HandleRequest(); return default; } private static void EmitRedirect( redb.Route.Abstractions.IExchange exchange, string redirectUri, OpenIddictResponse response, bool useFragment) { var query = BuildQueryString(response); string location; if (useFragment) { location = redirectUri + "#" + query; } else { var sep = redirectUri.Contains('?') ? "&" : "?"; location = redirectUri + sep + query; } EnsureOut(exchange); var msg = exchange.Out!; // Empty byte[] body so HttpConsumer copies headers (it skips header copy when Body is null). msg.Body = Array.Empty(); msg.Headers[HttpHeaders.ResponseCode] = 302; msg.Headers["Location"] = location; } private static void EmitFormPost( redb.Route.Abstractions.IExchange exchange, string redirectUri, OpenIddictResponse response) { var sb = new StringBuilder(512); sb.Append("Submit"); sb.Append("
"); foreach (var p in response.GetParameters()) { if (p.Value.GetRawValue() is null) continue; var value = p.Value.ToString(); if (value is null) continue; sb.Append(""); } sb.Append(""); sb.Append("
"); EnsureOut(exchange); var msg = exchange.Out!; msg.Body = Encoding.UTF8.GetBytes(sb.ToString()); msg.ContentType = "text/html; charset=utf-8"; msg.Headers[HttpHeaders.ResponseCode] = 200; msg.Headers[HttpHeaders.ResponseContentType] = "text/html; charset=utf-8"; } private static string BuildQueryString(OpenIddictResponse response) { var sb = new StringBuilder(); var first = true; foreach (var p in response.GetParameters()) { if (p.Value.GetRawValue() is null) continue; var value = p.Value.ToString(); if (value is null) continue; if (!first) sb.Append('&'); first = false; sb.Append(Uri.EscapeDataString(p.Key)); sb.Append('='); sb.Append(Uri.EscapeDataString(value)); } return sb.ToString(); } private static void EnsureOut(redb.Route.Abstractions.IExchange exchange) { if (exchange.Out is not null) return; exchange.Pattern = redb.Route.Abstractions.ExchangePattern.InOut; exchange.Out = exchange.In.Clone(); exchange.Out.Body = null; exchange.Out.Headers.Clear(); } } Path: redb-identity/src/redb.Identity.Core/OpenIddict/Handlers/ApplyDeviceResponseHandler.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/OpenIddict/Handlers/ApplyDeviceResponseHandler.cs ---- using OpenIddict.Server; using static OpenIddict.Server.OpenIddictServerEvents; namespace redb.Identity.Core.OpenIddict.Handlers; /// /// Writes the device authorization response to . /// internal sealed class ApplyDeviceResponseHandler : IOpenIddictServerHandler { public static OpenIddictServerHandlerDescriptor Descriptor { get; } = OpenIddictServerHandlerDescriptor.CreateBuilder() .UseSingletonHandler() .SetOrder(int.MaxValue - 50_000) .Build(); public ValueTask HandleAsync(ApplyDeviceAuthorizationResponseContext context) { var exchange = context.Transaction.GetRouteExchange(); if (exchange is null) return default; RedbRouteOpenIddictServerHelpers.WriteResponseToExchange(exchange, context.Response); context.HandleRequest(); return default; } } Path: redb-identity/src/redb.Identity.Core/OpenIddict/Handlers/ApplyDiscoveryResponseHandler.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/OpenIddict/Handlers/ApplyDiscoveryResponseHandler.cs ---- using System.Text.Json; using Microsoft.Extensions.Options; using OpenIddict.Server; using redb.Identity.Core.Configuration; using static OpenIddict.Server.OpenIddictServerEvents; namespace redb.Identity.Core.OpenIddict.Handlers; /// /// Writes the OpenID Connect discovery document response to . /// Maps to the .well-known/openid-configuration endpoint. /// internal sealed class ApplyDiscoveryResponseHandler : IOpenIddictServerHandler { private readonly RedbIdentityOptions _identityOptions; public ApplyDiscoveryResponseHandler(IOptions identityOptions) { _identityOptions = identityOptions.Value; } public static OpenIddictServerHandlerDescriptor Descriptor { get; } = OpenIddictServerHandlerDescriptor.CreateBuilder() .UseScopedHandler() .SetOrder(int.MaxValue - 50_000) .Build(); public ValueTask HandleAsync(ApplyConfigurationResponseContext context) { var exchange = context.Transaction.GetRouteExchange(); if (exchange is null) return default; // Add end_session_endpoint (logout is handled by LogoutProcessor, not OpenIddict pipeline) if (context.Options?.Issuer is not null) { var issuer = context.Options.Issuer.ToString().TrimEnd('/'); context.Response["end_session_endpoint"] = $"{issuer}/connect/logout"; // RFC 9126 §5 — advertise the PAR endpoint URL so clients can locate it without // hard-coding the path. OpenIddict's built-in discovery handler does NOT emit // `pushed_authorization_request_endpoint` even when PAR is wired (it surfaces // only the auth-methods list), so we add the URL here. The companion // `require_pushed_authorization_requests` flag is emitted only when the global // enforcement is on; per-client enforcement is not advertised globally because // it's a property of individual client registrations, not the AS. if (_identityOptions.Features.EnablePushedAuthorization) { context.Response["pushed_authorization_request_endpoint"] = $"{issuer}/connect/par"; if (_identityOptions.RequirePushedAuthorizationRequests) context.Response["require_pushed_authorization_requests"] = true; } } // OIDC Back-Channel Logout: we support RP-Initiated Logout via end_session_endpoint. // frontchannel_logout is NOT advertised — no iframe-based logout endpoint is implemented. // Per OIDC Back-Channel Logout 1.0 §3, advertise backchannel_logout_supported when // BackchannelLogoutDispatcher is wired (which it always is from C8 onwards). The // session-id ('sid') claim is included only when the RP opts in via // backchannel_logout_session_required on its client metadata, so we advertise the // session_supported flag accordingly. context.Response["backchannel_logout_supported"] = true; context.Response["backchannel_logout_session_supported"] = true; // OIDC Discovery §3 — claim types: we only emit Normal claims (no aggregated/distributed). context.Response["claim_types_supported"] = JsonSerializer.Deserialize("[\"normal\"]"); // OIDC Discovery §3 / Core §5.5 — the `claims` request parameter is honoured at // /connect/authorize for both the `userinfo` and `id_token` members, including the // `essential`, `value` and `values` qualifiers. OpenIddict does not implement the parameter // and hard-codes this flag to false, so RemoveParameter first — otherwise the two values // merge and the document ships a contradiction. // // This flag is a promise a reader can check in ten seconds with a single curl. It says true // only because AttachSessionPrincipalHandler + IdentityPrincipalBuilder + this document's // own claims_supported list actually deliver on it. context.Response.RemoveParameter("claims_parameter_supported"); context.Response["claims_parameter_supported"] = true; // OIDC Core §2 / §5.5.1.1 — advertise the acr values we can actually return. // IdentityPrincipalBuilder emits "1" (single-factor / password) or "2" (multi-factor // verified). "0" (no authentication) is currently unreachable, so it is not advertised. context.Response["acr_values_supported"] = JsonSerializer.Deserialize("[\"1\",\"2\"]"); // Client authentication methods. OpenIddict's built-in discovery under-reports the set // its client-auth pipeline actually accepts (empirically verified: client_secret_basic, // client_secret_post and private_key_jwt all succeed at /connect/token, and public // clients authenticate with 'none' via PKCE). Declare the real set explicitly so the // Basic OP conformance profile — which defaults to client_secret_basic and exercises // public/none clients — sees an accurate document. // • token endpoint : basic + post + private_key_jwt + none // • introspection / revocation: same confidential set WITHOUT 'none' — those // endpoints require an authenticated client (RFC 7662 / RFC 7009). context.Response.RemoveParameter("token_endpoint_auth_methods_supported"); context.Response["token_endpoint_auth_methods_supported"] = JsonSerializer.Deserialize( "[\"client_secret_basic\",\"client_secret_post\",\"private_key_jwt\",\"none\"]"); const string mgmtAuthMethods = "[\"client_secret_basic\",\"client_secret_post\",\"private_key_jwt\"]"; context.Response.RemoveParameter("introspection_endpoint_auth_methods_supported"); context.Response["introspection_endpoint_auth_methods_supported"] = JsonSerializer.Deserialize(mgmtAuthMethods); context.Response.RemoveParameter("revocation_endpoint_auth_methods_supported"); context.Response["revocation_endpoint_auth_methods_supported"] = JsonSerializer.Deserialize(mgmtAuthMethods); // RFC 8414 §2 / RFC 7591 §2 — when the server supports `private_key_jwt` // (or `client_secret_jwt`) it SHOULD advertise the JWS signing algorithms // it accepts on the JWT-bearer client assertion. OpenIddict 6 validates // assertions using its built-in IdentityModel-backed pipeline, which covers // RSA / ECDSA / RSA-PSS at standard hash widths. The same list applies to // /introspect and /revoke since those endpoints share the auth pipeline. var clientAssertionAlgs = JsonSerializer.Deserialize( "[\"RS256\",\"RS384\",\"RS512\",\"PS256\",\"PS384\",\"PS512\",\"ES256\",\"ES384\",\"ES512\"]"); context.Response.RemoveParameter("token_endpoint_auth_signing_alg_values_supported"); context.Response["token_endpoint_auth_signing_alg_values_supported"] = clientAssertionAlgs; context.Response.RemoveParameter("introspection_endpoint_auth_signing_alg_values_supported"); context.Response["introspection_endpoint_auth_signing_alg_values_supported"] = clientAssertionAlgs; context.Response.RemoveParameter("revocation_endpoint_auth_signing_alg_values_supported"); context.Response["revocation_endpoint_auth_signing_alg_values_supported"] = clientAssertionAlgs; // Z4 (RFC 9449 §5.1): advertise DPoP support and the supported signing algorithms. // OpenIddict's built-in discovery handler emits its own short list during the Handle // phase ([ES256, ES384, PS256, RS256]); when we set our (typically wider) list here // via the indexer, OpenIddictParameter merges array-typed parameters instead of // replacing them — producing a duplicated list. RemoveParameter() forces a clean // overwrite so discovery shows exactly the configured algorithms. if (_identityOptions.Dpop.Enabled && _identityOptions.Dpop.AllowedSigningAlgorithms.Length > 0) { context.Response.RemoveParameter("dpop_signing_alg_values_supported"); context.Response["dpop_signing_alg_values_supported"] = JsonSerializer.Deserialize( JsonSerializer.Serialize(_identityOptions.Dpop.AllowedSigningAlgorithms)); } // Z7 (RFC 9101): advertise JAR only when it is actually on. Announcing support the server // does not provide is the exact mistake that left oidcc-claims-essential a WARNING // (discovery said one thing, the endpoint did another), so this is gated on the same flag // the handler checks. request_uri support tracks JarOptions.EnableRequestUri. if (_identityOptions.Features.EnableJar) { context.Response.RemoveParameter("request_parameter_supported"); context.Response["request_parameter_supported"] = true; context.Response.RemoveParameter("request_uri_parameter_supported"); context.Response["request_uri_parameter_supported"] = _identityOptions.Jar.EnableRequestUri; // OIDC Discovery 1.0 §3: whether a request_uri must be pre-registered (request_uris metadata). context.Response.RemoveParameter("require_request_uri_registration"); if (_identityOptions.Jar.EnableRequestUri) context.Response["require_request_uri_registration"] = _identityOptions.Jar.RequireRequestUriRegistration; var jarAlgs = _identityOptions.Jar.AllowedSigningAlgorithms; if (jarAlgs.Length > 0) { context.Response.RemoveParameter("request_object_signing_alg_values_supported"); context.Response["request_object_signing_alg_values_supported"] = JsonSerializer.Deserialize(JsonSerializer.Serialize(jarAlgs)); } } // Federation providers (non-standard extension). Skip placeholder entries // (ClientId / Authority = REPLACE_ME) so discovery stays consistent with // the public-providers list endpoint: an operator should never see a // provider id in /.well-known/openid-configuration that the login page // refuses to render. The DI registration applies the same filter, so // FederationChallengeProcessor returns "Unknown federation provider" // for placeholder ids anyway — surfacing them in discovery would be a // dead pointer. if (_identityOptions.Features.EnableFederation && _identityOptions.FederationProviders.Count > 0) { static bool IsPlaceholder(string? v) => string.IsNullOrWhiteSpace(v) || v.Contains("REPLACE_ME", StringComparison.OrdinalIgnoreCase); var issuerBase = context.Options?.Issuer?.ToString().TrimEnd('/'); var providerList = _identityOptions.FederationProviders .Where(p => !IsPlaceholder(p.ClientId) && !IsPlaceholder(p.Authority)) .Select(p => new { id = p.ProviderId, display_name = p.DisplayName, authorization_endpoint = $"{issuerBase}/federation/{p.ProviderId}/login" }) .ToList(); if (providerList.Count > 0) { context.Response["federation_providers"] = JsonSerializer.Deserialize( JsonSerializer.Serialize(providerList)); } } RedbRouteOpenIddictServerHelpers.WriteResponseToExchange(exchange, context.Response); // OpenIddict's default discovery handler appends its own short DPoP-alg list // ([ES256, ES384, PS256, RS256]) AFTER our handler runs, even when we call // RemoveParameter — the merge happens later in the pipeline. Dedupe here, in // the already-materialised Out.Body, so the wire-shape is canonical. if (exchange.Out?.Body is Dictionary body) { // Device authorization and PAR read Basic client credentials as the token endpoint does // (ExtractDeviceClientCredentialsHandler, ExtractPushedAuthorizationClientCredentialsHandler); // OpenIddict's lists for them leave client_secret_basic out. AddToStringArray(body, "device_authorization_endpoint_auth_methods_supported", "client_secret_basic"); AddToStringArray(body, "pushed_authorization_request_endpoint_auth_methods_supported", "client_secret_basic"); DedupeStringArray(body, "dpop_signing_alg_values_supported"); DedupeStringArray(body, "id_token_signing_alg_values_supported"); DedupeStringArray(body, "code_challenge_methods_supported"); DedupeStringArray(body, "token_endpoint_auth_methods_supported"); DedupeStringArray(body, "introspection_endpoint_auth_methods_supported"); DedupeStringArray(body, "revocation_endpoint_auth_methods_supported"); DedupeStringArray(body, "device_authorization_endpoint_auth_methods_supported"); DedupeStringArray(body, "pushed_authorization_request_endpoint_auth_methods_supported"); DedupeStringArray(body, "grant_types_supported"); DedupeStringArray(body, "response_types_supported"); DedupeStringArray(body, "response_modes_supported"); DedupeStringArray(body, "scopes_supported"); DedupeStringArray(body, "claims_supported"); DedupeStringArray(body, "subject_types_supported"); DedupeStringArray(body, "prompt_values_supported"); } context.HandleRequest(); return default; } /// Puts first in the string array under when the array is present. private static void AddToStringArray(Dictionary body, string key, string value) { if (!body.TryGetValue(key, out var raw) || raw is not System.Collections.IEnumerable items || raw is string) return; var list = new List { value }; foreach (var item in items) { var s = item?.ToString(); if (s is not null && s != value) list.Add(s); } body[key] = list; } private static void DedupeStringArray(Dictionary body, string key) { if (!body.TryGetValue(key, out var raw) || raw is not List list || list.Count == 0) return; var seen = new HashSet(StringComparer.Ordinal); var deduped = new List(list.Count); foreach (var item in list) { var s = item?.ToString(); if (s is null) continue; if (seen.Add(s)) deduped.Add(item); } if (deduped.Count != list.Count) body[key] = deduped; } } Path: redb-identity/src/redb.Identity.Core/OpenIddict/Handlers/ApplyIntrospectionResponseHandler.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/OpenIddict/Handlers/ApplyIntrospectionResponseHandler.cs ---- using OpenIddict.Server; using static OpenIddict.Server.OpenIddictServerEvents; namespace redb.Identity.Core.OpenIddict.Handlers; /// /// Writes the introspection response to . /// internal sealed class ApplyIntrospectionResponseHandler : IOpenIddictServerHandler { public static OpenIddictServerHandlerDescriptor Descriptor { get; } = OpenIddictServerHandlerDescriptor.CreateBuilder() .UseSingletonHandler() .SetOrder(int.MaxValue - 50_000) .Build(); public ValueTask HandleAsync(ApplyIntrospectionResponseContext context) { var exchange = context.Transaction.GetRouteExchange(); if (exchange is null) return default; RedbRouteOpenIddictServerHelpers.WriteResponseToExchange(exchange, context.Response); context.HandleRequest(); return default; } } Path: redb-identity/src/redb.Identity.Core/OpenIddict/Handlers/ApplyJwksResponseHandler.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/OpenIddict/Handlers/ApplyJwksResponseHandler.cs ---- using OpenIddict.Server; using static OpenIddict.Server.OpenIddictServerEvents; namespace redb.Identity.Core.OpenIddict.Handlers; /// /// Writes the JSON Web Key Set (JWKS) response to . /// internal sealed class ApplyJwksResponseHandler : IOpenIddictServerHandler { public static OpenIddictServerHandlerDescriptor Descriptor { get; } = OpenIddictServerHandlerDescriptor.CreateBuilder() .UseSingletonHandler() .SetOrder(int.MaxValue - 50_000) .Build(); public ValueTask HandleAsync(ApplyJsonWebKeySetResponseContext context) { var exchange = context.Transaction.GetRouteExchange(); if (exchange is null) return default; RedbRouteOpenIddictServerHelpers.WriteResponseToExchange(exchange, context.Response); context.HandleRequest(); return default; } } Path: redb-identity/src/redb.Identity.Core/OpenIddict/Handlers/ApplyPushedAuthorizationResponseHandler.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/OpenIddict/Handlers/ApplyPushedAuthorizationResponseHandler.cs ---- using OpenIddict.Server; using static OpenIddict.Server.OpenIddictServerEvents; namespace redb.Identity.Core.OpenIddict.Handlers; /// /// Writes the Pushed Authorization Response (RFC 9126 §2.2 — request_uri/expires_in, /// or error) to with HTTP 201 Created on success. /// internal sealed class ApplyPushedAuthorizationResponseHandler : IOpenIddictServerHandler { public static OpenIddictServerHandlerDescriptor Descriptor { get; } = OpenIddictServerHandlerDescriptor.CreateBuilder() .UseSingletonHandler() .SetOrder(int.MaxValue - 50_000) .Build(); public ValueTask HandleAsync(ApplyPushedAuthorizationResponseContext context) { var exchange = context.Transaction.GetRouteExchange(); if (exchange is null) return default; RedbRouteOpenIddictServerHelpers.WriteResponseToExchange(exchange, context.Response); // RFC 9126 §2.2: 201 Created on success. On error, fall through to the // OAuth-error → HTTP-status mapper applied by the HTTP facade. if (string.IsNullOrEmpty(context.Response.Error) && exchange.HasOut && exchange.Out is not null) { exchange.Out.Headers["redbHttp.ResponseCode"] = 201; } context.HandleRequest(); return default; } } Path: redb-identity/src/redb.Identity.Core/OpenIddict/Handlers/ApplyRevocationResponseHandler.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/OpenIddict/Handlers/ApplyRevocationResponseHandler.cs ---- using OpenIddict.Server; using static OpenIddict.Server.OpenIddictServerEvents; namespace redb.Identity.Core.OpenIddict.Handlers; /// /// Writes the revocation response to . /// internal sealed class ApplyRevocationResponseHandler : IOpenIddictServerHandler { public static OpenIddictServerHandlerDescriptor Descriptor { get; } = OpenIddictServerHandlerDescriptor.CreateBuilder() .UseSingletonHandler() .SetOrder(int.MaxValue - 50_000) .Build(); public ValueTask HandleAsync(ApplyRevocationResponseContext context) { var exchange = context.Transaction.GetRouteExchange(); if (exchange is null) return default; RedbRouteOpenIddictServerHelpers.WriteResponseToExchange(exchange, context.Response); context.HandleRequest(); return default; } } Path: redb-identity/src/redb.Identity.Core/OpenIddict/Handlers/ApplyTokenResponseHandler.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/OpenIddict/Handlers/ApplyTokenResponseHandler.cs ---- using OpenIddict.Abstractions; using OpenIddict.Server; using static OpenIddict.Server.OpenIddictServerEvents; namespace redb.Identity.Core.OpenIddict.Handlers; /// /// Writes the token response to . /// internal sealed class ApplyTokenResponseHandler : IOpenIddictServerHandler { public static OpenIddictServerHandlerDescriptor Descriptor { get; } = OpenIddictServerHandlerDescriptor.CreateBuilder() .UseSingletonHandler() .SetOrder(int.MaxValue - 50_000) .Build(); public ValueTask HandleAsync(ApplyTokenResponseContext context) { // Z4 (RFC 9449 §6): if a DPoP proof was bound earlier in the pipeline, // override the response token_type from "Bearer" to "DPoP" right before // the response is serialised onto the exchange. if (context.Transaction.Properties.TryGetValue("dpop:jkt", out var jktObj) && jktObj is string jkt && !string.IsNullOrEmpty(jkt)) { context.Response[OpenIddictConstants.Parameters.TokenType] = "DPoP"; } // RFC 6749 §5.2 — normalise the token-endpoint error contract. `invalid_token` is a // resource-server error (RFC 6750) and is NOT a valid token-endpoint error code; OpenIddict // emits it (HTTP 401) for an already-redeemed authorization code (ID2010), which must instead // be reported as `invalid_grant` with HTTP 400. Rewrite it before serialising. var error = context.Response.Error; if (error == OpenIddictConstants.Errors.InvalidToken) { context.Response.Error = OpenIddictConstants.Errors.InvalidGrant; error = OpenIddictConstants.Errors.InvalidGrant; } var exchange = context.Transaction.GetRouteExchange(); if (exchange is null) return default; RedbRouteOpenIddictServerHelpers.WriteResponseToExchange(exchange, context.Response); // RFC 6749 §5.2 — token-endpoint error status: `invalid_client` MAY be 401 (with a // WWW-Authenticate challenge); every other error is 400. Set it explicitly so error codes // never leak a resource-server-style 401 from the token endpoint. if (!string.IsNullOrEmpty(error)) { exchange.Out!.Headers[redb.Route.Http.HttpHeaders.ResponseCode] = error == OpenIddictConstants.Errors.InvalidClient ? 401 : 400; } // Z4 P2 (RFC 9449 §8): if the validation pipeline staged a fresh nonce, // emit it as the DPoP-Nonce response header for clients to adopt. Done AFTER // WriteResponseToExchange so Out is initialised. if (exchange.HasOut && exchange.Properties.TryGetValue("dpop:nonce-to-issue", out var nonceObj) && nonceObj is string nonce && !string.IsNullOrEmpty(nonce)) { exchange.Out!.Headers["DPoP-Nonce"] = nonce; } context.HandleRequest(); return default; } } Path: redb-identity/src/redb.Identity.Core/OpenIddict/Handlers/ApplyUserinfoResponseHandler.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/OpenIddict/Handlers/ApplyUserinfoResponseHandler.cs ---- using OpenIddict.Server; using static OpenIddict.Server.OpenIddictServerEvents; namespace redb.Identity.Core.OpenIddict.Handlers; /// /// Writes the userinfo response to . /// internal sealed class ApplyUserinfoResponseHandler : IOpenIddictServerHandler { public static OpenIddictServerHandlerDescriptor Descriptor { get; } = OpenIddictServerHandlerDescriptor.CreateBuilder() .UseSingletonHandler() .SetOrder(int.MaxValue - 50_000) .Build(); public ValueTask HandleAsync(ApplyUserInfoResponseContext context) { var exchange = context.Transaction.GetRouteExchange(); if (exchange is null) return default; RedbRouteOpenIddictServerHelpers.WriteResponseToExchange(exchange, context.Response); context.HandleRequest(); return default; } } Path: redb-identity/src/redb.Identity.Core/OpenIddict/Handlers/ApplyVerificationResponseHandler.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/OpenIddict/Handlers/ApplyVerificationResponseHandler.cs ---- using OpenIddict.Server; using static OpenIddict.Server.OpenIddictServerEvents; namespace redb.Identity.Core.OpenIddict.Handlers; /// /// Writes the end-user verification response to . /// Part of the Device Code Flow (RFC 8628 §3.3). /// internal sealed class ApplyVerificationResponseHandler : IOpenIddictServerHandler { public static OpenIddictServerHandlerDescriptor Descriptor { get; } = OpenIddictServerHandlerDescriptor.CreateBuilder() .UseSingletonHandler() .SetOrder(int.MaxValue - 50_000) .Build(); public ValueTask HandleAsync(ApplyEndUserVerificationResponseContext context) { var exchange = context.Transaction.GetRouteExchange(); if (exchange is null) return default; RedbRouteOpenIddictServerHelpers.WriteResponseToExchange(exchange, context.Response); context.HandleRequest(); return default; } } Path: redb-identity/src/redb.Identity.Core/OpenIddict/Handlers/AttachAccessTokenResources.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/OpenIddict/Handlers/AttachAccessTokenResources.cs ---- using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using OpenIddict.Abstractions; using OpenIddict.Server; using redb.Core; using redb.Identity.Core.Configuration; using redb.Identity.Core.Models; using static OpenIddict.Server.OpenIddictServerEvents; using static OpenIddict.Server.OpenIddictServerHandlerDescriptor; namespace redb.Identity.Core.OpenIddict.Handlers; /// /// RFC 9068 §2.2/§3: composes the resource indicators of the sign-in principal, which /// OpenIddict's PrepareAccessTokenPrincipal turns into the access token's aud. /// /// /// The set is the union of the granted scopes' Resources (the OpenIddict-canonical /// scope → resource mapping served by the scope store) and the application's /// AccessTokenAudiences. The OP's own audience /// () joins whenever an /// identity:* scope is granted — those scopes ARE the OP's own API — and stands /// alone as the §3 default resource indicator when nothing else names a resource. A token /// minted for an external API only therefore never carries the OP's audience, and the /// local validation stack rejects it at the management API (§4). /// /// /// /// Fail-closed on lookup failures: an exception from the scope store or the application /// lookup propagates and the token is not issued — an access token with a wrong audience is a /// security defect. Absent infrastructure is a different matter: OpenIddict's degraded mode /// (no core, no stores — the unit-test and embedded configurations) has no scope manager and /// no application store, so there is nothing to look up and only the OP's own audience applies. /// /// internal sealed class AttachAccessTokenResources : IOpenIddictServerHandler { /// Scopes with this prefix belong to the OP's own API surface. internal const string OwnScopePrefix = "identity:"; private readonly IServiceProvider _sp; public AttachAccessTokenResources(IServiceProvider sp) => _sp = sp; public static OpenIddictServerHandlerDescriptor Descriptor { get; } = CreateBuilder() .UseScopedHandler() // Same slot family as AttachAdditionalIdTokenAudiences (+501) and // TouchSessionOnTokenRefresh (+502): after AttachAuthorization, before the // per-token principal clones read the resources. .SetOrder(OpenIddictServerHandlers.AttachAuthorization.Descriptor.Order + 503) .SetType(OpenIddictServerHandlerType.Custom) .Build(); public async ValueTask HandleAsync(ProcessSignInContext context) { ArgumentNullException.ThrowIfNull(context); if (context.Principal is null) return; // The OP's issuer as OpenIddict sees it (SetIssuer(options.Issuer) in production, so the // validation side computes the same value from options); the options value is the fallback. var options = _sp.GetRequiredService>().Value; var ownAudience = RedbIdentityOptions.ResolveDefaultAccessTokenAudience( context.Options.Issuer ?? options.Issuer, options.DefaultAccessTokenAudience); var scopes = context.Principal.GetScopes(); var resources = new HashSet(StringComparer.Ordinal); var scopeManager = _sp.GetService(); if (scopeManager is not null) { await foreach (var resource in scopeManager .ListResourcesAsync(scopes, context.CancellationToken) .ConfigureAwait(false)) { if (!string.IsNullOrWhiteSpace(resource)) resources.Add(resource); } } var redb = _sp.GetService(); if (redb is not null && !string.IsNullOrEmpty(context.ClientId)) { var app = await redb.GetByUniqueAsync(p => p.ClientId, context.ClientId) .ConfigureAwait(false); foreach (var audience in app?.Props.AccessTokenAudiences ?? []) { if (!string.IsNullOrWhiteSpace(audience)) resources.Add(audience); } } if (scopes.Any(s => s.StartsWith(OwnScopePrefix, StringComparison.Ordinal))) resources.Add(ownAudience); if (resources.Count == 0) resources.Add(ownAudience); // The requesting client is an audience of its own token as well (WSO2 default, Keycloak, // Entra for self-scoped tokens). Without it the issuing client could no longer introspect // the tokens it holds: once a token carries audiences, OpenIddict admits only audience // members to /connect/introspect (ID2077) and no longer falls back to the presenter. // Added after the default so "nothing configured → {issuer}/resources" still holds. if (!string.IsNullOrEmpty(context.ClientId)) resources.Add(context.ClientId); context.Principal.SetResources(resources); } } Path: redb-identity/src/redb.Identity.Core/OpenIddict/Handlers/AttachAdditionalIdTokenAudiences.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/OpenIddict/Handlers/AttachAdditionalIdTokenAudiences.cs ---- using System.Security.Claims; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using OpenIddict.Abstractions; using OpenIddict.Server; using redb.Core; using redb.Core.Query; using redb.Identity.Core.Models; using static OpenIddict.Abstractions.OpenIddictConstants; using static OpenIddict.Server.OpenIddictServerEvents; using static OpenIddict.Server.OpenIddictServerHandlerDescriptor; namespace redb.Identity.Core.OpenIddict.Handlers; /// /// A.3: Appends extra aud claims (destination ) /// onto the sign-in principal so the issued id_token can be consumed by federated /// downstream resource servers in addition to the issuing client. /// /// /// Per OIDC core §2 the default audience of an id_token is the client_id of the requesting /// client; OpenIddict sets this via its built-in /// . This /// handler is a strict superset operation — never replaces or removes the default — that /// reads each entry of and adds it as an /// additional aud claim restricted to the IdentityToken destination (it MUST NOT /// leak onto the access_token, whose audiences belong to the resource server and not the /// id_token consumer set). /// /// /// /// Pipeline order: registered alongside on /// , just after AttachAuthorization (which assigns the /// AuthorizationId) so the principal is already populated, and well before /// PrepareIdentityTokenPrincipal so the destinations propagate correctly. /// /// /// /// Failure modes are deliberately silent: a redb-lookup failure, a missing client_id, or /// a degraded service-provider state all short-circuit cleanly — token issuance continues /// with the default client_id-only audience. The handler never blocks sign-in. /// /// internal sealed class AttachAdditionalIdTokenAudiences : IOpenIddictServerHandler { private readonly IServiceProvider _sp; private readonly ILogger _logger; public AttachAdditionalIdTokenAudiences( IServiceProvider sp, ILogger logger) { _sp = sp; _logger = logger; } public static OpenIddictServerHandlerDescriptor Descriptor { get; } = CreateBuilder() .UseScopedHandler() // Same slot as AttachClaimMapperClaims — runs after AttachAuthorization // (which seeds the AuthorizationId) and before the principal clones that // build the per-token principals. Picking +501 puts us deterministically // after the claim-mapper pass, so any mapper-derived audience claims (if // a future mapper ever emits one) win and we layer on top. .SetOrder(OpenIddictServerHandlers.AttachAuthorization.Descriptor.Order + 501) .SetType(OpenIddictServerHandlerType.Custom) .Build(); public async ValueTask HandleAsync(ProcessSignInContext context) { ArgumentNullException.ThrowIfNull(context); if (context.Principal?.Identity is not ClaimsIdentity identity) return; var clientId = context.ClientId; if (string.IsNullOrEmpty(clientId)) return; var redb = _sp.GetService(); if (redb is null) return; // degraded — proceed without extra audiences. ApplicationProps? props = null; try { var app = await redb.GetByUniqueAsync(p => p.ClientId, clientId) .ConfigureAwait(false); props = app?.Props; } catch (Exception ex) { _logger.LogWarning(ex, "IdTokenAudiences: failed to resolve application by client_id '{ClientId}'; skipping extra audiences", clientId); return; } var extras = props?.IdTokenAudiences; if (extras is null || extras.Length == 0) return; // De-dupe against the client_id default and any audiences a previous handler // (e.g. a future claim-mapper) already attached. Reading // identity.FindAll(Claims.Audience) is cheap — usually 1-2 entries. var existing = new HashSet( identity.FindAll(Claims.Audience).Select(c => c.Value), StringComparer.Ordinal); existing.Add(clientId); // belt-and-braces: client_id is the implicit default. foreach (var aud in extras) { if (string.IsNullOrWhiteSpace(aud)) continue; if (!existing.Add(aud)) continue; var claim = new Claim(Claims.Audience, aud); // Restrict to IdentityToken — access_token audiences are a separate // concept (resource indicators / RFC 8707) composed by AttachAccessTokenResources. claim.SetDestinations(Destinations.IdentityToken); identity.AddClaim(claim); } } } Path: redb-identity/src/redb.Identity.Core/OpenIddict/Handlers/AttachAdditionalUserinfoClaims.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/OpenIddict/Handlers/AttachAdditionalUserinfoClaims.cs ---- using System.Collections.Immutable; using System.Text.Json; using OpenIddict.Abstractions; using OpenIddict.Server; using redb.Identity.Core.Services; using static OpenIddict.Abstractions.OpenIddictConstants; using static OpenIddict.Server.OpenIddictServerEvents; namespace redb.Identity.Core.OpenIddict.Handlers; /// /// Supplements OpenIddict's built-in AttachClaims handler by setting OIDC standard claims /// that the built-in handler does not populate: name, picture, email_verified, phone_number_verified. /// Also enriches with group/role claims when those scopes are requested. /// internal sealed class AttachAdditionalUserinfoClaims : IOpenIddictServerHandler { public static OpenIddictServerHandlerDescriptor Descriptor { get; } = OpenIddictServerHandlerDescriptor.CreateBuilder() .UseScopedHandler() .SetOrder(int.MaxValue - 100_000) .Build(); public async ValueTask HandleAsync(HandleUserInfoRequestContext context) { // OpenIddict 7 names the principal after the token it came from: on the userinfo // endpoint that is the access token. var principal = context.AccessTokenPrincipal; if (principal is null) return; // The full OIDC Core §5.1 `profile` claim set. The suite (oidcc-scope-profile / // oidcc-scope-all) diffs userinfo against exactly this list, so emit every one we hold. if (principal.HasScope(Scopes.Profile)) { foreach (var type in new[] { Claims.Name, Claims.GivenName, Claims.FamilyName, Claims.MiddleName, Claims.Nickname, Claims.PreferredUsername, Claims.Profile, Claims.Picture, Claims.Website, Claims.Gender, Claims.Birthdate, Claims.Zoneinfo, Claims.Locale }) { var value = principal.GetClaim(type); if (!string.IsNullOrEmpty(value)) context.Claims[type] = value; } // updated_at is a JSON NUMBER (seconds since the epoch), not a string — emit it typed, // otherwise it would go out quoted via the generic custom-claim copy below. var updatedAt = principal.GetClaim(Claims.UpdatedAt); if (!string.IsNullOrEmpty(updatedAt) && long.TryParse(updatedAt, out var epoch)) context.Claims[Claims.UpdatedAt] = epoch; } if (principal.HasScope(Scopes.Email)) { var emailVerified = principal.GetClaim(Claims.EmailVerified); if (!string.IsNullOrEmpty(emailVerified) && bool.TryParse(emailVerified, out var ev)) context.EmailVerified = ev; } if (principal.HasScope(Scopes.Phone)) { var phoneVerified = principal.GetClaim(Claims.PhoneNumberVerified); if (!string.IsNullOrEmpty(phoneVerified) && bool.TryParse(phoneVerified, out var pv)) context.PhoneNumberVerified = pv; } // Address scope: emit structured JSON from the claim stored by IdentityPrincipalBuilder if (principal.HasScope(Scopes.Address)) { var addressJson = principal.GetClaim(Claims.Address); if (!string.IsNullOrEmpty(addressJson)) { var addressObj = JsonSerializer.Deserialize(addressJson); context.Claims[Claims.Address] = addressObj; } } // OIDC Core §5.5 — claims the RP named individually via the `claims` parameter, rather than // pulling in a whole scope to get one of them. They are gated on that request and nothing // else: an RP that asked for `name` with scope=openid gets `name` here, while an RP that // asked for nothing still gets no profile data, exactly as before. The scope blocks above // may already have emitted some of these — hence TryAdd semantics, not overwrite. var requested = principal.GetClaim(IdentityPrincipalBuilder.RequestedUserInfoClaims); if (!string.IsNullOrEmpty(requested)) { foreach (var type in requested.Split(' ', StringSplitOptions.RemoveEmptyEntries)) { if (context.Claims.ContainsKey(type)) continue; var value = principal.GetClaim(type); if (string.IsNullOrEmpty(value)) continue; // Same JSON typing rules as the scope path (§5.1): numbers stay numbers, booleans // stay booleans, address stays an object. A claim's type must not depend on which // mechanism the RP used to ask for it. context.Claims[type] = type switch { Claims.UpdatedAt when long.TryParse(value, out var epoch) => epoch, Claims.EmailVerified or Claims.PhoneNumberVerified when bool.TryParse(value, out var flag) => flag, Claims.Address => JsonSerializer.Deserialize(value), _ => value }; } } // Custom (RP-defined) claims: copy them from the access-token principal into userinfo. // // This used to skip only a short list of "standard" claims and forward EVERYTHING else — // which quietly leaked the token's own plumbing into the userinfo response: OpenIddict's // internals (oi_tkn_id / oi_tkn_typ / oi_scp / oi_prst / oi_crt_dt / oi_exp_dt) and the JWT // protocol claims (jti, exp, iat, iss, aud, azp, at_hash, client_id...). Those describe the // TOKEN, not the end-user; userinfo (OIDC Core §5.3) must return the user's claims only. // An RP has no business learning our token-store ids or expiry bookkeeping. // // So: skip anything already emitted above, anything OpenIddict-internal (oi_ prefix), and // the token/protocol claims. What's left is exactly what this handler was meant for — the // RP's own custom claims (e.g. redb:user_id, tenant, department). if (principal.Identity is System.Security.Claims.ClaimsIdentity identity) { var alreadyEmitted = new HashSet(new[] { Claims.Subject, // profile scope (OIDC Core §5.1) — emitted above, typed where it matters Claims.Name, Claims.GivenName, Claims.FamilyName, Claims.MiddleName, Claims.Nickname, Claims.PreferredUsername, Claims.Profile, Claims.Picture, Claims.Website, Claims.Gender, Claims.Birthdate, Claims.Zoneinfo, Claims.Locale, Claims.UpdatedAt, // email / phone / address scopes Claims.Email, Claims.EmailVerified, Claims.PhoneNumber, Claims.PhoneNumberVerified, Claims.Address, GroupClaimsResolver.GroupsClaim, GroupClaimsResolver.RolesClaim, GroupClaimsResolver.OrgClaim, "scope", // Our own §5.5 bookkeeping — it records what the RP asked for, it is not a claim // about the user, and userinfo (§5.3) returns the user's claims only. IdentityPrincipalBuilder.RequestedUserInfoClaims }); // Claims that describe the token / the protocol, never the user. var tokenPlumbing = new HashSet(new[] { Claims.JwtId, Claims.ExpiresAt, Claims.IssuedAt, Claims.NotBefore, Claims.Issuer, Claims.Audience, Claims.AuthorizedParty, Claims.ClientId, Claims.AccessTokenHash, Claims.CodeHash, Claims.Nonce, Claims.TokenType, Claims.TokenUsage, Claims.Scope }); foreach (var claim in identity.Claims) { if (string.IsNullOrEmpty(claim.Value)) continue; if (alreadyEmitted.Contains(claim.Type)) continue; if (tokenPlumbing.Contains(claim.Type)) continue; // OpenIddict stamps its own bookkeeping with this prefix (oi_tkn_id, oi_scp, ...). if (claim.Type.StartsWith("oi_", StringComparison.Ordinal)) continue; context.Claims[claim.Type] = claim.Value; } } // Groups/Roles scope claims: read from principal (set by GroupClaimsResolver) if (principal.HasScope(GroupClaimsResolver.GroupsScope)) { var groupClaims = principal.FindAll(GroupClaimsResolver.GroupsClaim) .Select(c => (string?)c.Value).Distinct().ToImmutableArray(); if (groupClaims.Length > 0) context.Claims[GroupClaimsResolver.GroupsClaim] = groupClaims; var orgClaim = principal.FindFirst(GroupClaimsResolver.OrgClaim); if (orgClaim is not null) context.Claims[GroupClaimsResolver.OrgClaim] = orgClaim.Value; } if (principal.HasScope(GroupClaimsResolver.RolesScope)) { var roleClaims = principal.FindAll(GroupClaimsResolver.RolesClaim) .Select(c => (string?)c.Value).Distinct().ToImmutableArray(); if (roleClaims.Length > 0) context.Claims[GroupClaimsResolver.RolesClaim] = roleClaims; } } } Path: redb-identity/src/redb.Identity.Core/OpenIddict/Handlers/AttachClaimDefinitionEnforcement.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/OpenIddict/Handlers/AttachClaimDefinitionEnforcement.cs ---- using System.Security.Claims; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using OpenIddict.Abstractions; using OpenIddict.Server; using redb.Core; using redb.Core.Query; using redb.Identity.Core.Models; using redb.Identity.Core.Services; using static OpenIddict.Abstractions.OpenIddictConstants; using static OpenIddict.Server.OpenIddictServerEvents; using static OpenIddict.Server.OpenIddictServerHandlerDescriptor; namespace redb.Identity.Core.OpenIddict.Handlers; /// /// S2.4 — apply at token issuance: /// /// Per-application required-claim enforcement (Scope='application', /// ApplicationId matches the requesting client). Missing required /// claim without a DefaultValue → reject the sign-in with /// invalid_request; with a DefaultValue → silently emit the /// default in the token. /// Per-definition destination control — EmitOnIdToken / /// EmitOnAccessToken override the default (both-tokens) /// destination set assigned in /// . /// /// /// Runs AFTER AttachClaimMapperClaims so any mapper-emitted claim /// that matches a definition gets its destinations rewritten too. Skips for /// client_credentials grants (no user, nothing to enforce). /// internal sealed class AttachClaimDefinitionEnforcement : IOpenIddictServerHandler { private readonly IServiceProvider _sp; private readonly ILogger _logger; public AttachClaimDefinitionEnforcement(IServiceProvider sp, ILogger logger) { _sp = sp; _logger = logger; } public static OpenIddictServerHandlerDescriptor Descriptor { get; } = CreateBuilder() .UseScopedHandler() // Run AFTER AttachClaimMapperClaims (AttachAuthorization + 500) so any // mapper-emitted claim sharing a name with a definition also gets its // destinations rewritten. Still before token-mint preparation. .SetOrder(OpenIddictServerHandlers.AttachAuthorization.Descriptor.Order + 700) .SetType(OpenIddictServerHandlerType.Custom) .Build(); public async ValueTask HandleAsync(ProcessSignInContext context) { ArgumentNullException.ThrowIfNull(context); if (context.Principal?.Identity is not ClaimsIdentity identity) return; // client_credentials → no user → no per-user claim enforcement. var internalUid = context.Principal.FindFirst(IdentityPrincipalBuilder.InternalUserIdClaim)?.Value; if (string.IsNullOrEmpty(internalUid) || !long.TryParse(internalUid, out var userId) || userId <= 0) return; var redb = _sp.GetService(); if (redb is null) return; long? applicationId = null; var clientId = context.ClientId; if (!string.IsNullOrEmpty(clientId)) { try { var app = await redb.GetByUniqueAsync(p => p.ClientId, clientId) .ConfigureAwait(false); if (app is not null && app.Id > 0) applicationId = app.Id; } catch (Exception ex) { _logger.LogWarning(ex, "ClaimDefinitions: failed to resolve application by client_id '{ClientId}'; skipping per-app enforcement", clientId); } } // Pull every relevant definition in a single query. // global + (application-scoped for the resolved app, if any). var defs = await redb.Query() .Where(d => d.Scope == "global" || (d.Scope == "application" && d.ApplicationId == applicationId)) .ToListAsync() .ConfigureAwait(false); // Defensive null-guard: production providers always return a (possibly // empty) list, but mocked unit-test queries may not be configured for // ClaimDefinitionProps and return null — the handler then silently // no-ops which mirrors the empty-list path. if (defs is null || defs.Count == 0) return; // Step 1 — required enforcement (per-app only; global was already validated // at user create / update by ClaimSchemaValidator). foreach (var defObj in defs) { var def = defObj.Props; if (def.Scope != "application") continue; if (!def.Required) continue; var existing = identity.FindFirst(def.ClaimName); if (existing is not null && !string.IsNullOrEmpty(existing.Value)) continue; if (!string.IsNullOrEmpty(def.DefaultValue)) { // Apply default into the principal so the token carries it. identity.AddClaim(new Claim(def.ClaimName, def.DefaultValue)); continue; } _logger.LogWarning( "ClaimDefinitions: rejecting issuance — required application claim '{Claim}' missing for user {UserId}, client {ClientId}", def.ClaimName, userId, clientId); context.Reject( error: Errors.InvalidRequest, description: $"Required claim '{def.ClaimName}' is missing for application '{clientId}'."); return; } // Step 2 — per-definition destination override. Default in // IdentityPrincipalBuilder is BOTH tokens; per-definition flags // restrict to one or the other. var byName = new Dictionary(StringComparer.Ordinal); foreach (var d in defs) byName[d.Props.ClaimName] = d.Props; foreach (var claim in identity.Claims.ToList()) { if (!byName.TryGetValue(claim.Type, out var def)) continue; var dests = new List(2); if (def.EmitOnAccessToken) dests.Add(Destinations.AccessToken); if (def.EmitOnIdToken) dests.Add(Destinations.IdentityToken); // Both flags off — treat as access_token only (preferable over silent // claim drop; operator gets surprising-but-not-broken behaviour). if (dests.Count == 0) dests.Add(Destinations.AccessToken); claim.SetDestinations(dests.ToArray()); } } } Path: redb-identity/src/redb.Identity.Core/OpenIddict/Handlers/AttachClaimMapperClaims.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/OpenIddict/Handlers/AttachClaimMapperClaims.cs ---- using System.Security.Claims; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using OpenIddict.Abstractions; using OpenIddict.Server; using redb.Core; using redb.Core.Query; using redb.Identity.Core.Models; using redb.Identity.Core.Services; using static OpenIddict.Abstractions.OpenIddictConstants; using static OpenIddict.Server.OpenIddictServerEvents; using static OpenIddict.Server.OpenIddictServerHandlerDescriptor; namespace redb.Identity.Core.OpenIddict.Handlers; /// /// H5 (v1.0 DoD §5): Applies declarative rules to the /// principal at OpenIddict sign-in time, just before access_token / id_token issuance. /// /// Runs uniformly for every grant type (authorization_code, refresh_token, ROPC, device_code, /// client_credentials), giving Keycloak-equivalent behaviour: global mappers + per-Application /// overlay + assigned reusable Client Scope mappers, all gated by requested scopes. /// /// /// Order: registered late in the pipeline (after the built-in /// OpenIddictServerHandlers.Exchange.AttachSignInParameters step but before token /// minting) so the principal is already populated and we layer mapper-derived claims on top. /// /// internal sealed class AttachClaimMapperClaims : IOpenIddictServerHandler { private readonly IServiceProvider _sp; private readonly ILogger _logger; public AttachClaimMapperClaims(IServiceProvider sp, ILogger logger) { _sp = sp; _logger = logger; } public static OpenIddictServerHandlerDescriptor Descriptor { get; } = CreateBuilder() .UseScopedHandler() // CRITICAL: must run BEFORE OpenIddictServerHandlers.Exchange.ApplyTokenResponse // (fixed order 500_000), otherwise IsRequestHandled propagates and this handler is silently skipped. // Must also run before PrepareAccessTokenPrincipal (AttachAuthorization.Order + 1_000) so any // mapper-added claims are visible to the principal-cloning / destination filter logic. // Slot: just after AttachAuthorization (which assigns AuthorizationId), before token principal prep. .SetOrder(OpenIddictServerHandlers.AttachAuthorization.Descriptor.Order + 500) .SetType(OpenIddictServerHandlerType.Custom) .Build(); public async ValueTask HandleAsync(ProcessSignInContext context) { ArgumentNullException.ThrowIfNull(context); if (context.Principal?.Identity is not ClaimsIdentity identity) return; // Resolve internal user id. The public sub is now a GUID; the bigint _users._id // rides alongside in the `redb:user_id` claim (end-user grants only). For // client_credentials the principal carries no internal user-id claim — skip // mappers in that case since they're keyed on user attributes. var internalUid = context.Principal.FindFirst(IdentityPrincipalBuilder.InternalUserIdClaim)?.Value; if (string.IsNullOrEmpty(internalUid) || !long.TryParse(internalUid, out var userId) || userId <= 0) return; var redb = _sp.GetService(); if (redb is null) return; // degraded mode // Resolve application object id from client_id, if present long? applicationId = null; var clientId = context.ClientId; if (!string.IsNullOrEmpty(clientId)) { try { var app = await redb.GetByUniqueAsync(p => p.ClientId, clientId) .ConfigureAwait(false); if (app is not null && app.Id > 0) applicationId = app.Id; } catch (Exception ex) { // Don't block issuance on app-lookup failure — fall back to global mappers only. _logger.LogWarning(ex, "ClaimMappers: failed to resolve application by client_id '{ClientId}'; running global mappers only", clientId); } } // Scopes for this issuance — taken from the principal (already authoritative). var scopes = context.Principal.GetScopes(); var resolverLogger = _sp.GetService>(); var resolver = new ClaimMappersResolver(redb, resolverLogger); try { await resolver.EnrichPrincipalAsync( context.Principal, userId, applicationId, scopes, context.CancellationToken) .ConfigureAwait(false); } catch (InvalidOperationException ex) { // Required-mapper resolution failure — surface as invalid_request to the client. _logger.LogWarning(ex, "ClaimMappers: required mapper failed for user {UserId}, client {ClientId}", userId, clientId); context.Reject( error: Errors.InvalidRequest, description: "Required claim mapper resolution failed: " + ex.Message); } } } Path: redb-identity/src/redb.Identity.Core/OpenIddict/Handlers/AttachDpopConfirmationClaimHandler.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/OpenIddict/Handlers/AttachDpopConfirmationClaimHandler.cs ---- using System.Security.Claims; using System.Text.Json; using OpenIddict.Abstractions; using OpenIddict.Server; using static OpenIddict.Server.OpenIddictServerEvents; namespace redb.Identity.Core.OpenIddict.Handlers; /// /// Z4 (RFC 9449 §6.1 / RFC 7800): when a DPoP proof was validated for the current /// /token request, attaches the JWK thumbprint as the cnf claim of the access token /// so it carries the proof-of-possession binding. /// /// Runs on after OpenIddict has prepared the per-token /// principals and before it generates the tokens. OpenIddict 7 strips cnf from the /// sign-in principal when it clones the access token principal (a confirmation must never be /// inherited from a parent token), so the claim is set on AccessTokenPrincipal itself, /// and on IssuedTokenPrincipal when token exchange issues an access token. /// /// internal sealed class AttachDpopConfirmationClaimHandler : IOpenIddictServerHandler { public static OpenIddictServerHandlerDescriptor Descriptor { get; } = OpenIddictServerHandlerDescriptor.CreateBuilder() .UseSingletonHandler() // After the last Prepare*Principal handler, long before GenerateAccessToken (100_000). .SetOrder(OpenIddictServerHandlers.PrepareUserCodePrincipal.Descriptor.Order + 500) .SetType(OpenIddictServerHandlerType.Custom) .Build(); public ValueTask HandleAsync(ProcessSignInContext context) { ArgumentNullException.ThrowIfNull(context); if (!context.Transaction.Properties.TryGetValue("dpop:jkt", out var jktObj) || jktObj is not string jkt || string.IsNullOrEmpty(jkt)) { return default; } var cnf = JsonSerializer.SerializeToElement(new { jkt }); if (context.AccessTokenPrincipal is ClaimsPrincipal access) access.SetClaim(OpenIddictConstants.Claims.Confirmation, cnf); if (context.IssuedTokenPrincipal is ClaimsPrincipal issued && context.IssuedTokenType is OpenIddictConstants.TokenTypeIdentifiers.AccessToken) issued.SetClaim(OpenIddictConstants.Claims.Confirmation, cnf); return default; } } Path: redb-identity/src/redb.Identity.Core/OpenIddict/Handlers/AttachInternalUserIdToIntrospectionResponse.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/OpenIddict/Handlers/AttachInternalUserIdToIntrospectionResponse.cs ---- using OpenIddict.Server; using redb.Identity.Core.Services; using static OpenIddict.Server.OpenIddictServerEvents; namespace redb.Identity.Core.OpenIddict.Handlers; /// /// Surfaces the internal bigint user id ( /// = redb:user_id) on the RFC 7662 introspection response when the /// introspected token belongs to a user grant (ROPC / authorization_code / /// refresh / device_code). /// /// /// RFC 7662 §2.2 explicitly authorises implementation-defined top-level /// response members alongside the standard set. redb:user_id follows /// RFC 7519 §4.3 private-claim naming (colon-prefixed vendor namespace) so it /// won't collide with future IANA-registered names. /// /// /// /// Client-credentials tokens have no user — they're never enriched here. /// The claim is on the principal already (see /// ); OpenIddict's default /// introspection serializer only emits the standard whitelist, so this /// handler forwards the value into context.Response just before the /// builder-level writes the /// response to the route exchange. /// /// internal sealed class AttachInternalUserIdToIntrospectionResponse : IOpenIddictServerHandler { public static OpenIddictServerHandlerDescriptor Descriptor { get; } = OpenIddictServerHandlerDescriptor.CreateBuilder() .UseSingletonHandler() // Late in the handle stage — AFTER OpenIddict's standard claim- // projection handlers have populated context.Response with // sub/jti/iat/etc.; the surrounding Apply* writer descriptors // serialise the dictionary into the HTTP body. .SetOrder(int.MaxValue - 1000) .Build(); public ValueTask HandleAsync(HandleIntrospectionRequestContext context) { ArgumentNullException.ThrowIfNull(context); // Rejected / active=false paths skip the principal entirely. OpenIddict 7 names it after the // token it came from; the introspected token can be of any type, hence the generic one. var principal = context.GenericTokenPrincipal; if (principal is null) return default; var uid = principal.FindFirst(IdentityPrincipalBuilder.InternalUserIdClaim)?.Value; if (string.IsNullOrEmpty(uid)) return default; // OpenIddict's HandleIntrospectionRequestContext.Claims is the // dictionary the Apply* writer flattens into the JSON response // alongside the standard RFC 7662 fields. Idempotent — leave any // pre-existing value alone. if (context.Claims.ContainsKey(IdentityPrincipalBuilder.InternalUserIdClaim)) return default; context.Claims[IdentityPrincipalBuilder.InternalUserIdClaim] = uid; return default; } } Path: redb-identity/src/redb.Identity.Core/OpenIddict/Handlers/AttachRoleRegistryClaims.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/OpenIddict/Handlers/AttachRoleRegistryClaims.cs ---- using System.Security.Claims; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using OpenIddict.Abstractions; using OpenIddict.Server; using redb.Core; using redb.Core.Query; using redb.Identity.Core.Models; using redb.Identity.Core.Services; using static OpenIddict.Abstractions.OpenIddictConstants; using static OpenIddict.Server.OpenIddictServerEvents; using static OpenIddict.Server.OpenIddictServerHandlerDescriptor; namespace redb.Identity.Core.OpenIddict.Handlers; /// /// B.3 — emits the roles claim from the first-class Roles registry, /// independent of any group claim mapper. The emitted set is the user's /// EFFECTIVE role bundle: /// direct user assignments () /// ∪ assignments inherited via every group the user belongs to /// (). /// /// Filtered by audience at issuance time: /// * audience='organization' roles always emit; /// * audience='application' roles emit only when the role's /// ApplicationId matches the requesting client's redb object id. /// /// /// Runs after AttachClaimMapperClaims + AttachClaimDefinitionEnforcement /// so the existing per-membership role claim from groups is left /// intact — the two are complementary: the per-membership label is /// "what's your role IN this group?", the registry's roles claim is /// "what access bucket(s) do you hold?". OIDC convention is plural /// roles (RFC 7643 §4.1.2 / OIDC core §5.1.2); we use that name to /// match the prior groups+roles emitter behaviour. /// /// internal sealed class AttachRoleRegistryClaims : IOpenIddictServerHandler { public const string RolesClaim = "roles"; private readonly IServiceProvider _sp; private readonly ILogger _logger; public AttachRoleRegistryClaims(IServiceProvider sp, ILogger logger) { _sp = sp; _logger = logger; } public static OpenIddictServerHandlerDescriptor Descriptor { get; } = CreateBuilder() .UseScopedHandler() // After AttachClaimMapperClaims (+500), after // AttachClaimDefinitionEnforcement (+700); before token mint. .SetOrder(OpenIddictServerHandlers.AttachAuthorization.Descriptor.Order + 800) .SetType(OpenIddictServerHandlerType.Custom) .Build(); public async ValueTask HandleAsync(ProcessSignInContext context) { ArgumentNullException.ThrowIfNull(context); if (context.Principal?.Identity is not ClaimsIdentity identity) return; // client_credentials → no user → no role registry walk. var internalUid = context.Principal.FindFirst(IdentityPrincipalBuilder.InternalUserIdClaim)?.Value; if (string.IsNullOrEmpty(internalUid) || !long.TryParse(internalUid, out var userId) || userId <= 0) return; var redb = _sp.GetService(); if (redb is null) return; // Resolve the requesting application id (for audience='application' filter). long? applicationId = null; var clientId = context.ClientId; if (!string.IsNullOrEmpty(clientId)) { try { var app = await redb.GetByUniqueAsync(p => p.ClientId, clientId) .ConfigureAwait(false); if (app is not null && app.Id > 0) applicationId = app.Id; } catch (Exception ex) { _logger.LogWarning(ex, "AttachRoleRegistryClaims: failed to resolve application by client_id '{ClientId}'; emitting org-scoped roles only", clientId); } } // User's group memberships drive transitive role resolution. IGroupService // isn't DI-registered; instantiate GroupService directly against the // resolved IRedbService. var groupIds = new List(); try { var groupService = new GroupService(redb); var userGroups = await groupService.GetUserGroupsAsync(userId, context.CancellationToken).ConfigureAwait(false); groupIds = userGroups.Where(g => g.GroupId > 0).Select(g => g.GroupId).ToList(); } catch (Exception ex) { _logger.LogWarning(ex, "AttachRoleRegistryClaims: failed to resolve user {UserId} group memberships; emitting direct-role assignments only", userId); } try { var svc = new RoleService(redb); var roles = await svc.GetEffectiveRolesAsync(userId, groupIds, applicationId, context.CancellationToken) .ConfigureAwait(false); if (roles.Count == 0) return; // The scopes attached to these roles are NOT added to the token. A role is an entitlement: // a scope the client asked for (and OpenIddict checked against the client's permissions) // stays only when the user's roles carry it (RestrictAdminScopesByRoleHandler). Adding the // role's scopes here, after that check, gave every client a user signed in to the scopes of // the user's roles, identity:manage with Identity's own audience included, so an // administrator's token issued to any client administered Identity (RoleScopeAugmentationTests). // Idempotent vs prior emitters — drop any already-present `roles` // values that the role-registry walk also produces, then re-add // the union. Prior emitters (claim mappers, group `roles` scope // mapper) are left intact for non-registry sources. var existing = identity.FindAll(RolesClaim).Select(c => c.Value).ToHashSet(StringComparer.Ordinal); // OpenIddict drops any claim that has no Destinations set, so a // raw AddClaim AFTER IdentityPrincipalBuilder has finished its // destination switch silently disappears. Set destinations // explicitly here — `roles` is conventionally emitted on BOTH // tokens (id_token for the front-end, access_token so resource // servers don't need a userinfo round-trip). string[] destinations = { Destinations.AccessToken, Destinations.IdentityToken }; foreach (var role in roles) { var name = role.Props.Name; if (string.IsNullOrEmpty(name)) continue; if (existing.Contains(name)) continue; var claim = new Claim(RolesClaim, name); claim.SetDestinations(destinations); identity.AddClaim(claim); existing.Add(name); } } catch (Exception ex) { // Failure here must NOT 500 the token endpoint — the principal // still has its base claims; the operator just doesn't see the // registry-driven roles claim for this issuance. _logger.LogError(ex, "AttachRoleRegistryClaims: role-registry walk failed for user {UserId}, client {ClientId} — token still issued without registry roles claim", userId, clientId); } } } Path: redb-identity/src/redb.Identity.Core/OpenIddict/Handlers/AttachSessionPrincipalHandler.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/OpenIddict/Handlers/AttachSessionPrincipalHandler.cs ---- using System.Security.Claims; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using OpenIddict.Abstractions; using OpenIddict.Server; using redb.Core; using redb.Core.Query; using redb.Identity.Core.Models; using redb.Identity.Core.Services; using static OpenIddict.Abstractions.OpenIddictConstants; using static OpenIddict.Server.OpenIddictServerEvents; using static OpenIddict.Server.OpenIddictServerHandlerDescriptor; namespace redb.Identity.Core.OpenIddict.Handlers; /// /// Reads session_user_id from the route exchange (set by the HTTP session cookie processor) /// and builds a for the authorize endpoint. /// The session_user_id is a _users._id. The handler loads the Core user via /// and the OIDC profile via RedbObject.Key. /// internal sealed class AttachSessionPrincipalHandler : IOpenIddictServerHandler { private readonly IServiceProvider _sp; private readonly ILogger _logger; public AttachSessionPrincipalHandler(IServiceProvider sp, ILogger logger) { _sp = sp; _logger = logger; } public static OpenIddictServerHandlerDescriptor Descriptor { get; } = CreateBuilder() .UseScopedHandler() // Run BEFORE HandleAuthorizationRequestHandler (which is at AttachPrincipal + 100) .SetOrder(OpenIddictServerHandlers.Authentication.AttachPrincipal.Descriptor.Order + 50) .SetType(OpenIddictServerHandlerType.Custom) .Build(); public async ValueTask HandleAsync(HandleAuthorizationRequestContext context) { // If a principal is already set (shouldn't happen, but be safe), skip if (context.Principal is not null) return; var exchange = context.Transaction.GetRouteExchange(); if (exchange is null) return; // Check for session_user_id (set by SessionCookieProcessors.ReadSessionCookie) if (!exchange.In.Headers.TryGetValue("session_user_id", out var rawUserId) || rawUserId is not long userId) { // Also try string representation (from header) if (rawUserId is string userIdStr && long.TryParse(userIdStr, out userId)) { // parsed OK } else { return; // No session — HandleAuthorizationRequestHandler will reject with login_required } } var redb = _sp.GetService(); if (redb is null) return; // degraded mode — no redb, no session resolution // Per-session revocation check: if the cookie carries a session_id, verify the session is still active bool sessionMfaVerified = false; string? sessionMfaMethod = null; long sessionIdForLookup = 0; DateTimeOffset? sessionCreatedAt = null; if (exchange.In.Headers.TryGetValue("session_id", out var rawSessionId)) { long sessionId = rawSessionId is long sid ? sid : rawSessionId is string sidStr && long.TryParse(sidStr, out var parsed) ? parsed : 0; if (sessionId > 0) { sessionIdForLookup = sessionId; var sessionService = new SessionService(redb); if (await sessionService.IsSessionRevokedAsync(sessionId).ConfigureAwait(false)) { _logger.LogInformation("Session {SessionId} for user {UserId} is revoked — login_required", sessionId, userId); return; // No principal → OpenIddict rejects with login_required → redirect to login } // Load MFA flags so the resulting principal carries the correct amr claim var sessionObj = await redb.LoadAsync(sessionId).ConfigureAwait(false); if (sessionObj is not null) { sessionMfaVerified = sessionObj.Props.MfaVerified; sessionMfaMethod = sessionObj.Props.MfaMethod; // OIDC §2 — auth_time MUST reflect the original authentication, not the // moment the principal is rebuilt from the session cookie. The base // RedbObject.DateCreate is set when LoginService minted the session row, // so it is the right source for the End-User's actual authentication time. sessionCreatedAt = sessionObj.DateCreate; } } } // OIDC Core §5.5 — the `claims` request parameter. Parsed here because the authorization // endpoint is the only place it can arrive (a PAR request is replayed through this same // handler), and because its meaning is protocol, not transport: the HTTP façade's job ended // when it mapped the query string onto the exchange. // // A malformed value is the RP's bug and must be told so — silently dropping it would leave // the RP believing it requested claims that will never arrive. if (!OidcClaimsRequest.TryParse( context.Request.GetParameter(Parameters.Claims)?.ToString(), out var claimsRequest, out var claimsError)) { context.Reject(error: Errors.InvalidRequest, description: claimsError); return; } var profileService = _sp.GetService(); if (profileService is not null) { context.Principal = await profileService.BuildPrincipalAsync( userId, context.Request.GetScopes(), sessionMfaVerified, sessionMfaMethod, claimsRequest).ConfigureAwait(false); } else { // Fallback: load manually (degraded mode without DI) var coreUser = await redb.UserProvider.GetUserByIdAsync(userId).ConfigureAwait(false); if (coreUser is null || !coreUser.Enabled) return; var oidcObj = await redb.Query() .WhereRedb(o => o.Key == coreUser.Id) .FirstOrDefaultAsync() .ConfigureAwait(false); // Lazy-create the GUID identity if missing so legacy users get a stable sub // before token issuance. if (oidcObj is null) { oidcObj = new redb.Core.Models.Entities.RedbObject( new UserProps { UserId = coreUser.Id }) // V4-UNIQUE { name = coreUser.Login, key = coreUser.Id, value_guid = Guid.NewGuid() }; await redb.SaveAsync(oidcObj).ConfigureAwait(false); } else if (oidcObj.value_guid is null || oidcObj.value_guid == Guid.Empty) { oidcObj.value_guid = Guid.NewGuid(); await redb.SaveAsync(oidcObj).ConfigureAwait(false); } context.Principal = IdentityPrincipalBuilder.Build( coreUser, oidcObj.value_guid!.Value, oidcObj.Props, context.Request.GetScopes(), sessionMfaVerified, sessionMfaMethod, claimsRequest); } // OIDC Core §5.5.1 — a `claims` request that pins `sub` to a value is not a request for a // claim, it is an assertion about WHICH End-User must be signed in ("re-authenticate as // this user"). The spec is unambiguous: the OP must only respond positively if that End-User // is the one authenticated. Our session says otherwise, so we refuse rather than hand the RP // an id_token for somebody else — which is exactly the confusion the constraint exists to // prevent. login_required is the honest answer: a different login would satisfy the request. var requestedSub = claimsRequest!.IdToken.TryGetValue(Claims.Subject, out var idSub) ? idSub.Value : claimsRequest.UserInfo.TryGetValue(Claims.Subject, out var uiSub) ? uiSub.Value : null; if (!string.IsNullOrEmpty(requestedSub) && context.Principal?.GetClaim(Claims.Subject) is { } actualSub && !string.Equals(requestedSub, actualSub, StringComparison.Ordinal)) { // §5.5.1 allows the End-User to be "Authenticated as a result of the request", so the // default answer is login_required — the HTTP façade turns that into the local /login // page and the human can sign in as the requested sub. That is the useful outcome. // // Except under prompt=none (§3.1.2.6), where the RP has said "never show UI". The // façade's RedirectToLogin bails out on the `prompt_none` flag, but the flag is only // raised for the "nobody is signed in" case — here somebody IS signed in, just the // wrong person, so we must raise it ourselves or we would put a login form in front of // an RP that explicitly forbade one. if (context.Request.HasPromptValue(PromptValues.None)) exchange.Properties["prompt_none"] = true; _logger.LogInformation( "Rejecting authorize: 'claims' pinned sub={RequestedSub} but the session belongs to another user", requestedSub); context.Reject( error: Errors.LoginRequired, description: "The 'claims' parameter requested a specific 'sub' that does not match " + "the currently authenticated End-User."); return; } _logger.LogDebug( "Attached principal from session for user {UserId} (authorize endpoint)", userId); // Add sid (session ID) claim per OIDC Front-Channel/Back-Channel Logout specs if (context.Principal?.Identity is ClaimsIdentity identity && sessionIdForLookup > 0) { var sidClaim = new Claim("sid", sessionIdForLookup.ToString()); sidClaim.SetDestinations(Destinations.AccessToken, Destinations.IdentityToken); identity.AddClaim(sidClaim); // OIDC §2 — overwrite the auth_time that IdentityPrincipalBuilder stamped at // construction (= "now") with the session's actual creation time so max_age // and prompt=login-style staleness checks see real elapsed seconds, not zero. if (sessionCreatedAt.HasValue) { var existing = identity.FindAll(Claims.AuthenticationTime).ToList(); foreach (var c in existing) identity.RemoveClaim(c); var authTime = new Claim( Claims.AuthenticationTime, sessionCreatedAt.Value.ToUnixTimeSeconds().ToString(System.Globalization.CultureInfo.InvariantCulture), ClaimValueTypes.Integer64); authTime.SetDestinations(Destinations.AccessToken, Destinations.IdentityToken); identity.AddClaim(authTime); } } } } Path: redb-identity/src/redb.Identity.Core/OpenIddict/Handlers/BindDpopJktAtAuthorizeHandler.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/OpenIddict/Handlers/BindDpopJktAtAuthorizeHandler.cs ---- using System.Security.Claims; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using OpenIddict.Abstractions; using OpenIddict.Server; using redb.Identity.Core.Configuration; using static OpenIddict.Abstractions.OpenIddictConstants; using static OpenIddict.Server.OpenIddictServerEvents; namespace redb.Identity.Core.OpenIddict.Handlers; /// /// Z4 P2.1 (RFC 9449 §10): if the authorization request carries a dpop_jkt parameter, /// validate its format and bind it as a private claim on the issued authorization-code principal. /// At the token endpoint, requires the inbound DPoP /// proof's jkt to match this claim. /// /// The claim is added with an empty Destinations set so it persists in the auth-code /// principal serialization but never leaks into issued access / id tokens. /// /// internal sealed class BindDpopJktAtAuthorizeHandler : IOpenIddictServerHandler { /// Internal claim type used to carry the bound jkt across requests. public const string ClaimType = "oi_dpop_jkt_binding"; private readonly DpopOptions _options; private readonly ILogger _logger; public BindDpopJktAtAuthorizeHandler( IOptions identityOptions, ILogger logger) { _options = (identityOptions ?? throw new ArgumentNullException(nameof(identityOptions))).Value.Dpop; _logger = logger ?? throw new ArgumentNullException(nameof(logger)); } public static OpenIddictServerHandlerDescriptor Descriptor { get; } = OpenIddictServerHandlerDescriptor.CreateBuilder() .UseScopedHandler() // Must run AFTER HandleAuthorizationRequestHandler so a principal exists, // but BEFORE the AttachAuthorizationCode default handler so the claim is included. .SetOrder(OpenIddictServerHandlers.Authentication.AttachPrincipal.Descriptor.Order + 200) .SetType(OpenIddictServerHandlerType.Custom) .Build(); public ValueTask HandleAsync(HandleAuthorizationRequestContext context) { if (!_options.Enabled) return default; if (context.Principal is null) return default; var jkt = (string?)context.Request["dpop_jkt"]; if (string.IsNullOrEmpty(jkt)) return default; if (!IsWellFormedJkt(jkt)) { _logger.LogWarning("Authorize request rejected: malformed dpop_jkt parameter (length={Len})", jkt.Length); context.Reject( error: Errors.InvalidRequest, description: "dpop_jkt parameter must be a base64url-encoded SHA-256 thumbprint (43 chars)."); return default; } if (context.Principal.Identity is not ClaimsIdentity identity) return default; // Add binding claim with empty destinations: persisted in auth-code, absent from tokens. var claim = new Claim(ClaimType, jkt); identity.AddClaim(claim); claim.SetDestinations(Array.Empty()); _logger.LogDebug("Bound dpop_jkt {Jkt} to authorization-code principal (RFC 9449 \u00a710).", jkt); return default; } /// /// Per RFC 9449 §10 the parameter is a JWK thumbprint per RFC 7638: SHA-256 base64url-encoded /// without padding ⇒ exactly 43 base64url characters [A-Za-z0-9_-]. /// private static bool IsWellFormedJkt(string value) { if (value.Length != 43) return false; foreach (var ch in value) { var ok = (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9') || ch == '-' || ch == '_'; if (!ok) return false; } return true; } } Path: redb-identity/src/redb.Identity.Core/OpenIddict/Handlers/CaptureRevokedTokenUserHandler.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/OpenIddict/Handlers/CaptureRevokedTokenUserHandler.cs ---- using OpenIddict.Server; using redb.Identity.Core.Services; using static OpenIddict.Server.OpenIddictServerEvents; namespace redb.Identity.Core.OpenIddict.Handlers; /// /// Hands the internal user id of a token revoked at the revocation endpoint (RFC 7009) to the route /// exchange, so the TokenRevoked audit event names the user (RevocationEndpointProcessor). /// A subscriber that caches token checks per user (a resource server introspecting in process, for /// one) then drops only that user's entries instead of all of them. /// /// Only for user grants: a client-credentials token has no redb:user_id, and an unknown or /// invalid token has no principal; the event then carries no user, as before. /// /// internal sealed class CaptureRevokedTokenUserHandler : IOpenIddictServerHandler { /// The exchange property the internal user id is put in. public const string ExchangeProperty = "identity:revoked-user-id"; public static OpenIddictServerHandlerDescriptor Descriptor { get; } = OpenIddictServerHandlerDescriptor.CreateBuilder() .UseSingletonHandler() .SetOrder(int.MaxValue - 1000) .Build(); public ValueTask HandleAsync(HandleRevocationRequestContext context) { ArgumentNullException.ThrowIfNull(context); var userId = context.GenericTokenPrincipal?.FindFirst(IdentityPrincipalBuilder.InternalUserIdClaim)?.Value; if (!string.IsNullOrEmpty(userId) && context.Transaction.GetRouteExchange() is { } exchange) exchange.Properties[ExchangeProperty] = userId; return default; } } Path: redb-identity/src/redb.Identity.Core/OpenIddict/Handlers/DpopConfirmationPassThroughHandler.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/OpenIddict/Handlers/DpopConfirmationPassThroughHandler.cs ---- using System.Security.Claims; using System.Security.Cryptography; using System.Text; using System.Text.Json.Nodes; using Microsoft.IdentityModel.Tokens; using OpenIddict.Abstractions; using OpenIddict.Server; using OpenIddict.Validation; using redb.Identity.Core.Services; using static OpenIddict.Abstractions.OpenIddictConstants; namespace redb.Identity.Core.OpenIddict.Handlers; /// /// Proof of possession for DPoP-bound access tokens (RFC 9449 §7) at the server's own protected endpoints: /// /connect/userinfo and the management API. /// /// OpenIddict 7 checks the cnf claim of every token it validates and knows only the mTLS form /// (x5t#S256, RFC 8705): any other confirmation, such as the DPoP key thumbprint jkt that /// puts in access tokens, makes it throw (ID2196). A DPoP-only /// token therefore skips OpenIddict's check, and the DPoP proof is verified here instead, in the same handler, /// so the check is never turned off without the replacement having run. /// /// /// A token whose cnf carries jkt is accepted only under the DPoP authorization scheme with a /// proof signed by the bound key, matching the request method and URL, carrying the token hash (ath) and /// not seen before. A token without jkt under the DPoP scheme is rejected. A certificate-bound token /// keeps OpenIddict's check; with jkt alongside, the DPoP proof is required as well. /// /// internal static class DpopConfirmationPassThrough { /// The authorization scheme for DPoP-bound access tokens (RFC 9449 §7.1). internal const string DpopScheme = "DPoP"; /// Validation-stack transaction property: the authorization scheme the token came with. internal const string SchemeProperty = "identity:dpop-resource-scheme"; /// Validation-stack transaction property: the raw DPoP request header. internal const string ProofProperty = "identity:dpop-resource-proof"; /// Validation-stack transaction property: the HTTP method of the protected request. internal const string MethodProperty = "identity:dpop-resource-method"; /// Validation-stack transaction property: the absolute URL of the protected request. internal const string UrlProperty = "identity:dpop-resource-url"; /// /// Exchange (server stack) or transaction (validation stack) property: the WWW-Authenticate value for a /// rejection made here. /// internal const string ChallengeProperty = "identity:dpop-resource-challenge"; /// RFC 9449 §7.1 challenge: DPoP error="invalid_token", error_description="...". internal static string BuildChallenge(string description) { var safe = description.Replace("\\", "\\\\").Replace("\"", "\\\""); return $"{DpopScheme} error=\"{Errors.InvalidToken}\", error_description=\"{safe}\""; } internal static bool IsDpopOnly(ClaimsPrincipal? principal) { var cnf = ReadConfirmation(principal); return cnf is not null && cnf.ContainsKey("jkt") && !cnf.ContainsKey("x5t#S256"); } /// The DPoP key thumbprint the token is bound to, or null when it has none. internal static string? BoundJkt(ClaimsPrincipal? principal) { var cnf = ReadConfirmation(principal); if (cnf is null || !cnf.TryGetPropertyValue("jkt", out var node) || node is not JsonValue value) return null; return value.TryGetValue(out var jkt) && !string.IsNullOrEmpty(jkt) ? jkt : null; } /// /// Checks how a token is presented at a protected endpoint. Returns null when the request may proceed, /// otherwise the description of an invalid_token rejection. /// internal static async ValueTask CheckPresentationAsync( DpopProofValidator validator, ClaimsPrincipal? principal, string? token, string? scheme, string? proof, string? method, string? url, CancellationToken ct) { var dpopScheme = string.Equals(scheme, DpopScheme, StringComparison.OrdinalIgnoreCase); var boundJkt = BoundJkt(principal); if (boundJkt is null) return dpopScheme ? "The access token is not bound to a DPoP key." : null; if (!dpopScheme) return "A DPoP-bound access token must be presented with the DPoP authorization scheme."; if (string.IsNullOrEmpty(proof)) return "A DPoP proof is required for a DPoP-bound access token."; if (string.IsNullOrEmpty(token) || string.IsNullOrEmpty(method) || string.IsNullOrEmpty(url)) return "The DPoP proof cannot be checked on this transport."; var result = await validator.ValidateAsync( proof: proof, httpMethod: method, httpUri: url, expectedAth: ComputeAth(token), ct: ct).ConfigureAwait(false); if (!result.IsValid) return result.ErrorDescription ?? "The DPoP proof is invalid."; if (!string.Equals(result.Jkt, boundJkt, StringComparison.Ordinal)) return "The DPoP proof key does not match the key the access token is bound to."; return null; } /// RFC 9449 §4.2 ath: base64url SHA-256 of the ASCII access token. internal static string ComputeAth(string accessToken) => Base64UrlEncoder.Encode(SHA256.HashData(Encoding.ASCII.GetBytes(accessToken))); /// Splits an Authorization header into its scheme; null when there is none. internal static string? SchemeOf(string? authorizationHeader) { if (string.IsNullOrWhiteSpace(authorizationHeader)) return null; var trimmed = authorizationHeader.TrimStart(); var end = trimmed.IndexOfAny([' ', '\t']); return end < 0 ? trimmed : trimmed[..end]; } private static JsonObject? ReadConfirmation(ClaimsPrincipal? principal) { var confirmation = principal?.GetClaim(Claims.Confirmation); if (string.IsNullOrEmpty(confirmation)) return null; try { return JsonNode.Parse(confirmation) as JsonObject; } catch (System.Text.Json.JsonException) { return null; // malformed: leave it to OpenIddict, which rejects it } } } /// /// Server stack: proof of possession at /connect/userinfo (see ). /// Introspection and revocation are called by the client or resource server with its own credentials and carry /// no proof; for them only OpenIddict's check is skipped. /// internal sealed class DpopConfirmationServerPassThroughHandler : IOpenIddictServerHandler { private readonly DpopProofValidator _validator; public DpopConfirmationServerPassThroughHandler(DpopProofValidator validator) => _validator = validator ?? throw new ArgumentNullException(nameof(validator)); public static OpenIddictServerHandlerDescriptor Descriptor { get; } = OpenIddictServerHandlerDescriptor.CreateBuilder() .UseSingletonHandler() .SetOrder(OpenIddictServerHandlers.Protection.ValidateProofOfPossession.Descriptor.Order - 1) .SetType(OpenIddictServerHandlerType.Custom) .Build(); public async ValueTask HandleAsync(OpenIddictServerEvents.ValidateTokenContext context) { ArgumentNullException.ThrowIfNull(context); if (context.EndpointType is OpenIddictServerEndpointType.UserInfo) { var exchange = context.Transaction.GetRouteExchange(); var error = await DpopConfirmationPassThrough.CheckPresentationAsync( _validator, context.Principal, context.Token, DpopConfirmationPassThrough.SchemeOf(exchange?.In.GetHeader("Authorization")), exchange?.In.GetHeader("DPoP"), exchange?.In.GetHeader("redbHttp.Method"), exchange?.In.GetHeader("redbHttp.Url"), context.CancellationToken).ConfigureAwait(false); if (error is not null) { if (exchange is not null) exchange.Properties[DpopConfirmationPassThrough.ChallengeProperty] = DpopConfirmationPassThrough.BuildChallenge(error); context.Reject(error: Errors.InvalidToken, description: error); return; } } if (DpopConfirmationPassThrough.IsDpopOnly(context.Principal)) context.DisableProofOfPossessionValidation = true; } } /// /// Validation stack: proof of possession at the management API (see ). /// The request details come from the transaction properties set by /// . /// internal sealed class DpopConfirmationValidationPassThroughHandler : IOpenIddictValidationHandler { private readonly DpopProofValidator _validator; public DpopConfirmationValidationPassThroughHandler(DpopProofValidator validator) => _validator = validator ?? throw new ArgumentNullException(nameof(validator)); public static OpenIddictValidationHandlerDescriptor Descriptor { get; } = OpenIddictValidationHandlerDescriptor.CreateBuilder() .UseSingletonHandler() .SetOrder(OpenIddictValidationHandlers.Protection.ValidateProofOfPossession.Descriptor.Order - 1) .SetType(OpenIddictValidationHandlerType.Custom) .Build(); public async ValueTask HandleAsync(OpenIddictValidationEvents.ValidateTokenContext context) { ArgumentNullException.ThrowIfNull(context); var properties = context.Transaction.Properties; var error = await DpopConfirmationPassThrough.CheckPresentationAsync( _validator, context.Principal, context.Token, Read(properties, DpopConfirmationPassThrough.SchemeProperty), Read(properties, DpopConfirmationPassThrough.ProofProperty), Read(properties, DpopConfirmationPassThrough.MethodProperty), Read(properties, DpopConfirmationPassThrough.UrlProperty), context.CancellationToken).ConfigureAwait(false); if (error is not null) { properties[DpopConfirmationPassThrough.ChallengeProperty] = DpopConfirmationPassThrough.BuildChallenge(error); context.Reject(error: Errors.InvalidToken, description: error); return; } if (DpopConfirmationPassThrough.IsDpopOnly(context.Principal)) context.DisableProofOfPossessionValidation = true; static string? Read(IDictionary properties, string key) => properties.TryGetValue(key, out var value) ? value as string : null; } } Path: redb-identity/src/redb.Identity.Core/OpenIddict/Handlers/EnforceDpopJktBindingHandler.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/OpenIddict/Handlers/EnforceDpopJktBindingHandler.cs ---- using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using OpenIddict.Abstractions; using OpenIddict.Server; using redb.Identity.Core.Configuration; using static OpenIddict.Abstractions.OpenIddictConstants; using static OpenIddict.Server.OpenIddictServerEvents; namespace redb.Identity.Core.OpenIddict.Handlers; /// /// Z4 P2.1 (RFC 9449 §10): if the redeemed authorization-code carries a /// oi_dpop_jkt_binding claim, the token request MUST present a DPoP proof whose /// jkt matches that binding. Mismatched or missing proof rejects with /// invalid_grant. /// internal sealed class EnforceDpopJktBindingHandler : IOpenIddictServerHandler { private readonly DpopOptions _options; private readonly ILogger _logger; public EnforceDpopJktBindingHandler( IOptions identityOptions, ILogger logger) { _options = (identityOptions ?? throw new ArgumentNullException(nameof(identityOptions))).Value.Dpop; _logger = logger ?? throw new ArgumentNullException(nameof(logger)); } public static OpenIddictServerHandlerDescriptor Descriptor { get; } = OpenIddictServerHandlerDescriptor.CreateBuilder() .UseScopedHandler() // Run early — AFTER built-in AttachPrincipal but BEFORE any sign-in. .SetOrder(OpenIddictServerHandlers.Exchange.AttachPrincipal.Descriptor.Order + 50) .SetType(OpenIddictServerHandlerType.Custom) .Build(); public ValueTask HandleAsync(HandleTokenRequestContext context) { if (!_options.Enabled) return default; // Only authorization_code redemption can be jkt-bound at /authorize. if (!context.Request.IsAuthorizationCodeGrantType()) return default; var bindingJkt = context.Principal?.GetClaim(BindDpopJktAtAuthorizeHandler.ClaimType); if (string.IsNullOrEmpty(bindingJkt)) return default; // Pull the proof's jkt the ValidateDpopProofHandler already stashed. if (!context.Transaction.Properties.TryGetValue("dpop:jkt", out var proofObj) || proofObj is not string proofJkt || string.IsNullOrEmpty(proofJkt)) { _logger.LogWarning("authorization_code carries dpop_jkt binding {Jkt} but no DPoP proof was presented at /token.", bindingJkt); context.Reject( error: Errors.InvalidGrant, description: "DPoP proof required: the authorization_code is bound to a DPoP key (RFC 9449 \u00a710)."); return default; } if (!string.Equals(bindingJkt, proofJkt, StringComparison.Ordinal)) { _logger.LogWarning("DPoP jkt mismatch: bound={Bound} proof={Proof}", bindingJkt, proofJkt); context.Reject( error: Errors.InvalidGrant, description: "DPoP proof key thumbprint does not match the dpop_jkt bound to the authorization_code."); return default; } _logger.LogDebug("DPoP jkt binding satisfied: {Jkt}", proofJkt); return default; } } Path: redb-identity/src/redb.Identity.Core/OpenIddict/Handlers/ExtractAuthorizationRequestHandler.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/OpenIddict/Handlers/ExtractAuthorizationRequestHandler.cs ---- using OpenIddict.Server; using static OpenIddict.Server.OpenIddictServerEvents; namespace redb.Identity.Core.OpenIddict.Handlers; /// /// Extracts the authorization request parameters from . /// internal sealed class ExtractAuthorizationRequestHandler : IOpenIddictServerHandler { public static OpenIddictServerHandlerDescriptor Descriptor { get; } = OpenIddictServerHandlerDescriptor.CreateBuilder() .UseSingletonHandler() .SetOrder(int.MinValue + 50_000) .Build(); public ValueTask HandleAsync(ExtractAuthorizationRequestContext context) { var exchange = context.Transaction.GetRouteExchange(); if (exchange is null) return default; context.Request = RedbRouteOpenIddictServerHelpers.CreateRequestFromExchange(exchange); return default; } } Path: redb-identity/src/redb.Identity.Core/OpenIddict/Handlers/ExtractClientCredentialsHandler.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/OpenIddict/Handlers/ExtractClientCredentialsHandler.cs ---- using System.Text; using OpenIddict.Abstractions; using OpenIddict.Server; using redb.Identity.Contracts.Common; using static OpenIddict.Server.OpenIddictServerEvents; namespace redb.Identity.Core.OpenIddict.Handlers; /// /// Shared logic for extracting client credentials from Authorization: Basic header. /// Per RFC 6749 §2.3.1. Used by the Token, Introspection, Revocation, Device Authorization and /// Pushed Authorization endpoints. /// internal static class BasicAuthHelper { /// /// Challenge sent with invalid_client when the client authenticated through the /// Authorization header (RFC 6749 §5.2). /// internal const string Challenge = "Basic realm=\"identity\""; /// /// True when the request carries an Authorization: Basic header, readable or not. /// internal static bool HasBasicHeader(redb.Route.Abstractions.IExchange exchange) => exchange.In.Headers.TryGetValue("Authorization", out var headerValue) && headerValue is string auth && auth.StartsWith("Basic ", StringComparison.OrdinalIgnoreCase); internal static void Apply(BaseValidatingContext context, OpenIddictRequest? request) { if (request is null) return; var exchange = context.Transaction.GetRouteExchange(); if (exchange is null || !HasBasicHeader(exchange)) return; var encoded = ((string)exchange.In.Headers["Authorization"]!)["Basic ".Length..].Trim(); // The client attempted authentication through the header, so a value that cannot be read // (not canonical base64, or no client_id:client_secret pair) is a failed client // authentication, answered with invalid_client (RFC 6749 §5.2), not a missing client_id. string? decoded = Base64Canonical.TryDecode(encoded, out var bytes) ? Encoding.UTF8.GetString(bytes) : null; var colonIdx = decoded?.IndexOf(':') ?? -1; if (decoded is null || colonIdx <= 0) { context.Reject( error: OpenIddictConstants.Errors.InvalidClient, description: "The Authorization header does not carry readable Basic client credentials."); return; } request.ClientId = Uri.UnescapeDataString(decoded[..colonIdx]); request.ClientSecret = Uri.UnescapeDataString(decoded[(colonIdx + 1)..]); } } /// /// Extracts client credentials from Authorization: Basic on the Token endpoint. /// internal sealed class ExtractClientCredentialsHandler : IOpenIddictServerHandler { public static OpenIddictServerHandlerDescriptor Descriptor { get; } = OpenIddictServerHandlerDescriptor.CreateBuilder() .UseSingletonHandler() .SetOrder(int.MinValue + 50_001) .Build(); public ValueTask HandleAsync(ExtractTokenRequestContext context) { BasicAuthHelper.Apply(context, context.Request); return default; } } /// /// Extracts client credentials from Authorization: Basic on the Introspection endpoint. /// Per RFC 7662 §2.1. /// internal sealed class ExtractIntrospectionClientCredentialsHandler : IOpenIddictServerHandler { public static OpenIddictServerHandlerDescriptor Descriptor { get; } = OpenIddictServerHandlerDescriptor.CreateBuilder() .UseSingletonHandler() .SetOrder(int.MinValue + 50_001) .Build(); public ValueTask HandleAsync(ExtractIntrospectionRequestContext context) { BasicAuthHelper.Apply(context, context.Request); return default; } } /// /// Extracts client credentials from Authorization: Basic on the Revocation endpoint. /// Per RFC 7009 §2.1. /// internal sealed class ExtractRevocationClientCredentialsHandler : IOpenIddictServerHandler { public static OpenIddictServerHandlerDescriptor Descriptor { get; } = OpenIddictServerHandlerDescriptor.CreateBuilder() .UseSingletonHandler() .SetOrder(int.MinValue + 50_001) .Build(); public ValueTask HandleAsync(ExtractRevocationRequestContext context) { BasicAuthHelper.Apply(context, context.Request); return default; } } /// /// Extracts client credentials from Authorization: Basic on the Device Authorization endpoint. /// Per RFC 8628 §3.1. /// internal sealed class ExtractDeviceClientCredentialsHandler : IOpenIddictServerHandler { public static OpenIddictServerHandlerDescriptor Descriptor { get; } = OpenIddictServerHandlerDescriptor.CreateBuilder() .UseSingletonHandler() .SetOrder(int.MinValue + 50_001) .Build(); public ValueTask HandleAsync(ExtractDeviceAuthorizationRequestContext context) { BasicAuthHelper.Apply(context, context.Request); return default; } } /// /// Extracts client credentials from Authorization: Basic on the Pushed Authorization endpoint. /// Per RFC 9126 §2. /// internal sealed class ExtractPushedAuthorizationClientCredentialsHandler : IOpenIddictServerHandler { public static OpenIddictServerHandlerDescriptor Descriptor { get; } = OpenIddictServerHandlerDescriptor.CreateBuilder() .UseSingletonHandler() .SetOrder(int.MinValue + 50_001) .Build(); public ValueTask HandleAsync(ExtractPushedAuthorizationRequestContext context) { BasicAuthHelper.Apply(context, context.Request); return default; } } Path: redb-identity/src/redb.Identity.Core/OpenIddict/Handlers/ExtractConfigurationRequestHandler.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/OpenIddict/Handlers/ExtractConfigurationRequestHandler.cs ---- using OpenIddict.Abstractions; using OpenIddict.Server; using static OpenIddict.Server.OpenIddictServerEvents; namespace redb.Identity.Core.OpenIddict.Handlers; /// /// Extracts the discovery (configuration) request from . /// Discovery is a simple GET with no parameters, so we just set an empty request. /// internal sealed class ExtractConfigurationRequestHandler : IOpenIddictServerHandler { public static OpenIddictServerHandlerDescriptor Descriptor { get; } = OpenIddictServerHandlerDescriptor.CreateBuilder() .UseSingletonHandler() .SetOrder(int.MinValue + 50_000) .Build(); public ValueTask HandleAsync(ExtractConfigurationRequestContext context) { var exchange = context.Transaction.GetRouteExchange(); if (exchange is null) return default; // Discovery endpoint is a simple GET — set an empty OpenIddict request context.Request = new OpenIddictRequest(); return default; } } Path: redb-identity/src/redb.Identity.Core/OpenIddict/Handlers/ExtractDeviceRequestHandler.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/OpenIddict/Handlers/ExtractDeviceRequestHandler.cs ---- using OpenIddict.Server; using static OpenIddict.Server.OpenIddictServerEvents; namespace redb.Identity.Core.OpenIddict.Handlers; /// /// Extracts the device authorization request parameters from . /// internal sealed class ExtractDeviceRequestHandler : IOpenIddictServerHandler { public static OpenIddictServerHandlerDescriptor Descriptor { get; } = OpenIddictServerHandlerDescriptor.CreateBuilder() .UseSingletonHandler() .SetOrder(int.MinValue + 50_000) .Build(); public ValueTask HandleAsync(ExtractDeviceAuthorizationRequestContext context) { var exchange = context.Transaction.GetRouteExchange(); if (exchange is null) return default; context.Request = RedbRouteOpenIddictServerHelpers.CreateRequestFromExchange(exchange); return default; } } Path: redb-identity/src/redb.Identity.Core/OpenIddict/Handlers/ExtractIntrospectionRequestHandler.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/OpenIddict/Handlers/ExtractIntrospectionRequestHandler.cs ---- using OpenIddict.Server; using static OpenIddict.Server.OpenIddictServerEvents; namespace redb.Identity.Core.OpenIddict.Handlers; /// /// Extracts the introspection request parameters from . /// internal sealed class ExtractIntrospectionRequestHandler : IOpenIddictServerHandler { public static OpenIddictServerHandlerDescriptor Descriptor { get; } = OpenIddictServerHandlerDescriptor.CreateBuilder() .UseSingletonHandler() .SetOrder(int.MinValue + 50_000) .Build(); public ValueTask HandleAsync(ExtractIntrospectionRequestContext context) { var exchange = context.Transaction.GetRouteExchange(); if (exchange is null) return default; context.Request = RedbRouteOpenIddictServerHelpers.CreateRequestFromExchange(exchange); return default; } } Path: redb-identity/src/redb.Identity.Core/OpenIddict/Handlers/ExtractJwksRequestHandler.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/OpenIddict/Handlers/ExtractJwksRequestHandler.cs ---- using OpenIddict.Abstractions; using OpenIddict.Server; using static OpenIddict.Server.OpenIddictServerEvents; namespace redb.Identity.Core.OpenIddict.Handlers; /// /// Extracts the JWKS request from . /// JWKS is a simple GET with no parameters, so we just set an empty request. /// internal sealed class ExtractJwksRequestHandler : IOpenIddictServerHandler { public static OpenIddictServerHandlerDescriptor Descriptor { get; } = OpenIddictServerHandlerDescriptor.CreateBuilder() .UseSingletonHandler() .SetOrder(int.MinValue + 50_000) .Build(); public ValueTask HandleAsync(ExtractJsonWebKeySetRequestContext context) { var exchange = context.Transaction.GetRouteExchange(); if (exchange is null) return default; // JWKS endpoint is a simple GET — set an empty OpenIddict request context.Request = new OpenIddictRequest(); return default; } } Path: redb-identity/src/redb.Identity.Core/OpenIddict/Handlers/ExtractPushedAuthorizationRequestHandler.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/OpenIddict/Handlers/ExtractPushedAuthorizationRequestHandler.cs ---- using OpenIddict.Server; using static OpenIddict.Server.OpenIddictServerEvents; namespace redb.Identity.Core.OpenIddict.Handlers; /// /// Extracts the Pushed Authorization Request parameters (RFC 9126) from /// — same form-body shape as the Token endpoint. /// internal sealed class ExtractPushedAuthorizationRequestHandler : IOpenIddictServerHandler { public static OpenIddictServerHandlerDescriptor Descriptor { get; } = OpenIddictServerHandlerDescriptor.CreateBuilder() .UseSingletonHandler() .SetOrder(int.MinValue + 50_000) .Build(); public ValueTask HandleAsync(ExtractPushedAuthorizationRequestContext context) { var exchange = context.Transaction.GetRouteExchange(); if (exchange is null) return default; context.Request = RedbRouteOpenIddictServerHelpers.CreateRequestFromExchange(exchange); return default; } } Path: redb-identity/src/redb.Identity.Core/OpenIddict/Handlers/ExtractRevocationRequestHandler.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/OpenIddict/Handlers/ExtractRevocationRequestHandler.cs ---- using OpenIddict.Server; using static OpenIddict.Server.OpenIddictServerEvents; namespace redb.Identity.Core.OpenIddict.Handlers; /// /// Extracts the revocation request parameters from . /// internal sealed class ExtractRevocationRequestHandler : IOpenIddictServerHandler { public static OpenIddictServerHandlerDescriptor Descriptor { get; } = OpenIddictServerHandlerDescriptor.CreateBuilder() .UseSingletonHandler() .SetOrder(int.MinValue + 50_000) .Build(); public ValueTask HandleAsync(ExtractRevocationRequestContext context) { var exchange = context.Transaction.GetRouteExchange(); if (exchange is null) return default; context.Request = RedbRouteOpenIddictServerHelpers.CreateRequestFromExchange(exchange); return default; } } Path: redb-identity/src/redb.Identity.Core/OpenIddict/Handlers/ExtractTokenRequestHandler.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/OpenIddict/Handlers/ExtractTokenRequestHandler.cs ---- using OpenIddict.Server; using static OpenIddict.Server.OpenIddictServerEvents; namespace redb.Identity.Core.OpenIddict.Handlers; /// /// Extracts the token request parameters from . /// internal sealed class ExtractTokenRequestHandler : IOpenIddictServerHandler { public static OpenIddictServerHandlerDescriptor Descriptor { get; } = OpenIddictServerHandlerDescriptor.CreateBuilder() .UseSingletonHandler() .SetOrder(int.MinValue + 50_000) .Build(); public ValueTask HandleAsync(ExtractTokenRequestContext context) { var exchange = context.Transaction.GetRouteExchange(); if (exchange is null) return default; context.Request = RedbRouteOpenIddictServerHelpers.CreateRequestFromExchange(exchange); return default; } } Path: redb-identity/src/redb.Identity.Core/OpenIddict/Handlers/ExtractUserinfoRequestHandler.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/OpenIddict/Handlers/ExtractUserinfoRequestHandler.cs ---- using OpenIddict.Abstractions; using OpenIddict.Server; using static OpenIddict.Server.OpenIddictServerEvents; namespace redb.Identity.Core.OpenIddict.Handlers; /// /// Extracts the userinfo request parameters from . /// Additionally extracts Bearer token from the Authorization header. /// internal sealed class ExtractUserinfoRequestHandler : IOpenIddictServerHandler { public static OpenIddictServerHandlerDescriptor Descriptor { get; } = OpenIddictServerHandlerDescriptor.CreateBuilder() .UseSingletonHandler() .SetOrder(int.MinValue + 50_000) .Build(); public ValueTask HandleAsync(ExtractUserInfoRequestContext context) { var exchange = context.Transaction.GetRouteExchange(); if (exchange is null) return default; context.Request = RedbRouteOpenIddictServerHelpers.CreateRequestFromExchange(exchange); // The access token comes in the Authorization header under the Bearer scheme, or under the DPoP // scheme for a DPoP-bound token (RFC 9449 §7.1). Whether the scheme fits the token is checked by // DpopConfirmationServerPassThroughHandler once the token is validated. if (string.IsNullOrEmpty(context.Request.AccessToken) && exchange.In.Headers.TryGetValue("Authorization", out var authValue) && authValue is string auth) { foreach (var scheme in (ReadOnlySpan)["Bearer ", "DPoP "]) { if (auth.StartsWith(scheme, StringComparison.OrdinalIgnoreCase)) { context.Request.AccessToken = auth[scheme.Length..].Trim(); break; } } } return default; } } Path: redb-identity/src/redb.Identity.Core/OpenIddict/Handlers/ExtractVerificationRequestHandler.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/OpenIddict/Handlers/ExtractVerificationRequestHandler.cs ---- using OpenIddict.Server; using static OpenIddict.Server.OpenIddictServerEvents; namespace redb.Identity.Core.OpenIddict.Handlers; /// /// Extracts the end-user verification request parameters from . /// Part of the Device Code Flow (RFC 8628 §3.3). /// internal sealed class ExtractVerificationRequestHandler : IOpenIddictServerHandler { public static OpenIddictServerHandlerDescriptor Descriptor { get; } = OpenIddictServerHandlerDescriptor.CreateBuilder() .UseSingletonHandler() .SetOrder(int.MinValue + 50_000) .Build(); public ValueTask HandleAsync(ExtractEndUserVerificationRequestContext context) { var exchange = context.Transaction.GetRouteExchange(); if (exchange is null) return default; context.Request = RedbRouteOpenIddictServerHelpers.CreateRequestFromExchange(exchange); return default; } } Path: redb-identity/src/redb.Identity.Core/OpenIddict/Handlers/HandleAuthorizationRequestHandler.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/OpenIddict/Handlers/HandleAuthorizationRequestHandler.cs ---- using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using OpenIddict.Abstractions; using OpenIddict.Server; using redb.Core; using redb.Identity.Core.Models; using redb.Identity.Core.Services; using redb.Route.Abstractions; using static OpenIddict.Abstractions.OpenIddictConstants; using static OpenIddict.Server.OpenIddictServerEvents; using static OpenIddict.Server.OpenIddictServerHandlerDescriptor; namespace redb.Identity.Core.OpenIddict.Handlers; /// /// Handles for the authorization_code flow. /// Expects the principal to be already attached by /// (session cookie → user ID → principal). If no principal is present, rejects with login_required. /// Also handles consent tracking and session record creation. /// internal sealed class HandleAuthorizationRequestHandler : IOpenIddictServerHandler { private readonly IServiceProvider _sp; private readonly ILogger _logger; public HandleAuthorizationRequestHandler(IServiceProvider sp, ILogger logger) { _sp = sp; _logger = logger; } public static OpenIddictServerHandlerDescriptor Descriptor { get; } = CreateBuilder() .UseScopedHandler() .SetOrder(OpenIddictServerHandlers.Authentication.AttachPrincipal.Descriptor.Order + 100) .SetType(OpenIddictServerHandlerType.Custom) .Build(); public async ValueTask HandleAsync(HandleAuthorizationRequestContext context) { // RFC 9126 §5 — per-client Pushed Authorization Request enforcement. When the client's // registration carries `require_pushed_authorization_requests=true`, any direct // /connect/authorize that did NOT come through /connect/par (request_uri parameter) // must be rejected with `invalid_request` BEFORE we surface other errors like // login_required / consent_required — the request shape itself is non-conformant // for this client. Layered on top of the global enforcement flag so individual // high-assurance clients (FAPI / financial-grade APIs) can demand PAR even when // the rest of the deployment doesn't. var clientIdEarly = context.Request.ClientId; if (!string.IsNullOrEmpty(clientIdEarly) && string.IsNullOrEmpty(context.Request.RequestUri)) { var redbEarly = _sp.GetService(); if (redbEarly is not null) { var consentSvcEarly = new ConsentService(redbEarly); var appIdEarly = await consentSvcEarly.FindApplicationIdAsync(clientIdEarly).ConfigureAwait(false); if (appIdEarly is > 0) { var appEarly = (await redbEarly.LoadAsync(appIdEarly.Value) .ConfigureAwait(false)); if (appEarly?.Props.RequirePushedAuthorizationRequests == true) { context.Reject( error: Errors.InvalidRequest, description: "Pushed Authorization Requests (RFC 9126) are required for this " + "client. Submit the authorization request to /connect/par first " + "and use the returned request_uri."); return; } } } } var prompt = context.Request.Prompt; // Set once the re-auth gate below is satisfied; the marker cookie is consumed only on the // FINAL success (not here) so an intervening consent round-trip does not lose it. var reauthGateSatisfied = false; // ── Re-authentication gate (OIDC §3.1.2.1) — prompt=login / max_age ────────────────── // Both force the End-User to (re)authenticate: prompt=login unconditionally; max_age when // the last authentication (auth_time) is older than the allowed age. We enforce them the // SAME way — send the user to /login (a plain login_required that the HTTP facade turns // into a /login redirect, NOT an error delivered to the RP) and complete once they have // re-authenticated. The redirect loop is broken WITHOUT a bypass by a DataProtection-signed // re-auth marker cookie (see SessionCookieProcessors.HandleReauthCookie): we stamp "re-auth // requested at T" and only accept the request once the session's auth_time is >= T, i.e. the // End-User authenticated AFTER we asked. The marker is consumed (cookie expired) on success // so a stale marker can never satisfy a later prompt=login. Runs BEFORE the no-principal // check so prompt=login for a logged-out user needs only a single /login (the marker is set // even without a principal — it is just a timestamp). { var promptLogin = prompt?.Contains("login") == true; // max_age. OpenIddict normalises max_age=0 to null, but §3.1.2.1 still demands re-auth // in that case, so read the raw parameter as a fallback. long? maxAge = context.Request.MaxAge; if (!maxAge.HasValue) { var rawParam = context.Request.GetParameter("max_age"); var raw = rawParam?.ToString(); if (long.TryParse(raw, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var rawMaxAge) && rawMaxAge >= 0) { maxAge = rawMaxAge; } } var maxAgeStale = false; if (context.Principal is not null && maxAge.HasValue) { var authTimeClaim = context.Principal.GetClaim(Claims.AuthenticationTime); var nowSeconds = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); maxAgeStale = true; // absent auth_time → treat as stale if (long.TryParse(authTimeClaim, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var authTime)) { // `>=` so max_age=0 deterministically forces re-auth even at the second boundary. maxAgeStale = (nowSeconds - authTime) >= maxAge.Value; } } if (promptLogin || maxAgeStale) { var exchange = context.Transaction.GetRouteExchange(); // The session active on THIS request (0 = none). ReadSessionCookie decodes it from // the session ticket into the "session_id" header. long currentSessionId = 0; if (exchange is not null && exchange.In.Headers.TryGetValue("session_id", out var sidObj)) { currentSessionId = sidObj is long sl ? sl : (sidObj is string ss && long.TryParse(ss, out var psl) ? psl : 0); } // Did the End-User sign in again since we forced re-auth? The signed re-auth marker // (ReadSessionCookie → "reauth_marked_sid") carries the session that was active when // we asked; a fresh /login always mints a NEW session, so a CHANGED active session id // proves the re-authentication. Keying on the session id — not the second-precision // auth_time — removes the same-second window where an unchanged session could be // mistaken for a re-auth. var reauthSatisfied = false; if (exchange is not null && exchange.In.Headers.TryGetValue("reauth_marked_sid", out var markedObj)) { long markedSid = markedObj is long ml ? ml : (markedObj is string ms && long.TryParse(ms, out var pml) ? pml : 0); // currentSessionId != 0 covers the logged-out prompt=login case (marked 0, now a // real session); != markedSid covers the logged-in case (session replaced by /login). reauthSatisfied = currentSessionId != 0 && currentSessionId != markedSid; } if (reauthSatisfied) { // Re-auth done — proceed. The marker is consumed on the final success below, // so a consent round-trip in between does not drop it. reauthGateSatisfied = true; } else { // Force (re)authentication: mark the current session and reject with a plain // login_required (no force_login) so the facade redirects to /login. if (exchange is not null) exchange.Properties["reauth_set"] = currentSessionId; context.Reject( error: Errors.LoginRequired, description: promptLogin ? "Re-authentication required (prompt=login)." : "Re-authentication required (max_age exceeded)."); return; } } } // prompt=none: MUST NOT display any UI — if no principal, reject immediately. // Flag the exchange so downstream HTTP processors skip their /login & /consent UI // overrides; the OIDC §3.1.2.6 contract requires the error to flow back to redirect_uri. if (prompt?.Contains("none") == true && context.Principal is null) { var exchange = context.Transaction.GetRouteExchange(); if (exchange is not null) exchange.Properties["prompt_none"] = true; context.Reject( error: Errors.LoginRequired, description: "No active session and prompt=none was requested."); return; } // No principal = no session = user not authenticated → login_required if (context.Principal is null) { context.Reject( error: Errors.LoginRequired, description: "User authentication is required. Please log in."); return; } // The public sub claim is now a GUID; the bigint _users._id rides alongside in // the internal `redb:user_id` claim emitted by IdentityPrincipalBuilder. var subject = context.Principal.GetClaim(Claims.Subject); var internalUid = context.Principal.GetClaim(IdentityPrincipalBuilder.InternalUserIdClaim); if (string.IsNullOrEmpty(subject) || string.IsNullOrEmpty(internalUid) || !long.TryParse(internalUid, out var userId)) { context.Reject( error: Errors.ServerError, description: "Invalid session principal: missing subject."); return; } // ── Consent tracking ── var scopes = context.Request.GetScopes(); var clientId = context.Request.ClientId; long appObjectId = 0; // ── Consent + session tracking (requires IRedbService) ── var redb = _sp.GetService(); if (redb is null) { // Degraded mode — no tracking, just log and return _logger.LogDebug("Authorization granted for user {UserId} (degraded mode)", userId); return; } if (!string.IsNullOrEmpty(clientId)) { var consentService = new ConsentService(redb); var appId = await consentService.FindApplicationIdAsync(clientId) .ConfigureAwait(false); if (appId is > 0) { appObjectId = appId.Value; var app = (await redb.LoadAsync(appId.Value) .ConfigureAwait(false)); if (app?.Props.ConsentType == ConsentTypes.Explicit) { var scopeList = scopes.ToList(); var forceConsent = prompt?.Contains("consent") == true; var existingConsent = forceConsent ? null // prompt=consent: always re-prompt regardless of prior consent : await consentService.CheckAsync( userId, appId.Value, scopeList).ConfigureAwait(false); if (existingConsent is null) { // Signal to the HTTP facade that consent is required. // The facade will redirect to a consent page instead of completing authorize. // After the user grants consent, they'll be redirected back to /connect/authorize. var exchange = context.Transaction.GetRouteExchange(); if (exchange is not null) { exchange.Properties["consent_required"] = true; exchange.Properties["consent_client_id"] = clientId!; exchange.Properties["consent_app_name"] = app.Name ?? clientId!; exchange.Properties["consent_scopes"] = string.Join(" ", scopeList); exchange.Properties["consent_user_id"] = userId; } // Reject with consent_required — the response post-processor // (or HTTP facade) will intercept this and redirect to the consent page // instead of sending the error to the client's redirect_uri. context.Reject( error: "consent_required", description: "User consent is required for the requested scopes."); _logger.LogDebug( "Consent required for user {UserId} to client '{ClientId}' — scopes: [{Scopes}]", userId, clientId, string.Join(", ", scopeList)); return; } } } } // Re-auth (prompt=login / max_age) completed successfully — consume the marker so it can // never satisfy a LATER prompt=login (that would be a bypass). Done only here, on the final // success after the consent gate, so an intervening /consent round-trip keeps the marker. if (reauthGateSatisfied) { var reauthExchange = context.Transaction.GetRouteExchange(); if (reauthExchange is not null) reauthExchange.Properties["reauth_clear"] = true; } // Session is now created at login time (LoginProcessor) and tracked via session_id in cookie. // Per-app authorization tracking is handled by OpenIddict's built-in authorization store. // The relying party is about to hold tokens obtained through this browser session, so this // session's back-channel logout has to reach it (Back-Channel Logout 1.0 §2.1). This is the one // point that knows both the session and the client, so the binding is recorded here. if (appObjectId > 0) { var boundSessionId = SessionIdOf(context.Transaction.GetRouteExchange()); if (boundSessionId > 0) { await new SessionService(redb) .BindClientAsync(boundSessionId, appObjectId, context.CancellationToken) .ConfigureAwait(false); } } _logger.LogDebug("Authorization granted for user {UserId} via session", userId); } /// The session active on this request: ReadSessionCookie decodes it from the session ticket into the "session_id" header. 0 when none. private static long SessionIdOf(IExchange? exchange) { if (exchange is null || !exchange.In.Headers.TryGetValue("session_id", out var raw)) return 0; return raw switch { long value => value, string text when long.TryParse(text, out var parsed) => parsed, _ => 0, }; } } Path: redb-identity/src/redb.Identity.Core/OpenIddict/Handlers/HandleTokenRequestHandler.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/OpenIddict/Handlers/HandleTokenRequestHandler.cs ---- using System.Security.Claims; using System.Text.Json; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using OpenIddict.Abstractions; using OpenIddict.Server; using redb.Core; using redb.Identity.Core.Configuration; using redb.Identity.Core.Services; using static OpenIddict.Abstractions.OpenIddictConstants; using static OpenIddict.Server.OpenIddictServerEvents; using static OpenIddict.Server.OpenIddictServerHandlerDescriptor; namespace redb.Identity.Core.OpenIddict.Handlers; /// /// Handles for client_credentials, device_code, /// password (ROPC), and token exchange (RFC 8693) grant types. /// For authorization_code and refresh_token, OpenIddict resolves the principal from /// the stored code/token automatically — no custom handler needed; the same holds for /// device_code since OpenIddict 7. /// internal sealed class HandleTokenRequestHandler : IOpenIddictServerHandler { private readonly ILogger _logger; private readonly IServiceProvider _sp; public HandleTokenRequestHandler( ILogger logger, IServiceProvider sp) { _logger = logger; _sp = sp; } public static OpenIddictServerHandlerDescriptor Descriptor { get; } = CreateBuilder() .UseScopedHandler() .SetOrder(OpenIddictServerHandlers.Exchange.AttachPrincipal.Descriptor.Order + 100) .SetType(OpenIddictServerHandlerType.Custom) .Build(); public async ValueTask HandleAsync(HandleTokenRequestContext context) { // device_code: OpenIddict's built-in AttachPrincipal (ordered before this handler) restores // the principal from the device code, as it does for authorization_code and refresh_token. if (context.Request.IsDeviceCodeGrantType()) return; // ROPC: grant_type=password (opt-in via EnablePasswordFlow) if (context.Request.IsPasswordGrantType()) { var loginService = _sp.GetService(); if (loginService is null) { context.Reject( error: Errors.UnsupportedGrantType, description: "The password grant type is not configured."); return; } var username = context.Request.Username; var password = context.Request.Password; var result = await loginService.AuthenticateAsync(username ?? "", password ?? ""); if (result.MustChangePassword) { // H10 — ROPC cannot complete a password-change ceremony, so reject. The // standard OAuth error vocabulary doesn't have a password-expired code, // so use invalid_grant + a precise description that resource owners can // surface to the user. context.Reject( error: Errors.InvalidGrant, description: "Password expired; change required before token issuance."); return; } if (!result.Succeeded) { // C14 / SEC-A20: do NOT echo provider-specific failure text. The original // reason is in server logs; surface a generic message to defeat enumeration. context.Reject( error: Errors.AccessDenied, description: "Invalid credentials."); return; } var profileService = _sp.GetService(); if (profileService is not null) { // Fast path: LoginService already loaded IRedbUser + UserProps + subject GUID. // Skip when UserProps is missing (legacy / freshly-created user with no envelope) // or when value_guid hasn't been issued yet — slow path lazy-creates and persists. if (result.OidcProps is not null && result.SubjectGuid != Guid.Empty) { context.Principal = await profileService.BuildPrincipalAsync( result.User!, result.OidcProps, result.SubjectGuid, context.Request.GetScopes()).ConfigureAwait(false); } else { context.Principal = await profileService.BuildPrincipalAsync( result.User!.Id, context.Request.GetScopes()).ConfigureAwait(false); } } else { // Fallback if DI not configured (degraded mode) context.Principal = IdentityPrincipalBuilder.Build( result.User!, result.SubjectGuid, result.OidcProps, context.Request.GetScopes()); } _logger.LogTrace("Issued ClaimsPrincipal for password grant: {Username}", username); return; } // Only handle client_credentials — auth_code and refresh_token are handled // by OpenIddict's built-in handlers that restore the principal from the stored token/code if (context.Request.IsTokenExchangeGrantType()) { await HandleTokenExchangeAsync(context); return; } if (!context.Request.IsClientCredentialsGrantType()) return; var identity = new ClaimsIdentity( authenticationType: "OpenIddict.Server", nameType: Claims.Name, roleType: Claims.Role); identity.SetClaim(Claims.Subject, context.Request.ClientId); identity.SetScopes(context.Request.GetScopes()); // Set destinations so claims appear in the access token foreach (var claim in identity.Claims) claim.SetDestinations(new[] { Destinations.AccessToken }); context.Principal = new ClaimsPrincipal(identity); _logger.LogDebug("Issued ClaimsPrincipal for client_credentials: {ClientId}", context.Request.ClientId); } /// /// Handles the Token Exchange grant type (RFC 8693) on top of OpenIddict's built-in support. /// /// OpenIddict has already checked the parameters (subject, actor and requested token types are /// restricted to access tokens in AddRedbIdentityServer), validated the subject_token and /// the optional actor_token, and required the caller to be an audience or presenter of a token /// bound to both. This builds the principal of the issued token: delegation with an /// act claim chain, or impersonation when allowed. /// /// private async Task HandleTokenExchangeAsync(HandleTokenRequestContext context) { const string ActClaimType = "act"; var options = _sp.GetRequiredService>().Value; var subjectPrincipal = context.SubjectTokenPrincipal; if (subjectPrincipal is null) { context.Reject(Errors.InvalidGrant, "The subject_token is invalid or expired."); return; } var originalSubject = subjectPrincipal.GetClaim(Claims.Subject); if (string.IsNullOrEmpty(originalSubject)) { context.Reject(Errors.InvalidGrant, "The subject_token does not contain a valid subject claim."); return; } var actorPrincipal = context.ActorTokenPrincipal; // The server stack validates these tokens, so the bearer-side DisabledUserRejectionHandler // never sees them: a disabled or deleted user must not be able to exchange a token either. if (await RejectDisabledUserAsync(context, subjectPrincipal, "subject_token") || (actorPrincipal is not null && await RejectDisabledUserAsync(context, actorPrincipal, "actor_token"))) return; // ── 5. Determine delegation vs impersonation ── // If actor_token is provided → delegation (act claim chain) // If no actor_token → impersonation (only if allowed) var isDelegation = actorPrincipal is not null; if (!isDelegation && !options.TokenExchangeAllowImpersonation) { // Without actor_token and impersonation disabled, the requesting client acts as the actor isDelegation = true; } // ── 6. Check delegation chain depth ── if (isDelegation && options.TokenExchangeMaxDelegationDepth > 0) { var existingActClaim = subjectPrincipal.GetClaim(ActClaimType); var depth = CountActChainDepth(existingActClaim); if (depth >= options.TokenExchangeMaxDelegationDepth) { context.Reject(Errors.InvalidGrant, $"The delegation chain depth ({depth}) exceeds the maximum allowed ({options.TokenExchangeMaxDelegationDepth})."); return; } } // ── 7. Build new principal ── var newIdentity = new ClaimsIdentity( authenticationType: "OpenIddict.Server", nameType: Claims.Name, roleType: Claims.Role); // Carry over subject from the original token newIdentity.SetClaim(Claims.Subject, originalSubject); // Carry over name if present var originalName = subjectPrincipal.GetClaim(Claims.Name); if (!string.IsNullOrEmpty(originalName)) newIdentity.SetClaim(Claims.Name, originalName); // Use requested scopes if provided, otherwise carry over original scopes var requestedScopes = context.Request.GetScopes(); if (requestedScopes.Length > 0) { // Requested scopes must be a subset of the original token's scopes var originalScopes = subjectPrincipal.GetScopes(); var unauthorized = requestedScopes.Except(originalScopes).ToArray(); if (unauthorized.Length > 0) { context.Reject(Errors.InvalidScope, $"The requested scope(s) [{string.Join(", ", unauthorized)}] " + "are not present in the subject_token."); return; } newIdentity.SetScopes(requestedScopes); } else { newIdentity.SetScopes(subjectPrincipal.GetScopes()); } // ── 8. Add act claim for delegation ── if (isDelegation) { var actorSub = actorPrincipal?.GetClaim(Claims.Subject) ?? context.Request.ClientId; var actorClientId = context.Request.ClientId; // Build the act claim as a JSON object per RFC 8693 §4.1 var actClaim = new Dictionary { ["sub"] = actorSub }; if (actorSub != actorClientId) actClaim["client_id"] = actorClientId; // Chain existing act claim if present (delegation chain) var existingAct = subjectPrincipal.GetClaim(ActClaimType); if (!string.IsNullOrEmpty(existingAct)) actClaim["act"] = JsonSerializer.Deserialize(existingAct); var actJson = JsonSerializer.Serialize(actClaim); newIdentity.AddClaim(new Claim(ActClaimType, actJson, "JSON")); } // Set destinations foreach (var claim in newIdentity.Claims) { if (claim.Type == ActClaimType) claim.SetDestinations(Destinations.AccessToken, Destinations.IdentityToken); else claim.SetDestinations(Destinations.AccessToken); } context.Principal = new ClaimsPrincipal(newIdentity); _logger.LogDebug( "Token exchange completed: subject={Subject}, client={ClientId}, delegation={IsDelegation}", originalSubject, context.Request.ClientId, isDelegation); } /// /// Rejects the request with invalid_grant when the token points to a disabled or deleted redb user, /// and with server_error when the user store fails. Returns true when the request was rejected. /// private async Task RejectDisabledUserAsync( HandleTokenRequestContext context, ClaimsPrincipal principal, string parameter) { try { var (userId, state) = await DisabledUserRejectionHandler.GetUserStateAsync(_sp, principal); if (state is not (TokenUserState.Missing or TokenUserState.Disabled)) return false; _logger.LogInformation("Token exchange rejected: {Parameter} user {UserId} is {State}", parameter, userId, state is TokenUserState.Missing ? "missing" : "disabled"); context.Reject(Errors.InvalidGrant, $"The user account associated with the {parameter} has been disabled or deleted."); return true; } catch (Exception ex) { _logger.LogWarning(ex, "Token exchange: user lookup for the {Parameter} failed", parameter); context.Reject(Errors.ServerError, "Token validation failed due to an internal error."); return true; } } /// /// Counts the depth of an act claim chain (nested JSON objects). /// private static int CountActChainDepth(string? actClaimJson) { if (string.IsNullOrEmpty(actClaimJson)) return 0; var depth = 1; try { using var doc = JsonDocument.Parse(actClaimJson); var element = doc.RootElement; while (element.TryGetProperty("act", out var nested)) { depth++; element = nested; } } catch (JsonException) { // Malformed act claim — treat as depth 1 } return depth; } } Path: redb-identity/src/redb.Identity.Core/OpenIddict/Handlers/HandleVerificationRequestHandler.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/OpenIddict/Handlers/HandleVerificationRequestHandler.cs ---- using System.Security.Claims; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Microsoft.IdentityModel.JsonWebTokens; using Microsoft.IdentityModel.Tokens; using OpenIddict.Abstractions; using OpenIddict.Server; using redb.Core; using redb.Identity.Core.Services; using static OpenIddict.Abstractions.OpenIddictConstants; using static OpenIddict.Server.OpenIddictServerEvents; using static OpenIddict.Server.OpenIddictServerHandlerDescriptor; namespace redb.Identity.Core.OpenIddict.Handlers; /// /// Handles for the Device Code Flow (RFC 8628 §3.3). /// Authenticates the end-user and builds a full that OpenIddict /// associates with the pending device authorization. /// /// /// RFC 8628 §3.3 leaves end-user authentication on the verification endpoint to the /// implementation. Two paths are supported, tried in this order: /// /// /// /// Bearer access_token — when the request carries an Authorization: Bearer … /// header (forwarded into the route as the access_token exchange header by /// HttpIdentityProcessors.ExtractBearerToken), the JWT is validated locally /// against the host's own signing keys, the sub claim is resolved to a user, /// and the principal is built via . This is the /// BFF-relayed flow: the front-end is already authenticated via a session cookie that /// carries a host-issued access_token, and re-prompting for credentials would be /// both redundant and a worse UX. /// /// /// /// /// Username + password — direct host-UI flow (no prior session, no BFF), per /// RFC 8628 §3.3 the user authenticates on the verification endpoint by submitting /// credentials in the form body. Delegates to . /// /// /// /// If neither is present the handler rejects with . /// internal sealed class HandleVerificationRequestHandler : IOpenIddictServerHandler { private readonly IServiceProvider _sp; private readonly IOptionsMonitor _serverOptions; private readonly ILogger _logger; private static readonly JsonWebTokenHandler _tokenHandler = new(); public HandleVerificationRequestHandler( IServiceProvider sp, IOptionsMonitor serverOptions, ILogger logger) { _sp = sp; _serverOptions = serverOptions; _logger = logger; } public static OpenIddictServerHandlerDescriptor Descriptor { get; } = CreateBuilder() .UseScopedHandler() .SetOrder(100_000) .SetType(OpenIddictServerHandlerType.Custom) .Build(); public async ValueTask HandleAsync(HandleEndUserVerificationRequestContext context) { var scopes = context.Principal?.GetScopes() ?? []; var scopeList = scopes as IEnumerable; // Path 1 (RFC 8628 §3.3 — BFF-relayed): a host-issued access_token authenticates // the end-user without re-prompting for credentials. var bearerPrincipal = await TryBuildPrincipalFromBearerAsync(context, scopeList) .ConfigureAwait(false); if (bearerPrincipal is not null) { MergeIntoContextPrincipal(context, bearerPrincipal); _logger.LogDebug( "Device verification authorized via bearer access_token (sub={Sub})", bearerPrincipal.FindFirst(Claims.Subject)?.Value ?? bearerPrincipal.FindFirst("sub")?.Value); return; } // Path 2 (RFC 8628 §3.3 — direct host-UI flow): form-based credentials. var username = (string?)context.Request["username"]; var password = (string?)context.Request["password"]; if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password)) { context.Reject( error: Errors.LoginRequired, description: "User authentication is required. Provide username and password, or an Authorization: Bearer access_token."); return; } var loginService = _sp.GetRequiredService(); var result = await loginService.AuthenticateAsync(username, password); if (!result.Succeeded) { _logger.LogWarning("Device verification denied: {Error}", result.ErrorMessage); // C14 / SEC-A20: generic error to defeat account enumeration on the // device-code verification endpoint. context.Reject( error: Errors.AccessDenied, description: "Invalid credentials."); return; } // Build a full principal with OIDC claims (profile, address, custom claims, groups/roles) ClaimsPrincipal fullPrincipal; var profileService = _sp.GetService(); if (profileService is not null) { fullPrincipal = await profileService.BuildPrincipalAsync( result.User!.Id, scopeList).ConfigureAwait(false) ?? IdentityPrincipalBuilder.Build(result.User!, result.SubjectGuid, result.OidcProps, scopeList); } else { // Fallback: manual build (degraded mode without DI) fullPrincipal = IdentityPrincipalBuilder.Build(result.User!, result.SubjectGuid, result.OidcProps, scopeList); var redb = _sp.GetService(); if (redb is not null) { var resolver = new GroupClaimsResolver(redb); await resolver.EnrichPrincipalAsync(fullPrincipal, result.User!.Id, scopeList) .ConfigureAwait(false); } } MergeIntoContextPrincipal(context, fullPrincipal); _logger.LogDebug( "User '{Username}' (id={UserId}) authorized device code", username, result.UserId); } /// /// Validates a host-issued JWT access_token (if present) and builds a principal for the /// resolved sub. Returns null when no token is present or validation fails; /// the caller falls through to the form-credentials path (or rejects with login_required). /// /// /// Mirrors the validation parameters used by LogoutProcessor.ValidateIdTokenHintAsync /// (RP-Initiated Logout id_token_hint validation): trust the host's own signing keys, /// require valid lifetime, allow 5 minute clock skew, skip audience validation (the /// token's audience is the original API resource, not this endpoint). /// private async Task TryBuildPrincipalFromBearerAsync( HandleEndUserVerificationRequestContext context, IEnumerable scopes) { var exchange = context.Transaction.GetRouteExchange(); if (exchange is null) return null; // Set upstream by HttpIdentityProcessors.ExtractBearerToken (Authorization: Bearer … // header → "access_token" exchange header, "Bearer " prefix already stripped). var jwt = exchange.In.GetHeader("access_token"); if (string.IsNullOrEmpty(jwt)) return null; var opts = _serverOptions.CurrentValue; var signingKeys = opts.SigningCredentials.Select(c => c.Key).ToList(); if (signingKeys.Count == 0) { _logger.LogWarning( "No signing keys configured — cannot validate bearer access_token on /connect/device/verify"); return null; } // Accept both forms of the issuer (with and without trailing slash). OpenIddict // signs tokens with iss = Issuer.AbsoluteUri (trailing slash on the root); some // deployments configure the issuer without a trailing slash. Validate against // both so the same handler works in either configuration. var issuerString = opts.Issuer?.ToString(); var validIssuers = new List(); if (!string.IsNullOrEmpty(issuerString)) { validIssuers.Add(issuerString); var trimmed = issuerString.TrimEnd('/'); if (trimmed != issuerString) validIssuers.Add(trimmed); } var validationParams = new TokenValidationParameters { ValidIssuers = validIssuers, ValidateIssuer = opts.Issuer is not null, ValidateAudience = false, // access_token's audience is the API resource, not this endpoint ValidateLifetime = true, IssuerSigningKeys = signingKeys, ValidateIssuerSigningKey = true, ClockSkew = TimeSpan.FromMinutes(5) }; TokenValidationResult result; try { result = await _tokenHandler.ValidateTokenAsync(jwt, validationParams).ConfigureAwait(false); } catch (Exception ex) { _logger.LogWarning(ex, "Bearer access_token validation threw on /connect/device/verify"); return null; } if (!result.IsValid) { _logger.LogWarning( "Bearer access_token validation failed on /connect/device/verify: {Error}", result.Exception?.Message); return null; } var sub = result.ClaimsIdentity.FindFirst(Claims.Subject)?.Value ?? result.ClaimsIdentity.FindFirst("sub")?.Value; // The public sub is now a GUID; the bigint user id rides alongside in // the internal redb:user_id access-token claim (see IdentityPrincipalBuilder). var internalUid = result.ClaimsIdentity.FindFirst(IdentityPrincipalBuilder.InternalUserIdClaim)?.Value; if (string.IsNullOrEmpty(internalUid) || !long.TryParse(internalUid, out var userId)) { _logger.LogWarning( "Bearer access_token on /connect/device/verify has missing or non-numeric {Claim} claim (sub={Sub})", IdentityPrincipalBuilder.InternalUserIdClaim, sub); return null; } var profileService = _sp.GetService(); if (profileService is null) { _logger.LogWarning( "IUserProfileService not registered — cannot build bearer principal on /connect/device/verify"); return null; } var principal = await profileService .BuildPrincipalAsync(userId, scopes) .ConfigureAwait(false); if (principal is null) _logger.LogWarning( "Bearer access_token sub={Sub} does not resolve to an enabled user", userId); return principal; } /// /// Merges the freshly built user principal into the context principal. OpenIddict's /// built-in AttachUserCodePrincipal runs before this handler and sets /// to a principal that /// carries internal claims (authorization id, client id, scopes); we add our user claims /// on top so OpenIddict can later associate the device authorization with this user. /// private static void MergeIntoContextPrincipal( HandleEndUserVerificationRequestContext context, ClaimsPrincipal user) { if (context.Principal?.Identity is ClaimsIdentity existingIdentity) { var userIdentity = (ClaimsIdentity)user.Identity!; foreach (var claim in userIdentity.Claims) existingIdentity.AddClaim(claim); } else { context.Principal = user; } } } Path: redb-identity/src/redb.Identity.Core/OpenIddict/Handlers/RefreshClientAssertionKeysHandler.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/OpenIddict/Handlers/RefreshClientAssertionKeysHandler.cs ---- using Microsoft.IdentityModel.JsonWebTokens; using OpenIddict.Abstractions; using OpenIddict.Server; using redb.Core.Models.Entities; using redb.Identity.Core.Models; using redb.Identity.Core.Services; using static OpenIddict.Server.OpenIddictServerEvents; namespace redb.Identity.Core.OpenIddict.Handlers; /// /// RFC 7523 client assertions verified with keys from the client's jwks_uri: when the assertion names a /// kid that the cached set does not hold, the set is fetched again once, so a client that rotated its keys /// is not refused until the cache expires. The refresh is bounded by (at most one /// fetch per ClientKeys.MinimumRefreshInterval per address, shared by concurrent callers), so a caller that /// sends assertions with made-up kid values cannot drive fetches. A client with an inline JWKS is left alone: /// its inline set is the only source. /// internal sealed class RefreshClientAssertionKeysHandler : IOpenIddictServerHandler { // Resolved only once a client assertion is being validated: the handler runs for every token validation, // including hosts (degraded mode, resource-side validation) that register no application manager. private readonly IServiceProvider _services; public RefreshClientAssertionKeysHandler(IServiceProvider services) => _services = services ?? throw new ArgumentNullException(nameof(services)); public static OpenIddictServerHandlerDescriptor Descriptor { get; } = OpenIddictServerHandlerDescriptor.CreateBuilder() .UseScopedHandler() // Right after OpenIddict has put the client's key set into the validation parameters. .SetOrder(OpenIddictServerHandlers.Protection.ResolveTokenValidationParameters.Descriptor.Order + 100) .SetType(OpenIddictServerHandlerType.Custom) .Build(); public async ValueTask HandleAsync(ValidateTokenContext context) { ArgumentNullException.ThrowIfNull(context); var assertion = context.Request?.ClientAssertion; if (string.IsNullOrEmpty(assertion) || !string.Equals(assertion, context.Token, StringComparison.Ordinal)) return; var reader = new JsonWebTokenHandler(); if (!reader.CanReadToken(assertion)) return; var jwt = reader.ReadJsonWebToken(assertion); if (string.IsNullOrEmpty(jwt.Kid)) return; var clientId = context.Request!.ClientId ?? jwt.Issuer; if (string.IsNullOrEmpty(clientId)) return; if (_services.GetService(typeof(IOpenIddictApplicationManager)) is not IOpenIddictApplicationManager applications || _services.GetService(typeof(IClientKeyResolver)) is not IClientKeyResolver keyResolver) return; if (await applications.FindByClientIdAsync(clientId, context.CancellationToken).ConfigureAwait(false) is not RedbObject application) return; if (!string.IsNullOrWhiteSpace(application.Props.JsonWebKeySet) || string.IsNullOrWhiteSpace(application.Props.JwksUri)) return; var parameters = context.TokenValidationParameters; if (parameters.IssuerSigningKeys?.Any(k => string.Equals(k.KeyId, jwt.Kid, StringComparison.Ordinal)) == true) return; var keys = await keyResolver.GetSigningKeysAsync(application, forceRefresh: true, context.CancellationToken) .ConfigureAwait(false); parameters.IssuerSigningKeys = keys; } } Path: redb-identity/src/redb.Identity.Core/OpenIddict/Handlers/RestrictAdminScopesByRoleHandler.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/OpenIddict/Handlers/RestrictAdminScopesByRoleHandler.cs ---- using System.Collections.Immutable; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using OpenIddict.Abstractions; using OpenIddict.Server; using redb.Core; using redb.Identity.Core.Configuration; using redb.Identity.Core.Models; using redb.Identity.Core.Services; using static OpenIddict.Server.OpenIddictServerEvents; using static OpenIddict.Server.OpenIddictServerHandlerDescriptor; using static OpenIddict.Server.OpenIddictServerHandlers; namespace redb.Identity.Core.OpenIddict.Handlers; /// /// An administrative scope reaches a user-bound token only when that user's roles carry it. /// /// OAuth's scope check asks whether the client may request a scope. Nothing in it asks whether /// the person should have it, and the admin console legitimately requests /// identity:manage — so before this handler every account that could sign in to the console /// received the master management scope, and the management API, checking the token as it should, /// admitted them. Roles were already computed at issuance /// () but only ever added scopes; nothing removed one. /// /// /// This handler removes, it never rejects. A user who asked for more than their roles allow still /// signs in — with the administrative scopes stripped — because refusing the whole request would turn /// a missing role into a failed login, and the console asks for identity:manage for everyone. /// Every removal is logged at warning level with the user and the scopes. /// /// /// client_credentials is out of scope by construction: no user, nothing to entitle, and the /// application's own scp:{scope} permission is the authoritative gate there. Refresh flows run /// through as well, so revoking a role takes effect on the next /// refresh instead of lingering for the lifetime of the grant. /// /// /// Fail-closed on error: if roles cannot be resolved the administrative scopes are dropped rather than /// granted on trust. That direction costs an admin a page refresh after a database hiccup; the other /// direction costs everyone their user list. /// /// internal sealed class RestrictAdminScopesByRoleHandler : IOpenIddictServerHandler { private readonly IServiceProvider _sp; private readonly IOptions _options; private readonly ILogger _logger; public RestrictAdminScopesByRoleHandler( IServiceProvider sp, IOptions options, ILogger logger) { // IOptions, not IOptionsMonitor: hosts register identity options as a singleton // instance via Options.Create(...), and the monitor would hand back a fresh default — // silently disabling the gate. Same reasoning as RestrictScopeByGroupMembershipHandler. _sp = sp; _options = options; _logger = logger; } public static OpenIddictServerHandlerDescriptor Descriptor { get; } = CreateBuilder() .UseScopedHandler() // One tick after the group gate, which may already have rejected the request, and well // before the principal is cloned for token minting. .SetOrder(AttachDefaultScopes.Descriptor.Order + 600) .SetType(OpenIddictServerHandlerType.Custom) .Build(); public async ValueTask HandleAsync(ProcessSignInContext context) { ArgumentNullException.ThrowIfNull(context); var settings = _options.Value.AdminScopeEntitlement; if (settings is null || !settings.Enabled) return; if (context.Principal?.Identity is not System.Security.Claims.ClaimsIdentity identity) return; // The public sub is a GUID; the internal bigint rides in `redb:user_id`. Its absence means // there is no user behind this token (client_credentials) — not this handler's business. var internalUid = context.Principal.FindFirst(IdentityPrincipalBuilder.InternalUserIdClaim)?.Value; if (string.IsNullOrEmpty(internalUid) || !long.TryParse(internalUid, out var userId) || userId <= 0) return; var requested = context.Principal.GetScopes(); var gated = requested.Where(settings.IsGated).ToArray(); if (gated.Length == 0) return; var redb = _sp.GetService(); if (redb is null) { _logger.LogError( "AdminScopeEntitlement: IRedbService unavailable; dropping {Scopes} for user {UserId} rather than issuing them unverified", string.Join(",", gated), userId); Strip(identity, requested, gated); return; } HashSet entitled; try { entitled = await ResolveEntitledScopesAsync(redb, userId, context).ConfigureAwait(false); } catch (Exception ex) { _logger.LogError(ex, "AdminScopeEntitlement: role resolution failed for user {UserId}; dropping {Scopes}", userId, string.Join(",", gated)); Strip(identity, requested, gated); return; } var refused = gated.Where(s => !entitled.Contains(s)).ToArray(); if (refused.Length == 0) return; _logger.LogWarning( "AdminScopeEntitlement: user {UserId} requested {Refused} without a role that grants it; " + "issuing the token without those scopes (roles grant: {Entitled})", userId, string.Join(",", refused), entitled.Count == 0 ? "" : string.Join(",", entitled)); Strip(identity, requested, refused); } /// Scopes the user's effective roles attach, for the application this token is for. private async Task> ResolveEntitledScopesAsync( IRedbService redb, long userId, ProcessSignInContext context) { // Role audience filtering needs the requesting application's redb id: an // audience='application' role bound to app A must not entitle a token issued for app B. long? applicationId = null; var clientId = context.Request?.ClientId; if (!string.IsNullOrEmpty(clientId)) { var app = await redb.GetByUniqueAsync(p => p.ClientId, clientId).ConfigureAwait(false); if (app is not null && app.Id > 0) applicationId = app.Id; } // Roles come through groups as well as directly; IGroupService is not DI-registered, so the // service is built on the resolved redb exactly as AttachRoleRegistryClaims does it. var groupIds = new List(); var groups = await new GroupService(redb) .GetUserGroupsAsync(userId, context.CancellationToken) .ConfigureAwait(false); groupIds.AddRange(groups.Where(g => g.GroupId > 0).Select(g => g.GroupId)); var svc = new RoleService(redb); var roles = await svc.GetEffectiveRolesAsync(userId, groupIds, applicationId, context.CancellationToken) .ConfigureAwait(false); if (roles.Count == 0) return new HashSet(StringComparer.Ordinal); return await svc.GetEffectiveScopeNamesAsync(roles.Select(r => r.Id), context.CancellationToken) .ConfigureAwait(false); } private static void Strip( System.Security.Claims.ClaimsIdentity identity, ImmutableArray requested, IReadOnlyCollection refused) { var keep = requested.Where(s => !refused.Contains(s, StringComparer.Ordinal)).ToArray(); identity.SetScopes(keep); } } Path: redb-identity/src/redb.Identity.Core/OpenIddict/Handlers/RestrictApplicationByGroupMembershipHandler.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/OpenIddict/Handlers/RestrictApplicationByGroupMembershipHandler.cs ---- using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using OpenIddict.Abstractions; using OpenIddict.Server; using redb.Core; using redb.Core.Query; using redb.Identity.Core.Models; using redb.Identity.Core.Services; using static OpenIddict.Abstractions.OpenIddictConstants; using static OpenIddict.Server.OpenIddictServerEvents; using static OpenIddict.Server.OpenIddictServerHandlerDescriptor; namespace redb.Identity.Core.OpenIddict.Handlers; /// /// β: per-application whitelist gate. When /// is non-empty, only users who /// are a member of at least one listed group may authenticate against this /// application. Rejects with access_denied otherwise. /// /// /// Independent of and OR'd against /// (which gates per-scope /// rather than per-application). Both gates must pass — denying either /// short-circuits the sign-in. /// /// /// /// Pipeline order: same slot as the scope gate /// (AttachDefaultScopes.Order + 501) so we run just after the per-scope /// check and reject before any expensive principal-cloning happens. /// /// /// /// Skipped grants: /// - client_credentials — there's no end-user principal to verify, /// and the application's own permission to mint a token rides on its /// existing scp:* / gt:client_credentials permissions, not on user /// group membership. /// - Anonymous / no-client_id requests — handled by the standard /// OpenIddict validators upstream. /// /// /// /// Fail-closed semantics on redb / lookup failure: if we can't determine /// the user's group membership, we reject. Leaking access on infrastructure /// failure is the wrong default. /// /// internal sealed class RestrictApplicationByGroupMembershipHandler : IOpenIddictServerHandler { private readonly IServiceProvider _sp; private readonly ILogger _logger; public RestrictApplicationByGroupMembershipHandler( IServiceProvider sp, ILogger logger) { _sp = sp; _logger = logger; } public static OpenIddictServerHandlerDescriptor Descriptor { get; } = CreateBuilder() .UseScopedHandler() // Run one tick after the per-scope gate so a denied-by-scope request // never reaches us (and the audit log carries the more specific error). .SetOrder(OpenIddictServerHandlers.AttachDefaultScopes.Descriptor.Order + 501) .SetType(OpenIddictServerHandlerType.Custom) .Build(); public async ValueTask HandleAsync(ProcessSignInContext context) { ArgumentNullException.ThrowIfNull(context); if (context.Principal is null) return; var clientId = context.ClientId; if (string.IsNullOrEmpty(clientId)) return; // Skip client_credentials — no end-user principal to evaluate. The // application's own permission to mint a token already gated upstream // via scp:* / gt:client_credentials. var internalUid = context.Principal.FindFirst(IdentityPrincipalBuilder.InternalUserIdClaim)?.Value; if (string.IsNullOrEmpty(internalUid) || !long.TryParse(internalUid, out var userId) || userId <= 0) return; var redb = _sp.GetService(); if (redb is null) { _logger.LogError( "AppAuthorization: IRedbService unavailable; rejecting client_id='{ClientId}'", clientId); context.Reject( error: Errors.AccessDenied, description: "Application membership cannot be verified."); return; } // Resolve application by client_id. ApplicationProps? props; try { var app = await redb.GetByUniqueAsync(p => p.ClientId, clientId) .ConfigureAwait(false); props = app?.Props; } catch (Exception ex) { _logger.LogError(ex, "AppAuthorization: failed to resolve application by client_id '{ClientId}'", clientId); context.Reject( error: Errors.AccessDenied, description: "Application membership cannot be verified."); return; } if (props is null) return; // unknown client — let downstream validators 404 it var allowed = props.AllowedGroups; if (allowed is null || allowed.Length == 0) return; // no whitelist — feature disabled for this app var allowedSet = new HashSet(allowed, StringComparer.Ordinal); IGroupService groupService = new GroupService(redb); List userGroups; try { userGroups = await groupService .GetUserGroupsAsync(userId, context.CancellationToken) .ConfigureAwait(false); } catch (Exception ex) { _logger.LogError(ex, "AppAuthorization: GetUserGroupsAsync({UserId}) failed for client_id='{ClientId}'", userId, clientId); context.Reject( error: Errors.AccessDenied, description: "Application membership cannot be verified."); return; } var memberOf = userGroups .Select(g => g.GroupName) .Where(n => !string.IsNullOrEmpty(n)); foreach (var groupName in memberOf) { if (allowedSet.Contains(groupName!)) return; // user is in at least one allowed group — accept } _logger.LogInformation( "AppAuthorization: user {UserId} denied access to '{ClientId}' — not a member of any allowed group [{Groups}]", userId, clientId, string.Join(",", allowed)); context.Reject( error: Errors.AccessDenied, description: $"This application restricts access to specific groups; the user is not a member of any of them."); } } Path: redb-identity/src/redb.Identity.Core/OpenIddict/Handlers/RestrictScopeByGroupMembershipHandler.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/OpenIddict/Handlers/RestrictScopeByGroupMembershipHandler.cs ---- using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using OpenIddict.Abstractions; using OpenIddict.Server; using redb.Core; using redb.Identity.Core.Configuration; using redb.Identity.Core.Services; using static OpenIddict.Abstractions.OpenIddictConstants; using static OpenIddict.Server.OpenIddictServerEvents; using static OpenIddict.Server.OpenIddictServerHandlerDescriptor; namespace redb.Identity.Core.OpenIddict.Handlers; /// /// Authorization guard that gates selected OAuth scopes behind group membership. /// /// Configured via as a /// scopeName → groupName map. When a user-bound token request (any grant /// type that produces a numeric subject — authorization_code, password, /// device_code, refresh_token derived from the above) requests one of the /// listed scopes, the request is rejected with error=access_denied unless /// the authenticated user is a non-expired member of the required group. /// /// /// The client_credentials grant is intentionally excluded: it has no /// user identity to evaluate, so the existing OpenIddict scope-permission /// check (scp:{scope} on the application) is the only authoritative /// gate for that flow. /// /// /// Runs at earlier than /// so a denied request never reaches /// claim-mapper resolution or token minting. /// /// internal sealed class RestrictScopeByGroupMembershipHandler : IOpenIddictServerHandler { private readonly IServiceProvider _sp; private readonly IOptions _options; private readonly ILogger _logger; public RestrictScopeByGroupMembershipHandler( IServiceProvider sp, IOptions options, ILogger logger) { // NOTE: IOptions (not IOptionsMonitor) is intentional here. Some hosts register // identity options via Options.Create(...) as a singleton instance; IOptionsMonitor // would build a fresh empty default in that case and silently disable scope gating. // ScopeRequiredGroups is read-only after configuration, so no hot-reload is needed. _sp = sp; _options = options; _logger = logger; } public static OpenIddictServerHandlerDescriptor Descriptor { get; } = CreateBuilder() .UseScopedHandler() // CRITICAL: must run BEFORE OpenIddictServerHandlers.Exchange.ApplyTokenResponse // (fixed order 500_000), otherwise IsRequestHandled is propagated and we never execute. // We also must run before PrepareAccessTokenPrincipal (AttachAuthorization.Order + 1_000) // because rejecting later wastes principal-cloning work. Slot just after AttachDefaultScopes. .SetOrder(OpenIddictServerHandlers.AttachDefaultScopes.Descriptor.Order + 500) .SetType(OpenIddictServerHandlerType.Custom) .Build(); public async ValueTask HandleAsync(ProcessSignInContext context) { ArgumentNullException.ThrowIfNull(context); var requirements = _options.Value.ScopeRequiredGroups; if (requirements is null || requirements.Count == 0) return; // feature disabled if (context.Principal is null) return; // The public sub claim is now a GUID; the bigint _users._id rides alongside in // the internal `redb:user_id` access-token claim emitted by IdentityPrincipalBuilder. // client_credentials tokens carry only a string sub (client_id) and no internal // user-id claim → skip (gated scopes for that flow are enforced via scp:* permissions). var internalUid = context.Principal.FindFirst(IdentityPrincipalBuilder.InternalUserIdClaim)?.Value; if (string.IsNullOrEmpty(internalUid) || !long.TryParse(internalUid, out var userId) || userId <= 0) return; // Determine which gated scopes are being requested. var requestedScopes = context.Principal.GetScopes(); var gated = new List>(capacity: 1); foreach (var scope in requestedScopes) { if (requirements.TryGetValue(scope, out var requiredGroup) && !string.IsNullOrWhiteSpace(requiredGroup)) { gated.Add(new KeyValuePair(scope, requiredGroup)); } } if (gated.Count == 0) return; // no gated scopes requested var redb = _sp.GetService(); if (redb is null) { // Fail closed: if redb isn't available we cannot verify membership; // refusing the gated scope is safer than leaking it. _logger.LogError( "ScopeAuthorization: IRedbService unavailable; rejecting request for gated scopes {Scopes}", string.Join(",", gated.Select(g => g.Key))); context.Reject( error: Errors.AccessDenied, description: "Required group membership cannot be verified."); return; } IGroupService groupService = new GroupService(redb); List userGroups; try { userGroups = await groupService .GetUserGroupsAsync(userId, context.CancellationToken) .ConfigureAwait(false); } catch (Exception ex) { // Fail closed on lookup error. _logger.LogError(ex, "ScopeAuthorization: GetUserGroupsAsync({UserId}) failed; rejecting gated scopes", userId); context.Reject( error: Errors.AccessDenied, description: "Required group membership cannot be verified."); return; } var memberOf = new HashSet( userGroups .Select(g => g.GroupName) .Where(n => !string.IsNullOrEmpty(n)) .Cast(), StringComparer.Ordinal); foreach (var (scope, requiredGroup) in gated) { if (!memberOf.Contains(requiredGroup)) { _logger.LogInformation( "ScopeAuthorization: user {UserId} denied scope '{Scope}' — not a member of group '{Group}'", userId, scope, requiredGroup); context.Reject( error: Errors.AccessDenied, description: $"Scope '{scope}' requires membership in group '{requiredGroup}'."); return; } } } } Path: redb-identity/src/redb.Identity.Core/OpenIddict/Handlers/StripInternalClaimsFromIdentityToken.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/OpenIddict/Handlers/StripInternalClaimsFromIdentityToken.cs ---- using System.Security.Claims; using OpenIddict.Server; using static OpenIddict.Server.OpenIddictServerEvents; using static OpenIddict.Server.OpenIddictServerHandlerDescriptor; namespace redb.Identity.Core.OpenIddict.Handlers; /// /// Keeps OpenIddict's internal authorization-id reference claim oi_au_id OUT of the /// issued id_token. /// /// /// OpenIddict uses oi_au_id to link a token back to its stored authorization entry. In a /// JWT (self-contained) configuration it embeds it into the token payload, and because our /// sign-in principal carries the default [AccessToken, IdentityToken] destinations it /// leaks into the id_token too. It is a server-internal concern with no meaning to the client, /// and the OpenID conformance suite flags it as a non-requested id_token claim. We prune the /// final id_token claim set; the access_token keeps it for introspection linkage. /// /// /// /// NOTE: the sibling claim oi_tkn_id (token id) is INTENTIONALLY left in the id_token — /// it is the entry identifier OpenIddict needs to revoke the id_token and to drive /// back-channel logout, both of which this OP supports. It is stamped during id_token /// generation (not on the principal) and so is not reachable here anyway. /// /// /// /// Runs just before GenerateIdentityToken and edits the already-built /// . Public OIDC claims (sub, /// name, …) and our own redb:user_id are untouched (in the id_token by design). /// /// internal sealed class StripInternalClaimsFromIdentityToken : IOpenIddictServerHandler { private static readonly string[] InternalClaimTypes = { "oi_au_id" }; public static OpenIddictServerHandlerDescriptor Descriptor { get; } = CreateBuilder() .UseSingletonHandler() // Just before GenerateIdentityToken serializes context.IdentityTokenPrincipal. // OpenIddict copies its internal reference claims (oi_au_id at prepare time, // oi_tkn_id later when the token entry is stamped) straight onto the per-token // principal, bypassing the destination filter — running last catches both. .SetOrder(OpenIddictServerHandlers.GenerateIdentityToken.Descriptor.Order - 1) .SetType(OpenIddictServerHandlerType.Custom) .Build(); public ValueTask HandleAsync(ProcessSignInContext context) { ArgumentNullException.ThrowIfNull(context); if (context.IdentityTokenPrincipal?.Identity is not ClaimsIdentity identity) return default; foreach (var type in InternalClaimTypes) { foreach (var claim in identity.FindAll(type).ToList()) identity.RemoveClaim(claim); } return default; } } Path: redb-identity/src/redb.Identity.Core/OpenIddict/Handlers/TouchSessionOnTokenRefreshHandler.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/OpenIddict/Handlers/TouchSessionOnTokenRefreshHandler.cs ---- using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using OpenIddict.Abstractions; using OpenIddict.Server; using redb.Core; using redb.Identity.Core.Services; using static OpenIddict.Server.OpenIddictServerEvents; using static OpenIddict.Server.OpenIddictServerHandlerDescriptor; namespace redb.Identity.Core.OpenIddict.Handlers; /// /// S-track: bump LastAccessedAt on the session referenced by the /// principal's sid claim whenever the token endpoint successfully /// issues new tokens. Covers the refresh_token grant primarily — that's the /// canonical "this session is still alive" signal in OAuth — and also /// authorization_code (first issuance) so the row reflects the moment the /// user actually completed sign-in. /// /// /// Fail-closed-ish: any redb / lookup failure is logged + swallowed so a hot /// path bug never blocks token issuance. The session row will just stay at /// its previous LastAccessedAt and may get lazy-expired on next list, /// which is the safe default (slightly more aggressive expiry, never /// less). /// /// /// /// Pipeline slot: after + /// so the principal is fully /// populated, well before token minting so we don't dirty the principal. /// /// internal sealed class TouchSessionOnTokenRefreshHandler : IOpenIddictServerHandler { private readonly IServiceProvider _sp; private readonly ILogger _logger; public TouchSessionOnTokenRefreshHandler( IServiceProvider sp, ILogger logger) { _sp = sp; _logger = logger; } public static OpenIddictServerHandlerDescriptor Descriptor { get; } = CreateBuilder() .UseScopedHandler() // Just after AttachAdditionalIdTokenAudiences (AttachAuthorization + 501) // so the principal is fully resolved. We touch the session // regardless of which audience or claim path we took. .SetOrder(OpenIddictServerHandlers.AttachAuthorization.Descriptor.Order + 502) .SetType(OpenIddictServerHandlerType.Custom) .Build(); public async ValueTask HandleAsync(ProcessSignInContext context) { ArgumentNullException.ThrowIfNull(context); if (context.Principal is null) return; var sid = context.Principal.GetClaim("sid"); if (string.IsNullOrEmpty(sid) || !long.TryParse(sid, out var sessionId) || sessionId <= 0) return; // no sid → client_credentials or device flow that hasn't established a session var activity = context.Request.IsRefreshTokenGrantType() ? "refresh_token" : context.Request.IsAuthorizationCodeGrantType() ? "authorization_code" : context.Request.IsDeviceCodeGrantType() ? "device_code" : context.Request.IsPasswordGrantType() ? "password" : "token"; var redb = _sp.GetService(); if (redb is null) return; try { var sessions = new SessionService(redb); await sessions.TouchAsync(sessionId, activity, context.CancellationToken) .ConfigureAwait(false); } catch (Exception ex) { _logger.LogWarning(ex, "Sessions: TouchAsync({SessionId}, {Activity}) failed; session timestamp will lag", sessionId, activity); } } } Path: redb-identity/src/redb.Identity.Core/OpenIddict/Handlers/ValidateDpopProofHandler.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/OpenIddict/Handlers/ValidateDpopProofHandler.cs ---- using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using OpenIddict.Server; using redb.Core; using redb.Core.Query; using redb.Identity.Core.Configuration; using redb.Identity.Core.Models; using redb.Identity.Core.Services; using static OpenIddict.Server.OpenIddictServerEvents; using redb.Identity.Contracts.Routes; namespace redb.Identity.Core.OpenIddict.Handlers; /// /// Z4 (RFC 9449): validates the DPoP header on the token endpoint. /// On success, stores the JWK thumbprint (jkt) in /// context.Transaction.Properties["dpop:jkt"] so that downstream /// can bind it into the issued access token. /// /// Soft-mode (the default): if no header is present, the request is allowed through /// untouched (issuing a Bearer token). Strict-mode ( = true): /// missing header rejects with invalid_dpop_proof. /// /// internal sealed class ValidateDpopProofHandler : IOpenIddictServerHandler { private readonly DpopProofValidator _validator; private readonly IDpopNonceProvider _nonceProvider; private readonly DpopOptions _options; private readonly IServiceProvider _sp; private readonly ILogger _logger; public ValidateDpopProofHandler( DpopProofValidator validator, IDpopNonceProvider nonceProvider, IOptions identityOptions, IServiceProvider sp, ILogger logger) { _validator = validator ?? throw new ArgumentNullException(nameof(validator)); _nonceProvider = nonceProvider ?? throw new ArgumentNullException(nameof(nonceProvider)); _options = (identityOptions ?? throw new ArgumentNullException(nameof(identityOptions))).Value.Dpop; _sp = sp ?? throw new ArgumentNullException(nameof(sp)); _logger = logger ?? throw new ArgumentNullException(nameof(logger)); } /// /// A.8: look up the per-client DPoP-required flag. The handler short-circuits /// to "false" on any failure path so a redb hiccup never turns soft-mode into /// strict-mode by accident — same defensive posture as /// AttachAdditionalIdTokenAudiences and AttachClaimMapperClaims. /// private async ValueTask IsDpopRequiredForClientAsync(string? clientId, CancellationToken ct) { if (string.IsNullOrEmpty(clientId)) return false; var redb = _sp.GetService(); if (redb is null) return false; try { var app = await redb.GetByUniqueAsync(p => p.ClientId, clientId) .ConfigureAwait(false); return app?.Props.RequireDpop ?? false; } catch (Exception ex) { _logger.LogWarning(ex, "DPoP: failed to resolve application by client_id '{ClientId}'; treating as not-required", clientId); return false; } } public static OpenIddictServerHandlerDescriptor Descriptor { get; } = OpenIddictServerHandlerDescriptor.CreateBuilder() .UseScopedHandler() // Run before HandleTokenRequestHandler — after standard validators. .SetOrder(int.MaxValue - 50_000) .Build(); public async ValueTask HandleAsync(ValidateTokenRequestContext context) { if (!_options.Enabled) return; var exchange = context.Transaction.GetRouteExchange(); if (exchange is null) return; if (!exchange.In.Headers.TryGetValue("DPoP", out var rawProof) || rawProof is not string proof || string.IsNullOrEmpty(proof)) { // A.8: per-client opt-in is OR'd with the server-wide flag — either // path triggers strict-mode rejection on missing header. var perClientRequired = await IsDpopRequiredForClientAsync(context.ClientId, context.CancellationToken); if (_options.RequireForAccessTokens || perClientRequired) { IssueNonceHeader(exchange); context.Reject( error: "invalid_dpop_proof", description: "DPoP header is required."); } return; } var method = exchange.In.GetHeader("redbHttp.Method") ?? "POST"; var url = exchange.In.GetHeader("redbHttp.Url") ?? string.Empty; var result = await _validator.ValidateAsync( proof: proof, httpMethod: method, httpUri: url, ct: context.CancellationToken).ConfigureAwait(false); if (!result.IsValid) { _logger.LogWarning("DPoP proof validation failed: {Error} — {Desc}", result.Error, result.ErrorDescription); exchange.Properties["identity-event-type"] = redb.Identity.Contracts.Routes.IdentityAuditEventIds.DpopReplayDetected; exchange.Properties["identity-event-data"] = new { Error = result.Error, Description = result.ErrorDescription, }; IssueNonceHeader(exchange); context.Reject( error: result.Error ?? "invalid_dpop_proof", description: result.ErrorDescription); return; } // Z4 P2 (RFC 9449 §8): server-side nonce policy. The validator surfaced the parsed // claim; this handler decides whether the nonce is acceptable. if (_options.RequireNonce) { if (string.IsNullOrEmpty(result.Nonce) || !_nonceProvider.ValidateNonce(result.Nonce)) { IssueNonceHeader(exchange); context.Reject( error: "use_dpop_nonce", description: "DPoP proof is missing a valid server-issued nonce."); return; } } // Always rotate the nonce on success so the next proof can adopt a fresh one. IssueNonceHeader(exchange); // Store jkt for the sign-in handler to bind into the access token. context.Transaction.Properties["dpop:jkt"] = result.Jkt!; exchange.Properties["identity-event-type"] = redb.Identity.Contracts.Routes.IdentityAuditEventIds.DpopBindingApplied; exchange.Properties["identity-event-data"] = new { Jkt = result.Jkt }; } private void IssueNonceHeader(redb.Route.Abstractions.IExchange exchange) { // The Apply*ResponseHandlers copy this transaction property to the response Headers // (RFC 9449 §8). Keeping it here decouples policy from transport vocabulary. exchange.Properties["dpop:nonce-to-issue"] = _nonceProvider.IssueNonce(); } } Path: redb-identity/src/redb.Identity.Core/OpenIddict/Handlers/ValidateRequestObjectHandler.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/OpenIddict/Handlers/ValidateRequestObjectHandler.cs ---- using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Microsoft.IdentityModel.JsonWebTokens; using Microsoft.IdentityModel.Tokens; using OpenIddict.Abstractions; using OpenIddict.Server; using redb.Core.Models.Entities; using redb.Identity.Core.Configuration; using redb.Identity.Core.Models; using redb.Identity.Core.Services; using static OpenIddict.Abstractions.OpenIddictConstants; using static OpenIddict.Server.OpenIddictServerEvents; namespace redb.Identity.Core.OpenIddict.Handlers; /// /// Z7 (RFC 9101) — JWT-Secured Authorization Request. Accepts a signed request object on /// /connect/authorize, verifies it against the client's published keys, and replaces the /// request parameters with the ones carried inside the JWT. /// /// This handler replaces OpenIddict's built-in ValidateRequestParameter / /// ValidateRequestUriParameter, which unconditionally reject those parameters (6.3.0 has no /// request-object support at all). Removal happens in RedbRouteOpenIddictServerConfiguration. /// /// /// With Features.EnableJar = false the observable behaviour is identical to before: /// a request parameter is rejected with request_not_supported. The flag adds a code /// path; it does not change the default answer. /// /// /// Parameter precedence follows RFC 9101 §6.1 — values inside the request object win, and outside /// values that are not repeated inside are ignored. OIDC additionally requires response_type /// and client_id to appear as plain parameters, which is what lets us find the client (and /// therefore its keys) before we can trust anything in the JWT. /// /// internal sealed class ValidateRequestObjectHandler : IOpenIddictServerHandler { /// PAR issues request_uri values with this prefix; those are handled by OpenIddict, not here. private const string ParRequestUriPrefix = "urn:ietf:params:oauth:request_uri:"; private readonly IOpenIddictApplicationManager _applications; private readonly IClientKeyResolver _keyResolver; private readonly IHttpClientFactory _httpClientFactory; private readonly RedbIdentityOptions _identityOptions; private readonly ILogger _logger; /// Named used to fetch a request_uri. internal const string HttpClientName = "redb-identity-request-uri"; public ValidateRequestObjectHandler( IOpenIddictApplicationManager applications, IClientKeyResolver keyResolver, IHttpClientFactory httpClientFactory, IOptions identityOptions, ILogger logger) { _applications = applications ?? throw new ArgumentNullException(nameof(applications)); _keyResolver = keyResolver ?? throw new ArgumentNullException(nameof(keyResolver)); _httpClientFactory = httpClientFactory ?? throw new ArgumentNullException(nameof(httpClientFactory)); _identityOptions = (identityOptions ?? throw new ArgumentNullException(nameof(identityOptions))).Value; _logger = logger ?? throw new ArgumentNullException(nameof(logger)); } public static OpenIddictServerHandlerDescriptor Descriptor { get; } = OpenIddictServerHandlerDescriptor.CreateBuilder() .UseScopedHandler() // Must run before anything inspects the request parameters, because until the request // object is unpacked the plain parameters are not the real request. .SetOrder(OpenIddictServerHandlers.Authentication.ValidateRequestParameter.Descriptor.Order - 100) .SetType(OpenIddictServerHandlerType.Custom) .Build(); public async ValueTask HandleAsync(ValidateAuthorizationRequestContext context) { ArgumentNullException.ThrowIfNull(context); var requestObject = context.Request.Request; var requestUri = context.Request.RequestUri; // PAR hands out urn:ietf:params:oauth:request_uri:* and resolves it itself — leave it alone. if (!string.IsNullOrEmpty(requestUri) && requestUri.StartsWith(ParRequestUriPrefix, StringComparison.Ordinal)) return; if (string.IsNullOrEmpty(requestObject) && string.IsNullOrEmpty(requestUri)) return; if (!_identityOptions.Features.EnableJar) { // Same answer the built-in handlers gave before JAR existed. context.Reject( error: string.IsNullOrEmpty(requestObject) ? Errors.RequestUriNotSupported : Errors.RequestNotSupported, description: string.IsNullOrEmpty(requestObject) ? "The 'request_uri' parameter is not supported." : "The 'request' parameter is not supported."); return; } var options = _identityOptions.Jar; if (string.IsNullOrEmpty(requestObject) && !options.EnableRequestUri) { context.Reject( error: Errors.RequestUriNotSupported, description: "The 'request_uri' parameter is not supported."); return; } // client_id must be a plain parameter: without it there is no way to know whose keys should // verify the signature, and trusting the client_id from inside an unverified JWT is circular. // The client is looked up before a request_uri is fetched, so an unknown or missing client // never makes this server open a connection to an address the caller chose. var clientId = context.Request.ClientId; if (string.IsNullOrEmpty(clientId)) { Reject(context, "The 'client_id' parameter is required when a request object is used."); return; } if (await _applications.FindByClientIdAsync(clientId) is not RedbObject application) { Reject(context, "The client application is unknown."); return; } // request_uri (by reference): fetch the request object over HTTP, then validate it exactly // like an inline one. The fetch is SSRF-guarded — the URL came from the client. if (string.IsNullOrEmpty(requestObject)) { if (!IsRegisteredRequestUri(application, requestUri!, clientId, options, context)) return; requestObject = await FetchRequestUriAsync(requestUri!, options, context).ConfigureAwait(false); if (requestObject is null) return; // FetchRequestUriAsync already rejected the context } if (requestObject.Length > options.MaxRequestObjectLength) { Reject(context, "The request object is too large."); return; } var handler = new JsonWebTokenHandler(); if (!handler.CanReadToken(requestObject)) { Reject(context, "The request object is not a well-formed JWT."); return; } var token = handler.ReadJsonWebToken(requestObject); var algorithm = token.Alg; // 'none' is refused unconditionally: an unsigned request object drops the exact integrity // guarantee JAR exists to provide, so accepting it would be worse than not supporting JAR. if (string.IsNullOrEmpty(algorithm) || string.Equals(algorithm, "none", StringComparison.OrdinalIgnoreCase)) { Reject(context, "Unsigned request objects are not accepted."); return; } if (!options.AllowedSigningAlgorithms.Contains(algorithm, StringComparer.Ordinal)) { Reject(context, $"The request object algorithm '{algorithm}' is not supported."); return; } if (!CheckDeclaredAlgorithm(application, algorithm, clientId, options, context, out var rejected) && rejected) return; var keys = await _keyResolver.GetSigningKeysAsync(application).ConfigureAwait(false); if (keys.Count == 0) { // No keys, nothing to verify against. Failing closed is the point. _logger.LogWarning( "JAR: client {ClientId} sent a request object but publishes no usable keys.", clientId); Reject(context, "The client has no keys registered to verify the request object."); return; } // Issuer is a Uri; the audience of a request object is this server's issuer string. // Match the trimming ApplyDiscoveryResponseHandler uses so aud comparison is consistent. var issuerString = _identityOptions.Issuer?.ToString().TrimEnd('/'); var result = await handler.ValidateTokenAsync(requestObject, new TokenValidationParameters { IssuerSigningKeys = keys, ValidateIssuerSigningKey = true, // RFC 9101 §4: iss MUST be the client_id, aud MUST be the authorization server. ValidIssuer = clientId, ValidateIssuer = true, ValidAudience = issuerString, ValidateAudience = !string.IsNullOrEmpty(issuerString), ValidateLifetime = true, RequireExpirationTime = options.RequireExpiration, ClockSkew = options.ClockSkew, ValidAlgorithms = options.AllowedSigningAlgorithms, }).ConfigureAwait(false); if (!result.IsValid) { _logger.LogWarning( result.Exception, "JAR: request object from client {ClientId} failed validation.", clientId); Reject(context, "The request object signature or claims could not be validated."); return; } var validated = (JsonWebToken)result.SecurityToken; // A request object naming a different client than the outer parameter is either a mix-up // or an attempt to have one client's key authorize another client's request. if (validated.TryGetPayloadValue(Parameters.ClientId, out var innerClientId) && !string.IsNullOrEmpty(innerClientId) && !string.Equals(innerClientId, clientId, StringComparison.Ordinal)) { Reject(context, "The request object's 'client_id' does not match the request."); return; } MergeParameters(context, validated); _logger.LogDebug("JAR: request object accepted for client {ClientId} (alg {Algorithm}).", clientId, algorithm); } /// /// OIDC Dynamic Client Registration 1.0 §2: a request_uri must be one of the client's registered /// request_uris, compared exactly (ordinal, whole value, query and fragment included). A client that /// registered values is always held to them; one without values is refused while /// is on, and passes with a warning while it is off. /// The warning names the client only: the address may carry values in its query. /// private bool IsRegisteredRequestUri( RedbObject application, string requestUri, string clientId, JarOptions options, ValidateAuthorizationRequestContext context) { var registered = application.Props.RequestUris; if (registered is { Length: > 0 }) { if (registered.Contains(requestUri, StringComparer.Ordinal)) return true; } else if (!options.RequireRequestUriRegistration) { _logger.LogWarning( "JAR: client {ClientId} passed a request_uri without registered request_uris. It is accepted because " + "Jar.RequireRequestUriRegistration is off; it would be refused when it is on.", clientId); return true; } context.Reject( error: Errors.InvalidRequestUri, description: "The request_uri is not registered for this client."); return false; } /// /// Fetches the request object referenced by request_uri. Returns the raw JWT, or /// after rejecting the context (SSRF-blocked, unreachable, or too large). /// private async Task FetchRequestUriAsync( string requestUri, JarOptions options, ValidateAuthorizationRequestContext context) { var rejection = await OutboundUrlGuard.ValidateAsync( requestUri, options.RequestUriRequireHttps, options.RequestUriAllowPrivateNetworkTargets, context.CancellationToken).ConfigureAwait(false); if (rejection != OutboundUrlGuard.Rejection.None) { // Refused before any socket opens: the URL is client-controlled, so an internal target // is an SSRF attempt, not a fetch. _logger.LogWarning("JAR: refusing to fetch request_uri: {Reason}.", OutboundUrlGuard.Describe(rejection)); Reject(context, "The request_uri could not be retrieved."); return null; } try { var http = _httpClientFactory.CreateClient(HttpClientName); http.Timeout = options.RequestUriFetchTimeout; http.MaxResponseContentBufferSize = options.MaxRequestObjectLength; // The fragment (the standard's place for a hash of the content) identifies the registered value // only; it is not part of the address that is fetched. var address = new UriBuilder(requestUri) { Fragment = string.Empty }.Uri; var body = await http.GetStringAsync(address, context.CancellationToken).ConfigureAwait(false); if (string.IsNullOrWhiteSpace(body)) { Reject(context, "The request_uri returned an empty document."); return null; } return body; } catch (Exception e) when (e is not OperationCanceledException) { // Unreachable / too large / bad response → fail closed. _logger.LogWarning(e, "JAR: failed to fetch request_uri."); Reject(context, "The request_uri could not be retrieved."); return null; } } /// /// Compares the request object's algorithm against the client's declared /// RequestObjectSigningAlg. Returns whether they match; /// reports whether the request was rejected (only in ). /// private bool CheckDeclaredAlgorithm( RedbObject application, string algorithm, string clientId, JarOptions options, ValidateAuthorizationRequestContext context, out bool rejected) { rejected = false; var declared = application.Props.RequestObjectSigningAlg; if (string.IsNullOrWhiteSpace(declared) || options.EnforcementMode == JarEnforcementMode.Off) return true; if (string.Equals(declared, algorithm, StringComparison.Ordinal)) return true; if (options.EnforcementMode == JarEnforcementMode.LogOnly) { _logger.LogWarning( "JAR: client {ClientId} declares request_object_signing_alg '{Declared}' but signed with " + "'{Actual}'. Allowed because JarEnforcementMode is LogOnly; it would be rejected under Enforce.", clientId, declared, algorithm); return false; } Reject(context, $"The request object must be signed with '{declared}'."); rejected = true; return false; } /// /// RFC 9101 §6.1 — parameters inside the request object take precedence, and outside values /// that are not repeated inside are ignored. Copying the JWT's claims over the request achieves /// both: everything the client meant is present, and anything it did not sign cannot influence /// the decision. /// private static void MergeParameters(ValidateAuthorizationRequestContext context, JsonWebToken token) { foreach (var claim in token.Claims) { // JWT plumbing describes the request object itself, not the authorization request. if (claim.Type is "iss" or "aud" or "exp" or "nbf" or "iat" or "jti") continue; context.Request.SetParameter(claim.Type, new OpenIddictParameter(claim.Value)); } // The request object has been unpacked into individual parameters; drop it so nothing // downstream re-reads or re-validates it (and so the wire request now looks like a plain // authorization request, which every later handler already understands). context.Request.RemoveParameter(Parameters.Request); context.Request.RemoveParameter(Parameters.RequestUri); // `context.RedirectUri` is a strongly-typed context property that OpenIddict populates from // the request BEFORE this handler runs — so in a JAR flow, where redirect_uri arrived only // inside the JWT, it was seeded empty. ValidateRedirectUriParameter reads THAT property // (not context.Request.RedirectUri), so without this line it rejects the request as // "redirect_uri missing" even though the merged parameter is present. Re-seed it from the // now-merged request. (Other validators — response_type, scope, … — read context.Request // directly, so only redirect_uri needs this bridge.) if (!string.IsNullOrEmpty(context.Request.RedirectUri)) context.SetRedirectUri(context.Request.RedirectUri); } /// /// All JAR failures surface as invalid_request_object (RFC 9101 §5) with a description /// that says what was wrong but never echoes token content back to the caller. /// private static void Reject(ValidateAuthorizationRequestContext context, string description) => context.Reject(error: "invalid_request_object", description: description); } Path: redb-identity/src/redb.Identity.Core/OpenIddict/Handlers/ValidateResourcesAgainstScopesHandler.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/OpenIddict/Handlers/ValidateResourcesAgainstScopesHandler.cs ---- using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using OpenIddict.Abstractions; using OpenIddict.Server; using static OpenIddict.Abstractions.OpenIddictConstants; using static OpenIddict.Server.OpenIddictServerEvents; using static OpenIddict.Server.OpenIddictServerHandlerDescriptor; namespace redb.Identity.Core.OpenIddict.Handlers; /// /// RFC 8707 resource indicators: a resource parameter must name a resource the server knows. /// /// OpenIddict 7 checks the parameter against the static OpenIddictServerOptions.Resources set /// (RegisterResources). In redb.Identity the resources are the Resources of the scopes, /// kept in redb and edited at runtime through the management API, so a set fixed at startup would go /// stale. The static check is turned off (DisableResourceValidation) and these handlers take its /// place, in its slot, against the scope store: a resource is known when at least one scope lists it. /// /// /// The rest of OpenIddict's resource handling stays built in: the format check (absolute URI, no /// fragment) and the client permission check (rsrc: + resource on the application). /// /// internal static class ValidateResourcesAgainstScopes { internal static async ValueTask RejectUnknownAsync( BaseValidatingContext context, OpenIddictRequest request, IServiceProvider sp, ILogger logger) { var requested = request.GetResources(); if (requested.IsDefaultOrEmpty) return false; // Degraded mode (no core, no stores: the unit-test and embedded configurations) has no scope // manager. With no scope store no resource is known, so a requested one is rejected. var scopes = sp.GetService(); foreach (var resource in requested) { var known = false; if (scopes is not null) { await foreach (var _ in scopes.FindByResourceAsync(resource)) { known = true; break; } } if (known) continue; logger.LogInformation("Rejected resource {Resource}: no scope lists it", resource); context.Reject( error: Errors.InvalidTarget, description: OpenIddictResources.FormatID2190(Parameters.Resource), uri: OpenIddictResources.FormatID8000(OpenIddictResources.ID2190)); return true; } return false; } } /// Authorization endpoint slot of . internal sealed class ValidateAuthorizationResourcesHandler : IOpenIddictServerHandler { private readonly IServiceProvider _sp; private readonly ILogger _logger; public ValidateAuthorizationResourcesHandler(IServiceProvider sp, ILogger logger) { _sp = sp; _logger = logger; } public static OpenIddictServerHandlerDescriptor Descriptor { get; } = CreateBuilder() .UseScopedHandler() .SetOrder(OpenIddictServerHandlers.Authentication.ValidateResources.Descriptor.Order) .SetType(OpenIddictServerHandlerType.Custom) .Build(); public async ValueTask HandleAsync(ValidateAuthorizationRequestContext context) { ArgumentNullException.ThrowIfNull(context); await ValidateResourcesAgainstScopes.RejectUnknownAsync(context, context.Request, _sp, _logger); } } /// Pushed authorization endpoint slot of . internal sealed class ValidatePushedAuthorizationResourcesHandler : IOpenIddictServerHandler { private readonly IServiceProvider _sp; private readonly ILogger _logger; public ValidatePushedAuthorizationResourcesHandler(IServiceProvider sp, ILogger logger) { _sp = sp; _logger = logger; } public static OpenIddictServerHandlerDescriptor Descriptor { get; } = CreateBuilder() .UseScopedHandler() .SetOrder(OpenIddictServerHandlers.Authentication.ValidatePushedResources.Descriptor.Order) .SetType(OpenIddictServerHandlerType.Custom) .Build(); public async ValueTask HandleAsync(ValidatePushedAuthorizationRequestContext context) { ArgumentNullException.ThrowIfNull(context); await ValidateResourcesAgainstScopes.RejectUnknownAsync(context, context.Request, _sp, _logger); } } /// Token endpoint (token exchange) slot of . internal sealed class ValidateTokenResourcesHandler : IOpenIddictServerHandler { private readonly IServiceProvider _sp; private readonly ILogger _logger; public ValidateTokenResourcesHandler(IServiceProvider sp, ILogger logger) { _sp = sp; _logger = logger; } public static OpenIddictServerHandlerDescriptor Descriptor { get; } = CreateBuilder() .UseScopedHandler() .SetOrder(OpenIddictServerHandlers.Exchange.ValidateResources.Descriptor.Order) .SetType(OpenIddictServerHandlerType.Custom) .Build(); public async ValueTask HandleAsync(ValidateTokenRequestContext context) { ArgumentNullException.ThrowIfNull(context); await ValidateResourcesAgainstScopes.RejectUnknownAsync(context, context.Request, _sp, _logger); } } Path: redb-identity/src/redb.Identity.Core/OpenIddict/Handlers/ValidateTokenEntryStatusHandler.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/OpenIddict/Handlers/ValidateTokenEntryStatusHandler.cs ---- using Microsoft.Extensions.Logging; using OpenIddict.Abstractions; using OpenIddict.Validation; using redb.Core; using redb.Identity.Core.Models; using static OpenIddict.Validation.OpenIddictValidationEvents; namespace redb.Identity.Core.OpenIddict.Handlers; /// /// The token entry check of the resource side (management API, SCIM, account endpoints): the token must still be /// valid in the store. It takes the place of OpenIddict's built-in entry check at the same order and reads only the /// token's object row: its base value_bool is while the token is valid and /// once it is revoked, redeemed or otherwise ended (kept by the store, see /// TokenStatus). A token that is not found (deleted, or in the trash) is refused. A row written before that /// mirror existed has value_bool NULL and is checked by the full read of the entry and its status. /// It does not refuse an entry carrying a ReferenceId, as the built-in step does: no reference access or refresh /// tokens exist here, and ReferenceTokenGuardTests fails the day they are turned on. /// internal sealed class ValidateTokenEntryStatusHandler : IOpenIddictValidationHandler { public static OpenIddictValidationHandlerDescriptor Descriptor { get; } = OpenIddictValidationHandlerDescriptor.CreateBuilder() .UseScopedHandler() .SetOrder(OpenIddictValidationHandlers.Protection.ValidateTokenEntry.Descriptor.Order) .SetType(OpenIddictValidationHandlerType.Custom) .Build(); private readonly IRedbService _redb; private readonly IOpenIddictTokenManager _tokenManager; public ValidateTokenEntryStatusHandler(IRedbService redb, IOpenIddictTokenManager tokenManager) { ArgumentNullException.ThrowIfNull(redb); ArgumentNullException.ThrowIfNull(tokenManager); _redb = redb; _tokenManager = tokenManager; } public async ValueTask HandleAsync(ValidateTokenContext context) { ArgumentNullException.ThrowIfNull(context); // The built-in entry steps (RestoreTokenEntryProperties, ValidateTokenEntry) are off, so the context's // TokenId stays unset: the id comes from the principal, as those steps take it. A token without an id // claim has no entry (OpenIddict issues such tokens only with token storage off; this server always // stores them) and is passed, as RestoreTokenEntryProperties passes it. var tokenId = context.Principal?.GetTokenId(); if (string.IsNullOrEmpty(tokenId)) return; if (await IsValidAsync(tokenId, context.CancellationToken).ConfigureAwait(false)) return; context.Logger.LogInformation("The token '{TokenId}' is no longer valid.", tokenId); context.Reject( error: OpenIddictConstants.Errors.InvalidToken, description: "The specified token is no longer valid."); } private async ValueTask IsValidAsync(string tokenId, CancellationToken cancellationToken) { if (!long.TryParse(tokenId, out var id)) return false; var row = await _redb.Query() .WhereRedb(o => o.Id == id) .Select(o => new { o.Id, o.ValueBool }) .FirstOrDefaultAsync(cancellationToken) .ConfigureAwait(false); if (row is null) return false; if (row.ValueBool is { } valid) return valid; var token = await _tokenManager.FindByIdAsync(tokenId, cancellationToken).ConfigureAwait(false); return token is not null && await _tokenManager.HasStatusAsync(token, OpenIddictConstants.Statuses.Valid, cancellationToken) .ConfigureAwait(false); } } Path: redb-identity/src/redb.Identity.Core/OpenIddict/OidcClaimsRequest.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/OpenIddict/OidcClaimsRequest.cs ---- using System.Text.Json; namespace redb.Identity.Core.OpenIddict; /// /// A single entry of the OIDC claims request parameter (OpenID Connect Core 1.0 §5.5.1): /// {"name": null}, {"name": {"essential": true}}, /// {"sub": {"value": "..."}} or {"acr": {"values": ["1","2"]}}. /// public sealed class OidcClaimsRequestEntry { /// /// §5.5.1 — the RP marks the claim as Essential: it needs the claim to serve the End-User. /// A voluntary claim (the default, and what null means) is a nice-to-have. Note the /// spec is explicit that "essential" does NOT make the claim mandatory for the OP to return — /// it must still be omitted when we simply do not hold a value for this user. /// public bool Essential { get; init; } /// §5.5.1 — the RP requests this exact value for the claim. public string? Value { get; init; } /// §5.5.1 — the RP will accept any one of these values. public IReadOnlyList? Values { get; init; } /// /// Whether a value we hold satisfies the RP's value / values constraint. /// When neither is present, every value is acceptable (the RP just asked for the claim). /// A constrained request that we cannot satisfy means we must NOT return the claim — the /// RP asked for a specific value, and sending a different one would be a lie, not a /// best-effort answer. /// public bool Accepts(string? actual) { if (string.IsNullOrEmpty(actual)) return false; if (Value is not null) return string.Equals(Value, actual, StringComparison.Ordinal); if (Values is { Count: > 0 }) return Values.Contains(actual, StringComparer.Ordinal); return true; } } /// /// The parsed OIDC claims request parameter (OpenID Connect Core 1.0 §5.5) — the RP's /// per-claim request, as opposed to the coarse per-scope request. /// /// Two top-level members are meaningful: userinfo (deliver via /connect/userinfo) and /// id_token (embed in the id_token). §5.5 allows other members to be defined by /// extensions; we ignore what we do not understand rather than rejecting the request, because /// rejecting would break an RP that added a member some other OP understands. /// /// /// This type is protocol-only: it is a parse of one request parameter and is never persisted. /// It carries no storage concern and no HTTP concern — the HTTP layer is a façade that maps the /// query string into the exchange body; the meaning of claims is decided here, in Core. /// /// public sealed class OidcClaimsRequest { private static readonly IReadOnlyDictionary Empty = new Dictionary(StringComparer.Ordinal); private OidcClaimsRequest( IReadOnlyDictionary idToken, IReadOnlyDictionary userInfo) { IdToken = idToken; UserInfo = userInfo; } /// Claims the RP asked to have embedded in the id_token. public IReadOnlyDictionary IdToken { get; } /// Claims the RP asked to be able to fetch from /connect/userinfo. public IReadOnlyDictionary UserInfo { get; } /// True when the parameter carried nothing we act on. public bool IsEmpty => IdToken.Count == 0 && UserInfo.Count == 0; /// /// Parses the raw claims parameter. Returns false with an /// suitable for an invalid_request description when the value is not a JSON object of /// the shape §5.5 defines. A malformed claims parameter is a client bug and must be /// reported as such — silently ignoring it would leave the RP believing it asked for claims /// that it will never receive. /// public static bool TryParse(string? raw, out OidcClaimsRequest? request, out string? error) { request = null; error = null; if (string.IsNullOrWhiteSpace(raw)) { request = new OidcClaimsRequest(Empty, Empty); return true; } JsonElement root; try { using var doc = JsonDocument.Parse(raw); root = doc.RootElement.Clone(); } catch (JsonException ex) { error = $"The 'claims' parameter is not valid JSON: {ex.Message}"; return false; } if (root.ValueKind != JsonValueKind.Object) { error = "The 'claims' parameter must be a JSON object (OpenID Connect Core 1.0 §5.5)."; return false; } if (!TryParseMember(root, "id_token", out var idToken, out error)) return false; if (!TryParseMember(root, "userinfo", out var userInfo, out error)) return false; request = new OidcClaimsRequest(idToken, userInfo); return true; } private static bool TryParseMember( JsonElement root, string member, out IReadOnlyDictionary entries, out string? error) { entries = Empty; error = null; if (!root.TryGetProperty(member, out var element)) return true; // §5.5 — the member may be explicitly null, meaning "nothing requested here". if (element.ValueKind == JsonValueKind.Null) return true; if (element.ValueKind != JsonValueKind.Object) { error = $"The '{member}' member of the 'claims' parameter must be a JSON object."; return false; } var map = new Dictionary(StringComparer.Ordinal); foreach (var property in element.EnumerateObject()) { if (!TryParseEntry(property, member, out var entry, out error)) return false; map[property.Name] = entry!; } entries = map; return true; } private static bool TryParseEntry( JsonProperty property, string member, out OidcClaimsRequestEntry? entry, out string? error) { entry = null; error = null; // §5.5 — `null` requests the claim as Voluntary. This is the common case: // {"userinfo": {"email": null}}. if (property.Value.ValueKind == JsonValueKind.Null) { entry = new OidcClaimsRequestEntry(); return true; } if (property.Value.ValueKind != JsonValueKind.Object) { error = $"Claim '{property.Name}' in '{member}' must be null or a JSON object."; return false; } var essential = false; if (property.Value.TryGetProperty("essential", out var essentialElement)) { if (essentialElement.ValueKind is not (JsonValueKind.True or JsonValueKind.False)) { error = $"'essential' for claim '{property.Name}' must be a JSON boolean."; return false; } essential = essentialElement.GetBoolean(); } string? value = null; if (property.Value.TryGetProperty("value", out var valueElement) && valueElement.ValueKind != JsonValueKind.Null) { value = ScalarToString(valueElement); if (value is null) { error = $"'value' for claim '{property.Name}' must be a JSON string, number or boolean."; return false; } } List? values = null; if (property.Value.TryGetProperty("values", out var valuesElement) && valuesElement.ValueKind != JsonValueKind.Null) { if (valuesElement.ValueKind != JsonValueKind.Array) { error = $"'values' for claim '{property.Name}' must be a JSON array."; return false; } values = new List(); foreach (var item in valuesElement.EnumerateArray()) { var scalar = ScalarToString(item); if (scalar is null) { error = $"'values' for claim '{property.Name}' must contain scalars only."; return false; } values.Add(scalar); } } entry = new OidcClaimsRequestEntry { Essential = essential, Value = value, Values = values }; return true; } /// /// Renders a JSON scalar the way the corresponding claim is stored on the principal, so that /// compares like with like. Claims live on a /// ClaimsIdentity as strings regardless of their JSON type, so a request for /// {"email_verified": {"value": true}} has to be matched against the string "true". /// private static string? ScalarToString(JsonElement element) => element.ValueKind switch { JsonValueKind.String => element.GetString(), JsonValueKind.Number => element.GetRawText(), JsonValueKind.True => "true", JsonValueKind.False => "false", _ => null }; } Path: redb-identity/src/redb.Identity.Core/OpenIddict/RedbApplicationManager.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/OpenIddict/RedbApplicationManager.cs ---- using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using OpenIddict.Abstractions; using OpenIddict.Core; using redb.Identity.Core.Configuration; namespace redb.Identity.Core.OpenIddict; /// /// Application manager that adds RFC 8252 §7.3 loopback redirect handling on top of OpenIddict's /// exact-match redirect validation. /// /// Why this class and not a server handler. ValidateRedirectUriAsync is the single /// point that decides whether a redirect_uri belongs to a client. OpenIddict's authorization /// validation calls it, and so does our own error-redirect gate in /// RedbRouteOpenIddictServerHandler, which must never bounce an error to an unregistered URI /// (RFC 6749 §4.1.2.1). Widening the rule anywhere else would let those two answers diverge — the /// request would be rejected as invalid while the error was still redirected to the attacker's URI, /// which is precisely the open redirect we closed. One rule, one place. /// /// internal sealed class RedbApplicationManager : OpenIddictApplicationManager where TApplication : class { private readonly RedbIdentityOptions _identityOptions; private readonly ILogger> _log; public RedbApplicationManager( IOpenIddictApplicationCache cache, ILogger> logger, IOptionsMonitor options, IOpenIddictApplicationStore store, IOptions identityOptions, ILogger> log) : base(cache, logger, options, store) { _identityOptions = identityOptions.Value; _log = log; } /// /// Exact match first — unchanged OpenIddict behaviour, and the answer for every web client. /// Only if that fails do we consider the loopback rule, and only for a client that already /// registered a loopback redirect. A client registered at https://app.example.com/cb can /// never be talked into accepting http://127.0.0.1:1234/cb: it has no loopback URI to /// match against, so nothing widens. /// public override async ValueTask ValidateRedirectUriAsync( TApplication application, string uri, CancellationToken cancellationToken = default) { if (await base.ValidateRedirectUriAsync(application, uri, cancellationToken)) return true; if (!_identityOptions.AllowLoopbackRedirectPortWildcard) return false; // RFC 8252 §7.3 — a native app cannot know its callback port in advance: it asks the OS for // an ephemeral one at launch, so the port differs on every run and cannot be registered. // The spec's answer is that the port, and ONLY the port, is not compared for loopback // redirects. This is what makes `az login`, `gh auth login` and every desktop OAuth client // work; without it they cannot use this provider at all. if (!TryParseLoopback(uri, out var requested)) return false; var registeredUris = await GetRedirectUrisAsync(application, cancellationToken); foreach (var registered in registeredUris) { if (!TryParseLoopback(registered, out var candidate)) continue; if (!MatchesIgnoringPort(candidate!, requested!)) continue; _log.LogDebug( "Loopback redirect accepted per RFC 8252 §7.3: registered {Registered} matched {Requested} (port ignored)", registered, uri); return true; } return false; } /// /// Parses a URI and returns it only if it is a loopback redirect in the strict sense of /// RFC 8252 §7.3. /// /// The host must be the IP literal 127.0.0.1 or [::1]. "localhost" is /// deliberately excluded — §8.3 warns against it: it is a name, so it goes through /// resolution, and a poisoned resolver or a hosts-file entry can point it somewhere that is not /// the loopback interface. Treating it as loopback would hand port-wildcarding to whatever that /// name resolves to. An app that wants the wildcard uses the IP literal, as the spec says. /// /// /// Userinfo (user:pass@) is rejected outright: it has no business in a redirect URI and /// is a classic way to make a URI read as one host while pointing at another. /// /// private static bool TryParseLoopback(string? value, out Uri? uri) { uri = null; if (string.IsNullOrEmpty(value)) return false; if (!Uri.TryCreate(value, UriKind.Absolute, out var parsed)) return false; if (!string.IsNullOrEmpty(parsed.UserInfo)) return false; // The loopback IP literals, and nothing else. Uri normalises [::1] to "[::1]" in Host. var isLoopbackLiteral = string.Equals(parsed.Host, "127.0.0.1", StringComparison.Ordinal) || string.Equals(parsed.Host, "[::1]", StringComparison.Ordinal) || string.Equals(parsed.Host, "::1", StringComparison.Ordinal); if (!isLoopbackLiteral) return false; uri = parsed; return true; } /// /// Equality over everything except the port: scheme, host, path, query and fragment must all /// match exactly. §7.3 widens the port and nothing else, so a registration for /// http://127.0.0.1/cb does not authorise http://127.0.0.1:5000/evil. /// The scheme is compared too, so an http registration never authorises an https /// callback or vice versa. /// private static bool MatchesIgnoringPort(Uri registered, Uri requested) => string.Equals(registered.Scheme, requested.Scheme, StringComparison.OrdinalIgnoreCase) && string.Equals(registered.Host, requested.Host, StringComparison.OrdinalIgnoreCase) && string.Equals(registered.AbsolutePath, requested.AbsolutePath, StringComparison.Ordinal) && string.Equals(registered.Query, requested.Query, StringComparison.Ordinal) && string.Equals(registered.Fragment, requested.Fragment, StringComparison.Ordinal); } Path: redb-identity/src/redb.Identity.Core/OpenIddict/RedbRouteOpenIddictServerBuilder.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/OpenIddict/RedbRouteOpenIddictServerBuilder.cs ---- using Microsoft.Extensions.DependencyInjection; using OpenIddict.Server; namespace redb.Identity.Core.OpenIddict; /// /// Exposes the configuration methods for the redb.Route OpenIddict Server host adapter. /// Obtained via . /// public sealed class RedbRouteOpenIddictServerBuilder { public RedbRouteOpenIddictServerBuilder(OpenIddictServerBuilder builder) { ArgumentNullException.ThrowIfNull(builder); Builder = builder; } /// /// Gets the underlying . /// public OpenIddictServerBuilder Builder { get; } /// /// Disables the transport security (HTTPS) requirement. /// Should only be used in development or when TLS is terminated at a reverse proxy. /// public RedbRouteOpenIddictServerBuilder DisableTransportSecurityRequirement() { Builder.Services.Configure( options => options.DisableTransportSecurityRequirement = true); return this; } } Path: redb-identity/src/redb.Identity.Core/OpenIddict/RedbRouteOpenIddictServerBuilderExtensions.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/OpenIddict/RedbRouteOpenIddictServerBuilderExtensions.cs ---- using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Options; using OpenIddict.Server; using redb.Identity.Core.OpenIddict.Handlers; using redb.Identity.Core.Services; namespace redb.Identity.Core.OpenIddict; /// /// Extension methods for configuring the redb.Route OpenIddict Server host adapter. /// public static class RedbRouteOpenIddictServerBuilderExtensions { /// /// All handler descriptors registered by the redb.Route adapter. /// internal static readonly OpenIddictServerHandlerDescriptor[] HandlerDescriptors = [ // Extract handlers ExtractTokenRequestHandler.Descriptor, ExtractAuthorizationRequestHandler.Descriptor, ExtractUserinfoRequestHandler.Descriptor, ExtractIntrospectionRequestHandler.Descriptor, ExtractRevocationRequestHandler.Descriptor, ExtractDeviceRequestHandler.Descriptor, ExtractVerificationRequestHandler.Descriptor, ExtractConfigurationRequestHandler.Descriptor, ExtractJwksRequestHandler.Descriptor, ExtractPushedAuthorizationRequestHandler.Descriptor, // Client credentials from Authorization header (Basic auth) ExtractClientCredentialsHandler.Descriptor, ExtractIntrospectionClientCredentialsHandler.Descriptor, ExtractRevocationClientCredentialsHandler.Descriptor, ExtractDeviceClientCredentialsHandler.Descriptor, ExtractPushedAuthorizationClientCredentialsHandler.Descriptor, // Apply handlers ApplyTokenResponseHandler.Descriptor, ApplyAuthorizationResponseHandler.Descriptor, ApplyUserinfoResponseHandler.Descriptor, ApplyIntrospectionResponseHandler.Descriptor, // RFC 7662 §2.2 — surface the internal bigint user id (redb:user_id) // on introspection responses for user-grant tokens. Runs immediately // BEFORE the response writer above so the field is in // context.Response before serialisation. AttachInternalUserIdToIntrospectionResponse.Descriptor, // The owner of a revoked token, for the TokenRevoked audit event. CaptureRevokedTokenUserHandler.Descriptor, ApplyRevocationResponseHandler.Descriptor, ApplyDeviceResponseHandler.Descriptor, ApplyVerificationResponseHandler.Descriptor, ApplyDiscoveryResponseHandler.Descriptor, ApplyJwksResponseHandler.Descriptor, ApplyPushedAuthorizationResponseHandler.Descriptor, // Handle (business logic) handlers HandleTokenRequestHandler.Descriptor, AttachSessionPrincipalHandler.Descriptor, HandleAuthorizationRequestHandler.Descriptor, HandleVerificationRequestHandler.Descriptor, // Userinfo: supplement built-in AttachClaims with additional OIDC standard claims AttachAdditionalUserinfoClaims.Descriptor, // Group-membership scope authorization (gates scopes like 'identity:manage' // behind admin group membership). Runs earlier than AttachClaimMapperClaims // so a denied request never triggers mapper resolution. RestrictScopeByGroupMembershipHandler.Descriptor, // Role-driven entitlement for administrative scopes. OAuth asks whether the CLIENT may // request a scope; this asks whether the USER should hold it. Without it every account able // to sign in to a console permitted to request identity:manage held the master management // scope. Removes the unentitled scopes, never rejects the sign-in. RestrictAdminScopesByRoleHandler.Descriptor, // β: per-application group whitelist (ApplicationProps.AllowedGroups). // Runs one tick after the scope gate so denied-by-scope requests carry // the more specific scope error rather than the generic app error. RestrictApplicationByGroupMembershipHandler.Descriptor, // H5 (DoD §5): apply declarative claim mappers (global + per-app + Client-Scope) at sign-in AttachClaimMapperClaims.Descriptor, // S2.4: per-app ClaimDefinitionProps enforcement (required-claim gate at // token issuance) + per-definition EmitOnIdToken/AccessToken destinations. // Runs AFTER claim mappers so mapper-added claims also get destinations // rewritten when they match a definition name. AttachClaimDefinitionEnforcement.Descriptor, // B.3: Roles registry → `roles` claim. Effective role set = direct user // assignments ∪ transitive assignments via groups, filtered by audience. // Runs AFTER claim mappers (+500) AND definition enforcement (+700) so // the registry is the LAST word on the `roles` claim. AttachRoleRegistryClaims.Descriptor, // A.3: append extra audiences from ApplicationProps.IdTokenAudiences to the // sign-in principal so the issued id_token's aud claim covers federated // downstream resource servers in addition to the implicit client_id default. AttachAdditionalIdTokenAudiences.Descriptor, // RFC 9068 §2.2/§3: access_token aud = scope Resources ∪ ApplicationProps. // AccessTokenAudiences, plus the OP's own audience for identity:* scopes or as // the default resource indicator when nothing else names one. AttachAccessTokenResources.Descriptor, // Strip OpenIddict's internal oi_au_id (authorization id) reference claim from the // id_token (leaks in a JWT config; kept on the access_token). oi_tkn_id is left in // by design — it drives id_token revocation / back-channel logout. OIDC hygiene. StripInternalClaimsFromIdentityToken.Descriptor, // S-track: bump SessionProps.LastAccessedAt on the session carried by // the principal whenever the token endpoint mints new tokens — proves // the session is still alive, drives idle-timeout calculation. TouchSessionOnTokenRefreshHandler.Descriptor, // Z4 (RFC 9449): DPoP proof validation + cnf.jkt binding ValidateDpopProofHandler.Descriptor, AttachDpopConfirmationClaimHandler.Descriptor, // Z4 P2 (RFC 9449 \u00a710): dpop_jkt binding on /authorize \u2194 enforcement at /token BindDpopJktAtAuthorizeHandler.Descriptor, EnforceDpopJktBindingHandler.Descriptor, // OpenIddict 7 validates only the mTLS cnf form and throws on a DPoP jkt. DpopConfirmationServerPassThroughHandler.Descriptor, // Z7 (RFC 9101): JAR \u2014 replaces OpenIddict's built-in rejection of 'request' / // 'request_uri' (removed in RedbRouteOpenIddictServerConfiguration). ValidateRequestObjectHandler.Descriptor, // RFC 7523: one bounded refresh of a jwks_uri key set when a client assertion names an unknown kid. RefreshClientAssertionKeysHandler.Descriptor, // RFC 8707: 'resource' must be listed by a scope. Takes the slot of OpenIddict's static // resource check, which AddRedbIdentityServer turns off (DisableResourceValidation). ValidateAuthorizationResourcesHandler.Descriptor, ValidatePushedAuthorizationResourcesHandler.Descriptor, ValidateTokenResourcesHandler.Descriptor, ]; /// /// Registers the redb.Route host adapter for the OpenIddict Server pipeline. /// This enables processing OAuth/OIDC requests through /// instead of ASP.NET Core or OWIN. /// /// The OpenIddict Server builder. /// A for further configuration. public static RedbRouteOpenIddictServerBuilder UseRedbRoute( this OpenIddictServerBuilder builder) { ArgumentNullException.ThrowIfNull(builder); // Register the entry-point handler that routes use to drive the pipeline builder.Services.TryAddSingleton(); // Register handler services in DI (required for dispatcher resolution) foreach (var descriptor in HandlerDescriptors) { builder.Services.TryAdd(descriptor.ServiceDescriptor); } // Z4 (RFC 9449): the DPoP handlers above are registered unconditionally, // so their dependencies must always resolve from DI. Provide safe defaults // (Memory replay-store) here; full configuration override lives in // RedbIdentityServiceExtensions when DPoP is enabled. builder.Services.TryAddSingleton(sp => new MemoryDpopReplayStore(sp.GetService(), null)); builder.Services.TryAddSingleton(); // Z4 P2 (RFC 9449 §8): default stateless HMAC nonce provider. Override with // a Redis/redb-backed instance for shared validity across cluster nodes. builder.Services.TryAddSingleton(); // Register the PostConfigure that adds handler descriptors to options.Handlers builder.Services.TryAddEnumerable( ServiceDescriptor.Singleton, RedbRouteOpenIddictServerConfiguration>()); return new RedbRouteOpenIddictServerBuilder(builder); } } Path: redb-identity/src/redb.Identity.Core/OpenIddict/RedbRouteOpenIddictServerConfiguration.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/OpenIddict/RedbRouteOpenIddictServerConfiguration.cs ---- using Microsoft.Extensions.Options; using OpenIddict.Server; namespace redb.Identity.Core.OpenIddict; /// /// Registers the redb.Route Extract/Apply handlers in the OpenIddict Server pipeline. /// Single source of truth: . /// internal sealed class RedbRouteOpenIddictServerConfiguration : IPostConfigureOptions { public void PostConfigure(string? name, OpenIddictServerOptions options) { // Z7 (RFC 9101): OpenIddict 6.3.0 has no request-object support — its built-in handlers // reject 'request' / 'request_uri' outright. ValidateRequestObjectHandler takes over both // parameters: it unpacks and verifies a signed request object when Features.EnableJar is // on, and returns the very same request_not_supported / request_uri_not_supported answer // when it is off. Removing them is therefore behaviour-preserving by default. // (PAR's urn:ietf:params:oauth:request_uri:* keeps working — our handler ignores it.) options.Handlers.Remove(OpenIddictServerHandlers.Authentication.ValidateRequestParameter.Descriptor); options.Handlers.Remove(OpenIddictServerHandlers.Authentication.ValidateRequestUriParameter.Descriptor); foreach (var descriptor in RedbRouteOpenIddictServerBuilderExtensions.HandlerDescriptors) options.Handlers.Add(descriptor); // CRITICAL: OpenIddictServerDispatcher iterates options.Handlers in INSERTION // ORDER (per its source comment: "sorted during options initialization for // performance reasons"). It relies on the list being pre-sorted by Order; it // does NOT re-sort at dispatch time. Since our IPostConfigureOptions runs // AFTER OpenIddict's own (which sorted the 272 built-ins), we must re-sort // here, otherwise our handlers are appended to the tail and the dispatcher // will short-circuit (e.g. via Exchange.ApplyTokenResponse // at order 500_000) long before reaching them. options.Handlers.Sort((a, b) => a.Order.CompareTo(b.Order)); } } Path: redb-identity/src/redb.Identity.Core/OpenIddict/RedbRouteOpenIddictServerHandler.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/OpenIddict/RedbRouteOpenIddictServerHandler.cs ---- using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using OpenIddict.Abstractions; using OpenIddict.Server; using redb.Route.Abstractions; using static OpenIddict.Server.OpenIddictServerEvents; namespace redb.Identity.Core.OpenIddict; /// /// Transport-agnostic entry point for processing OAuth/OIDC requests /// through the OpenIddict Server pipeline from an . /// /// Usage in a route definition: /// /// From("direct-vm://identity-token") /// .Process(async (exchange, ct) => /// { /// var handler = context.GetService<RedbRouteOpenIddictServerHandler>(); /// await handler.ProcessAsync(exchange, OpenIddictServerEndpointType.Token, ct); /// }); /// /// /// /// Lifetime (A2): registered as Singleton. Per-exchange Scoped dependencies /// (, ) are /// resolved through when available — redb.Route opens /// a fresh per exchange and exposes it on the exchange — falling /// back to a private scope created via . This avoids the /// captive-Scoped-into-Singleton trap. /// /// public sealed class RedbRouteOpenIddictServerHandler { private readonly IServiceScopeFactory _scopeFactory; private readonly IOptionsMonitor _options; private readonly ILogger? _logger; public RedbRouteOpenIddictServerHandler( IServiceScopeFactory scopeFactory, IOptionsMonitor options, ILogger? logger = null) { _scopeFactory = scopeFactory ?? throw new ArgumentNullException(nameof(scopeFactory)); _options = options ?? throw new ArgumentNullException(nameof(options)); _logger = logger; } /// /// Processes an OAuth/OIDC request through the OpenIddict Server pipeline. /// The exchange body is parsed by registered Extract handlers, and the /// response is written to by Apply handlers. /// /// Route exchange containing the OAuth request. /// The OAuth endpoint type to process. /// Cancellation token. public async Task ProcessAsync( IExchange exchange, OpenIddictServerEndpointType endpointType, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(exchange); // Prefer the per-exchange scope opened by redb.Route IF it actually carries our // OpenIddict registrations. In .tpkg mode the route-context host SP does NOT have // Identity registrations — only the Identity child SP (captured via _scopeFactory) // does. Probe the exchange SP for the marker service and fall back to the private // scope on miss. This keeps the in-process / single-SP path on the per-exchange // scope (correct OpenIddict scoping) while making the isolated-module path work. var exchangeSp = exchange.ServiceProvider; IServiceScope? privateScope = null; IServiceProvider sp; if (exchangeSp is not null && exchangeSp.GetService() is not null) { sp = exchangeSp; } else { privateScope = _scopeFactory.CreateScope(); sp = privateScope.ServiceProvider; } // Bind this scope to the exchange BEFORE anything resolves IRedbService. // // Everything OpenIddict is about to touch — RedbTokenStore, RedbAuthorizationStore, // RedbApplicationStore — is Scoped and pulls IRedbService out of `sp`. Until this line // existed, the private scope's HostRedbScope opened a host scope of its OWN, i.e. a SECOND // connection. A route-level redb transaction runs on the connection redb.Route caches on the // exchange, so every store write landed outside it: no atomicity — and the second connection // then blocked on the row locks the first one held while the first awaited this very call. // Deadlock, cleared only by the 30s transaction timeout. That is why WithRedbTx had to be stripped from the token route. // // With the exchange in hand, HostRedbScope binds IRedbService to the exchange's instance — // the one enlisted into the route's ambient transaction. One connection, one transaction, // the stores enlisted in it. // // Best-effort: the in-process single-SP path has no HostRedbScope (IRedbService comes // straight from AddRedbPro on the exchange scope) and no accessor to seed. Nothing to do // there — it was already on the right connection. if (sp.GetService() is { } accessor) accessor.Exchange = exchange; try { _logger?.LogDebug( "OpenIddict ProcessAsync start: endpoint={Endpoint} issuer={Issuer} hasExchangeSp={HasExchangeSp}", endpointType, _options.CurrentValue.Issuer, exchangeSp is not null); var factory = sp.GetRequiredService(); var dispatcher = sp.GetRequiredService(); var transaction = await factory.CreateTransactionAsync(); transaction.EndpointType = endpointType; transaction.CancellationToken = cancellationToken; transaction.BaseUri = _options.CurrentValue.Issuer; transaction.Properties[RedbRouteOpenIddictServerHelpers.ExchangePropertyKey] = exchange; var context = new ProcessRequestContext(transaction); try { await dispatcher.DispatchAsync(context); } catch (Exception dispatchEx) { _logger?.LogError(dispatchEx, "OpenIddict DispatchAsync threw for endpoint={Endpoint}. " + "context.Error={Error} context.ErrorDescription={Desc} context.IsRejected={Rejected}", endpointType, context.Error, context.ErrorDescription, context.IsRejected); throw; } _logger?.LogDebug( "OpenIddict ProcessAsync done: endpoint={Endpoint} handled={Handled} skipped={Skipped} rejected={Rejected} error={Error} desc={Desc} hasResponse={HasResp}", endpointType, context.IsRequestHandled, context.IsRequestSkipped, context.IsRejected, context.Error, context.ErrorDescription, transaction.Response is not null); // If Apply handlers wrote the response, we're done. if (context.IsRequestHandled || context.IsRequestSkipped) return; // The pipeline was rejected (e.g., unsupported_grant_type) but the error // response was not written to the exchange by Apply handlers (the built-in // error Apply path may not fire for all rejection scenarios). // Write the error response directly. if (context.IsRejected) { var response = new OpenIddictResponse { Error = context.Error, ErrorDescription = context.ErrorDescription, ErrorUri = context.ErrorUri }; // RFC 6749 §5.2 — the token endpoint must not report `invalid_token` (a resource-server // error). OpenIddict emits it for an already-redeemed authorization code (ID2010); map // it to `invalid_grant`. (Userinfo etc. legitimately use invalid_token, so scope to token.) if (endpointType == OpenIddictServerEndpointType.Token && string.Equals(context.Error, OpenIddictConstants.Errors.InvalidToken, StringComparison.Ordinal)) { response.Error = OpenIddictConstants.Errors.InvalidGrant; } // RFC 6749 §4.1.2.1 / §3.1.2.4 — authorization endpoint errors are reported via the // redirect_uri ONLY when that redirect_uri is a REGISTERED redirect for the client. // transaction.Request.RedirectUri is attacker-supplied; redirecting to it before it // is validated against the client is an open redirect (§4.1.2.1 MUST NOT), and when // the client_id is missing/unknown there is no client to validate against at all. // // We validate the request redirect_uri against the client application here — this // replaces the earlier brittle OpenIddict error-code sniffing (ID2043/2052/…), which // both leaked an open redirect on early validation errors that carried no matching // code (missing client_id / code_challenge → ID2029) AND wrongly forced errors like // invalid_scope (ID2052) inline even when the redirect_uri was perfectly valid. // Now: redirect the error only to a validated redirect_uri; otherwise respond inline. var redirectValidated = false; if (endpointType == OpenIddictServerEndpointType.Authorization && !string.IsNullOrEmpty(transaction.Request?.RedirectUri) && !string.IsNullOrEmpty(transaction.Request?.ClientId)) { var applicationManager = sp.GetService(); if (applicationManager is not null) { var application = await applicationManager .FindByClientIdAsync(transaction.Request.ClientId!, cancellationToken); if (application is not null) { redirectValidated = await applicationManager.ValidateRedirectUriAsync( application, transaction.Request.RedirectUri!, cancellationToken); } } } // OIDC §3.1.2.6: login_required / consent_required WITHOUT a prompt flag are deferred // to the local /login (or /consent) page by the HTTP facade, not bounced to the RP. // prompt=none (prompt_none=true) — RP opted into "never show UI"; the error MUST // flow back to the (validated) redirect_uri so the RP can drive its own UX. // prompt=login (force_login=true) — session present, RP wants re-auth; surface // login_required on the redirect_uri (a /login page would just cookie-reauth loop). // neither flag — the user simply has no session; defer to the local /login page. var promptNone = exchange.Properties.TryGetValue("prompt_none", out var pn) && pn is true; var forceLogin = exchange.Properties.TryGetValue("force_login", out var fl) && fl is true; var interactiveDeferred = !promptNone && !forceLogin && (string.Equals(context.Error, "login_required", StringComparison.Ordinal) || string.Equals(context.Error, "consent_required", StringComparison.Ordinal)); if (redirectValidated && !interactiveDeferred && exchange.In.Headers.ContainsKey(redb.Route.Http.HttpHeaders.Method)) { if (!string.IsNullOrEmpty(transaction.Request!.State)) response.State = transaction.Request.State; WriteAuthorizationErrorRedirect( exchange, transaction.Request.RedirectUri!, transaction.Request.ResponseMode, response); return; } RedbRouteOpenIddictServerHelpers.WriteResponseToExchange(exchange, response); // RFC 9449 §7.1: a DPoP presentation rejected at userinfo answers with the DPoP challenge // staged by DpopConfirmationServerPassThroughHandler. if (exchange.Out is not null && exchange.Properties.TryGetValue(Handlers.DpopConfirmationPassThrough.ChallengeProperty, out var challenge) && challenge is string dpopChallenge && dpopChallenge.Length > 0) { exchange.Out.Headers["WWW-Authenticate"] = dpopChallenge; } // RFC 6749 §5.2 — token-endpoint error status: invalid_client → 401, everything else → 400. if (endpointType == OpenIddictServerEndpointType.Token && exchange.Out is not null && !string.IsNullOrEmpty(response.Error)) { exchange.Out.Headers[redb.Route.Http.HttpHeaders.ResponseCode] = string.Equals(response.Error, OpenIddictConstants.Errors.InvalidClient, StringComparison.Ordinal) ? 401 : 400; } return; } // Fallback: response exists on transaction but wasn't written to exchange if (transaction.Response != null && exchange.Out?.Body == null) { RedbRouteOpenIddictServerHelpers.WriteResponseToExchange(exchange, transaction.Response); } } catch (Exception ex) { _logger?.LogError(ex, "RedbRouteOpenIddictServerHandler.ProcessAsync FAILED: endpoint={Endpoint} type={ExType} msg={Msg}", endpointType, ex.GetType().FullName, ex.Message); throw; } finally { privateScope?.Dispose(); } } /// /// Builds the RFC 6749 §4.1.2.1 error redirect for the authorization endpoint: /// 302 to redirect_uri with error/error_description/state on the /// query string (default) or the URL fragment (when response_mode=fragment). /// private static void WriteAuthorizationErrorRedirect( IExchange exchange, string redirectUri, string? responseMode, OpenIddictResponse response) { var sb = new System.Text.StringBuilder(); var first = true; foreach (var p in response.GetParameters()) { if (p.Value.GetRawValue() is null) continue; var value = p.Value.ToString(); if (value is null) continue; if (!first) sb.Append('&'); first = false; sb.Append(Uri.EscapeDataString(p.Key)); sb.Append('='); sb.Append(Uri.EscapeDataString(value)); } var payload = sb.ToString(); string location; if (string.Equals(responseMode, "fragment", StringComparison.Ordinal)) { location = redirectUri + "#" + payload; } else { var sep = redirectUri.Contains('?') ? "&" : "?"; location = redirectUri + sep + payload; } if (exchange.Out is null) { exchange.Pattern = ExchangePattern.InOut; exchange.Out = exchange.In.Clone(); exchange.Out.Body = null; exchange.Out.Headers.Clear(); } var msg = exchange.Out!; msg.Body = Array.Empty(); msg.Headers[redb.Route.Http.HttpHeaders.ResponseCode] = 302; msg.Headers["Location"] = location; } } Path: redb-identity/src/redb.Identity.Core/OpenIddict/RedbRouteOpenIddictServerHelpers.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/OpenIddict/RedbRouteOpenIddictServerHelpers.cs ---- using System.Collections.Immutable; using System.Text.Json; using System.Text.Json.Nodes; using OpenIddict.Abstractions; using OpenIddict.Server; using redb.Route.Abstractions; namespace redb.Identity.Core.OpenIddict; /// /// Internal helpers for bridging and . /// internal static class RedbRouteOpenIddictServerHelpers { internal const string ExchangePropertyKey = "redb.route.exchange"; /// /// Retrieves the stored in the transaction properties. /// Returns null if the current request is not handled by the redb.Route adapter. /// internal static IExchange? GetRouteExchange(this OpenIddictServerTransaction transaction) { if (transaction.Properties.TryGetValue(ExchangePropertyKey, out var value)) return value as IExchange; return null; } /// /// Creates an from the exchange body. /// Supports , IDictionary<string, string>, /// IDictionary<string, object?>, and form-urlencoded strings. /// internal static OpenIddictRequest CreateRequestFromExchange(IExchange exchange) { switch (exchange.In.Body) { case OpenIddictRequest existing: return existing; case IDictionary form: { var request = new OpenIddictRequest(); foreach (var (key, value) in form) request.SetParameter(key, new OpenIddictParameter(value)); return request; } case IDictionary dict: { var request = new OpenIddictRequest(); foreach (var (key, value) in dict) { if (value is string s) request.SetParameter(key, new OpenIddictParameter(s)); else if (value is string[] arr) request.SetParameter(key, new OpenIddictParameter(string.Join(" ", arr))); else if (value != null) request.SetParameter(key, new OpenIddictParameter(value.ToString())); } return request; } case string text when !string.IsNullOrEmpty(text): { var request = new OpenIddictRequest(); foreach (var segment in text.Split('&', StringSplitOptions.RemoveEmptyEntries)) { var eqIdx = segment.IndexOf('='); if (eqIdx > 0) { var k = Uri.UnescapeDataString(segment[..eqIdx]); var v = Uri.UnescapeDataString(segment[(eqIdx + 1)..]); request.SetParameter(k, new OpenIddictParameter(v)); } } return request; } default: return new OpenIddictRequest(); } } /// /// Writes an to the exchange Out message. /// Creates the Out message if it doesn't exist (sets InOut pattern). /// internal static void WriteResponseToExchange(IExchange exchange, OpenIddictResponse response) { if (exchange.Out == null) { exchange.Pattern = ExchangePattern.InOut; exchange.Out = exchange.In.Clone(); exchange.Out.Body = null; exchange.Out.Headers.Clear(); } var result = new Dictionary(); foreach (var param in response.GetParameters()) { result[param.Key] = NormalizeParameterValue(param.Value); } exchange.Out.Body = result; exchange.Out.ContentType = "application/json"; // RFC 6749 §5.2: a client that authenticated through the Authorization header and failed // gets invalid_client with a challenge naming the scheme it used. if (string.Equals(response.Error, OpenIddictConstants.Errors.InvalidClient, StringComparison.Ordinal) && Handlers.BasicAuthHelper.HasBasicHeader(exchange)) { exchange.Out.Headers["WWW-Authenticate"] = Handlers.BasicAuthHelper.Challenge; } } /// /// Normalizes an to a CLR value suitable for /// . Arrays become List<object?>, /// objects become Dictionary<string, object?>, primitives are unwrapped. /// private static object? NormalizeParameterValue(OpenIddictParameter parameter) { // OpenIddict 7 keeps arrays as ImmutableArray and complex values as either // JsonElement or JsonNode. Arrays leave as string?[] (the shape the transports had // before 7); a JsonNode goes through the same JsonElement normalisation. return parameter.GetRawValue() switch { null => null, JsonElement element => NormalizeJsonElement(element), JsonNode node => NormalizeJsonElement(JsonSerializer.SerializeToElement(node)), ImmutableArray array => array.ToArray(), var value => value }; } private static object? NormalizeJsonElement(JsonElement element) { return element.ValueKind switch { JsonValueKind.String => element.GetString(), JsonValueKind.Number when element.TryGetInt64(out var l) => l, JsonValueKind.Number => element.GetDouble(), JsonValueKind.True => true, JsonValueKind.False => false, JsonValueKind.Null => null, JsonValueKind.Array => NormalizeJsonArray(element), JsonValueKind.Object => NormalizeJsonObject(element), _ => element.GetRawText() }; } private static List NormalizeJsonArray(JsonElement element) { var list = new List(); foreach (var item in element.EnumerateArray()) { list.Add(NormalizeJsonElement(item)); } return list; } private static Dictionary NormalizeJsonObject(JsonElement element) { var dict = new Dictionary(StringComparer.Ordinal); foreach (var prop in element.EnumerateObject()) { dict[prop.Name] = NormalizeJsonElement(prop.Value); } return dict; } } Path: redb-identity/src/redb.Identity.Core/OpenIddict/RedbRouteOpenIddictServerOptions.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/OpenIddict/RedbRouteOpenIddictServerOptions.cs ---- namespace redb.Identity.Core.OpenIddict; /// /// Configuration options for the redb.Route OpenIddict Server host adapter. /// public sealed class RedbRouteOpenIddictServerOptions { /// /// Gets or sets a value indicating whether the transport security requirement /// (HTTPS) should be disabled. Default is false. /// public bool DisableTransportSecurityRequirement { get; set; } } Path: redb-identity/src/redb.Identity.Core/PasswordReset/IPasswordResetTokenStore.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/PasswordReset/IPasswordResetTokenStore.cs ---- using System; using System.Threading; using System.Threading.Tasks; namespace redb.Identity.Core.PasswordReset; /// /// N-4 (Session C): server-side password-reset token store — issues and atomically consumes /// single-use reset tokens so that the plaintext token lives only in transient memory /// (generator → e-mail channel) and never appears in the database, access logs, or referer /// headers. /// /// Mirrors : each issuance writes a single row /// containing sha256(pepper || token), an absolute TTL, and a /// single-use flag. Verify loads the row under LockForUpdate, checks the hash in /// constant time, flips the flag, commits — so a second verify with the same token hits an /// already-consumed row and fails regardless of correctness. /// /// public interface IPasswordResetTokenStore { /// /// Issues a new reset token. Generates a 32-byte CSPRNG secret (base64url-encoded), /// persists its peppered SHA-256 hash, and returns the jti + plaintext token so /// the caller can embed both into the e-mail link. /// /// User the reset is bound to. /// /// The caller-supplied reset URL captured at issue time. Recorded for audit; the /// whitelist / open-redirect check is enforced by the HTTP facade against the configured /// allow-list before this method is invoked. /// /// Time-to-live for this token. Typically 30 minutes. Task IssueAsync( long userId, string callerResetUrl, TimeSpan ttl, CancellationToken ct = default); /// /// Verifies and atomically consumes a reset token keyed by . On /// success the row is marked Consumed and the bound UserId is returned; /// on failure Attempts increments so downstream telemetry can flag guessing /// attempts. Already-consumed, expired, or unknown values return /// = false with the appropriate /// . /// /// Per-issuance identifier carried on the reset URL. /// Plaintext token carried on the reset URL. Task VerifyAndConsumeAsync( Guid jti, string token, CancellationToken ct = default); } /// Result of . /// Random per-issuance identifier. Embed into the reset URL. /// Plaintext token for e-mail delivery. Must NOT be persisted by the caller. /// Absolute expiry; surface as {ttlMinutes} in the e-mail template. public readonly record struct PasswordResetIssueResult( Guid Jti, string PlaintextToken, DateTimeOffset ExpiresAt); /// Result of . /// Whether the token verified AND the row was successfully consumed. /// Owner user id when is true; otherwise 0. /// Diagnostic reason; values: ok, not_found, expired, /// already_consumed, bad_token. public readonly record struct PasswordResetVerifyResult( bool Success, long UserId, string Reason); Path: redb-identity/src/redb.Identity.Core/PasswordReset/RedbPasswordResetTokenStore.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/PasswordReset/RedbPasswordResetTokenStore.cs ---- using System; using System.Security.Cryptography; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Core; using redb.Core.Models.Entities; using redb.Identity.Core.Models; using redb.Identity.Core.Services; namespace redb.Identity.Core.PasswordReset; /// /// N-4 (Session C): redb-backed . Singleton; resolves /// through a fresh DI scope per operation (identical pattern to /// PropsServerSideOtpStore / PropsSigningKeyStore) to avoid captive-scope-in-singleton. /// /// Tokens are 32 bytes of CSPRNG, base64url-encoded (no padding). Only the peppered /// SHA-256 hex of the plaintext is persisted (); /// the plaintext is returned to the caller exactly once for e-mail delivery. /// /// /// Verify runs inside a redb transaction + LockForUpdateAsync on the token row so /// concurrent verify calls against the same jti serialize cleanly — the first /// successful call flips , subsequent calls /// see the flag under the lock and return with /// Reason = already_consumed. /// /// public sealed class RedbPasswordResetTokenStore : IPasswordResetTokenStore { private readonly IServiceScopeFactory _scopeFactory; private readonly RecoveryCodePepperProvider _pepperProvider; private readonly ILogger _logger; private readonly TimeProvider _timeProvider; public RedbPasswordResetTokenStore( IServiceScopeFactory scopeFactory, RecoveryCodePepperProvider pepperProvider, ILogger logger, TimeProvider? timeProvider = null) { _scopeFactory = scopeFactory ?? throw new ArgumentNullException(nameof(scopeFactory)); _pepperProvider = pepperProvider ?? throw new ArgumentNullException(nameof(pepperProvider)); _logger = logger ?? throw new ArgumentNullException(nameof(logger)); _timeProvider = timeProvider ?? TimeProvider.System; } /// public async Task IssueAsync( long userId, string callerResetUrl, TimeSpan ttl, CancellationToken ct = default) { if (userId <= 0) throw new ArgumentOutOfRangeException(nameof(userId)); if (ttl <= TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(ttl)); var jti = Guid.NewGuid(); var token = GenerateToken(); var now = _timeProvider.GetUtcNow(); var expires = now + ttl; var hash = RecoveryCodePepperProvider.PepperedSha256Hex(_pepperProvider.Pepper, token); await using var scope = _scopeFactory.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); var obj = new RedbObject(new PasswordResetTokenProps { Jti = jti.ToString("N"), UserId = userId, TokenHash = hash, PepperId = _pepperProvider.PepperId, IssuedAt = now, ExpiresAt = expires, Consumed = false, Attempts = 0, CallerResetUrl = callerResetUrl ?? string.Empty, }); obj.name = jti.ToString("N"); await redb.SaveAsync(obj).ConfigureAwait(false); return new PasswordResetIssueResult(jti, token, expires); } /// public async Task VerifyAndConsumeAsync( Guid jti, string token, CancellationToken ct = default) { if (jti == Guid.Empty) return new PasswordResetVerifyResult(false, 0, "not_found"); if (string.IsNullOrEmpty(token)) return new PasswordResetVerifyResult(false, 0, "bad_token"); await using var scope = _scopeFactory.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); var key = jti.ToString("N"); await using var tx = await redb.Context.BeginTransactionAsync().ConfigureAwait(false); var row = await redb.Query() .Where(o => o.Jti == key) .FirstOrDefaultAsync() .ConfigureAwait(false); if (row is null) { await tx.RollbackAsync().ConfigureAwait(false); return new PasswordResetVerifyResult(false, 0, "not_found"); } // Serialize concurrent verify attempts against the same row. if (row.key.HasValue) await redb.LockForUpdateAsync(row.key.Value).ConfigureAwait(false); var p = row.Props; var now = _timeProvider.GetUtcNow(); if (p.Consumed) { await tx.CommitAsync().ConfigureAwait(false); return new PasswordResetVerifyResult(false, 0, "already_consumed"); } if (p.ExpiresAt < now) { await tx.CommitAsync().ConfigureAwait(false); return new PasswordResetVerifyResult(false, 0, "expired"); } if (_pepperProvider.PeppersFor(p.PepperId).Count == 0) _logger.LogWarning("The token was hashed with pepper {PepperId}, which is no longer configured.", p.PepperId); var ok = _pepperProvider.MatchesTokenHash(token.Trim(), p.TokenHash, p.PepperId); p.Attempts++; if (ok) { p.Consumed = true; } try { await redb.SaveAsync(row).ConfigureAwait(false); await tx.CommitAsync().ConfigureAwait(false); } catch { await tx.RollbackAsync().ConfigureAwait(false); throw; } return ok ? new PasswordResetVerifyResult(true, p.UserId, "ok") : new PasswordResetVerifyResult(false, 0, "bad_token"); } private static string GenerateToken() { // 32 bytes CSPRNG → base64url (no padding). ~43 chars; comfortably > 128 bits of entropy. Span buf = stackalloc byte[32]; RandomNumberGenerator.Fill(buf); return Base64UrlEncode(buf); } private static string Base64UrlEncode(ReadOnlySpan bytes) { var s = Convert.ToBase64String(bytes); return s.TrimEnd('=').Replace('+', '-').Replace('/', '_'); } } Path: redb-identity/src/redb.Identity.Core/Routes/IdentityCoreRouteBuilder.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/Routes/IdentityCoreRouteBuilder.cs ---- using System.Data.Common; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Microsoft.IdentityModel.Tokens; using OpenIddict.Server; using redb.Core; using redb.Core.Services; using redb.Identity.Core.Configuration; using redb.Identity.Core.OpenIddict; using redb.Identity.Core.Routes.Processors; using redb.Identity.Core.Services; using redb.Route; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Mail; using redb.Route.RedbCore.Models; using redb.Route.RedbCore.Repositories; using redb.Route.RedbCore.Transactions; using redb.Route.Transactions; using redb.Identity.Contracts.Routes; using redb.Identity.Contracts.Common; namespace redb.Identity.Core.Routes; /// /// Core route builder for the redb Identity Server. /// Registers all 15 direct-vm:// endpoints with error handling, throttle, and event dispatch. /// public class IdentityCoreRouteBuilder : RouteBuilder { private readonly IServiceProvider _sp; private readonly string? _redbName; private readonly RedbIdentityOptions _options; private readonly IdentityAuditOptions _auditOptions; /// The thread pool profile of the wire taps that carry events to the events route. internal const string EventTapPool = "identity-audit"; private readonly IProcessor? _managementAuth; private readonly IProcessor? _scimAuth; /// /// How many times a transient is redelivered. Two places must agree on /// it — MaximumRedeliveries and the RetryWhile predicate that replaces it — so they /// read the same constant instead of each carrying its own literal. See the handler below. /// private const int MaxDbRedeliveries = 3; /// /// The gate at the entrance of the management, self-service and SCIM surface. Created once per /// Configure() with the security logger; every route on that surface takes it as its first processor /// through or explicitly. See . /// private RequireManagementContextProcessor? _requireManagementContext; private RequireManagementContextProcessor RequireManagementContext => _requireManagementContext ?? throw new InvalidOperationException("The management-context gate is created at the start of Configure(); a management route was wired before it."); public IdentityCoreRouteBuilder( IServiceProvider sp, IOptions options, IOptions? auditOptions = null, IProcessor? managementAuth = null, IProcessor? scimAuth = null) { _sp = sp; _options = options.Value; _auditOptions = auditOptions?.Value ?? new IdentityAuditOptions(); _redbName = _options.RedbInstanceName; _managementAuth = managementAuth; _scimAuth = scimAuth; } protected override void Configure() { var handler = _sp.GetRequiredService(); var timeProvider = _sp.GetService() ?? TimeProvider.System; // One subscription cache per route set: the events route reads it, the webhook management // processor drops it on every change. The registered instance when AddRedbIdentityServer ran. var webhookCache = _sp.GetService() ?? new redb.Identity.Core.Events.WebhookSubscriptionCache(timeProvider, _options.Delivery.SubscriptionCache); var uniqueViolationMetrics = _sp.GetService(); // Every event leaves its route on a wire tap to the events route. The taps share one bounded pool // profile: at most Identity:Audit:TapConcurrency events in the events route at once per tap; past // the queue the request that raised the event runs it itself, so a slow audit write slows the // requests instead of piling up work without bound. Context?.AddThreadPoolProfile(EventTapPool, new redb.Route.Configuration.ThreadPoolProfile { MaxConcurrency = Math.Max(1, _auditOptions.TapConcurrency), }); // ── Builder-level error handling ── // DB errors: transient ones are retried, deterministic ones are not. // // One handler and not two: the context registers a global handler per exception type and refuses a // second for DbException, so the distinction has to be made inside. // // A unique-constraint violation collides on the third attempt exactly as it did on the first, so // RetryWhile keeps the retries for real outages. And it is a conflict, not an outage: answering // 503 tells the caller "the database is down, come back later" about something only they can fix // and that will never fix itself. This handler sees the violations the driver raises itself: the // _users table (login, UX_users_email), reached by users and SCIM. A SCIM demo reusing one e-mail // address used to be told the database was unavailable, and the hunt started there instead of // ending there. A violated [RedbUnique] key arrives as RedbUniqueViolationException and has its // own handler below. OnException() .MaximumRedeliveries(MaxDbRedeliveries) .RedeliveryDelay(TimeSpan.FromMilliseconds(200)) .UseExponentialBackOff() .BackOffMultiplier(2.0) // A retry starts the route over, and by then the body is what the steps before the failure left in it: // on a transacted route that fails at commit, the processor's own answer. Replayed as the request, it // came back as a validation error ("Id is required") for an outage. The retry gets the request again. .UseOriginalBody() // The bound is carried INSIDE the predicate, and that is not a duplicate of the line above. // RetryWhile does not narrow MaximumRedeliveries — it REPLACES it: OnExceptionProcessor // takes the predicate instead of the count check, inside a `while (true)` with no outer // bound. A predicate asking only "is this not a unique violation?" retries an ordinary // outage forever, and since the delay doubles every round the route stops answering // altogether. MaximumRedeliveries stays above as the documented policy and as the bound // that applies the day this predicate goes away. .RetryWhile(e => !IdentityProcessorHelpers.IsUniqueViolation(e.Exception) && e.In.GetHeader("CamelRedeliveryCounter") < MaxDbRedeliveries) .Handled() .LogStackTrace() .Process(e => { var outMsg = EnsureOut(e); if (IdentityProcessorHelpers.IsUniqueViolation(e.Exception)) { AnswerDuplicate(e, uniqueViolationMetrics); return; } outMsg.Body = ErrorResponse("server_error", "Database temporarily unavailable."); outMsg.Headers["redbHttp.ResponseCode"] = 503; }); // A violated [RedbUnique] key that the processor did not catch itself: the loser of a concurrent // create, whose check before the insert saw nothing. The typed exception needs a handler of its // own. It carries the driver exception as its cause, but the handler is chosen by the closest // type over the whole chain: RedbUniqueViolationException is one step from Exception, while // Npgsql's PostgresException is two steps from DbException, so on PostgreSQL the catch-all below // won and the caller was told 500 about a conflict. Not retried: it collides again every time. OnException() .Handled() .LogStackTrace() .Process(e => AnswerDuplicate(e, uniqueViolationMetrics)); // Catch-all: unexpected errors → generic server_error, no internals leaked OnException() .Handled() .LogStackTrace() .Process(e => { var outMsg = EnsureOut(e); outMsg.Body = ErrorResponse("server_error", "An unexpected error occurred."); outMsg.Headers["redbHttp.ResponseCode"] = 500; }); // ── Protocol endpoints ── // C2 — single shared trusted-proxy resolver. Sanitizes redbHttp.RemoteAddress on // routes consumed by per-IP throttling / per-IP lockout BEFORE any of those see it. // Secure-by-default: when ReverseProxies.TrustForwardedFor is false (default) the // processor is a no-op. See ReverseProxyOptions for trust model. var trustedProxy = new TrustedProxyResolverProcessor( _options.ReverseProxies, _sp.GetService()?.CreateLogger()); // C1 — Per-IP / per-(IP+username) rate limit. Built only when enabled in config so // that disabled-installations have zero overhead. Camel-style conditional pipeline: // the route chain is split at trustedProxy and the optional Process(...) calls are // appended via local IRouteDefinition references before the OnException/business // processors are attached. var rlEnabled = _options.RateLimit.Enabled; // E5: security-channel logger — rate-limit breaches and per-(IP+user) failure // ceilings are audit-class signals and flow through RedbIdentity.Security so // downstream log-routing can mirror them to SIEM/audit sinks. var securityLogger = _sp.GetService() is { } lf ? Security.IdentitySecurityLog.CreateLogger(lf) : null; // The management surface refuses exchanges without a management context; the gate is one // instance shared by every route on that surface, created before the first of them is wired. _requireManagementContext = new RequireManagementContextProcessor(securityLogger); var rlLogger = securityLogger; var perIpThrottle = rlEnabled ? new RateLimitProcessor( _sp, bucketTag: "any", limitSelector: o => o.PerIpPerMinute, windowSelector: _ => TimeSpan.FromMinutes(1), logger: rlLogger) : null; var loginFailureRecorder = rlEnabled ? new LoginFailureRecorderProcessor( _sp, securityLogger) : null; // 1. Token — issuance is atomic: the token entry and the authorization entry either both // land or neither does. // // This wrap USED to be impossible. The OpenIddict stores (RedbTokenStore, // RedbAuthorizationStore) resolve IRedbService from Identity's child container, and in the // .tpkg topology that container used to open a host scope of its own per DI scope — a SECOND // connection. The route transaction runs on the connection redb.Route caches on the exchange, // so the stores wrote OUTSIDE it (no atomicity), and the second connection then blocked on the // row locks the first one held while the first awaited the call that opened the second. // Deadlock, cleared only by the 30s transaction timeout. Not a // SQLite quirk: it happens on Npgsql as well; SQLite (single writer) only made it louder. // // HostRedbScope now binds IRedbService to the exchange's instance (see IdentityExchangeAccessor), // so the stores enlist in this transaction instead of fighting it. Same reason the addon // scenario works: an addon that wraps its own route in WithRedbTx and calls // direct-vm://identity-token now gets ONE atomic commit across its own write and the token issue. // // Note on the password grant: Argon2id verify (~250 ms at OWASP parameters) happens inside this // route, hence inside the transaction window. The redb transaction is deferred — the write lock // is taken at the first WRITE, which is after the verify — but this is the thing to watch under // load on SQLite, where there is a single writer per database. // RouteId goes INSIDE From(...), before the wrap: WithRedbTx returns the transaction // definition, and an id set on that would not land on the route the registry looks up. var tokenRoute = WithRedbTx(From(IdentityEndpoints.Token) .RouteId(IdentityEndpoints.RouteIds.Token)) .Process(trustedProxy); if (perIpThrottle is not null) tokenRoute = tokenRoute.Process(perIpThrottle); tokenRoute .OnException() .OnWhen(e => IsOAuthError(e.Exception)) .Handled() .Process(MapOAuthExceptionToRfc6749Response) .EndOnException() .Throttle( ExtractClientIdForThrottle, _options.TokenThrottleMaxPerPeriod, _options.TokenThrottlePeriod) .RejectOnOverflow() // F3: emit `identity.token-request` metric (count + latency histogram) and a // matching OTEL span. Static step-name keeps Prometheus cardinality bounded. .Traced("identity.token-request") .Metered("identity.token-request", new TokenEndpointProcessor(handler, timeProvider)) .EndTraced() .WireTap(IdentityEndpoints.Events, EventTapPool); // 2. Authorize (WireTap). Not route-transacted, and correctly so: the only write is a single // authorization-code entry through OpenIddict's authorization store — one store operation, // atomic on its own. There is no multi-row write here for a route transaction to make atomic. // (This is a different situation from Token, which DOES write two coupled entries — token + // authorization — and is therefore wrapped; see its note above.) From(IdentityEndpoints.Authorize) .RouteId(IdentityEndpoints.RouteIds.Authorize) .Process(new AuthorizeEndpointProcessor(handler)) .WireTap(IdentityEndpoints.Events, EventTapPool); // 3. Userinfo (read-only, no WireTap) From(IdentityEndpoints.Userinfo) .RouteId(IdentityEndpoints.RouteIds.Userinfo) .Process(new UserinfoEndpointProcessor(handler)); // 4. Introspect (DoTry/DoCatch expired tokens, read-only). // H6 (RFC 7662): emits TokenIntrospected audit event for every well-formed call, // so the route DOES WireTap to events even though it does not mutate state itself. From(IdentityEndpoints.Introspect) .RouteId(IdentityEndpoints.RouteIds.Introspect) .DoTry() .Process(new IntrospectionEndpointProcessor(handler)) .DoCatch() .Process(e => { e.Out ??= e.In; e.Out.Body = new redb.Identity.Contracts.Tokens.IntrospectionResponse { Active = false }; }) .End() .WireTap(IdentityEndpoints.Events, EventTapPool); // 5. Revoke (WireTap). Not route-transacted, correctly: a single token-status write through // OpenIddict's token store — one atomic store operation, no multi-row write for a route // transaction to guard. Do NOT add WithRedbTx here expecting an atomicity gain; there is none // to be had. From(IdentityEndpoints.Revoke) .RouteId(IdentityEndpoints.RouteIds.Revoke) .Process(new RevocationEndpointProcessor(handler, timeProvider)) .WireTap(IdentityEndpoints.Events, EventTapPool); // 6. Discovery (read-only, no WireTap) From(IdentityEndpoints.Discovery) .RouteId(IdentityEndpoints.RouteIds.Discovery) .Process(new DiscoveryEndpointProcessor(handler)); // 7. JWKS (read-only, no WireTap) // When the PROPS signing-key store is enabled, the JWKS is served LIVE from the // store on every request so admin /signing-keys/rotate and /retire reflect // immediately — see LiveJwksProcessor. Otherwise we fall back to OpenIddict's // static JWKS handler that picks from the frozen options.SigningCredentials list. if (_options.UsePropsSigningKeyStore) { var signingKeyStore = _sp.GetRequiredService(); From(IdentityEndpoints.Jwks) .RouteId(IdentityEndpoints.RouteIds.Jwks) .Process(new LiveJwksProcessor(signingKeyStore)); } else { From(IdentityEndpoints.Jwks) .RouteId(IdentityEndpoints.RouteIds.Jwks) .Process(new JwksEndpointProcessor(handler)); } // 8. Device Authorization (RFC 8628). Device-code persist + state update both go // through OpenIddict stores (DI-scoped IRedbService) — atomicity is at the store // level. Route-level redb-tx wrap removed (see Token endpoint note). if (_options.Features.EnableDeviceCodeFlow) { From(IdentityEndpoints.Device) .RouteId(IdentityEndpoints.RouteIds.Device) .Process(new DeviceEndpointProcessor(handler)) .WireTap(IdentityEndpoints.Events, EventTapPool); // 9. End-User Verification (RFC 8628 §3.3). From(IdentityEndpoints.Verification) .RouteId(IdentityEndpoints.RouteIds.Verification) .Process(new VerificationEndpointProcessor(handler)) .WireTap(IdentityEndpoints.Events, EventTapPool); } // Pushed Authorization Requests (RFC 9126 / Z6). PAR persists a one-time request_uri // via OpenIddict's authorization store on its own DI-scoped IRedbService — same // pattern as Authorize. Throttled per-IP same as Token because PAR is a back-channel // POST that can be brute-forced. Route-level redb-tx wrap removed (see Token note). if (_options.Features.EnablePushedAuthorization) { var parRoute = From(IdentityEndpoints.PushedAuthorization) .RouteId(IdentityEndpoints.RouteIds.PushedAuthorization) .Process(trustedProxy); if (perIpThrottle is not null) parRoute = parRoute.Process(perIpThrottle); parRoute .Throttle( ExtractClientIdForThrottle, _options.TokenThrottleMaxPerPeriod, _options.TokenThrottlePeriod) .RejectOnOverflow() .Traced("identity.par-request") .Metered("identity.par-request", new PushedAuthorizationEndpointProcessor(handler)) .EndTraced() .WireTap(IdentityEndpoints.Events, EventTapPool); } // Dynamic Client Registration (RFC 7591). No Idempotency-Key cache: a registrant has no caller identity of its // own to key a replay by (the initial access token is one shared value, open registration has none); a // repeated registration registers again. NOTE on tx: DynamicRegistrationProcessor // ONLY calls _context.GetIdentityService() — the // application persist + secret-hash both flow through OpenIddict's DI-scoped // RedbApplicationStore (a different IRedbService, different SqliteRedbConnection) // than the per-exchange one any route-level WithRedbTx wraps. The wrap was therefore // a no-op atomicity-wise but held the SQLite single-writer lock during the // ~30-second OpenIddict pipeline, causing every concurrent writer to time out with // SQLITE_BUSY (the failure mode the diag run captured). Removed. if (_options.Features.EnableDynamicRegistration) { From(IdentityEndpoints.DynamicRegister) .RouteId(IdentityEndpoints.RouteIds.DynamicRegister) .Throttle( e => e.In.GetHeader("redbHttp.RemoteAddress") ?? "anonymous", _options.DynamicRegistrationThrottleMaxPerPeriod, _options.DynamicRegistrationThrottlePeriod) .RejectOnOverflow() .Process(new DynamicRegistrationProcessor( Context!, _sp.GetRequiredService>(), timeProvider: null, loggerFactory: _sp.GetService())) .WireTap(IdentityEndpoints.Events, EventTapPool); // Z2 (RFC 7592): Client configuration endpoint. Read/Update/Delete gated by the // registration_access_token issued at DCR time. ClientRegistrationManagementProcessor // does its primary read+write via OpenIddict's ApplicationManager (DI-scoped, // separate IRedbService → separate SqliteRedbConnection); the per-exchange IRedbService // at line 153 is used only for minor side-effects. A route-level WithRedbTx held the // SQLite writer lock on the per-exchange connection while OpenIddict's manager // opened a SECOND connection on the same DB file for the actual DELETE — self- // deadlock, 5s busy_timeout × ~7 retries = ~34s observed on RFC 7592 DELETE. Same // pattern as account/register. Atomicity at OpenIddict store level is preserved. From(IdentityEndpoints.DynamicRegisterManage) .RouteId(IdentityEndpoints.RouteIds.DynamicRegisterManage) .Process(new ClientRegistrationManagementProcessor(Context!, _redbName, _options)) .WireTap(IdentityEndpoints.Events, EventTapPool); } // 10. Login (credential verification → session cookie set by HTTP facade). // // Deliberately NOT route-transacted, and this one is a trap worth spelling out. Login always // runs Argon2id verify (~250 ms, up to seconds under load) BEFORE it writes anything. A // route-level WithRedbTx opens the transaction at the top of the route, so on SQLite (single // writer) it would hold the write lock across that whole CPU-bound verify, serialising every // concurrent login — a real, measured stall, not a theoretical one. // // And there is nothing to make atomic anyway: the sole transactional write is one // SessionService.CreateAsync (a single SaveAsync, atomic on its own). The password auto-rehash // is fire-and-forget on its own scope by design and must not be pulled into a login // transaction. So a wrap here would buy zero atomicity at the cost of a writer-lock over // Argon2id. If a future change makes login write multiple coupled rows, wrap THAT write inside // the processor (a segment transaction after the verify), never the whole route. var loginRoute = From(IdentityEndpoints.Login) .RouteId(IdentityEndpoints.RouteIds.Login) .Process(trustedProxy); if (perIpThrottle is not null) loginRoute = loginRoute.Process(perIpThrottle); // F3: identity.login span+meter — covers credential check + failure-recorder. The // LoginFailureRecorder is intentionally inside the same span so brute-force lockout // increments are visible in distributed traces. loginRoute = loginRoute .Traced("identity.login") .Metered("identity.login", new LoginProcessor(_sp)); if (loginFailureRecorder is not null) loginRoute = loginRoute.Process(loginFailureRecorder); loginRoute.EndTraced().WireTap(IdentityEndpoints.Events, EventTapPool); // 11. MFA TOTP verification (code → session with mfaVerified) // B3: dedup by (jti, code) — defends against retransmits / captured-request replay, // legitimate retry with a different code still passes through. // The B1 row-lock + FailedAttempts++ inside the processor remain the brute-force guard. var mfaIdempotentRepo = new RedbIdempotentRepository( _sp.GetRequiredService(), new RedbIdempotentOptions { ProcessorName = "identity-mfa-verify", Ttl = TimeSpan.FromMinutes(15) // matches MfaState TTL ceiling }); var mfaStateProtector = _sp.GetRequiredService(); // MfaVerify: NOT route-transacted, because the processor already opens its OWN segment // transaction exactly where it is needed — BeginTransactionAsync around // LockForUpdate(mfaObj) + verify + persist(FailedAttempts/Lockout). That is the correct // pattern (a transaction around the write, not around the whole route), and it is cheap here // because MFA verify is TOTP, not Argon2id. A route-level WithRedbTx would NEST an outer // transaction over that inner one — strictly worse than leaving the inner one to do its job. From(IdentityEndpoints.MfaVerify) .RouteId(IdentityEndpoints.RouteIds.MfaVerify) .Process(trustedProxy) .IdempotentConsumer(e => { var body = e.In.Body as IDictionary; var token = body?.TryGetValue("mfa_state", out var s) == true ? s?.ToString() : null; var code = body?.TryGetValue("code", out var c) == true ? c?.ToString() : null; if (string.IsNullOrEmpty(token) || string.IsNullOrEmpty(code)) return string.Empty; // bad request — let processor return invalid_request var st = mfaStateProtector.Unprotect(token); if (st is null || st.Jti == Guid.Empty) return string.Empty; // expired/invalid/legacy state — let processor handle return $"mfa-verify:{st.Jti:N}:{code}"; }, mfaIdempotentRepo, skipDuplicate: true) // F3: identity.mfa-verify — security-critical step, span enables forensic timeline // reconstruction; histogram detects slow TOTP-secret-protector decryption. .Traced("identity.mfa-verify") .Metered("identity.mfa-verify", new MfaVerifyProcessor(_sp)) .EndTraced() .WireTap(IdentityEndpoints.Events, EventTapPool); // 11b. MFA challenge dispatch (SMS/Email OTP send) From(IdentityEndpoints.MfaChallenge) .RouteId(IdentityEndpoints.RouteIds.MfaChallenge) .Process(trustedProxy) .Process(new MfaChallengeProcessor(_sp)) .WireTap(IdentityEndpoints.Events, EventTapPool); // 11c. B9 / BUG-9 — Auth0-style gated method enumeration. From(IdentityEndpoints.MfaListMethods) .RouteId(IdentityEndpoints.RouteIds.MfaListMethods) .Process(trustedProxy) .Process(new MfaListMethodsProcessor(_sp)); // 11d. Phase 9d — cross-context broker queries served to other Tsak contexts // (currently only the redb.Identity.Http facade in 'identity.http'). // All three are read-only, in-memory after warm-up, and bypass throttle/audit // because the caller is a trusted in-process facade, not external traffic. From(IdentityEndpoints.CorsCheck) .RouteId(IdentityEndpoints.RouteIds.CorsCheck) .Process(new CorsCheckProcessor(_sp)); From(IdentityEndpoints.ValidatePostLogoutRedirect) .RouteId(IdentityEndpoints.RouteIds.ValidatePostLogoutRedirect) .Process(new ValidatePostLogoutRedirectProcessor(_sp)); From(IdentityEndpoints.MfaMethodsFromState) .RouteId(IdentityEndpoints.RouteIds.MfaMethodsFromState) .Process(new MfaMethodsFromStateProcessor(_sp)); // 12. MFA recovery code verification — marks recovery code consumed. // Same as MfaVerify: NOT route-transacted because the processor opens its own segment // transaction around LockForUpdate(mfaObj) + match + mark-consumed, which is exactly where // the atomicity is needed (so two concurrent uses of one code cannot both succeed). No // Argon2id in the window; a route-level wrap would only nest over that inner transaction. From(IdentityEndpoints.MfaRecovery) .RouteId(IdentityEndpoints.RouteIds.MfaRecovery) .Process(trustedProxy) .Process(new MfaRecoveryProcessor(_sp)) .WireTap(IdentityEndpoints.Events, EventTapPool); // 13. MFA management (setup, confirm, disable, status) // B8: RequireSelfOrAdminProcessor enforces self-vs-admin so a token with the // self-service scope (identity:account) cannot mutate another user's MFA. An exchange // without a management context is refused twice over: by RequireManagementContext at the // route entrance and by this processor itself — direct-vm is a transport, not a trust level. // E2: Idempotency-Key cache placed AFTER mfaSelfOrAdmin so authorization is always // re-checked on replays (a revoked token must not unlock cached responses). // The granular MFA scopes admit as admin, as the scope table promises: identity:mfa:write for every // operation, identity:mfa:read for status. var mfaSelfOrAdmin = new RequireSelfOrAdminProcessor( _options.ManagementScope, _options.AccountScope, securityLogger, new RequireSelfOrAdminProcessor.SurfaceScopes( redb.Identity.Contracts.Configuration.IdentityScopes.MfaWrite, redb.Identity.Contracts.Configuration.IdentityScopes.MfaRead, new HashSet(StringComparer.Ordinal) { "status" })); // MfaManage (setup / confirm / disable): NOT route-transacted. Each operation is a single // MFA-object mutation through MfaSetupProcessor — one write, atomic on its own — so there is // no multi-row write for a route transaction to guard. The idempotency pre/post below are // independent of any DB transaction (they cache the response), so they stay. var mfaManageRoute = From(IdentityEndpoints.MfaManage) .RouteId(IdentityEndpoints.RouteIds.MfaManage) .Process(RequireManagementContext) .Process(mfaSelfOrAdmin); var mfaManagePre = BuildIdempotencyPre("mfa-manage"); if (mfaManagePre is not null) mfaManageRoute = mfaManageRoute.Process(mfaManagePre); mfaManageRoute = mfaManageRoute.Process(new MfaSetupProcessor(_sp)); var mfaManagePost = BuildIdempotencyPost(); if (mfaManagePost is not null) mfaManageRoute = mfaManageRoute.Process(mfaManagePost); mfaManageRoute.WireTap(IdentityEndpoints.Events, EventTapPool); // ── Management endpoints (all with WireTap) ── // 8. Manage Apps — E2: Idempotency-Key cache, no redb-tx wrap (wrapInRedbTx:false). // ApplicationManagementProcessor does its work through OpenIddict's ApplicationManager, and // each Create/Update/Delete is a single atomic manager operation — there is no multi-row // write here for a route transaction to make atomic. The idempotency cache below is // independent of any DB transaction, so it stays. (Historically a route wrap here also // deadlocked the manager's own connection against the route lock — the connection-binding // fix that restored WithRedbTx on Token would remove that hazard, but there is still no // atomicity to gain, so the wrap stays off on purpose.) WithIdempotentTx( From(IdentityEndpoints.ManageApps).RouteId(IdentityEndpoints.RouteIds.ManageApps), "manage-apps", new ApplicationManagementProcessor(Context!, _redbName, _options), wrapInRedbTx: false) .WireTap(IdentityEndpoints.Events, EventTapPool); // 9. Manage Scopes — E1: tx-wrapped. E2: Idempotency-Key cache. WithIdempotentTx( From(IdentityEndpoints.ManageScopes).RouteId(IdentityEndpoints.RouteIds.ManageScopes), "manage-scopes", new ScopeManagementProcessor(Context!, _redbName)) .WireTap(IdentityEndpoints.Events, EventTapPool); // 10. Manage Users — E1: tx-wrapped (multi-row writes for users + props). E2: Idempotency-Key cache. WithIdempotentTx( From(IdentityEndpoints.ManageUsers).RouteId(IdentityEndpoints.RouteIds.ManageUsers), "manage-users", new UserManagementProcessor(Context!, _redbName)) .WireTap(IdentityEndpoints.Events, EventTapPool); // 11. Manage Tokens — E1: tx-wrapped (revoke/cleanup batches). E2: Idempotency-Key cache. var backgroundDeletion = _sp.GetService(); var cleanupProcessor = new TokenCleanupProcessor(Context!, _sp.GetRequiredService>(), _redbName, backgroundDeletion); WithIdempotentTx( From(IdentityEndpoints.ManageTokens).RouteId(IdentityEndpoints.RouteIds.ManageTokens), "manage-tokens", new TokenManagementProcessor(Context!, _redbName, cleanupProcessor)) .WireTap(IdentityEndpoints.Events, EventTapPool); // 12. Manage Groups — E1: tx-wrapped. E2: Idempotency-Key cache. WithIdempotentTx( From(IdentityEndpoints.ManageGroups).RouteId(IdentityEndpoints.RouteIds.ManageGroups), "manage-groups", new GroupManagementProcessor(Context!, _redbName, backgroundDeletion)) .WireTap(IdentityEndpoints.Events, EventTapPool); // 13. Manage Consents — E1: tx-wrapped. E2: Idempotency-Key cache. WithIdempotentTx( From(IdentityEndpoints.ManageConsents).RouteId(IdentityEndpoints.RouteIds.ManageConsents), "manage-consents", new ConsentManagementProcessor(Context!, _redbName)) .WireTap(IdentityEndpoints.Events, EventTapPool); // 13b. H9 — Audit query (read-only, no tx/idempotency/WireTap). From(IdentityEndpoints.ManageAudit) .RouteId(IdentityEndpoints.RouteIds.ManageAudit) .Process(RequireManagementContext) .Process(new AuditQueryProcessor(Context!, _redbName)); // 13b-iv. Signing-key lifecycle (list / rotate / retire). Mounted unconditionally // so the admin surface is the same regardless of whether the PROPS store is enabled // — when disabled, the processor just returns an empty list / "no active store" // error. WireTap fires SigningKeyRotated / SigningKeyRetired audit events. { var signingKeyStore = _sp.GetService(); if (signingKeyStore is not null) { From(IdentityEndpoints.ManageSigningKeys) .RouteId(IdentityEndpoints.RouteIds.ManageSigningKeys) .Process(RequireManagementContext) .Process(new SigningKeysManagementProcessor(signingKeyStore)) .WireTap(IdentityEndpoints.Events, EventTapPool); } } // 13b-i. N7-3 — Admin impersonation overlay (start/stop). Does not mint tokens; // emits audit events only. No tx / no idempotency cache (purely an audit beacon). From(IdentityEndpoints.ManageImpersonation) .RouteId(IdentityEndpoints.RouteIds.ManageImpersonation) .Process(RequireManagementContext) .Process(new ImpersonationManagementProcessor(Context!, _redbName)) .WireTap(IdentityEndpoints.Events, EventTapPool); // 13c. H5 — Manage Claim Mappers (declarative claims). E1: tx, E2: Idempotency-Key cache. WithIdempotentTx( From(IdentityEndpoints.ManageClaimMappers).RouteId(IdentityEndpoints.RouteIds.ManageClaimMappers), "manage-claim-mappers", new ClaimMapperManagementProcessor(Context!, _redbName)) .WireTap(IdentityEndpoints.Events, EventTapPool); // 13d. H5 — Manage Claim Scopes (reusable mapper bundles + Application↔Scope assignments). WithIdempotentTx( From(IdentityEndpoints.ManageClaimScopes).RouteId(IdentityEndpoints.RouteIds.ManageClaimScopes), "manage-claim-scopes", new ClaimScopeManagementProcessor(Context!, _redbName)) .WireTap(IdentityEndpoints.Events, EventTapPool); // 13e. S2 — Manage Claim Definitions (schema with required + type + regex). WithIdempotentTx( From(IdentityEndpoints.ManageClaimDefinitions).RouteId(IdentityEndpoints.RouteIds.ManageClaimDefinitions), "manage-claim-definitions", new ClaimDefinitionsManagementProcessor(Context!, _redbName, _sp.GetRequiredService().CreateLogger())) .WireTap(IdentityEndpoints.Events, EventTapPool); // 13f. B.3 — Manage Roles (registry + assignments). WithIdempotentTx( From(IdentityEndpoints.ManageRoles).RouteId(IdentityEndpoints.RouteIds.ManageRoles), "manage-roles", new RoleManagementProcessor(Context!, _redbName, _sp.GetRequiredService().CreateLogger())) .WireTap(IdentityEndpoints.Events, EventTapPool); // 13g. W1 — Manage Webhook subscriptions (admin CRUD). WithIdempotentTx( From(IdentityEndpoints.ManageWebhooks).RouteId(IdentityEndpoints.RouteIds.ManageWebhooks), "manage-webhooks", new WebhookManagementProcessor(Context!, _redbName, _sp.GetRequiredService().CreateLogger(), webhookCache)) .WireTap(IdentityEndpoints.Events, EventTapPool); // 14. Logout — E1: tx-wrapped (revokes session + tokens). var logoutLogger = _sp.GetRequiredService().CreateLogger(); var oidcServerOptions = _sp.GetRequiredService>(); var logoutConfirmation = _sp.GetRequiredService(); WithRedbTx(From(IdentityEndpoints.Logout) .RouteId(IdentityEndpoints.RouteIds.Logout)) .Process(new LogoutProcessor(Context!, oidcServerOptions, logoutConfirmation, _redbName, logoutLogger)) .WireTap(IdentityEndpoints.Events, EventTapPool); // 14b. Consent grant (user-facing approval from consent page) — E1: tx-wrapped. WithRedbTx(From(IdentityEndpoints.ConsentGrant) .RouteId(IdentityEndpoints.RouteIds.ConsentGrant)) .Process(new ConsentGrantProcessor(Context!, _redbName)) .WireTap(IdentityEndpoints.Events, EventTapPool); // 15. Manage Sessions — E1: tx-wrapped. E2: Idempotency-Key cache. WithIdempotentTx( From(IdentityEndpoints.ManageSessions).RouteId(IdentityEndpoints.RouteIds.ManageSessions), "manage-sessions", new SessionManagementProcessor(Context!, _redbName)) .WireTap(IdentityEndpoints.Events, EventTapPool); // 15a. W6-0: Backchannel revoked-sids list — `add` and `since` operations. // E1: tx-wrapped. E2: Idempotency-Key cache (RPs may retry add on transient errors). WithIdempotentTx( From(IdentityEndpoints.RevokedSids).RouteId(IdentityEndpoints.RouteIds.RevokedSids), "revoked-sids", new RevokedSidsManagementProcessor( Context!, _sp.GetRequiredService>(), _redbName, timeProvider)) .WireTap(IdentityEndpoints.Events, EventTapPool); // 15b. /me/sessions — H3-SSO (v1.0 DoD §6 scoped-subset). Self-service list/revoke // of the caller's own sessions. User id is derived from the authenticated token // subject; request body is NOT trusted for user targeting. Supports both // `identity:manage` and `identity:account` scopes — admins calling the /me endpoint // get their own sessions, identical to non-admin callers. Cross-user administration // remains on the admin route above. WithRedbTx( From(IdentityEndpoints.MeSessions).RouteId(IdentityEndpoints.RouteIds.MeSessions)) .Process(RequireManagementContext) .Process(new MeSessionsProcessor(Context!, _redbName)) .WireTap(IdentityEndpoints.Events, EventTapPool); // 15c. /me/profile + /me/password + /me/mfa + /me/consents — H3 (v1.0 DoD §6). // Self-service "complete SSO account console" surface. Each processor derives // the user id from the authenticated token subject (NEVER from the request // body) so that admin callers using their own access token can only manage // their own profile through these routes. Cross-user administration stays on // the corresponding admin endpoints (/users, /mfa, /users/{id}/consents). // MeProfile / MePassword / Password* / EmailVerify* / ChangeEmail* : // these processors take BOTH per-exchange IRedbService AND _sp (DI scope) for stores // like IPasswordHistoryStore / IEmailVerificationTokenStore / IChangeEmailTokenStore / // ISigningKeyStore that internally call _scopeFactory.CreateAsyncScope() and resolve // their own IRedbService — a SECOND SqliteRedbConnection on the same DB file. A route- // level WithRedbTx held the writer lock on conn A while the store opened conn B for // its INSERT/UPDATE, causing 5 s busy_timeout × ~7 retries = ~34s on every invocation // (confirmed for AccountRegister via [Diag-AR] anchor: 34,204 ms in historyStore.RecordAsync // alone). Per-exchange atomicity for the processor's own writes is preserved // (each redb.SaveAsync still uses one short tx) — only the cross-store atomicity goes, // which was never enforceable anyway because the store ran on a separate connection. From(IdentityEndpoints.MeProfile).RouteId(IdentityEndpoints.RouteIds.MeProfile) .Process(RequireManagementContext) .Process(new MeProfileProcessor(Context!, _redbName)) .WireTap(IdentityEndpoints.Events, EventTapPool); From(IdentityEndpoints.MePassword).RouteId(IdentityEndpoints.RouteIds.MePassword) .Process(RequireManagementContext) .Process(new MePasswordProcessor(Context!, _redbName)) .WireTap(IdentityEndpoints.Events, EventTapPool); // N-4 (Session C): anonymous password-recovery endpoints. Anti-enumeration is // enforced inside the processor (always 200/success). trustedProxy + perIpThrottle // are layered upstream so brute-force enumeration of the email field is rate-limited // per real client IP (X-Forwarded-For respected only behind trusted proxies). var passwordForgotRoute = From(IdentityEndpoints.PasswordForgot) .RouteId(IdentityEndpoints.RouteIds.PasswordForgot) .Process(trustedProxy); if (perIpThrottle is not null) passwordForgotRoute = passwordForgotRoute.Process(perIpThrottle); passwordForgotRoute .Process(new PasswordForgotProcessor(Context!, _sp, _redbName)) .WireTap(IdentityEndpoints.Events, EventTapPool); var passwordResetRoute = From(IdentityEndpoints.PasswordReset) .RouteId(IdentityEndpoints.RouteIds.PasswordReset) .Process(trustedProxy); if (perIpThrottle is not null) passwordResetRoute = passwordResetRoute.Process(perIpThrottle); passwordResetRoute .Process(new PasswordResetProcessor(Context!, _sp, _redbName)) .WireTap(IdentityEndpoints.Events, EventTapPool); // N-4 (Session C, N4-6): e-mail-verification routes. Feature-gated by // RedbIdentityOptions.EmailVerification.Enabled (default OFF) so existing // deployments without an IEmailNotificationChannel keep the same route count. // /me/verify-email/send is authenticated (Me* convention); /account/verify-email/confirm // is anonymous and rate-limited identically to password-recovery. if (_options.EmailVerification.Enabled) { From(IdentityEndpoints.MeEmailVerifySend).RouteId(IdentityEndpoints.RouteIds.MeEmailVerifySend) .Process(RequireManagementContext) .Process(new EmailVerifySendProcessor(Context!, _sp, _redbName)) .WireTap(IdentityEndpoints.Events, EventTapPool); var emailVerifyConfirmRoute = From(IdentityEndpoints.EmailVerifyConfirm) .RouteId(IdentityEndpoints.RouteIds.EmailVerifyConfirm) .Process(trustedProxy); if (perIpThrottle is not null) emailVerifyConfirmRoute = emailVerifyConfirmRoute.Process(perIpThrottle); emailVerifyConfirmRoute .Process(new EmailVerifyConfirmProcessor(Context!, _sp, _redbName)) .WireTap(IdentityEndpoints.Events, EventTapPool); } // N-4 (Session E, N4-7): strict verify-then-commit change-of-e-mail routes. // Feature-gated by RedbIdentityOptions.ChangeEmail.Enabled (default OFF). // /me/change-email/request is authenticated (Me* convention); /change-email/confirm // is anonymous and rate-limited identically to password-recovery / verify-email. if (_options.ChangeEmail.Enabled) { From(IdentityEndpoints.MeChangeEmailRequest).RouteId(IdentityEndpoints.RouteIds.MeChangeEmailRequest) .Process(RequireManagementContext) .Process(new ChangeEmailRequestProcessor(Context!, _sp, _redbName)) .WireTap(IdentityEndpoints.Events, EventTapPool); var changeEmailConfirmRoute = From(IdentityEndpoints.ChangeEmailConfirm) .RouteId(IdentityEndpoints.RouteIds.ChangeEmailConfirm) .Process(trustedProxy); if (perIpThrottle is not null) changeEmailConfirmRoute = changeEmailConfirmRoute.Process(perIpThrottle); changeEmailConfirmRoute .Process(new ChangeEmailConfirmProcessor(Context!, _sp, _redbName)) .WireTap(IdentityEndpoints.Events, EventTapPool); } // N-3 (sub-step N3-7): anonymous self-service account registration. Feature-gated // by RedbIdentityOptions.Registration.Enabled (default OFF) so corporate / SCIM- // provisioned deployments do not silently expose a public sign-up surface. When // enabled the route shares the same trustedProxy + perIpThrottle envelope as the // password-recovery routes so brute-force enumeration of the e-mail field via // duplicate-account probes is rate-limited per real client IP. // AccountRegister write-path uses two distinct IRedbService instances: // (1) the per-exchange one for CreateUserAsync + SaveAsync(propsObj), AND // (2) PropsPasswordHistoryStore's own CreateAsyncScope() resolution for the // password-history record + cleanup query. // A route-level WithRedbTx wraps only (1) on its per-exchange connection but holds // the SQLite writer lock for the whole route — (2) opens a SECOND SqliteConnection // on the same DB file and self-deadlocks against (1), eating ~30s of busy_timeout // retries before the swallow-catch in AccountRegisterProcessor finally lets the // route return 200. Confirmed via [Diag-AR] timing anchors: 34,204ms spent in // historyStore.RecordAsync alone, every other step <10ms. Atomicity loss is // benign here: CreateUserAsync is atomic in itself; SaveAsync(propsObj) failing // afterwards leaves the user with a valid _users row but no OIDC props (login // still works); password history is best-effort by contract (swallowed catch). if (_options.Registration.Enabled) { var accountRegisterRoute = From(IdentityEndpoints.AccountRegister) .RouteId(IdentityEndpoints.RouteIds.AccountRegister) .Process(trustedProxy); if (perIpThrottle is not null) accountRegisterRoute = accountRegisterRoute.Process(perIpThrottle); accountRegisterRoute .Process(new AccountRegisterProcessor(Context!, _sp, _redbName)) .WireTap(IdentityEndpoints.Events, EventTapPool); } // MeMfa / MeWebAuthn / MfaWebAuthn — all three processors resolve IRedbService // through _sp (DI scope), so a route-level redb-tx wrap on the per-exchange // connection covered nothing. Removed (see Token note). From(IdentityEndpoints.MeMfa).RouteId(IdentityEndpoints.RouteIds.MeMfa) .Process(RequireManagementContext) .Process(new MeMfaProcessor(_sp)) .WireTap(IdentityEndpoints.Events, EventTapPool); // MFA-3: WebAuthn routes are gated on the master switch. When disabled the controller // surface still binds (returns 404 if no route) but no in-process route exists. if (_options.WebAuthn.Enabled) { From(IdentityEndpoints.MeWebAuthn).RouteId(IdentityEndpoints.RouteIds.MeWebAuthn) .Process(RequireManagementContext) .Process(new MeWebAuthnProcessor(_sp)) .WireTap(IdentityEndpoints.Events, EventTapPool); From(IdentityEndpoints.MfaWebAuthn).RouteId(IdentityEndpoints.RouteIds.MfaWebAuthn) .Process(new WebAuthnAssertProcessor(_sp)) .WireTap(IdentityEndpoints.Events, EventTapPool); } WithRedbTx( From(IdentityEndpoints.MeConsents).RouteId(IdentityEndpoints.RouteIds.MeConsents)) .Process(RequireManagementContext) .Process(new MeConsentsProcessor(Context!, _redbName)) .WireTap(IdentityEndpoints.Events, EventTapPool); // H8 (DoD §4 gap (b)/(d)): self-service federated identity link/unlink/list. WithRedbTx( From(IdentityEndpoints.MeFederatedIdentities).RouteId(IdentityEndpoints.RouteIds.MeFederatedIdentities)) .Process(RequireManagementContext) .Process(new MeFederatedIdentitiesProcessor(Context!, _sp, _redbName)) .WireTap(IdentityEndpoints.Events, EventTapPool); // H8 (DoD §4 gap (e)): admin CRUD over PROPS-stored federation providers. // E1 tx + E2 Idempotency-Key cache, mirroring the ClaimMapperManagement wiring above. WithIdempotentTx( From(IdentityEndpoints.ManageFederationProviders).RouteId(IdentityEndpoints.RouteIds.ManageFederationProviders), "manage-federation-providers", new FederationProviderManagementProcessor(Context!, _redbName)) .WireTap(IdentityEndpoints.Events, EventTapPool); // ── SCIM 2.0 endpoints (RFC 7644) ── if (_options.Features.EnableScim) { // E1: SCIM provisioning is RFC 7644 mutation API — tx-wrapped end-to-end. // E2: Idempotency-Key cache for safe retries. WithIdempotentTx( From(IdentityEndpoints.ScimUsers).RouteId(IdentityEndpoints.RouteIds.ScimUsers), "scim-users", new ScimUserProcessor(Context!, _redbName)) .WireTap(IdentityEndpoints.Events, EventTapPool); WithIdempotentTx( From(IdentityEndpoints.ScimGroups).RouteId(IdentityEndpoints.RouteIds.ScimGroups), "scim-groups", new ScimGroupProcessor(Context!, _redbName, backgroundDeletion: backgroundDeletion)) .WireTap(IdentityEndpoints.Events, EventTapPool); // H1 (RFC 7644 §3.7): SCIM Bulk endpoint. Each inner op is dispatched to its // own SCIM route (which is itself WithIdempotentTx), so partial-success // semantics fall out for free — the bulk processor never runs inside a single // outer transaction. if (_options.Features.EnableScimBulk) { From(IdentityEndpoints.ScimBulk).RouteId(IdentityEndpoints.RouteIds.ScimBulk) .Process(RequireManagementContext) .Process(new ScimBulkProcessor(Context!, _options.ScimBulkMaxOperations, _options.ScimBulkMaxPayloadSize)) .WireTap(IdentityEndpoints.Events, EventTapPool); } } // ── Federation endpoints (OIDC external IdP) ── if (_options.Features.EnableFederation && _options.FederationProviders.Count > 0) { From(IdentityEndpoints.FederationChallenge) .RouteId(IdentityEndpoints.RouteIds.FederationChallenge) .Process(new FederationChallengeProcessor(_sp)) .WireTap(IdentityEndpoints.Events, EventTapPool); // Federation callback creates/updates federated user + identity link. // FederationCallbackProcessor takes ONLY IServiceProvider (no IRouteContext); // it does ALL its DB work via `_sp.CreateScope().GetService()` — // a SECOND SqliteRedbConnection on the same DB file. A route-level WithRedbTx // wrapped the per-exchange connection while the processor's scope opened conn B // for user provisioning + session creation, self-deadlocking at ~15s (HTTP // client gives up first) — observed in demo_federation_{e2e,github}.ps1 as // "callback returned 0" (connection abort, no provisioning happened). Same // pure-group-A pattern as Token/Login/etc. From(IdentityEndpoints.FederationCallback) .RouteId(IdentityEndpoints.RouteIds.FederationCallback) .Process(new FederationCallbackProcessor(_sp)) .WireTap(IdentityEndpoints.Events, EventTapPool); } // ── Cross-context auth processors (consumed by the HTTP facade module) ── // // The HTTP facade lives in a separate Tsak context (.tpkg) with its own ALC // and cannot construct ManagementBearerAuthProcessor itself (the type is // internal to Core and depends on scoped OpenIddict validation services). // Exposing the auth step as direct-vm consumers lets the facade call them // inline via .To(...) — synchronous, zero-copy, same exchange — and removes // the need for any cross-module static state. if (_managementAuth is not null) From(IdentityEndpoints.AuthManagement) .RouteId(IdentityEndpoints.RouteIds.AuthManagement) .Process(_managementAuth); if (_scimAuth is not null) From(IdentityEndpoints.AuthScim) .RouteId(IdentityEndpoints.RouteIds.AuthScim) .Process(_scimAuth); // F5 — granular scope check, transport-neutral. Always registered: unlike the auth processors // above it needs nothing injected, and a facade calling an address that is not there would fail // open at the route layer, which is the one direction an authorization gate must never fail. From(IdentityEndpoints.AuthzCheck) .RouteId(IdentityEndpoints.RouteIds.AuthzCheck) .Process(new AuthorizationCheckProcessor()); // ── B1: emergency-admin bootstrap ── // Always registered (even when disabled) so the HTTP facade does not 404 at the // route-dispatch layer; the processor itself short-circuits with a 404-shaped body // when BootstrapOptions.Enabled=false. Wrapped in WithRedbTx so any failure between // scope/group/user/membership/client/flag rolls back atomically — the spec's primary // acceptance criterion. WireTap to events for audit (ClientRegistered + bootstrap // marker in event-data). var bootstrapOpts = _sp.GetRequiredService>(); var bootstrapLoggerFactory = _sp.GetService(); WithRedbTx(From(IdentityEndpoints.BootstrapAdmin) .RouteId(IdentityEndpoints.RouteIds.BootstrapAdmin)) .Process(new BootstrapAdminProcessor(Context!, bootstrapOpts, timeProvider, bootstrapLoggerFactory)) .WireTap(IdentityEndpoints.Events, EventTapPool); // ── Event dispatch + Audit ── // 16. Events consumer (receives WireTap copies → audit targets) var evtLogger = _sp.GetRequiredService() .CreateLogger(); var eventsRoute = From(IdentityEndpoints.Events) .RouteId(IdentityEndpoints.RouteIds.Events) .Process(new EventDispatchProcessor(evtLogger, _auditOptions, timeProvider)); // R1: built-in relational sink — always-on when audit is enabled and PersistToProps=true // (option name retained for backwards compat; actual storage is now the flat // `identity_audit_log` table created at boot by IdentityAuditLogTableInitListener, // not REDB props). Authoritative local trail for `GET /api/v1/identity/audit`; // external multicast targets run afterwards and are independent. if (_auditOptions is { Enabled: true, PersistToProps: true }) { var sinkLogger = _sp.GetRequiredService() .CreateLogger(); eventsRoute = eventsRoute.Process(new AuditRelationalSinkProcessor(Context!, sinkLogger, _redbName)); } // W1: outbound webhook delivery — runs after the audit sink so the // local trail is durable BEFORE we fan out to subscribers. Delivery // goes through redb.Route's IProducerTemplate so the subscription URL // is opaque (https://, kafka://, amqp://, …) — Core stays // transport-agnostic; the producer the URI resolves to picks the wire. // // ProducerTemplate is constructed LAZILY by the processor on first // event (using IRouteContext captured at processor-construction time). // Eager construction here would null-deref ProducerTemplate.ctor for // tests that pass a null context to Configure — those are pure // route-shape probes that never actually deliver. // Webhooks: the event is put into the outbox (identity_delivery_outbox), one row per matching // subscription, after the audit row; the delivery worker below sends it. Nothing is sent from // here, so a slow subscriber never holds this route. eventsRoute = eventsRoute.Process(new WebhookEnqueueProcessor( Context!, _redbName, webhookCache, _sp.GetRequiredService().CreateLogger())); // External audit targets (Identity:Audit:Targets): one outbox row per enabled target, sent by the // same worker with retries, so a target that is down neither holds this route nor loses the event. var enabledTargets = AuditTargetEnqueueProcessor.EnabledTargets(_auditOptions); if (enabledTargets.Count > 0) { eventsRoute = eventsRoute.Process(new AuditTargetEnqueueProcessor( Context!, _redbName, enabledTargets, _sp.GetRequiredService().CreateLogger())); } // The delivery worker: leader-only under a Tsak cluster (.Cluster(true)); every row is also // leased by the database, so several nodes without a cluster policy never send one row twice. var delivery = _options.Delivery; if (delivery.PollInterval > TimeSpan.Zero && delivery.PollInterval != Timeout.InfiniteTimeSpan) { From(TimerDsl.Every("webhook-delivery") .Period((int)Math.Max(1, delivery.PollInterval.TotalMilliseconds)) .Delay((int)Math.Max(1, delivery.PollInterval.TotalMilliseconds))) .RouteId(IdentityEndpoints.RouteIds.WebhookDelivery) .Cluster(true) .Process(new WebhookDeliveryWorker(_sp, Context!, delivery, timeProvider, _sp.GetRequiredService().CreateLogger(), auditTargets: enabledTargets)); } // Finished outbox rows past their retention go in batches; pending rows never do. Leader-only. if (delivery.CleanupInterval > TimeSpan.Zero && delivery.CleanupInterval != Timeout.InfiniteTimeSpan) { From(TimerDsl.Every("delivery-cleanup") .Period((int)Math.Min(int.MaxValue, delivery.CleanupInterval.TotalMilliseconds)) .Delay(60_000)) .RouteId(IdentityEndpoints.RouteIds.DeliveryCleanup) .Cluster(true) .Process(new OutboxCleanupProcessor(_sp, delivery, _sp.GetRequiredService().CreateLogger())); } // The backlog gauges read the outbox on every node, whichever runs the worker. if (_sp.GetService() is { } backlog) _sp.GetService()?.ObserveDeliveryBacklog(backlog); // ── Token cleanup timer ── // 17. Periodic cleanup of expired tokens and orphaned authorizations var cleanupInterval = _options.TokenCleanupInterval; if (cleanupInterval > TimeSpan.Zero && cleanupInterval != Timeout.InfiniteTimeSpan) { From(TimerDsl.Every("token-cleanup") .Period((int)cleanupInterval.TotalMilliseconds) .Delay(30_000)) .RouteId("identity-token-cleanup") .Cluster(true) // A5: leader-only when Tsak.Cluster.Enabled=true; silently ignored in standalone .Process(cleanupProcessor) .WireTap(IdentityEndpoints.Events, EventTapPool); } // ── Session cleanup timer ── // 18. Periodic cleanup of revoked sessions older than retention var sessionCleanupInterval = _options.SessionCleanupInterval; if (sessionCleanupInterval > TimeSpan.Zero && sessionCleanupInterval != Timeout.InfiniteTimeSpan) { var sessionCleanupProcessor = new SessionCleanupProcessor( Context!, _sp.GetRequiredService>(), _redbName, backgroundDeletion); From(TimerDsl.Every("session-cleanup") .Period((int)sessionCleanupInterval.TotalMilliseconds) .Delay(60_000)) .RouteId("identity-session-cleanup") .Cluster(true) // A5: leader-only when Tsak.Cluster.Enabled=true; silently ignored in standalone .Process(sessionCleanupProcessor) .WireTap(IdentityEndpoints.Events, EventTapPool); } // ── Revoked-SIDs cleanup timer (W6-0) ── // 18a. Periodic cleanup of expired entries in the backchannel revoked-sids list. // Runs leader-only on the timer; soft-deletes via IBackgroundDeletionService when // available (cluster-safe claim pattern), otherwise direct hard-delete. var revokedSidsCleanupInterval = _options.RevokedSidsCleanupInterval; if (revokedSidsCleanupInterval > TimeSpan.Zero && revokedSidsCleanupInterval != Timeout.InfiniteTimeSpan) { var revokedSidsCleanupProcessor = new RevokedSidsCleanupProcessor( Context!, _sp.GetRequiredService>(), _redbName, backgroundDeletion, timeProvider); From(TimerDsl.Every("revoked-sids-cleanup") .Period((int)revokedSidsCleanupInterval.TotalMilliseconds) .Delay(75_000)) .RouteId(IdentityEndpoints.RouteIds.RevokedSidsCleanup) .Cluster(true) // A5: leader-only when Tsak.Cluster.Enabled=true; silently ignored in standalone .Process(revokedSidsCleanupProcessor) .WireTap(IdentityEndpoints.Events, EventTapPool); } // ── Idempotency record cleanup timer ── // 18d. Periodic deletion of idempotency records past their time to live. The cache ignores them already; // without this timer they would stay in the database for good. var idempotencyCleanupInterval = _options.IdempotencyCleanupInterval; if (_options.Idempotency.Enabled && idempotencyCleanupInterval > TimeSpan.Zero && idempotencyCleanupInterval != Timeout.InfiniteTimeSpan) { var idempotencyCleanupProcessor = new IdempotencyRecordCleanupProcessor( Context!, _sp.GetRequiredService>(), _redbName, backgroundDeletion, timeProvider); From(TimerDsl.Every("idempotency-cleanup") .Period((int)idempotencyCleanupInterval.TotalMilliseconds) .Delay(105_000)) .RouteId("identity-idempotency-cleanup") .Cluster(true) // A5: leader-only when Tsak.Cluster.Enabled=true; silently ignored in standalone .Process(idempotencyCleanupProcessor) .WireTap(IdentityEndpoints.Events, EventTapPool); } // ── MFA OTP cleanup timer (B3) ── // 18b. Periodic cleanup of expired MfaOtpProps rows (SMS/Email OTP server-side store). // Verify already rejects expired rows at read time; this timer is purely storage hygiene. var mfaOtpCleanupInterval = _options.MfaOtpCleanupInterval; if (mfaOtpCleanupInterval > TimeSpan.Zero && mfaOtpCleanupInterval != Timeout.InfiniteTimeSpan) { var mfaOtpCleanupProcessor = new MfaOtpCleanupProcessor( Context!, _redbName, backgroundDeletion); From(TimerDsl.Every("mfa-otp-cleanup") .Period((int)mfaOtpCleanupInterval.TotalMilliseconds) .Delay(90_000)) .RouteId("identity-mfa-otp-cleanup") .Cluster(true) // A5: leader-only when Tsak.Cluster.Enabled=true; silently ignored in standalone .Process(mfaOtpCleanupProcessor) .WireTap(IdentityEndpoints.Events, EventTapPool); } // ── Pepper rotation report ── // 18b'. While previous peppers are configured, the leader logs once after start and then daily how many users // still hold recovery codes under each of them, so the operator knows when a value can be removed. // The provider is resolved when the timer first fires, as the MFA and link stores do on first use, so a host // that never touches the pepper does not have to configure one. if (_options.RecoveryCodePreviousPeppers is { Length: > 0 }) { var pepperReportProcessor = new PepperUsageReportProcessor( Context!, _redbName, () => _sp.GetRequiredService(), _sp.GetRequiredService().CreateLogger()); From(TimerDsl.Every("pepper-usage-report") .Period((int)TimeSpan.FromDays(1).TotalMilliseconds) .Delay(60_000)) .RouteId("identity-pepper-usage-report") .Cluster(true) // leader-only when Tsak.Cluster.Enabled=true; silently ignored in standalone .Process(pepperReportProcessor); } // ── MFA-3: WebAuthn consumed-challenge cleanup timer ── // 18c. Periodic cleanup of WebAuthnConsumedChallengeProps rows past their TTL. // Replay protection is enforced at consume time by the unique index on ChallengeHash; // this timer is purely storage hygiene. Gated on the master WebAuthn switch. if (_options.WebAuthn.Enabled) { var webAuthnCleanupInterval = _options.WebAuthn.ChallengeCleanupInterval; if (webAuthnCleanupInterval > TimeSpan.Zero && webAuthnCleanupInterval != Timeout.InfiniteTimeSpan) { var webAuthnCleanupProcessor = new WebAuthnConsumedChallengeCleanupProcessor( Context!, _redbName, backgroundDeletion); From(TimerDsl.Every("webauthn-challenge-cleanup") .Period((int)webAuthnCleanupInterval.TotalMilliseconds) .Delay(120_000)) .RouteId("identity-mfa-webauthn-challenge-cleanup") .Cluster(true) .Process(webAuthnCleanupProcessor) .WireTap(IdentityEndpoints.Events, EventTapPool); } } // ── DataProtection XML key-ring refresh timer ── // 19. A1: per-replica reload of RedbXmlRepository snapshot from PROPS storage. // NOT .Cluster(true) — EVERY node must refresh its own local snapshot to pick up // keys rotated by other replicas; leader-only would defeat the purpose (other // nodes would still encrypt with stale keys until restart). var xmlRefreshInterval = _options.XmlRepositoryRefreshInterval; if (xmlRefreshInterval > TimeSpan.Zero && xmlRefreshInterval != Timeout.InfiniteTimeSpan) { From(TimerDsl.Every("identity-xml-refresh") .Period((int)xmlRefreshInterval.TotalMilliseconds) .Delay(120_000)) .RouteId("identity-xml-refresh") .Process(new DataProtection.XmlRepositoryRefreshProcessor(_sp)); } // ── N-4 (Session C): outbound transactional e-mail backbone ── // 20. SMTP send route. The SmtpEmailNotificationChannel publishes here; the route // forwards to MailKit via the redb.Route.Mail DSL. Built only when SMTP is // explicitly enabled — hosts that ship their own channel (in-memory tests, // SendGrid satellite, …) simply leave Smtp.Enabled = false and replace the // IEmailNotificationChannel registration. var smtp = _options.Smtp; if (smtp.Enabled && !string.IsNullOrWhiteSpace(smtp.Host)) { var smtpBuilder = Smtp.Send(smtp.Host) .Port(smtp.Port) .Security(smtp.Security ?? "None") .From(smtp.FromAddress) .ContentType("text/html") .AlternativeBody() // Disconnect after every send. Transactional Identity mail is sparse // (forgot-password, verify-email) and pooled long-lived SMTP connections // routinely fail against test servers (GreenMail SO_TIMEOUT=30s) and real // relays alike — the cost of an extra TCP handshake per mail is dwarfed by // the operational headache of "Service shutting down" replays mid-flight. .Disconnect(); if (!string.IsNullOrWhiteSpace(smtp.Username)) smtpBuilder = smtpBuilder.Username(smtp.Username); if (!string.IsNullOrWhiteSpace(smtp.Password)) smtpBuilder = smtpBuilder.Password(smtp.Password); if (smtp.SkipCertificateValidation) smtpBuilder = smtpBuilder.TrustAllCertificates(); From(IdentityEndpoints.EmailSend) .RouteId(IdentityEndpoints.RouteIds.EmailSend) .To(smtpBuilder) .WireTap(IdentityEndpoints.Events, EventTapPool); } } // ── Helpers ── /// /// E1: Wraps a route in redb transaction boundary so that all writes performed /// during route execution commit/rollback atomically at the standard /// TransactedProcessor route boundary. Idempotent — safe to call once per route. /// Uses the configured when present. /// /// /// E1: Wraps a route in a redb transaction boundary so that all writes performed /// during route execution commit/rollback atomically at the standard /// TransactedProcessor route boundary. /// /// Requires to be configured. Only the /// named resolution path is safe for transactions: it gives every exchange its own /// per-exchange scoped (see /// ), /// so the transaction never bleeds across concurrent exchanges. The anonymous singleton /// IRedbService is shared and would serialize all in-flight requests onto a single /// connection, so we deliberately no-op when the name is missing (typically in unit tests /// that intentionally skip the named-factory registration). /// /// private IRouteDefinition WithRedbTx(IRouteDefinition route) { if (string.IsNullOrEmpty(_redbName)) return route; // No named per-exchange scope → cannot safely open a route-level tx. // The ambient TransactionScope IS the transaction now: redb enlists into it through the // core's AmbientConnectionRegistry, so one connection per database serves the whole // exchange and the scope owns commit and rollback. The former pairing — // Transacted(Suppress) + BeginRedbTransaction — existed only because the core used to // reject an explicit redb transaction while Transaction.Current was non-null; that // reason is gone and BeginRedbTransaction is obsolete. // // Consequence for processors: nothing inside a transacted route may call // redb.Context.BeginTransactionAsync() — the core throws there and points at // ExecuteAtomicAsync, which joins the ambient transaction instead. // // The timeout is stated rather than inherited. This scope covers Argon2id plus the whole // OpenIddict pipeline on the token route, which sits uncomfortably close to the // framework default of 30 s under load; and a default that belongs to another component // should not silently decide when an Identity request dies. Identity is single-database, // so a longer window brings no distributed-transaction escalation with it. return route.Transacted(new TransactionPolicy { Timeout = TimeSpan.FromMinutes(2) }); } /// /// E2 — wraps an admin/SCIM mutation route in Idempotency-Key response caching. /// Inserts a PRE processor (cache lookup → short-circuit on hit) immediately after the /// transaction-scope opener returned by , runs the supplied /// processor, then appends a POST processor that captures /// the response into the cache. Idempotency is a no-op when the named-redb factory is /// not configured (tests / dev) or when is /// false — in either case the route degrades to plain . /// /// /// RFC 6749 §2.3 client identifier extractor for per-client throttle buckets on /// /connect/token and /connect/par. OAuth clients deliver /// client_id via one of two channels: /// /// HTTP Basic Auth header — confidential clients (RFC 6749 §2.3.1); /// Form-encoded body parameter — public clients (RFC 6749 §3.2.1). /// /// The original extractor read only HTTP headers, which always returned null for /// either channel (the header name is Authorization, not client_id; and /// form params are body, not headers). Every token request therefore fell back to the /// literal string "anonymous" — collapsing the per-client throttle into a single /// shared bucket. Visible in demo_throttle_rfc6585 ("KeyedThrottle isolation /// broken") and as collateral 429s in demo_jwks_rotation once unrelated demos ran /// faster than the throttle window could reset. /// internal static string ExtractClientIdForThrottle(IExchange e) { // (1) HTTP Basic Auth — RFC 6749 §2.3.1. Decode "Basic base64(client_id:client_secret)". if (e.In.Headers.TryGetValue("Authorization", out var authObj) && authObj is string auth && auth.Length > 6 && auth.StartsWith("Basic ", StringComparison.OrdinalIgnoreCase)) { try { var decoded = System.Text.Encoding.UTF8.GetString(Base64Canonical.Decode(auth.AsSpan(6).ToString())); var colon = decoded.IndexOf(':'); var clientId = colon > 0 ? decoded[..colon] : decoded; if (!string.IsNullOrEmpty(clientId)) return clientId; } catch { // Malformed Basic — fall through to body lookup. } } // (2) Form-encoded body — RFC 6749 §3.2.1. The HTTP transport parses // application/x-www-form-urlencoded into IDictionary. if (e.In.Body is IDictionary body && body.TryGetValue("client_id", out var cid) && cid?.ToString() is { Length: > 0 } cidStr) return cidStr; return "anonymous"; } private IRouteDefinition WithIdempotentTx(IRouteDefinition route, string scope, IProcessor business, bool wrapInRedbTx = true) { // wrapInRedbTx=false: routes whose business processor primarily writes through a // DI-scoped store / OpenIddict manager (which opens its OWN IRedbService and hence // its own SqliteRedbConnection) — wrapping in route-level redb-tx holds the writer // lock on the per-exchange connection while the store's separate connection races // for the same SQLite file, causing self-deadlock + busy_timeout cascades (~34s // observed). Idempotency pre/post still apply (their cache hits/writes go through // the per-exchange redb), they just no longer share a transaction with the body. var withTx = wrapInRedbTx ? WithRedbTx(route) : route; // First on the route: no management context, no idempotency lookup, no business processor. withTx = withTx.Process(RequireManagementContext); var pre = BuildIdempotencyPre(scope); if (pre is not null) withTx = withTx.Process(pre); withTx = withTx.Process(business); var post = BuildIdempotencyPost(); if (post is not null) withTx = withTx.Process(post); return withTx; } /// /// E2 helper: builds the PRE idempotency processor for routes whose chain includes /// extra steps (Throttle, RequireSelfOrAdmin, etc.) that prevent using /// . Returns null when idempotency is disabled or /// the named-redb factory is missing — callers conditionally append the result. /// private IProcessor? BuildIdempotencyPre(string scope) { if (!_options.Idempotency.Enabled) return null; var loggerFactory = _sp.GetService(); return new IdempotencyProcessor( Context!, _redbName, scope, _options.Idempotency, _sp.GetService() ?? TimeProvider.System, loggerFactory?.CreateLogger()); } /// E2 paired POST processor; see . private IProcessor? BuildIdempotencyPost() { if (!_options.Idempotency.Enabled) return null; var loggerFactory = _sp.GetService(); return new IdempotencyCaptureProcessor( Context!, _redbName, _options.Idempotency, _sp.GetService() ?? TimeProvider.System, loggerFactory?.CreateLogger()); } private static void MapOAuthExceptionToRfc6749Response(IExchange exchange) { var ex = exchange.Exception; var error = ex?.Data["error"]?.ToString() ?? "server_error"; var description = ex?.Data["error_description"]?.ToString() ?? ex?.Message ?? "An error occurred."; var outMsg = EnsureOut(exchange); outMsg.Body = ErrorResponse(error, description); outMsg.Headers["redbHttp.ResponseCode"] = 400; } /// /// Ensures exists as a separate message. Never alias /// Out to In: writing the response into the request message corrupts /// the original body for anything that re-reads it later in the pipeline. /// private static IMessage EnsureOut(IExchange exchange) { if (exchange.Out is null) { exchange.Pattern = ExchangePattern.InOut; exchange.Out = exchange.In.Clone(); exchange.Out.Body = null; exchange.Out.Headers.Clear(); } return exchange.Out; } private static object ErrorResponse(string error, string description) => new Dictionary { ["error"] = error, ["error_description"] = description }; /// /// The answer to a unique-key violation that reached the builder-level handlers: 409 with the same /// vocabulary the management processors use for a duplicate, so a caller sees one answer for one /// situation regardless of which surface produced it. /// internal static void AnswerDuplicate(IExchange exchange, redb.Identity.Core.Metrics.IdentityMetrics? metrics) { IdentityProcessorHelpers.CountUniqueViolation(metrics, exchange.Exception); var outMsg = EnsureOut(exchange); outMsg.Body = ErrorResponse("duplicate", "A record with these values already exists."); outMsg.Headers["redbHttp.ResponseCode"] = 409; } private static bool IsOAuthError(Exception? ex) => ex?.Data.Contains("error") == true; } Path: redb-identity/src/redb.Identity.Core/Routes/Processors/AccountRegisterProcessor.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/Routes/Processors/AccountRegisterProcessor.cs ---- using System; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using redb.Core; using redb.Core.Models.Entities; using redb.Core.Models.Users; using redb.Core.Query; using redb.Identity.Contracts.Routes; using redb.Identity.Contracts.Users; using redb.Identity.Core.Configuration; using redb.Identity.Core.Models; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.RedbCore.Extensions; using CoreCreateUserRequest = redb.Core.Models.Users.CreateUserRequest; namespace redb.Identity.Core.Routes.Processors; /// /// N-3 (sub-step N3-7): anonymous self-service account-registration processor backing /// direct-vm://identity-account-register. /// /// Distinct from (admin create): runs on the /// anonymous prefix /api/v1/identity/account/, is per-IP throttled by the upstream /// route chain, validates inputs against the same helpers, and \u2014 unlike the password /// recovery flow \u2014 deliberately surfaces duplicate / weak_password /// errors so the sign-up UI can render actionable feedback. Duplicate-login attempts are /// an expected user mistake; treating them as anti-enumeration would block legitimate /// users without preventing the trivial probe (anyone can already attempt to log in). /// /// /// The processor does NOT dispatch the verify-e-mail link itself \u2014 after the BFF /// auto-signs the user in it calls /api/auth/account/verify-email/send, which /// already routes through the dedicated EmailVerifySendProcessor with full /// per-client URL whitelist enforcement. /// /// internal sealed class AccountRegisterProcessor : IProcessor { private readonly IRouteContext _context; private readonly IServiceProvider _sp; private readonly string? _redbName; public AccountRegisterProcessor(IRouteContext context, IServiceProvider sp, string? redbName = null) { _context = context; _sp = sp; _redbName = redbName; } public async Task Process(IExchange exchange, CancellationToken ct = default) { var request = exchange.In.Body as RegisterAccountRequest; if (request is null) { Reject(exchange, 400, "validation_error", "Request body is required."); return; } var options = _sp.GetRequiredService>().Value; var regOptions = options.Registration; // Master switch \u2014 even if the route is wired at startup but disabled later // via config reload, refuse with 403 so the BFF/SDK can show a deterministic // "sign-up is disabled" message. if (!regOptions.Enabled) { Reject(exchange, 403, "registration_disabled", "Self-service account registration is disabled on this server."); return; } // Hard input validation \u2014 mirrors UserManagementProcessor.Create except that // e-mail is REQUIRED here (the anonymous flow has no other recovery surface). var err = IdentityProcessorHelpers.ValidateIdentifier(request.Login, "Login"); if (err is not null) { Reject(exchange, 400, "validation_error", err); return; } err = IdentityProcessorHelpers.ValidateDisplayName(request.DisplayName, "DisplayName"); if (err is not null) { Reject(exchange, 400, "validation_error", err); return; } if (string.IsNullOrWhiteSpace(request.Email)) { Reject(exchange, 400, "validation_error", "Email is required."); return; } err = IdentityProcessorHelpers.ValidateEmail(request.Email); if (err is not null) { Reject(exchange, 400, "validation_error", err); return; } // Normalise before the uniqueness check and the INSERT: e-mail is case-insensitive in // practice, but the UX_users_email unique index is a plain index on _email, so "A@x.com" // and "a@x.com" would otherwise slip past it as distinct rows. Lower-invariant + trim makes // the stored value canonical, so the index (and EmailExact lookups) enforce one identity. request.Email = request.Email.Trim().ToLowerInvariant(); // Full password policy gate (length + composition + breach). userId is null // because we have not minted the row yet. err = await IdentityProcessorHelpers.ValidatePasswordPolicyAsync( exchange, _context, request.Password, userId: null, "Password", ct).ConfigureAwait(false); if (err is not null) { Reject(exchange, 400, "weak_password", err); return; } var redb = _context.GetRedbService(_redbName, exchange); var logger = _sp.GetService()?.CreateLogger("AccountRegisterProcessor"); // S2.3 — enforce global claim schema BEFORE creating the relational // user row. Failed validation here must NOT leave a half-created // user behind. account/register has no inbound customClaims yet, so // we pass null — defaults are filled in, required claims without a // default fail with 400. var (defaultClaims, schemaErr) = await Services.ClaimSchemaValidator.EnforceGlobalAsync(redb, null, ct) .ConfigureAwait(false); if (schemaErr is not null) { Reject(exchange, 400, "validation_error", schemaErr); return; } // Pre-check e-mail uniqueness when the option is on. UserProvider.CreateUserAsync // enforces login uniqueness atomically; e-mail is not enforced at the relational // layer, so we surface a deterministic error before allocating a row. if (regOptions.RequireUniqueEmail) { var existing = await redb.UserProvider.GetUsersAsync(new UserSearchCriteria { EmailExact = request.Email, }).ConfigureAwait(false); if (existing is { Count: > 0 }) { Reject(exchange, 409, "duplicate", $"An account with email '{request.Email}' already exists."); return; } } // Create the relational user row. redb.Core.Models.Contracts.IRedbUser coreUser; try { coreUser = await redb.UserProvider.CreateUserAsync(new CoreCreateUserRequest { Login = request.Login, Password = request.Password, Name = request.DisplayName ?? request.Login, Email = request.Email, Phone = null, Enabled = true, }).ConfigureAwait(false); } catch (InvalidOperationException ex) when (ex.Message.Contains("already taken")) { Reject(exchange, 409, "duplicate", $"Login '{request.Login}' is already taken."); return; } catch (Exception ex) when ( (ex.Message?.Contains("UX_users_email", StringComparison.OrdinalIgnoreCase) ?? false) || (ex.InnerException?.Message?.Contains("UX_users_email", StringComparison.OrdinalIgnoreCase) ?? false)) { // The UX_users_email unique index fired: another registration committed the same e-mail // between our advisory check and this INSERT. This is the atomic backstop the advisory // GetUsersAsync check cannot provide — surface it as the same 409 the check would have. IdentityProcessorHelpers.CountUniqueViolation(_context, exchange, ex); Reject(exchange, 409, "duplicate", $"An account with email '{request.Email}' already exists."); return; } catch (Exception ex) { throw; } // Persist OIDC profile extension (UserProps) linked via key = _users._id. // value_guid: stable, instance-unique public identity used as the OIDC `sub` claim. // PasswordChangedAt + HasUserPassword are baked into THIS save so we do not need // a follow-up read-modify-write in the password-history helper. The helper's // stamp path opens a fresh DI scope (separate Npgsql connection) and would race // for 30 s on row locks against the row we are inserting right here \u2014 one save // is enough, the row is up-to-date as of registration time. var nowUtc = DateTimeOffset.UtcNow; var propsObj = new RedbObject(new UserProps { UserId = coreUser.Id, // V4-UNIQUE: written alongside key at every creation site EmailVerified = false, PasswordChangedAt = nowUtc, HasUserPassword = true, CustomClaims = defaultClaims is { Count: > 0 } ? defaultClaims : null, }) { name = coreUser.Login, key = coreUser.Id, value_guid = Guid.NewGuid(), }; await redb.SaveAsync(propsObj).ConfigureAwait(false); // Record initial password in history so subsequent change attempts cannot // immediately reuse the sign-up password. We call the store directly (rather // than through RecordPasswordHistoryAsync) to skip its stamp path \u2014 see above. var historyStore = _sp.GetService(); var keep = options.PasswordPolicy?.HistoryCount ?? 0; if (historyStore is not null && keep > 0) { try { await historyStore.RecordAsync(coreUser.Id, request.Password, keep, ct) .ConfigureAwait(false); } catch (Exception ex) { // Non-fatal: history is best-effort, mirrors the helper's swallow contract. } } logger?.LogDebug( "AccountRegister: user {UserId} ({Login}) created via self-service", coreUser.Id, coreUser.Login); exchange.Out ??= new Message(); exchange.Out.Body = new RegisterAccountResponse { Success = true, UserId = coreUser.Id, Login = coreUser.Login, }; exchange.Properties["identity-event-type"] = IdentityAuditEventIds.UserCreated; exchange.Properties["identity-event-data"] = new { UserId = coreUser.Id, Login = coreUser.Login, SelfService = true, }; } private static void Reject(IExchange exchange, int status, string error, string description) { exchange.Out ??= new Message(); exchange.Out.Headers["redbHttp.ResponseCode"] = status; exchange.Out.Body = new RegisterAccountResponse { Success = false, Error = error, ErrorDescription = description, }; } } Path: redb-identity/src/redb.Identity.Core/Routes/Processors/ApplicationManagementProcessor.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/Routes/Processors/ApplicationManagementProcessor.cs ---- using System.Text.Json; using Microsoft.Extensions.DependencyInjection; using OpenIddict.Abstractions; using redb.Core; using redb.Core.Models.Entities; using redb.Core.Services; using redb.Identity.Contracts.Applications; using redb.Identity.Contracts.Common; using redb.Identity.Core.Models; using redb.Identity.Core.Module; using redb.Identity.Contracts.Cors; using redb.Identity.Core.Security; using redb.Identity.Core.Services; using redb.Route.Abstractions; using redb.Route.RedbCore.Extensions; using redb.Identity.Contracts.Routes; namespace redb.Identity.Core.Routes.Processors; /// /// CRUD management processor for OAuth applications. /// Dispatches on the "operation" header: create, read, update, delete, list. /// internal sealed class ApplicationManagementProcessor : IProcessor { private readonly IRouteContext _context; private readonly string? _redbName; private readonly redb.Identity.Core.Configuration.RedbIdentityOptions _options; public ApplicationManagementProcessor( IRouteContext context, string? redbName = null, redb.Identity.Core.Configuration.RedbIdentityOptions? options = null) { _context = context; _redbName = redbName; _options = options ?? new redb.Identity.Core.Configuration.RedbIdentityOptions(); } public async Task Process(IExchange exchange, CancellationToken ct = default) { var redb = _context.GetRedbService(_redbName, exchange); var operation = exchange.In.GetHeader("operation") ?? throw new InvalidOperationException("Missing 'operation' header"); switch (operation) { case "create": await Create(redb, exchange, ct); break; case "read": await Read(redb, exchange, ct); break; case "update": await Update(redb, exchange, ct); break; case "delete": await Delete(redb, exchange, ct); break; case "list": await List(redb, exchange, ct); break; case "rotate-secret": await RotateSecret(redb, exchange, ct); break; default: exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new ErrorResponse { Error = "invalid_operation", ErrorDescription = $"Unknown operation: {operation}" }; break; } } private async Task Create(IRedbService _redb, IExchange exchange, CancellationToken ct) { var request = exchange.In.Body as CreateApplicationRequest; // Validate ClientId var err = IdentityProcessorHelpers.ValidateIdentifier(request?.ClientId, "ClientId"); if (err != null) { SetError(exchange, "validation_error", err); return; } if (request!.ClientType is not (null or "public" or "confidential")) { SetError(exchange, "validation_error", "ClientType must be 'public' or 'confidential'"); return; } if (request.ConsentType is not (null or "explicit" or "implicit" or "external")) { SetError(exchange, "validation_error", "ConsentType must be 'explicit', 'implicit', or 'external'"); return; } if (request.ApplicationType is not (null or "web" or "native")) { SetError(exchange, "validation_error", "ApplicationType must be 'web' or 'native'"); return; } err = IdentityProcessorHelpers.ValidateDisplayName(request.DisplayName, "DisplayName"); if (err != null) { SetError(exchange, "validation_error", err); return; } err = IdentityProcessorHelpers.ValidateUris(request.RedirectUris, "redirect URI"); if (err != null) { SetError(exchange, "validation_error", err); return; } err = IdentityProcessorHelpers.ValidateUris(request.PostLogoutRedirectUris, "post-logout redirect URI"); if (err != null) { SetError(exchange, "validation_error", err); return; } if (!string.IsNullOrWhiteSpace(request.BackchannelLogoutUri)) { err = await IdentityProcessorHelpers.ValidateBackchannelLogoutUriAsync( request.BackchannelLogoutUri.Trim(), _options.BackchannelLogout, ct).ConfigureAwait(false); if (err != null) { SetError(exchange, "validation_error", err); return; } } if (request.ClientSecret is not null && request.ClientSecret.Length > IdentityProcessorHelpers.MaxPasswordLength) { SetError(exchange, "validation_error", $"ClientSecret must not exceed {IdentityProcessorHelpers.MaxPasswordLength} characters"); return; } // Resolve OpenIddict application manager — required so that client_secret is hashed via // the same mechanism used by ValidateClientSecretAsync (BCrypt). Bypassing the manager // here would create credentials that token endpoint cannot verify. // Prefer the per-exchange scope so that scoped services (IOpenIddictApplicationManager // and its IRedbService dependency) are not captured from the root provider — doing so // would force every concurrent admin call onto a single Npgsql connection. var manager = _context.GetIdentityService(exchange); // Check uniqueness via the manager (single source of truth, also hits the OpenIddict cache) if (await manager.FindByClientIdAsync(request.ClientId, ct) is not null) { SetError(exchange, "duplicate", $"ClientId '{request.ClientId}' already exists"); return; } var descriptor = new OpenIddictApplicationDescriptor { ClientId = request.ClientId, ClientSecret = string.IsNullOrEmpty(request.ClientSecret) ? null : request.ClientSecret, // Smart default: confidential clients require a secret. When the caller omits both // ClientType and ClientSecret, default to public to keep the API ergonomic and to // avoid the OpenIddict "confidential without secret" validation error. ClientType = request.ClientType ?? (string.IsNullOrEmpty(request.ClientSecret) ? "public" : "confidential"), ConsentType = request.ConsentType ?? "explicit", DisplayName = request.DisplayName ?? request.ClientId, }; if (request.ApplicationType == "native") descriptor.ApplicationType = OpenIddictConstants.ApplicationTypes.Native; else if (request.ApplicationType == "web") descriptor.ApplicationType = OpenIddictConstants.ApplicationTypes.Web; if (request.RedirectUris is { Length: > 0 }) foreach (var uri in request.RedirectUris) descriptor.RedirectUris.Add(new Uri(uri)); if (request.PostLogoutRedirectUris is { Length: > 0 }) foreach (var uri in request.PostLogoutRedirectUris) descriptor.PostLogoutRedirectUris.Add(new Uri(uri)); if (request.Permissions is { Length: > 0 }) foreach (var p in request.Permissions) descriptor.Permissions.Add(p); if (request.Requirements is { Length: > 0 }) foreach (var r in request.Requirements) descriptor.Requirements.Add(r); // OIDC Back-Channel Logout 1.0 §2.2 — store endpoint + sid flag as custom // properties so BackchannelLogoutDispatcher can read them at logout time. if (!string.IsNullOrWhiteSpace(request.BackchannelLogoutUri)) { descriptor.Properties["backchannel_logout_uri"] = JsonDocument.Parse(JsonSerializer.Serialize(request.BackchannelLogoutUri)).RootElement.Clone(); descriptor.Properties["backchannel_logout_session_required"] = JsonDocument.Parse((request.BackchannelLogoutSessionRequired ?? true) ? "true" : "false").RootElement.Clone(); } RedbObject created; try { created = (await manager.CreateAsync(descriptor, ct)) as RedbObject ?? throw new InvalidOperationException("Application manager returned unexpected entity type"); } catch (redb.Core.Exceptions.RedbUniqueViolationException violation) { IdentityProcessorHelpers.CountUniqueViolation(_context, exchange, violation); // Concurrent writer won the race — the [RedbUnique] ClientId index rejected this // insert (V4-UNIQUE; typed on every provider, MSSQL included, which the retired // value_string index never covered). Same error as the app-level check above. SetError(exchange, "duplicate", $"ClientId '{request.ClientId}' already exists"); return; } // C15 / per-route CORS: registered-client origin snapshot is now stale. _context.GetIdentityServiceOrDefault(exchange)?.Invalidate(); exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = MapToResponse(created); exchange.Properties["identity-event-type"] = IdentityAuditEventIds.ClientRegistered; exchange.Properties["identity-event-data"] = new { ClientId = request.ClientId }; } private async Task Read(IRedbService _redb, IExchange exchange, CancellationToken ct) { RedbObject? app = null; if (exchange.In.Body is Dictionary dict) { if (dict.TryGetValue("id", out var idVal) && idVal != null && long.TryParse(idVal.ToString(), out var id) && id > 0) app = (await _redb.LoadAsync(id)); else if (dict.TryGetValue("clientId", out var cidVal) && cidVal is string clientId && !string.IsNullOrEmpty(clientId)) app = await _redb.GetByUniqueAsync(p => p.ClientId, clientId); else throw new InvalidOperationException("Either 'id' or 'clientId' required"); } else { throw new InvalidOperationException("Expected body with 'id' or 'clientId'"); } if (app is null) { exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new ErrorResponse { Error = "not_found", ErrorDescription = "Application not found" }; return; } exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = MapToResponse(app); } private async Task Update(IRedbService _redb, IExchange exchange, CancellationToken ct) { var request = exchange.In.Body as UpdateApplicationRequest; if (request is null || !long.TryParse(request.Id, out var objectId) || objectId <= 0) { SetError(exchange, "validation_error", "Id is required"); return; } var app = (await _redb.LoadAsync(objectId)); if (app is null) { exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new ErrorResponse { Error = "not_found", ErrorDescription = $"Application {request.Id} not found" }; return; } // Validate updatable fields if (request.ClientType is not (null or "public" or "confidential")) { SetError(exchange, "validation_error", "ClientType must be 'public' or 'confidential'"); return; } if (request.ConsentType is not (null or "explicit" or "implicit" or "external")) { SetError(exchange, "validation_error", "ConsentType must be 'explicit', 'implicit', or 'external'"); return; } var err = IdentityProcessorHelpers.ValidateDisplayName(request.DisplayName, "DisplayName"); if (err != null) { SetError(exchange, "validation_error", err); return; } err = IdentityProcessorHelpers.ValidateUris(request.RedirectUris, "redirect URI"); if (err != null) { SetError(exchange, "validation_error", err); return; } err = IdentityProcessorHelpers.ValidateUris(request.PostLogoutRedirectUris, "post-logout redirect URI"); if (err != null) { SetError(exchange, "validation_error", err); return; } if (request.DisplayName != null) app.Name = request.DisplayName; if (request.ClientType != null) app.Props.ClientType = request.ClientType; if (request.ConsentType != null) app.Props.ConsentType = request.ConsentType; if (request.Permissions != null) app.Props.Permissions = request.Permissions; if (request.RedirectUris != null) app.Props.RedirectUris = request.RedirectUris; if (request.PostLogoutRedirectUris != null) app.Props.PostLogoutRedirectUris = request.PostLogoutRedirectUris; if (request.Requirements != null) app.Props.Requirements = request.Requirements; // N-4 (Session C/E): per-client password-reset / verify-email / change-email // landing-URL whitelists. Without these wired through admin Update, the // server-side enforcement is unreachable from any external caller (the only // alternative is direct DB writes via the seed pipeline). if (request.PasswordResetUris != null) app.Props.PasswordResetUris = request.PasswordResetUris; if (request.EmailVerifyUris != null) app.Props.EmailVerifyUris = request.EmailVerifyUris; if (request.ChangeEmailUris != null) app.Props.ChangeEmailUris = request.ChangeEmailUris; // A.1 (Batch 1 follow-up): protocol-tab editable fields. // - PATCH semantics: a non-null empty string clears the value; null leaves // the existing value alone. // - Validate Back-Channel Logout URI shape via the same helper as the // redirect-URI list (single-element list for re-use). if (request.BackchannelLogoutUri != null) { var bclTrimmed = request.BackchannelLogoutUri.Trim(); if (bclTrimmed.Length == 0) { app.Props.BackchannelLogoutUri = null; } else { err = IdentityProcessorHelpers.ValidateUris(new[] { bclTrimmed }, "back-channel logout URL"); if (err != null) { SetError(exchange, "validation_error", err); return; } err = await IdentityProcessorHelpers.ValidateBackchannelLogoutUriAsync(bclTrimmed, _options.BackchannelLogout, ct) .ConfigureAwait(false); if (err != null) { SetError(exchange, "validation_error", err); return; } app.Props.BackchannelLogoutUri = bclTrimmed; } } if (request.BackchannelLogoutSessionRequired.HasValue) app.Props.BackchannelLogoutSessionRequired = request.BackchannelLogoutSessionRequired.Value; if (request.RequirePushedAuthorizationRequests.HasValue) app.Props.RequirePushedAuthorizationRequests = request.RequirePushedAuthorizationRequests.Value; if (request.JsonWebKeySet != null) { // Empty string clears; otherwise we accept the raw JSON as the caller // supplied it. We do NOT parse-validate here because we want the same // tolerant behaviour as our other JSON-bearing fields (the caller's // JWKS may carry vendor extensions OpenIddict ignores). A future // refinement: validate via JsonWebKeySet.Create at admin time. app.Props.JsonWebKeySet = request.JsonWebKeySet.Length == 0 ? null : request.JsonWebKeySet; } // A.2: per-client token lifetime overrides — write through to // ApplicationProps.Settings using OpenIddict's well-known setting keys. // RedbApplicationStore.GetSettingsAsync surfaces this dict verbatim, and // OpenIddict's built-in AttachAccessTokenLifetime / AttachIdentityToken- // Lifetime / AttachRefreshTokenLifetime handlers prefer per-client values // over the server-wide RedbIdentityOptions defaults. Negative or zero // clears the override (reverts to global default). ApplyLifetimeSetting(app, OpenIddictConstants.Settings.TokenLifetimes.AccessToken, request.AccessTokenLifetimeSeconds); ApplyLifetimeSetting(app, OpenIddictConstants.Settings.TokenLifetimes.RefreshToken, request.RefreshTokenLifetimeSeconds); ApplyLifetimeSetting(app, OpenIddictConstants.Settings.TokenLifetimes.IdentityToken, request.IdentityTokenLifetimeSeconds); // A.3: extra id_token audiences. null leaves alone, empty clears, // non-empty replaces. The trim/dedupe pass below mirrors how we // sanitise RedirectUris — caller can paste duplicates without // poisoning the array. if (request.IdTokenAudiences != null) { app.Props.IdTokenAudiences = request.IdTokenAudiences .Where(a => !string.IsNullOrWhiteSpace(a)) .Select(a => a.Trim()) .Distinct(StringComparer.Ordinal) .ToArray(); if (app.Props.IdTokenAudiences.Length == 0) app.Props.IdTokenAudiences = null; } // RFC 9068: access_token resource indicators — same PATCH and sanitising semantics. if (request.AccessTokenAudiences != null) { app.Props.AccessTokenAudiences = request.AccessTokenAudiences .Where(a => !string.IsNullOrWhiteSpace(a)) .Select(a => a.Trim()) .Distinct(StringComparer.Ordinal) .ToArray(); if (app.Props.AccessTokenAudiences.Length == 0) app.Props.AccessTokenAudiences = null; } // OIDC DCR §2 request_uris — PATCH semantics: empty array clears, null leaves alone. Stored as given: // the authorization endpoint matches them exactly. if (request.RequestUris != null) { err = IdentityProcessorHelpers.ValidateRequestUris(request.RequestUris); if (err != null) { SetError(exchange, "validation_error", err); return; } app.Props.RequestUris = request.RequestUris.Length == 0 ? null : request.RequestUris.Distinct(StringComparer.Ordinal).ToArray(); } // A.6 (Request Object) — PATCH semantics: empty string clears, null leaves alone. if (request.RequestObjectSigningAlg != null) app.Props.RequestObjectSigningAlg = request.RequestObjectSigningAlg.Length == 0 ? null : request.RequestObjectSigningAlg; if (request.RequestObjectEncryptionAlg != null) app.Props.RequestObjectEncryptionAlg = request.RequestObjectEncryptionAlg.Length == 0 ? null : request.RequestObjectEncryptionAlg; if (request.RequestObjectEncryptionEnc != null) app.Props.RequestObjectEncryptionEnc = request.RequestObjectEncryptionEnc.Length == 0 ? null : request.RequestObjectEncryptionEnc; // A.8: per-client strict DPoP opt-in. if (request.RequireDpop.HasValue) app.Props.RequireDpop = request.RequireDpop.Value; // A.10: Advanced-tab toggles. if (request.SkipLogoutConsent.HasValue) app.Props.SkipLogoutConsent = request.SkipLogoutConsent.Value; if (request.IsFidoTrusted.HasValue) app.Props.IsFidoTrusted = request.IsFidoTrusted.Value; // β: AllowedGroups whitelist (per-app group restriction). Empty array // clears the whitelist (any user); non-empty trim + dedupe + dropna so // the stored array is tidy regardless of operator input shape. if (request.AllowedGroups != null) { app.Props.AllowedGroups = request.AllowedGroups .Where(g => !string.IsNullOrWhiteSpace(g)) .Select(g => g.Trim()) .Distinct(StringComparer.Ordinal) .ToArray(); if (app.Props.AllowedGroups.Length == 0) app.Props.AllowedGroups = null; } // A.7: JWKS endpoint URL — validate as a single URI when present so we // reject obviously malformed input at admin time rather than discovering // it during the first RP authentication round-trip. if (request.JwksUri != null) { var trimmed = request.JwksUri.Trim(); if (trimmed.Length == 0) { app.Props.JwksUri = null; } else { err = IdentityProcessorHelpers.ValidateUris(new[] { trimmed }, "JWKS URI"); if (err != null) { SetError(exchange, "validation_error", err); return; } app.Props.JwksUri = trimmed; } } await _redb.SaveAsync(app); // C15 / per-route CORS: invalidate registry whenever redirect URIs may have changed. if (request.RedirectUris != null || request.PostLogoutRedirectUris != null) _context.GetIdentityServiceOrDefault(exchange)?.Invalidate(); exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = MapToResponse(app); exchange.Properties["identity-event-type"] = IdentityAuditEventIds.ClientUpdated; exchange.Properties["identity-event-data"] = new { app.Props.ClientId }; } private async Task Delete(IRedbService _redb, IExchange exchange, CancellationToken ct) { if (exchange.In.Body is not Dictionary dict || !dict.TryGetValue("id", out var idVal) || idVal == null || !long.TryParse(idVal.ToString(), out var id) || id <= 0) { SetError(exchange, "validation_error", "Id is required"); return; } var bg = _context.GetIdentityServiceOrDefault(exchange); // Delete only a record of this resource: the typed load answers null for an unknown id // and for the id of a record of another resource alike. if (await _redb.LoadAsync(id) is null) { SetError(exchange, "not_found", $"Application {id} not found"); return; } // The client's tokens stop working with it: their entries are revoked before the record goes, so the // resource side, which checks the stored entry, refuses them at once. if (_context.GetIdentityServiceOrDefault(exchange) is { } tokens) await tokens.RevokeByApplicationIdAsync(id.ToString(System.Globalization.CultureInfo.InvariantCulture), ct); await IdentityDeletionHelper.DeleteAsync(_redb, bg, id); // C15 / per-route CORS: a deleted application may have contributed origins. _context.GetIdentityServiceOrDefault(exchange)?.Invalidate(); exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new SuccessResponse(); exchange.Properties["identity-event-type"] = IdentityAuditEventIds.ClientDeleted; exchange.Properties["identity-event-data"] = new { Id = id }; } private async Task List(IRedbService _redb, IExchange exchange, CancellationToken ct) { var request = exchange.In.Body as ListRequest ?? new ListRequest(); var query = _redb.Query() .OrderByRedb(o => o.Id); var total = await query.CountAsync(); var count = Math.Min(request.Count, 100); var items = await query .Skip(request.Offset) .Take(count) .ToListAsync(); exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new PagedResult { Items = items.Select(MapToResponse).ToList(), Total = total, Offset = request.Offset, Count = request.Count }; } /// /// Generates a fresh BCrypt-hashed client_secret for a confidential application /// and returns the plaintext value once in the HTTP response. The old secret is /// invalidated immediately — any client_credentials/refresh flow using the previous /// secret will receive 401 from the next call onward. /// /// Hashing goes through /// so that the same code path used at credential validation (BCrypt) produces the stored hash; /// bypassing the manager would yield a hash format the token endpoint cannot verify. /// /// /// Audit payload carries only the ClientId; the new plaintext secret is NEVER /// written to audit logs (see ). /// /// private async Task RotateSecret(IRedbService _redb, IExchange exchange, CancellationToken ct) { if (exchange.In.Body is not Dictionary dict || !dict.TryGetValue("id", out var idVal) || idVal == null || !long.TryParse(idVal.ToString(), out var id) || id <= 0) { SetError(exchange, "validation_error", "Id is required"); return; } var app = (await _redb.LoadAsync(id)); if (app is null) { exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new ErrorResponse { Error = "not_found", ErrorDescription = $"Application {id} not found" }; return; } // Public clients have no secret by definition (RFC 6749 §2.1) — reject explicitly. if (string.Equals(app.Props.ClientType, "public", StringComparison.OrdinalIgnoreCase)) { SetError(exchange, "invalid_client_type", "Public clients have no client_secret to rotate. Switch the client to 'confidential' first."); return; } // CSPRNG: 32 random bytes → ~44 chars Base64. The plaintext is returned exactly once // in the HTTP response and never persisted (the manager stores only the BCrypt hash). var newSecret = Convert.ToBase64String(System.Security.Cryptography.RandomNumberGenerator.GetBytes(32)); var manager = _context.GetIdentityService(exchange); // Hand the entity we already loaded straight to the manager — its store-side // UpdateAsync re-loads under a row lock for optimistic concurrency, so calling // FindByIdAsync first would only add a wasted round-trip and risk passing in a // separately-cached instance whose hash() would not match the locked snapshot. // Dedicated overload: hashes the secret (BCrypt) and persists in one atomic call. await manager.UpdateAsync(app, newSecret, ct); exchange.Out ??= new redb.Route.Core.Message(); var response = MapToResponse(app); response.NewSecret = newSecret; exchange.Out.Body = response; exchange.Properties["identity-event-type"] = IdentityAuditEventIds.ClientSecretRotated; // SECURITY: payload deliberately omits the plaintext secret. ClientId is enough // to correlate against tokens issued before/after the rotation in audit queries. exchange.Properties["identity-event-data"] = new { app.Props.ClientId }; } private static void SetError(IExchange exchange, string error, string description) => IdentityProcessorHelpers.SetError(exchange, error, description); private static ApplicationResponse MapToResponse(RedbObject app) => new() { Id = app.Id.ToString(), ClientId = app.Props.ClientId, DisplayName = app.Name, ClientType = app.Props.ClientType, ConsentType = app.Props.ConsentType, ApplicationType = app.Props.ApplicationType, Permissions = app.Props.Permissions, RedirectUris = app.Props.RedirectUris, PostLogoutRedirectUris = app.Props.PostLogoutRedirectUris, Requirements = app.Props.Requirements, PasswordResetUris = app.Props.PasswordResetUris, EmailVerifyUris = app.Props.EmailVerifyUris, ChangeEmailUris = app.Props.ChangeEmailUris, // A.1 (Batch 1 follow-up): surface the previously-write-only protocol // properties so the admin UI can render and edit them on the Protocol tab. BackchannelLogoutUri = app.Props.BackchannelLogoutUri, BackchannelLogoutSessionRequired = app.Props.BackchannelLogoutSessionRequired, RequirePushedAuthorizationRequests = app.Props.RequirePushedAuthorizationRequests, JsonWebKeySet = app.Props.JsonWebKeySet, // A.2: per-client lifetime overrides — pulled out of ApplicationProps.Settings // back into typed int? seconds so the admin client doesn't need to parse the // OpenIddict TimeSpan format itself. AccessTokenLifetimeSeconds = ReadLifetimeSetting(app, OpenIddictConstants.Settings.TokenLifetimes.AccessToken), RefreshTokenLifetimeSeconds = ReadLifetimeSetting(app, OpenIddictConstants.Settings.TokenLifetimes.RefreshToken), IdentityTokenLifetimeSeconds = ReadLifetimeSetting(app, OpenIddictConstants.Settings.TokenLifetimes.IdentityToken), // A.3 IdTokenAudiences = app.Props.IdTokenAudiences, AccessTokenAudiences = app.Props.AccessTokenAudiences, // A.6 RequestObjectSigningAlg = app.Props.RequestObjectSigningAlg, RequestUris = app.Props.RequestUris, RequestObjectEncryptionAlg = app.Props.RequestObjectEncryptionAlg, RequestObjectEncryptionEnc = app.Props.RequestObjectEncryptionEnc, // A.7 JwksUri = app.Props.JwksUri, // A.8 RequireDpop = app.Props.RequireDpop, // A.10 SkipLogoutConsent = app.Props.SkipLogoutConsent, IsFidoTrusted = app.Props.IsFidoTrusted, // β AllowedGroups = app.Props.AllowedGroups, }; /// /// Apply / clear one per-client lifetime override. OpenIddict stores these as /// invariant-culture TimeSpan strings in the application's Settings dictionary /// (its AttachAccessTokenLifetime / IdentityToken / RefreshToken handlers parse /// via ). /// Null seconds → leave alone. Zero or negative → clear (revert to global default). /// Positive → set the override. /// private static void ApplyLifetimeSetting(RedbObject app, string key, int? seconds) { if (seconds is null) return; var settings = app.Props.Settings is null ? new Dictionary(StringComparer.Ordinal) : new Dictionary(app.Props.Settings, StringComparer.Ordinal); if (seconds.Value <= 0) { settings.Remove(key); } else { settings[key] = TimeSpan.FromSeconds(seconds.Value) .ToString("c", System.Globalization.CultureInfo.InvariantCulture); } app.Props.Settings = settings.Count == 0 ? null : settings; } /// /// Project one stored lifetime back into int? seconds. Missing key → null /// (means "use the global RedbIdentityOptions default"). Unparseable value → /// null (defensive — bad data in Settings should not 500 the admin GET). /// private static int? ReadLifetimeSetting(RedbObject app, string key) { if (app.Props.Settings is null || !app.Props.Settings.TryGetValue(key, out var raw)) return null; if (TimeSpan.TryParse(raw, System.Globalization.CultureInfo.InvariantCulture, out var ts)) return (int)Math.Round(ts.TotalSeconds); return null; } } Path: redb-identity/src/redb.Identity.Core/Routes/Processors/AuditQueryProcessor.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/Routes/Processors/AuditQueryProcessor.cs ---- using System.Text; using System.Text.Json.Serialization; using redb.Core; using redb.Identity.Contracts.Audit; using redb.Route.Abstractions; using redb.Route.RedbCore.Extensions; namespace redb.Identity.Core.Routes.Processors; /// /// R1 — admin audit log query. Reads from the flat identity_audit_log /// relational table (created by /// ) via redb's raw-SQL /// API. Replaces the props-based query that used to scan AuditEventProps /// rows in _objects + _values. /// /// /// Why raw SQL instead of redb.Query<T>: audit is an append-only /// flat shape with no per-event prop variability; a direct index seek on /// (login, timestamp DESC) or (user_id, timestamp DESC) wins /// trivially over EAV. We still go through IRedbService.Context so /// connection / dialect / transaction management stays in redb's hands. /// /// /// /// Filter precedence matches the prior implementation: /// /// UserId AND Login both set → OR (catch emitters that stamped only one) /// Either alone → that single column /// EventType / Category / ClientId / From / To → AND-composed /// /// /// internal sealed class AuditQueryProcessor : IProcessor { private const int MaxPageSize = 500; private readonly IRouteContext _context; private readonly string? _redbName; public AuditQueryProcessor(IRouteContext context, string? redbName = null) { _context = context; _redbName = redbName; } public async Task Process(IExchange exchange, CancellationToken ct = default) { var request = exchange.In.Body as AuditQueryRequest ?? new AuditQueryRequest(); var offset = Math.Max(0, request.Offset); var count = Math.Clamp(request.Count, 1, MaxPageSize); var redb = _context.GetRedbService(_redbName, exchange); // Build WHERE incrementally with positional @p0..@pN parameters. Same // syntax NpgsqlRedbConnection / MSSQL adapters both accept; Postgres // rewrites to $N internally. var where = new StringBuilder(); var args = new List(); void AddClause(string clause, object value) { where.Append(where.Length == 0 ? " WHERE " : " AND "); where.Append(clause.Replace("{P}", "@p" + args.Count)); args.Add(value); } if (!string.IsNullOrEmpty(request.EventType)) AddClause("event_type = {P}", request.EventType); if (!string.IsNullOrEmpty(request.Category)) AddClause("category = {P}", request.Category); // user_id column is BIGINT — parse the HTTP query string once. If it // fails to parse, drop the userId filter (treat as not-supplied) so // the query still returns whatever the login filter matches. long? userIdNum = null; if (!string.IsNullOrEmpty(request.UserId) && long.TryParse(request.UserId, out var parsedUid)) userIdNum = parsedUid; var hasUserId = userIdNum.HasValue; var hasLogin = !string.IsNullOrEmpty(request.Login); if (hasUserId && hasLogin) { // Two-parameter OR — both placeholders consume the same args slot // pair so the next clause builder picks up from the right index. where.Append(where.Length == 0 ? " WHERE " : " AND "); where.Append("(user_id = @p").Append(args.Count).Append(" OR login = @p").Append(args.Count + 1).Append(")"); args.Add(userIdNum!.Value); args.Add(request.Login!); } else if (hasUserId) { AddClause("user_id = {P}", userIdNum!.Value); } else if (hasLogin) { AddClause("login = {P}", request.Login!); } if (!string.IsNullOrEmpty(request.ClientId)) AddClause("client_id = {P}", request.ClientId); if (request.From is { } fromTs) AddClause("timestamp >= {P}", fromTs); if (request.To is { } toTs) AddClause("timestamp < {P}", toTs); var whereSql = where.ToString(); // Total — single scalar. var countSql = "SELECT COUNT(*) FROM identity_audit_log" + whereSql; var total = await redb.Context.ExecuteScalarAsync(countSql, args.ToArray()).ConfigureAwait(false); // Page rows — same WHERE + ORDER + pagination. Append the pagination // params after the filter args so positional indices line up. // // Pagination dialect varies per provider: // * PostgreSQL / SQLite — "LIMIT N OFFSET M" (rejected by MSSQL). // * SQL Server — "OFFSET M ROWS FETCH NEXT N ROWS ONLY". // // The audit query goes through redb.Context.QueryAsync (raw SQL), so it // can't ride the IDialect.FormatPagination path the structured query // pipeline uses. We sniff the connection type at the callsite to pick // the right tail clause — cheap, no IRedbConnection API change. var connTypeName = redb.Context.Db.GetType().Name; var isMsSql = connTypeName.Contains("Sql", StringComparison.OrdinalIgnoreCase) && !connTypeName.Contains("Sqlite", StringComparison.OrdinalIgnoreCase) && !connTypeName.Contains("Npgsql", StringComparison.OrdinalIgnoreCase); var paginationSql = isMsSql ? $"OFFSET @p{args.Count + 1} ROWS FETCH NEXT @p{args.Count} ROWS ONLY" // MSSQL: offset first, then count : $"LIMIT @p{args.Count} OFFSET @p{args.Count + 1}"; // PG / SQLite var rowsSql = $""" SELECT event_id, event_type, category, "timestamp", user_id, login, client_id, ip_address, user_agent, details, actor_subject FROM identity_audit_log {whereSql} ORDER BY "timestamp" DESC {paginationSql} """; args.Add(count); args.Add(offset); var rows = await redb.Context.QueryAsync(rowsSql, args.ToArray()).ConfigureAwait(false); var items = rows.Select(r => new AuditQueryItem { EventId = NormalizeEventId(r.EventId), EventType = r.EventType ?? "", Category = r.Category ?? "", Timestamp = r.Timestamp, UserId = r.UserId?.ToString(System.Globalization.CultureInfo.InvariantCulture), Login = r.Login, ClientId = r.ClientId, ActorSubject = r.ActorSubject, IpAddress = r.IpAddress, UserAgent = r.UserAgent, Details = AuditRelationalSinkProcessor.TryDeserializeDetails(r.Details) }).ToList(); exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new AuditQueryResponse { Total = (int)Math.Min(total, int.MaxValue), Offset = offset, Count = count, Items = items }; } /// /// Row DTO for redb.Context.QueryAsync<T>. Column → property /// mapping uses JsonPropertyName (snake_case → PascalCase) so the /// names mirror the DDL exactly. /// /// EventId is typed object? because Postgres returns /// Guid (UUID column), MSSQL returns Guid /// (UNIQUEIDENTIFIER), and SQLite returns string (TEXT). The /// generic mapper can't Convert.ChangeType a Guid into a string /// slot — we normalise in . /// /// private sealed class AuditRow { [JsonPropertyName("event_id")] public object? EventId { get; set; } [JsonPropertyName("event_type")] public string? EventType { get; set; } [JsonPropertyName("category")] public string? Category { get; set; } [JsonPropertyName("timestamp")] public DateTimeOffset Timestamp { get; set; } [JsonPropertyName("user_id")] public long? UserId { get; set; } [JsonPropertyName("login")] public string? Login { get; set; } [JsonPropertyName("client_id")] public string? ClientId { get; set; } [JsonPropertyName("ip_address")] public string? IpAddress { get; set; } [JsonPropertyName("user_agent")] public string? UserAgent { get; set; } [JsonPropertyName("details")] public string? Details { get; set; } [JsonPropertyName("actor_subject")] public string? ActorSubject { get; set; } } private static string NormalizeEventId(object? v) => v switch { null => "", Guid g => g.ToString("N"), string s => s.Replace("-", "").ToLowerInvariant(), _ => v.ToString() ?? "" }; } Path: redb-identity/src/redb.Identity.Core/Routes/Processors/AuditRelationalSinkProcessor.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/Routes/Processors/AuditRelationalSinkProcessor.cs ---- using System.Text.Json; using Microsoft.Extensions.Logging; using redb.Core; using redb.Core.Query; using redb.Identity.Contracts.Routes; using redb.Identity.Core.Module; using redb.Route.Abstractions; using redb.Route.RedbCore.Extensions; namespace redb.Identity.Core.Routes.Processors; /// /// R1 — replaces AuditEventSinkProcessor (props-based) with a flat /// relational INSERT into identity_audit_log (DDL ensured by /// ). /// /// /// Same input contract: reads event_type, event_id, /// timestamp, details JSON, user_id, login, /// client_id, ip_address, user_agent off the message /// headers populated by . Derives the /// category from . Tolerantly /// extracts login from the JSON details payload when the emitter /// stamped identity-event-data.Login but not the per-exchange header /// — same fallback the props sink used to keep per-user audit aligned with /// emitters that pre-date the explicit login header. /// /// /// /// Failures are swallowed, logged and counted (identity.audit.write_failures): audit persistence must never kill the /// originating mutation. /// /// internal sealed class AuditRelationalSinkProcessor : IProcessor { private readonly IRouteContext _context; private readonly ILogger _logger; private readonly string? _redbName; public AuditRelationalSinkProcessor(IRouteContext context, ILogger logger, string? redbName = null) { _context = context; _logger = logger; _redbName = redbName; } public async Task Process(IExchange exchange, CancellationToken ct = default) { // EventDispatchProcessor writes the canonical envelope onto Out.Headers // (event_id / event_type / user_id / details / ...). Older emitters that // bypass the dispatcher leave the same shape on In.Headers — prefer Out // when populated, fall back to In to stay compatible with both paths. var headers = (exchange.Out?.Headers?.Count > 0) ? exchange.Out.Headers : exchange.In.Headers; var eventType = GetString(headers, "event_type"); if (string.IsNullOrEmpty(eventType)) return; try { var redb = _context.GetRedbService(_redbName, exchange); var eventId = GetGuid(headers, "event_id") ?? Guid.NewGuid(); var category = IdentityAuditEventIds.CategoryOf(eventType); var timestamp = GetDateTimeOffset(headers, "timestamp") ?? DateTimeOffset.UtcNow; var detailsJson = GetString(headers, "details"); var login = GetString(headers, "login") ?? ExtractLoginFromDetailsJson(detailsJson); // user_id column is BIGINT. Emitters hand us a string (long.ToString()) // for indexed seeks; parse here. Non-numeric → NULL so federated // pre-link events still land instead of crashing the INSERT. var userIdRaw = GetString(headers, "user_id"); object userIdParam = DBNull.Value; if (!string.IsNullOrEmpty(userIdRaw)) { if (long.TryParse(userIdRaw, out var uid)) userIdParam = uid; else _logger.LogWarning( "AuditRelationalSinkProcessor: '{EventType}' carried non-numeric user_id '{UserId}' — storing NULL", eventType, userIdRaw); } // The statement is the dialect's (sql/events/*.sql, insert_audit), run by the event store. var store = new Events.IdentityEventStore(redb, _context.GetIdentityService(exchange)); await store.InsertAuditAsync(new object[] { (object?)eventId ?? DBNull.Value, eventType, (object?)category ?? DBNull.Value, timestamp, userIdParam, (object?)login ?? DBNull.Value, (object?)GetString(headers, "client_id") ?? DBNull.Value, (object?)GetString(headers, "ip_address") ?? DBNull.Value, (object?)GetString(headers, "user_agent") ?? DBNull.Value, (object?)detailsJson ?? DBNull.Value, (object?)GetString(headers, "actor_subject") ?? DBNull.Value, }, ct).ConfigureAwait(false); } catch (Exception ex) { _logger.LogError(ex, "AuditRelationalSinkProcessor failed to persist {EventType}", eventType); // The event goes on, and the missing row must be visible as more than a log line: a // gap in the audit trail is something an operator alerts on. _context.GetIdentityServiceOrDefault(exchange)?.AuditWriteFailures.Add( 1, new KeyValuePair("event_type", eventType)); } } // A header value of DBNull.Value (EventDispatchProcessor stamps it for absent // client_id/ip_address/user_agent so the same dictionary doubles as SQL bind // params) must round-trip back to null here — DBNull.Value.ToString() is "", // which would otherwise land an empty string in a column meant to be NULL. private static string? GetString(IDictionary headers, string key) => headers.TryGetValue(key, out var v) && v is not null and not DBNull ? v.ToString() : null; private static Guid? GetGuid(IDictionary headers, string key) { if (!headers.TryGetValue(key, out var v) || v is null) return null; return v switch { Guid g => g, string s => Guid.TryParse(s, out var parsed) ? parsed : null, _ => null }; } private static DateTimeOffset? GetDateTimeOffset(IDictionary headers, string key) { if (!headers.TryGetValue(key, out var v) || v is null) return null; return v switch { DateTimeOffset dto => dto, DateTime dt => new DateTimeOffset(DateTime.SpecifyKind(dt, DateTimeKind.Utc)), string s => DateTimeOffset.TryParse(s, out var parsed) ? parsed : null, _ => null }; } private static string? ExtractLoginFromDetailsJson(string? detailsJson) { if (string.IsNullOrEmpty(detailsJson)) return null; try { using var doc = JsonDocument.Parse(detailsJson); if (doc.RootElement.ValueKind != JsonValueKind.Object) return null; if (doc.RootElement.TryGetProperty("Login", out var l) && l.ValueKind == JsonValueKind.String) return l.GetString(); if (doc.RootElement.TryGetProperty("login", out var l2) && l2.ValueKind == JsonValueKind.String) return l2.GetString(); return null; } catch { return null; } } /// /// Used by AuditQueryProcessor to deserialise the JSON details /// column back to a structured dictionary for the API response. /// Returns null on any failure so the surrounding row still surfaces in /// the audit page. /// public static Dictionary? TryDeserializeDetails(string? detailsJson) { if (string.IsNullOrEmpty(detailsJson)) return null; try { return JsonSerializer.Deserialize>(detailsJson); } catch { return null; } } } Path: redb-identity/src/redb.Identity.Core/Routes/Processors/AuditTargetEnqueueProcessor.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/Routes/Processors/AuditTargetEnqueueProcessor.cs ---- using System.Text.Json; using Microsoft.Extensions.Logging; using redb.Core.Query; using redb.Identity.Contracts.Events; using redb.Identity.Core.Configuration; using redb.Identity.Core.Events; using redb.Identity.Core.Metrics; using redb.Identity.Core.Module; using redb.Route.Abstractions; using redb.Route.RedbCore.Extensions; using redb.Route.Serialization; namespace redb.Identity.Core.Routes.Processors; /// /// Puts an event into the delivery outbox once for every enabled external audit target /// (Identity:Audit:Targets). Runs in the events route after the audit row and the webhook rows; /// the delivery worker sends the rows with its own parallelism, leases and retries, so a target that is /// down or slow neither holds the events route nor loses the event. /// /// The payload is the event as the targets have always received it (the JSON of /// ); the worker rebuilds the message from it, headers included, /// with . /// /// internal sealed class AuditTargetEnqueueProcessor : IProcessor { internal const string Kind = "audit"; private readonly IRouteContext _context; private readonly string? _redbName; private readonly IReadOnlyList _targets; private readonly ILogger _logger; public AuditTargetEnqueueProcessor(IRouteContext context, string? redbName, IReadOnlyList targets, ILogger logger) { _context = context; _redbName = redbName; _targets = targets; _logger = logger; } public async Task Process(IExchange exchange, CancellationToken ct = default) { if (exchange.In.Body is not IdentityEvent evt || _targets.Count == 0) return; var payload = AuditTargetMessage.Payload(evt); var eventId = Guid.TryParse(evt.EventId, out var parsed) ? parsed : Guid.NewGuid(); var entries = _targets .Select(t => new OutboxEntry(Guid.NewGuid(), eventId, Kind, t.Name, evt.EventType, payload)) .ToList(); try { var redb = _context.GetRedbService(_redbName, exchange); var dialect = _context.GetIdentityService(exchange); await new IdentityEventStore(redb, dialect).InsertOutboxAsync(entries, ct).ConfigureAwait(false); } catch (Exception ex) { _logger.LogError(ex, "Audit targets: could not enqueue event {EventType} for {Count} target(s); the audit row is written, these deliveries are lost.", evt.EventType, entries.Count); _context.GetIdentityServiceOrDefault(exchange)?.DeliveryEnqueueFailures.Add(1, new KeyValuePair("event_type", evt.EventType), new KeyValuePair("kind", Kind)); } } /// /// The enabled targets of the configuration, checked: every one needs a name of at most 200 /// characters, unique among them, because its outbox rows are addressed by it. /// internal static IReadOnlyList EnabledTargets(IdentityAuditOptions options) { if (!options.Enabled) return []; var enabled = options.Targets.Where(t => t.Enabled && !string.IsNullOrEmpty(t.Uri)).ToList(); for (var i = 0; i < enabled.Count; i++) { var name = enabled[i].Name; if (string.IsNullOrWhiteSpace(name) || name.Length > 200) throw new InvalidOperationException( $"redb.Identity: the audit target with Uri '{Scheme(enabled[i].Uri)}...' needs Identity:Audit:Targets:N:Name " + "(at most 200 characters): its deliveries are kept in the outbox under that name."); } var duplicate = enabled.GroupBy(t => t.Name, StringComparer.Ordinal).FirstOrDefault(g => g.Count() > 1); if (duplicate is not null) throw new InvalidOperationException( $"redb.Identity: two enabled audit targets are named '{duplicate.Key}'. Identity:Audit:Targets:N:Name must be unique."); return enabled; } // Only the scheme of a target URI goes into a message: the rest may carry credentials. private static string Scheme(string uri) { var colon = uri.IndexOf(':'); return colon > 0 ? uri[..colon] : "?"; } } /// /// The message an audit target receives, the same as before the outbox: the event as JSON bytes in the /// body, and headers named for SQL parameter binding (event_id, event_type, /// timestamp, user_id, client_id, ip_address, user_agent, /// details) plus event-type. /// internal static class AuditTargetMessage { /// /// The stored payload: the body exactly as the targets' Marshal step used to produce it, and the /// details header exactly as the events route used to set it. The two encode nested values /// differently (camelCase in the body, as declared in the header), so both are kept as written. /// public static string Payload(IdentityEvent evt) => JsonSerializer.Serialize(new Stored( JsonSerializer.Serialize(evt, JsonMessageSerializer.DefaultOptions), evt.Details is { Count: > 0 } details ? JsonSerializer.Serialize(details) : null)); public static redb.Route.Core.Message Build(string payload) { var stored = JsonSerializer.Deserialize(payload) ?? throw new InvalidOperationException("redb.Identity: an audit outbox row holds no event."); var evt = JsonSerializer.Deserialize(stored.Body, JsonMessageSerializer.DefaultOptions) ?? throw new InvalidOperationException("redb.Identity: an audit outbox row holds no event."); var message = new redb.Route.Core.Message(System.Text.Encoding.UTF8.GetBytes(stored.Body)) { ContentType = "application/json" }; message.Headers["event-type"] = evt.EventType; message.Headers["event_id"] = Guid.Parse(evt.EventId); message.Headers["event_type"] = evt.EventType; message.Headers["timestamp"] = evt.Timestamp; message.Headers["user_id"] = evt.UserId ?? (object)DBNull.Value; message.Headers["client_id"] = evt.ClientId ?? (object)DBNull.Value; message.Headers["ip_address"] = evt.IpAddress ?? (object)DBNull.Value; message.Headers["user_agent"] = evt.UserAgent ?? (object)DBNull.Value; message.Headers["details"] = stored.Details ?? (object)DBNull.Value; return message; } private sealed record Stored( [property: System.Text.Json.Serialization.JsonPropertyName("body")] string Body, [property: System.Text.Json.Serialization.JsonPropertyName("details")] string? Details); } Path: redb-identity/src/redb.Identity.Core/Routes/Processors/AuthorizationCheckProcessor.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/Routes/Processors/AuthorizationCheckProcessor.cs ---- using System.Text.Json; using redb.Identity.Contracts.Configuration; using redb.Identity.Contracts.Serialization; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Identity.Core.Routes.Processors; /// /// F5 — the granular scope check for the management surface, behind /// direct-vm://identity-authz-check. Runs after the authentication step has validated the bearer /// token and stashed identity:management-scopes. /// /// This table used to live in the HTTP facade. It is here now because a second transport was about to /// need it, and the failure mode of two copies is not that they disagree loudly — it is that one of them /// quietly grants more than the other, on the surface where that matters most. Moved verbatim: same /// order, same write-implies-read rule, same account branch, same default-deny, same messages. A refusal /// worded differently would have broken the HTTP negative matrix, and rewriting those expectations is /// exactly how a regression net gets cut. /// /// /// Inputs, all transport-neutral: /// /// identity:authz-resource — canonical resource identifier. The identifiers are the /// management paths (/api/v1/identity/users, …) because that is what they have always been /// called; HTTP passes its own path unchanged and other transports map their addresses onto the same /// names. /// identity:authz-action — read or write. /// identity:management-scopes — from the authentication step. /// identity:management-anonymous — short-circuit for routes that are open by design. /// /// /// internal sealed class AuthorizationCheckProcessor : IProcessor { /// Exchange property naming the resource being reached. public const string ResourceProperty = "identity:authz-resource"; /// Exchange property naming the action: read or write. public const string ActionProperty = "identity:authz-action"; // Mapping resource-prefix → (read, write) pair. Order matters: longest prefix first wins via // OrdinalIgnoreCase StartsWith. Moved verbatim from GranularScopeGuardProcessor. private static readonly (string Prefix, string Read, string Write)[] Map = { ("/api/v1/identity/audit", IdentityScopes.AuditRead, IdentityScopes.AuditRead), ("/api/v1/identity/users", IdentityScopes.UsersRead, IdentityScopes.UsersWrite), ("/api/v1/identity/groups", IdentityScopes.GroupsRead, IdentityScopes.GroupsWrite), ("/api/v1/identity/consents", IdentityScopes.ConsentsRead, IdentityScopes.ConsentsWrite), ("/api/v1/identity/mfa", IdentityScopes.MfaRead, IdentityScopes.MfaWrite), ("/api/v1/identity/sessions", IdentityScopes.SessionsRead, IdentityScopes.SessionsWrite), ("/api/v1/identity/tokens", IdentityScopes.TokensRead, IdentityScopes.TokensWrite), ("/api/v1/identity/revoked-sids", IdentityScopes.SessionsRead, IdentityScopes.SessionsWrite), ("/api/v1/identity/applications", IdentityScopes.ApplicationsRead, IdentityScopes.ApplicationsWrite), ("/api/v1/identity/scopes", IdentityScopes.ScopesRead, IdentityScopes.ScopesWrite), ("/api/v1/identity/claim-mappers", IdentityScopes.ClaimsRead, IdentityScopes.ClaimsWrite), ("/api/v1/identity/claim-scopes", IdentityScopes.ClaimsRead, IdentityScopes.ClaimsWrite), ("/api/v1/identity/claim-definitions", IdentityScopes.ClaimsRead, IdentityScopes.ClaimsWrite), ("/api/v1/identity/roles", IdentityScopes.RolesRead, IdentityScopes.RolesWrite), ("/api/v1/identity/webhooks", IdentityScopes.WebhooksRead, IdentityScopes.WebhooksWrite), ("/api/v1/identity/federation-providers", IdentityScopes.FederationRead, IdentityScopes.FederationWrite), ("/api/v1/identity/signing-keys", IdentityScopes.SigningKeysRead, IdentityScopes.SigningKeysWrite), ("/api/v1/identity/admin/impersonate", IdentityScopes.Impersonate, IdentityScopes.Impersonate), // /me/* paths are NOT mapped here — they are reached via Account scope and // the self-service downstream check, which both already pass the gate above. }; /// public Task Process(IExchange exchange, CancellationToken ct = default) => Enforce(exchange, ct); internal static Task Enforce(IExchange e, CancellationToken ct) { if (e.Properties.TryGetValue("identity:management-anonymous", out var anon) && anon is true) return Task.CompletedTask; if (!e.Properties.TryGetValue("identity:management-scopes", out var scopesObj) || scopesObj is not string[] scopes || scopes.Length == 0) { // Bearer-auth must have populated scopes by this point. Defensive deny. Reject(e, 403, "insufficient_scope", "Access token carries no scopes."); return Task.CompletedTask; } // Master admin scope — bypass. if (Array.IndexOf(scopes, IdentityScopes.Manage) >= 0) return Task.CompletedTask; var path = ReadResource(e); var isMutation = ReadAction(e) == "write"; // ReadOnly admin: any admin path, GET-class only. if (Array.IndexOf(scopes, IdentityScopes.ReadOnly) >= 0 && !isMutation) return Task.CompletedTask; // /me/* and explicitly anonymous self-service paths are admitted on Account scope // alone — RequireSelfOrAdminProcessor enforces self-only further down. if (Array.IndexOf(scopes, IdentityScopes.Account) >= 0) { if (path.StartsWith("/api/v1/identity/me", StringComparison.OrdinalIgnoreCase) || path.StartsWith("/api/v1/identity/account/", StringComparison.OrdinalIgnoreCase) || path.StartsWith("/api/v1/identity/password/", StringComparison.OrdinalIgnoreCase)) { return Task.CompletedTask; } } // Per-path granular check. Pick the read or write scope by action. // Write implies read by RBAC convention — if the caller holds the // surface's :write, GET on the same surface is admitted without // also requiring :read. The inverse never holds (read does NOT // imply write). foreach (var (prefix, read, write) in Map) { if (!path.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) continue; if (isMutation) { if (Array.IndexOf(scopes, write) >= 0) return Task.CompletedTask; Reject(e, 403, "insufficient_scope", $"This endpoint requires the '{write}' scope (received: {string.Join(", ", scopes)})."); return Task.CompletedTask; } // GET-class — accept either :read OR :write (write implies read). if (Array.IndexOf(scopes, read) >= 0 || Array.IndexOf(scopes, write) >= 0) return Task.CompletedTask; Reject(e, 403, "insufficient_scope", $"This endpoint requires the '{read}' scope (or '{write}', which implies read) (received: {string.Join(", ", scopes)})."); return Task.CompletedTask; } // Unmapped admin path with no Manage / ReadOnly: default-deny. Reject(e, 403, "insufficient_scope", $"Access token does not carry a scope authorising '{path}'."); return Task.CompletedTask; } /// /// The resource the caller is reaching. A transport states it explicitly; HTTP does not have to, /// because its path already is the canonical identifier and passing it twice would let the two drift. /// private static string ReadResource(IExchange e) { if (e.Properties.TryGetValue(ResourceProperty, out var resource) && resource is string named && !string.IsNullOrEmpty(named)) { return named; } return e.In.GetHeader("redbHttp.Path") ?? string.Empty; } /// /// Read or write. Stated explicitly by transports that have no HTTP method; derived from the method /// otherwise, with the same GET/HEAD/OPTIONS split as before. /// private static string ReadAction(IExchange e) { if (e.Properties.TryGetValue(ActionProperty, out var action) && action is string named && !string.IsNullOrEmpty(named)) { return named.Equals("write", StringComparison.OrdinalIgnoreCase) ? "write" : "read"; } var method = (e.In.GetHeader("redbHttp.Method") ?? "GET").ToUpperInvariant(); return method is "GET" or "HEAD" or "OPTIONS" ? "read" : "write"; } private static void Reject(IExchange exchange, int statusCode, string error, string description) { var body = JsonSerializer.SerializeToUtf8Bytes(new Dictionary { ["error"] = error, ["error_description"] = description }, IdentityWireProfiles.OAuthOptions); exchange.Out = new Message(body); exchange.Out.ContentType = "application/json"; exchange.Out.Headers["redbHttp.ResponseCode"] = statusCode; exchange.Out.Headers["redbHttp.ResponseContentType"] = "application/json"; var safeDesc = description.Replace("\\", "\\\\").Replace("\"", "\\\""); var safeError = error.Replace("\\", "\\\\").Replace("\"", "\\\""); exchange.Out.Headers["WWW-Authenticate"] = $"Bearer realm=\"identity\", error=\"{safeError}\", error_description=\"{safeDesc}\""; exchange.Exception = new UnauthorizedAccessException(description); exchange.ExceptionHandled = true; exchange.Stop(); } } Path: redb-identity/src/redb.Identity.Core/Routes/Processors/BootstrapAdminProcessor.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/Routes/Processors/BootstrapAdminProcessor.cs ---- using System.Security.Cryptography; using System.Text; using System.Text.Json; using System.Text.Json.Nodes; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using OpenIddict.Abstractions; using redb.Core; using redb.Core.Models.Entities; using redb.Core.Models.Users; using redb.Identity.Contracts.Endpoints; using redb.Identity.Contracts.Routes; using redb.Identity.Core.Configuration; using redb.Identity.Core.Models; using redb.Identity.Core.Module; using redb.Identity.Core.Security; using redb.Identity.Core.Services; using redb.Route.Abstractions; using redb.Route.RedbCore.Extensions; namespace redb.Identity.Core.Routes.Processors; /// /// B1 — one-shot emergency-admin bootstrap processor for /// direct-vm://identity-bootstrap-admin. /// /// Atomically creates: scope identity:admin, group /// , the admin user, the membership, /// the canonical OIDC client () with /// backchannel_logout_uri, and the /// SystemFlag(name=bootstrap_completed) sentinel that gates further /// invocations. The whole flow runs inside the route-level WithRedbTx /// wrapper so any partial failure rolls back. /// /// /// Authenticated via the X-Bootstrap-Secret header (compared in constant /// time). Self-locks via the unique SystemFlag sentinel — second call /// returns 410 Gone. /// /// internal sealed class BootstrapAdminProcessor : IProcessor { private const string FlagName = "bootstrap_completed"; // JSON options matching the HTTP wire format produced by browsers / curl / // System.Net.Http.Json.JsonContent.Create — camelCase property names with // case-insensitive fallback so PascalCase test bodies also work. private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web); private readonly IRouteContext _context; private readonly BootstrapOptions _options; private readonly TimeProvider _timeProvider; private readonly string? _redbName; private readonly ILogger? _securityLog; public BootstrapAdminProcessor( IRouteContext context, IOptions identityOptions, TimeProvider? timeProvider = null, ILoggerFactory? loggerFactory = null) { _context = context; _options = identityOptions.Value.Bootstrap ?? new BootstrapOptions(); _redbName = identityOptions.Value.RedbInstanceName; _timeProvider = timeProvider ?? TimeProvider.System; _securityLog = loggerFactory is null ? null : IdentitySecurityLog.CreateLogger(loggerFactory); } public async Task Process(IExchange exchange, CancellationToken ct = default) { // ── 1. Master switch — disabled deployments hide the route entirely. ── if (!_options.Enabled) { // Spec §5: Bootstrap_Throws_When_Bootstrap_Disabled → 404 Not Found so the // endpoint is indistinguishable from "no such route" for un-trusted callers. SetError(exchange, 404, "not_found", "Bootstrap endpoint is not enabled."); return; } // ── 2. Constant-time secret comparison. ── var providedSecret = exchange.In.GetHeader("X-Bootstrap-Secret"); var expectedSecret = _options.Secret; if (string.IsNullOrEmpty(expectedSecret) || string.IsNullOrEmpty(providedSecret) || !FixedTimeStringEquals(providedSecret, expectedSecret)) { _securityLog?.LogWarning( "B1 bootstrap-admin invocation rejected: invalid X-Bootstrap-Secret " + "(remote={Remote})", exchange.In.GetHeader("redbHttp.RemoteAddress")); SetError(exchange, 403, "forbidden", "Invalid bootstrap secret."); return; } // ── 3. Parse request body (the HTTP facade hands a typed DTO; tests can also // pass raw JSON / dictionary). ── var request = ParseRequest(exchange); if (request is null) { SetError(exchange, 400, "validation_error", "Invalid or missing request body."); return; } var validationError = ValidateRequest(request); if (validationError is not null) { SetError(exchange, 400, "validation_error", validationError); return; } var redb = _context.GetRedbService(_redbName, exchange); // ── 4. Sentinel check: bootstrap already completed → 410 Gone. ── if (await IsBootstrapCompletedAsync(redb, ct).ConfigureAwait(false)) { SetError(exchange, 410, "gone", "Bootstrap already completed."); return; } // ── 5. Resolve required services from the per-exchange scope. ── var applicationManager = _context.GetIdentityService(exchange); var groupService = _context.GetIdentityServiceOrDefault(exchange) ?? new GroupService(redb); var groupName = string.IsNullOrWhiteSpace(request.GroupName) ? _options.AdminGroupName : request.GroupName!; var scopeName = _options.AdminScope; var clientId = _options.WebClientId; try { // ── 6. Find-or-create OAuth scope (identity:admin). ── var scopeObj = await FindOrCreateScopeAsync(redb, scopeName, ct).ConfigureAwait(false); // ── 7. Find-or-create the admin group. ── long groupId = await FindOrCreateGroupAsync(redb, groupService, groupName, ct) .ConfigureAwait(false); // ── 8. Create the admin user via the relational UserProvider. ── // Uniqueness is enforced inside CreateUserAsync (throws on duplicate login). var coreUser = await redb.UserProvider.CreateUserAsync(new CreateUserRequest { Login = request.Email!, Password = request.Password!, Name = request.Email!, Email = request.Email, Enabled = true, }).ConfigureAwait(false); // OIDC profile extension (linked via key = _users._id) — required so that // password / authorization_code logins can hydrate id_token claims. // value_guid: stable, instance-unique public identity used as the OIDC `sub` claim. var oidcObj = new RedbObject(new UserProps { EmailVerified = true, }); oidcObj.Name = request.Email!; oidcObj.Key = coreUser.Id; oidcObj.Props.UserId = coreUser.Id; // V4-UNIQUE oidcObj.value_guid = Guid.NewGuid(); await redb.SaveAsync(oidcObj).ConfigureAwait(false); // ── 9. Add membership (skip-if-exists handled inside helper). ── var alreadyMember = await groupService.IsMemberAsync(groupId, coreUser.Id, ct) .ConfigureAwait(false); if (!alreadyMember) { await groupService.AddMemberAsync(groupId, coreUser.Id, role: "admin", ct: ct) .ConfigureAwait(false); } // ── 9b. Mirror the membership into the B.3 admin role. // Bootstrap pre-dates the system-roles registry (B.3 added // SeedSystemRolesListener with admin / system / everyone / // impersonator), so installs created on the old code path // have the admin user in the "admins" group but NOT in the // "admin" role — the two authorisation models stay parallel // instead of converging. Authorisation still works (group // carries the identity:admin scope) but UI surfaces that // enumerate role assignees (/admin/roles/{id} Users tab) // correctly show "no users" for admin. Wire the bootstrap // admin into the role here so the two models agree. // Idempotent: RoleService.AssignUserAsync no-ops if the // assignment already exists. try { var adminRole = await redb.Query() .Where(p => p.Name == "admin") .Where(p => p.Audience == "organization") .FirstOrDefaultAsync() .ConfigureAwait(false); if (adminRole is not null) { var roleSvc = new RoleService(redb); await roleSvc.AssignUserAsync(adminRole.Id, coreUser.Id, actingUserId: null, ct) .ConfigureAwait(false); } // If the admin role isn't seeded yet (race with // SeedSystemRolesListener on the same startup) just skip — // the BootstrapAdminBackfillListener (see Module/) catches // up on the next startup. } catch (Exception ex) { _securityLog?.LogWarning(ex, "B1 bootstrap-admin: failed to mirror admin user into admin role — operator can fix via /admin/roles UI; group-scope auth path remains functional."); } // ── 10. Create the canonical admin Web Console OIDC client. ── // Confidential / authorization_code + PKCE / refresh_token, with // backchannel_logout_uri stored as a custom property (OpenID Connect // Back-Channel Logout 1.0 §2.2). var existingApp = await applicationManager.FindByClientIdAsync(clientId, ct) .ConfigureAwait(false); if (existingApp is not null) { // Idempotent rollback path — Bootstrap_Idempotent_When_Group_Or_Scope_Already_Exists. // The flag must still be set, so we treat this as success and re-issue a fresh // client_secret only if no existing client. For an existing client we surface a // duplicate error to avoid silently rotating credentials. SetError(exchange, 409, "duplicate", $"OIDC client '{clientId}' already exists; bootstrap state is inconsistent — " + "delete the client manually or restore the bootstrap_completed flag."); return; } var clientSecret = GenerateClientSecret(); var descriptor = new OpenIddictApplicationDescriptor { ClientId = clientId, ClientSecret = clientSecret, ClientType = OpenIddictConstants.ClientTypes.Confidential, ConsentType = OpenIddictConstants.ConsentTypes.Implicit, DisplayName = "Identity Admin Web Console", ApplicationType = OpenIddictConstants.ApplicationTypes.Web, }; descriptor.RedirectUris.Add(new Uri(request.RedirectUri!)); descriptor.PostLogoutRedirectUris.Add(new Uri(request.PostLogoutRedirectUri!)); foreach (var permission in new[] { OpenIddictConstants.Permissions.Endpoints.Authorization, OpenIddictConstants.Permissions.Endpoints.Token, OpenIddictConstants.Permissions.Endpoints.EndSession, OpenIddictConstants.Permissions.GrantTypes.AuthorizationCode, OpenIddictConstants.Permissions.GrantTypes.RefreshToken, OpenIddictConstants.Permissions.ResponseTypes.Code, OpenIddictConstants.Permissions.Scopes.Email, OpenIddictConstants.Permissions.Scopes.Profile, OpenIddictConstants.Permissions.Scopes.Roles, OpenIddictConstants.Permissions.Prefixes.Scope + "openid", OpenIddictConstants.Permissions.Prefixes.Scope + "offline_access", OpenIddictConstants.Permissions.Prefixes.Scope + scopeName, }) { descriptor.Permissions.Add(permission); } descriptor.Requirements.Add(OpenIddictConstants.Requirements.Features.ProofKeyForCodeExchange); if (!string.IsNullOrWhiteSpace(request.BackchannelLogoutUri)) { // OpenIddict stores client metadata in System.Text.Json.JsonElement values // — build them via JsonDocument so the backchannel-logout dispatcher can // read them back out without an extra type conversion. descriptor.Properties["backchannel_logout_uri"] = JsonDocument.Parse(JsonSerializer.Serialize(request.BackchannelLogoutUri)).RootElement.Clone(); descriptor.Properties["backchannel_logout_session_required"] = JsonDocument.Parse("true").RootElement.Clone(); } var application = await applicationManager.CreateAsync(descriptor, ct) .ConfigureAwait(false); // ── 11. Set the bootstrap_completed sentinel. The UNIQUE index on // SystemFlag._name guarantees that two concurrent successful bootstraps // cannot both win — the second SaveAsync throws and the surrounding // WithRedbTx rolls back this entire processor's writes. ── try { await SetBootstrapCompletedAsync(redb, clientId, ct).ConfigureAwait(false); } catch (redb.Core.Exceptions.RedbUniqueViolationException violation) { IdentityProcessorHelpers.CountUniqueViolation(_context, exchange, violation); // Race lost — another caller's transaction committed the one-shot flag first // (core ValueUnique index, V4-UNIQUE). Map to 410. SetError(exchange, 410, "gone", "Bootstrap already completed (concurrent invocation won the race)."); return; } _securityLog?.LogWarning( "B1 bootstrap-admin completed: created admin user {UserId} in group {Group} " + "with OIDC client {ClientId} and scope {Scope}", coreUser.Id, groupName, clientId, scopeName); // ── 12. Build response — clientSecret is returned in plain ONLY here. ── exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new Dictionary(StringComparer.Ordinal) { ["userId"] = coreUser.Id, ["groupId"] = groupId, ["applicationId"] = clientId, ["clientSecret"] = clientSecret, ["scopeName"] = scopeName, }; exchange.Out.Headers["redbHttp.ResponseCode"] = 201; exchange.Properties["identity-event-type"] = IdentityAuditEventIds.ClientRegistered; exchange.Properties["identity-event-data"] = new { ClientId = clientId, Source = "bootstrap_admin", AdminUserId = coreUser.Id, AdminGroupId = groupId, Scope = scopeName, }; } catch (InvalidOperationException ex) when (ex.Message.Contains("already taken")) { // Login conflict — surface as 409 so operator can pick a different email. SetError(exchange, 409, "duplicate", $"User '{request.Email}' already exists; choose a different email or " + "restore the bootstrap_completed flag."); } } // ── Helpers ───────────────────────────────────────────────── private static BootstrapAdminRequest? ParseRequest(IExchange exchange) { try { return exchange.In.Body switch { BootstrapAdminRequest typed => typed, byte[] bytes => JsonSerializer.Deserialize(bytes, JsonOptions), string json => JsonSerializer.Deserialize(json, JsonOptions), Dictionary dict => DictToRequest(dict), _ => null, }; } catch (JsonException) { return null; } } private static BootstrapAdminRequest DictToRequest(Dictionary dict) => new() { // Canonical lower-invariant e-mail so the admin created here and a later self-register // resolve to one identity under the UX_users_email unique index (bootstrap uses email as login). Email = dict.GetValueOrDefault("email")?.ToString()?.Trim().ToLowerInvariant(), Password = dict.GetValueOrDefault("password")?.ToString(), GroupName = dict.GetValueOrDefault("groupName")?.ToString(), RedirectUri = dict.GetValueOrDefault("redirectUri")?.ToString(), PostLogoutRedirectUri = dict.GetValueOrDefault("postLogoutRedirectUri")?.ToString(), BackchannelLogoutUri = dict.GetValueOrDefault("backchannelLogoutUri")?.ToString(), }; private static string? ValidateRequest(BootstrapAdminRequest r) { if (string.IsNullOrWhiteSpace(r.Email)) return "Email is required."; if (string.IsNullOrWhiteSpace(r.Password) || r.Password!.Length < 8) return "Password is required and must be at least 8 characters."; if (string.IsNullOrWhiteSpace(r.RedirectUri) || !Uri.TryCreate(r.RedirectUri, UriKind.Absolute, out _)) return "RedirectUri is required and must be an absolute URI."; if (string.IsNullOrWhiteSpace(r.PostLogoutRedirectUri) || !Uri.TryCreate(r.PostLogoutRedirectUri, UriKind.Absolute, out _)) return "PostLogoutRedirectUri is required and must be an absolute URI."; if (!string.IsNullOrWhiteSpace(r.BackchannelLogoutUri) && !Uri.TryCreate(r.BackchannelLogoutUri, UriKind.Absolute, out _)) return "BackchannelLogoutUri must be an absolute URI when provided."; return null; } private static async Task IsBootstrapCompletedAsync(IRedbService redb, CancellationToken ct) { // V4-UNIQUE: the flag identity lives in ValueUnique (probe of the core unique index); // the Name lookup covers a legacy row the transition backfill has not repaired yet. var existing = await redb.Query() .WhereRedb(o => o.ValueUnique == FlagName) .FirstOrDefaultAsync() .ConfigureAwait(false); existing ??= await redb.Query() .WhereRedb(o => o.Name == FlagName) .FirstOrDefaultAsync() .ConfigureAwait(false); return existing is not null && existing.ValueBool == true; } private async Task SetBootstrapCompletedAsync(IRedbService redb, string clientId, CancellationToken ct) { var flag = new RedbObject(new IdentitySystemFlagProps()); flag.Name = FlagName; flag.ValueUnique = FlagName; // V4-UNIQUE: DB-enforced one-shot on every provider flag.value_bool = true; flag.value_datetime = _timeProvider.GetUtcNow().UtcDateTime; flag.value_string = clientId; flag.note = "B1 — bootstrap completed; remove this row + the OIDC client to re-bootstrap."; // First-wins by design: on a race the core ValueUnique index rejects this insert with // RedbUniqueViolationException, and the CALLER maps it to 410 Gone — the losing // bootstrap must NOT report success. Deliberately NOT SaveByUniqueAsync // (last-writer-wins would overwrite the winner's audit trail). await redb.SaveAsync(flag).ConfigureAwait(false); } private static async Task> FindOrCreateScopeAsync( IRedbService redb, string scopeName, CancellationToken ct) { var existing = await redb.GetByUniqueAsync(p => p.ScopeName, scopeName) .ConfigureAwait(false); if (existing is not null) return existing; var obj = new RedbObject(new ScopeProps { ScopeName = scopeName, Description = "Identity admin operations", }); obj.Name = scopeName; await redb.SaveAsync(obj).ConfigureAwait(false); return obj; } private static async Task FindOrCreateGroupAsync( IRedbService redb, IGroupService groupService, string groupName, CancellationToken ct) { // By the unique name key: names are unique across the tree, compared without case. var existing = await groupService.FindGroupByNameAsync(groupName, ct).ConfigureAwait(false); if (existing is not null) return existing.Id; var created = await groupService .CreateGroupAsync(groupName, groupType: "role", description: "Identity Administrators", ct: ct) .ConfigureAwait(false); return created.Id; } private static string GenerateClientSecret() { // 32 bytes of CSPRNG entropy → URL-safe base64 (43 chars, no padding). Span buffer = stackalloc byte[32]; RandomNumberGenerator.Fill(buffer); return Base64UrlNoPad(buffer); } private static string Base64UrlNoPad(ReadOnlySpan bytes) => Convert.ToBase64String(bytes) .TrimEnd('=') .Replace('+', '-') .Replace('/', '_'); private static bool FixedTimeStringEquals(string a, string b) { // Encode both to UTF-8 first; CryptographicOperations.FixedTimeEquals requires // equal-length spans, so we compare lengths only after producing the byte buffers // via a constant-time path. When lengths differ we still spin a comparison over // the longer span to keep the runtime independent of the supplied secret length. var bytesA = Encoding.UTF8.GetBytes(a); var bytesB = Encoding.UTF8.GetBytes(b); if (bytesA.Length != bytesB.Length) { // Force a length-independent dummy compare so timing remains stable. var dummy = new byte[bytesA.Length]; CryptographicOperations.FixedTimeEquals(bytesA, dummy); return false; } return CryptographicOperations.FixedTimeEquals(bytesA, bytesB); } private static void SetError(IExchange exchange, int httpStatus, string error, string description) { exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new Dictionary(StringComparer.Ordinal) { ["error"] = error, ["error_description"] = description, }; exchange.Out.Headers["redbHttp.ResponseCode"] = httpStatus; } } Path: redb-identity/src/redb.Identity.Core/Routes/Processors/ChangeEmailConfirmProcessor.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/Routes/Processors/ChangeEmailConfirmProcessor.cs ---- using System; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Core; using redb.Core.Models.Entities; using redb.Identity.Contracts.Routes; using redb.Identity.Contracts.Users; using redb.Identity.Core.ChangeEmail; using redb.Identity.Core.Models; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.RedbCore.Extensions; using CoreUpdateUserRequest = redb.Core.Models.Users.UpdateUserRequest; namespace redb.Identity.Core.Routes.Processors; /// /// N-4 (Session E, sub-step N4-7): anonymous change-of-e-mail confirmation backing /// direct-vm://identity-change-email-confirm. /// /// Verifies + atomically consumes the single-use token via /// . On success it loads the /// user, enforces the race-guard (current e-mail still matches the snapshot captured at /// issue time), re-checks uniqueness of the new address, then in one logical step /// updates _users.email to the new value AND flips /// to true. /// /// /// All failure modes return the generic OAuth-style invalid_token error; the /// granular reason is only persisted to audit /// () so an anonymous caller cannot /// enumerate which jti values exist. /// /// internal sealed class ChangeEmailConfirmProcessor : IProcessor { private readonly IRouteContext _context; private readonly IServiceProvider _sp; private readonly string? _redbName; public ChangeEmailConfirmProcessor(IRouteContext context, IServiceProvider sp, string? redbName = null) { _context = context; _sp = sp; _redbName = redbName; } public async Task Process(IExchange exchange, CancellationToken ct = default) { var request = exchange.In.Body as ChangeEmailConfirmRequest; if (request is null || string.IsNullOrWhiteSpace(request.Jti) || string.IsNullOrWhiteSpace(request.Token)) { Reject(exchange, 400, "validation_error", "Jti and Token are required."); return; } if (!Guid.TryParseExact(request.Jti, "N", out var jti) && !Guid.TryParse(request.Jti, out jti)) { EmitFailureAudit(exchange, "bad_jti_format", userId: 0); Reject(exchange, 400, "invalid_token", "The confirmation token is invalid or has expired."); return; } var logger = _sp.GetService()?.CreateLogger("ChangeEmailConfirmProcessor"); var store = _sp.GetRequiredService(); var verify = await store.VerifyAndConsumeAsync(jti, request.Token, ct).ConfigureAwait(false); if (!verify.Success) { EmitFailureAudit(exchange, verify.Reason, verify.UserId); Reject(exchange, 400, "invalid_token", "The confirmation token is invalid or has expired."); return; } var redb = _context.GetRedbService(_redbName, exchange); var user = await redb.UserProvider.GetUserByIdAsync(verify.UserId).ConfigureAwait(false); if (user is null) { EmitFailureAudit(exchange, "user_not_found", verify.UserId); Reject(exchange, 400, "invalid_token", "The confirmation token is invalid or has expired."); return; } // ── Race-guard: e-mail must not have changed since the token was issued ── var currentEmail = (user.Email ?? string.Empty).Trim().ToLowerInvariant(); if (!string.Equals(currentEmail, verify.CurrentEmail, StringComparison.Ordinal)) { EmitFailureAudit(exchange, "current_email_changed", user.Id); Reject(exchange, 400, "invalid_token", "The confirmation token is invalid or has expired."); return; } // ── Uniqueness re-check at commit time ── var existingUsers = await redb.UserProvider.GetUsersAsync(new redb.Core.Models.Users.UserSearchCriteria { EmailExact = verify.NewEmail, }).ConfigureAwait(false); if (existingUsers.Count > 0 && existingUsers[0].Id != user.Id) { EmitFailureAudit(exchange, "email_taken", user.Id); Reject(exchange, 400, "invalid_token", "The confirmation token is invalid or has expired."); return; } // ── Commit: swap address AND mark verified atomically ── var updated = await redb.UserProvider.UpdateUserAsync(user, new CoreUpdateUserRequest { Email = verify.NewEmail, }).ConfigureAwait(false); var oidcObj = await MeProcessorHelpers.LoadOidcProps(redb, user.Id).ConfigureAwait(false); if (oidcObj is null) { oidcObj = new RedbObject(new UserProps { EmailVerified = true, UserId = updated.Id }); oidcObj.name = updated.Login; oidcObj.key = updated.Id; oidcObj.value_guid = Guid.NewGuid(); } else { oidcObj.Props.EmailVerified = true; } await redb.SaveAsync(oidcObj).ConfigureAwait(false); exchange.Out ??= new Message(); exchange.Out.Body = new ChangeEmailConfirmResponse { Success = true }; exchange.Properties["identity-event-type"] = IdentityAuditEventIds.EmailChangeCompleted; exchange.Properties["identity-event-data"] = new { UserId = updated.Id, Login = updated.Login, OldEmail = verify.CurrentEmail, NewEmail = verify.NewEmail, Jti = jti.ToString("N"), }; } private static void EmitFailureAudit(IExchange exchange, string reason, long userId) { exchange.Properties["identity-event-type"] = IdentityAuditEventIds.EmailChangeFailed; exchange.Properties["identity-event-data"] = new { Reason = reason, UserId = userId }; } private static void Reject(IExchange exchange, int status, string error, string description) { exchange.Out ??= new Message(); exchange.Out.Headers["redbHttp.ResponseCode"] = status; exchange.Out.Body = new ChangeEmailConfirmResponse { Success = false, Error = error, ErrorDescription = description, }; } } Path: redb-identity/src/redb.Identity.Core/Routes/Processors/ChangeEmailRequestProcessor.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/Routes/Processors/ChangeEmailRequestProcessor.cs ---- using System; using System.Collections.Generic; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using redb.Core; using redb.Core.Query; using redb.Identity.Contracts.Routes; using redb.Identity.Contracts.Users; using redb.Identity.Core.ChangeEmail; using redb.Identity.Core.Configuration; using redb.Identity.Core.Models; using redb.Identity.Core.Services; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.RedbCore.Extensions; namespace redb.Identity.Core.Routes.Processors; /// /// N-4 (Session E, sub-step N4-7): authenticated change-of-e-mail dispatch backing /// direct-vm://identity-me-change-email-request. /// /// Caller user is derived from the access-token subject (via /// ); the body carries the requested /// NewEmail, the BFF's ClientId, and the page that will host the confirm /// form (CallerConfirmUrl). The URL must match the client's /// ApplicationProps.ChangeEmailUris whitelist exactly (string compare). /// /// /// The issued token is bound to BOTH the requested new address and a snapshot of the /// current address — the confirm step swaps them atomically only when no other path /// has mutated the e-mail in the meantime. /// /// internal sealed class ChangeEmailRequestProcessor : IProcessor { private readonly IRouteContext _context; private readonly IServiceProvider _sp; private readonly string? _redbName; public ChangeEmailRequestProcessor(IRouteContext context, IServiceProvider sp, string? redbName = null) { _context = context; _sp = sp; _redbName = redbName; } public async Task Process(IExchange exchange, CancellationToken ct = default) { var request = exchange.In.Body as ChangeEmailRequestRequest; if (request is null || string.IsNullOrWhiteSpace(request.NewEmail) || string.IsNullOrWhiteSpace(request.ClientId) || string.IsNullOrWhiteSpace(request.CallerConfirmUrl)) { MeProcessorHelpers.Reject(exchange, 400, "validation_error", "NewEmail, ClientId and CallerConfirmUrl are required."); return; } var emailErr = IdentityProcessorHelpers.ValidateEmail(request.NewEmail); if (emailErr is not null) { MeProcessorHelpers.Reject(exchange, 400, "validation_error", emailErr); return; } var callerUserId = MeProcessorHelpers.TryGetCallerUserId(exchange); if (callerUserId is null) { MeProcessorHelpers.Reject(exchange, 401, "unauthorized", "Caller subject missing or invalid."); return; } var redb = _context.GetRedbService(_redbName, exchange); var logger = _sp.GetService()?.CreateLogger("ChangeEmailRequestProcessor"); var user = await redb.UserProvider.GetUserByIdAsync(callerUserId.Value).ConfigureAwait(false); if (user is null || string.IsNullOrEmpty(user.Email)) { MeProcessorHelpers.Reject(exchange, 400, "invalid_request", "Caller has no e-mail on file."); return; } var newEmail = request.NewEmail.Trim().ToLowerInvariant(); var currentEmail = user.Email.Trim().ToLowerInvariant(); // No-op request: the user already has the address they're asking for. if (string.Equals(newEmail, currentEmail, StringComparison.Ordinal)) { MeProcessorHelpers.Reject(exchange, 400, "invalid_request", "The new address is identical to the current one."); return; } // ── Gate: client whitelist ──────────────────────────────────────────────── var app = await redb.GetByUniqueAsync(p => p.ClientId, request.ClientId) .ConfigureAwait(false); if (app is null) { MeProcessorHelpers.Reject(exchange, 400, "invalid_client", "Unknown client_id."); return; } var whitelist = app.Props.ChangeEmailUris; if (whitelist is null || whitelist.Length == 0) { MeProcessorHelpers.Reject(exchange, 400, "invalid_request", "Change-of-e-mail is not enabled for this client."); return; } var allowed = false; for (var i = 0; i < whitelist.Length; i++) { if (string.Equals(whitelist[i], request.CallerConfirmUrl, StringComparison.Ordinal)) { allowed = true; break; } } if (!allowed) { MeProcessorHelpers.Reject(exchange, 400, "invalid_request", "CallerConfirmUrl is not whitelisted for this client."); return; } // ── Uniqueness pre-check ────────────────────────────────────────────────── // The address-must-be-unique guard also runs at commit time (see confirm); doing // it here keeps the UX honest by failing fast before we send a confirmation // e-mail that would never be redeemable. var existingUsers = await redb.UserProvider.GetUsersAsync(new redb.Core.Models.Users.UserSearchCriteria { EmailExact = newEmail, }).ConfigureAwait(false); if (existingUsers.Count > 0 && existingUsers[0].Id != user.Id) { MeProcessorHelpers.Reject(exchange, 409, "email_taken", "Another account already uses this e-mail address."); return; } // ── Issue + dispatch ────────────────────────────────────────────────────── var store = _sp.GetRequiredService(); var emailChannel = _sp.GetService(); if (emailChannel is null) { logger?.LogError( "ChangeEmail-request: no IEmailNotificationChannel registered \u2014 dropping (host misconfiguration)"); MeProcessorHelpers.Reject(exchange, 503, "service_unavailable", "E-mail channel unavailable."); return; } var opts = _sp.GetRequiredService>().Value.ChangeEmail; var ttl = opts.TokenTtl; var issued = await store.IssueAsync( user.Id, newEmail, currentEmail, request.CallerConfirmUrl, ttl, opts.InvalidatePreviousTokensOnRequest, ct) .ConfigureAwait(false); var confirmLink = BuildConfirmLink(request.CallerConfirmUrl, issued.Jti, issued.PlaintextToken); var vars = new Dictionary(StringComparer.Ordinal) { ["userName"] = user.Name ?? user.Login, ["oldEmail"] = currentEmail, ["newEmail"] = newEmail, ["confirmLink"] = confirmLink, ["ttlHours"] = ((int)ttl.TotalHours).ToString(System.Globalization.CultureInfo.InvariantCulture), }; try { // The confirmation link MUST be delivered to the NEW address — the whole // point of verify-then-commit is that we will not trust the new address // until the user proves control of it. await emailChannel.SendTemplateAsync(newEmail, IdentityEmailTemplates.ChangeEmail, vars, ct) .ConfigureAwait(false); } catch (Exception ex) { logger?.LogError(ex, "ChangeEmail-request: e-mail delivery failed for user {UserId}", user.Id); MeProcessorHelpers.Reject(exchange, 502, "delivery_failed", "Could not dispatch confirmation e-mail."); return; } exchange.Out ??= new Message(); exchange.Out.Body = new ChangeEmailRequestResponse { Success = true }; exchange.Properties["identity-event-type"] = IdentityAuditEventIds.EmailChangeRequested; exchange.Properties["identity-event-data"] = new { UserId = user.Id, Login = user.Login, ClientId = request.ClientId, OldEmail = currentEmail, NewEmail = newEmail, Jti = issued.Jti.ToString("N"), ExpiresAt = issued.ExpiresAt, }; } private static string BuildConfirmLink(string callerConfirmUrl, Guid jti, string plaintextToken) { var sep = callerConfirmUrl.Contains('?') ? '&' : '?'; var sb = new StringBuilder(callerConfirmUrl.Length + 128); sb.Append(callerConfirmUrl); sb.Append(sep); sb.Append("token="); sb.Append(Uri.EscapeDataString(plaintextToken)); sb.Append("&jti="); sb.Append(jti.ToString("N")); return sb.ToString(); } } Path: redb-identity/src/redb.Identity.Core/Routes/Processors/ClaimDefinitionsManagementProcessor.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/Routes/Processors/ClaimDefinitionsManagementProcessor.cs ---- using Microsoft.Extensions.Logging; using redb.Core; using redb.Core.Models.Entities; using redb.Core.Query; using redb.Identity.Contracts.ClaimDefinitions; using redb.Identity.Contracts.Common; using redb.Identity.Contracts.Routes; using redb.Identity.Core.Models; using redb.Identity.Core.Module; using redb.Route.Abstractions; using redb.Route.RedbCore.Extensions; namespace redb.Identity.Core.Routes.Processors; /// /// S2 — admin CRUD for claim definitions. Routes via /// with the same /// operation-header convention every other admin processor uses /// (create / list / get / update / delete). /// /// /// Validation: /// * (ClaimName, Scope, ApplicationId) triplet must be unique. /// * Type must be one of the supported tokens (string / int / long / bool / /// datetime / url / email). /// * Scope = "application" requires a non-null ApplicationId; Scope = /// "global" requires ApplicationId = null. /// /// internal sealed class ClaimDefinitionsManagementProcessor : IProcessor { private readonly IRouteContext _context; private readonly string? _redbName; private readonly ILogger _logger; private static readonly HashSet AllowedTypes = new(StringComparer.OrdinalIgnoreCase) { "string", "int", "long", "bool", "datetime", "url", "email" }; public ClaimDefinitionsManagementProcessor(IRouteContext context, string? redbName, ILogger logger) { _context = context; _redbName = redbName; _logger = logger; } public async Task Process(IExchange exchange, CancellationToken ct = default) { var operation = exchange.In.GetHeader("operation") ?? ""; var redb = _context.GetRedbService(_redbName, exchange); switch (operation) { case "create": await Create(redb, exchange, ct); break; case "list": await List(redb, exchange, ct); break; case "get": await Get(redb, exchange, ct); break; case "update": await Update(redb, exchange, ct); break; case "delete": await Delete(redb, exchange, ct); break; default: exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new ErrorResponse { Error = "invalid_operation", ErrorDescription = $"Unknown operation: {operation}" }; break; } } private async Task Create(IRedbService redb, IExchange exchange, CancellationToken ct) { if (exchange.In.Body is not CreateClaimDefinitionRequest request) { SetError(exchange, "validation_error", "Body must be a CreateClaimDefinitionRequest"); return; } var claimName = request.ClaimName?.Trim() ?? ""; if (string.IsNullOrEmpty(claimName)) { SetError(exchange, "validation_error", "claimName is required"); return; } if (!AllowedTypes.Contains(request.Type)) { SetError(exchange, "validation_error", $"type must be one of: {string.Join(", ", AllowedTypes)}"); return; } if (request.Scope is not ("global" or "application")) { SetError(exchange, "validation_error", "scope must be 'global' or 'application'"); return; } if (request.Scope == "application" && (request.ApplicationId is null or 0)) { SetError(exchange, "validation_error", "scope='application' requires a non-null applicationId"); return; } if (request.Scope == "global" && request.ApplicationId is not null) { SetError(exchange, "validation_error", "scope='global' requires applicationId to be null"); return; } // Uniqueness check — (ClaimName, Scope, ApplicationId) var dupe = await redb.Query() .Where(p => p.ClaimName == claimName) .Where(p => p.Scope == request.Scope) .Where(p => p.ApplicationId == request.ApplicationId) .FirstOrDefaultAsync(); if (dupe is not null) { SetError(exchange, "conflict", $"A definition for claimName='{claimName}' with the same scope already exists (id={dupe.Id})"); return; } var obj = new RedbObject { name = claimName, Props = new ClaimDefinitionProps { ClaimName = claimName, DisplayName = string.IsNullOrWhiteSpace(request.DisplayName) ? null : request.DisplayName.Trim(), Description = request.Description, Type = request.Type, Required = request.Required, DefaultValue = request.DefaultValue, ValidationPattern = request.ValidationPattern, Scope = request.Scope, ApplicationId = request.ApplicationId, EmitOnIdToken = request.EmitOnIdToken, EmitOnAccessToken = request.EmitOnAccessToken, } }; obj.id = await redb.SaveAsync(obj); exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = MapToResponse(obj); } private async Task List(IRedbService redb, IExchange exchange, CancellationToken ct) { var request = exchange.In.Body as ListRequest ?? new ListRequest(); var count = Math.Min(request.Count, 200); // Optional filter — scope or applicationId from the body dict shape. string? scopeFilter = null; long? appIdFilter = null; if (exchange.In.Body is Dictionary dict) { if (dict.TryGetValue("scope", out var s) && s is string sStr && !string.IsNullOrEmpty(sStr)) scopeFilter = sStr; if (dict.TryGetValue("applicationId", out var a) && a is not null && long.TryParse(a.ToString(), out var parsedApp)) appIdFilter = parsedApp; } var q = redb.Query(); if (scopeFilter is not null) q = q.Where(p => p.Scope == scopeFilter); if (appIdFilter is not null) q = q.Where(p => p.ApplicationId == appIdFilter); var total = await q.CountAsync(); var items = await q .Skip(request.Offset) .Take(count) .ToListAsync(); exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new PagedResult { Items = items.Select(MapToResponse).ToList(), Total = total, Offset = request.Offset, Count = request.Count }; } private async Task Get(IRedbService redb, IExchange exchange, CancellationToken ct) { if (exchange.In.Body is not Dictionary dict || !dict.TryGetValue("id", out var idVal) || !long.TryParse(idVal?.ToString(), out var id) || id <= 0) { SetError(exchange, "validation_error", "id is required"); return; } var obj = await redb.LoadAsync(id); if (obj is null) { exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new ErrorResponse { Error = "not_found", ErrorDescription = $"ClaimDefinition {id} not found" }; return; } exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = MapToResponse(obj); } private async Task Update(IRedbService redb, IExchange exchange, CancellationToken ct) { if (exchange.In.Body is not UpdateClaimDefinitionRequest request || request.Id <= 0) { SetError(exchange, "validation_error", "id is required"); return; } var obj = await redb.LoadAsync(request.Id); if (obj is null) { exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new ErrorResponse { Error = "not_found", ErrorDescription = $"ClaimDefinition {request.Id} not found" }; return; } if (request.Type is not null) { if (!AllowedTypes.Contains(request.Type)) { SetError(exchange, "validation_error", $"type must be one of: {string.Join(", ", AllowedTypes)}"); return; } obj.Props.Type = request.Type; } if (request.DisplayName is not null) obj.Props.DisplayName = string.IsNullOrWhiteSpace(request.DisplayName) ? null : request.DisplayName.Trim(); if (request.Description is not null) obj.Props.Description = request.Description; if (request.Required.HasValue) obj.Props.Required = request.Required.Value; if (request.DefaultValue is not null) obj.Props.DefaultValue = request.DefaultValue; if (request.ValidationPattern is not null) obj.Props.ValidationPattern = request.ValidationPattern; if (request.EmitOnIdToken.HasValue) obj.Props.EmitOnIdToken = request.EmitOnIdToken.Value; if (request.EmitOnAccessToken.HasValue) obj.Props.EmitOnAccessToken = request.EmitOnAccessToken.Value; await redb.SaveAsync(obj); exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = MapToResponse(obj); } private async Task Delete(IRedbService redb, IExchange exchange, CancellationToken ct) { if (exchange.In.Body is not Dictionary dict || !dict.TryGetValue("id", out var idVal) || !long.TryParse(idVal?.ToString(), out var id) || id <= 0) { SetError(exchange, "validation_error", "id is required"); return; } // Delete only a record of this resource: the typed load answers null for an unknown id // and for the id of a record of another resource alike. if (await redb.LoadAsync(id) is null) { SetError(exchange, "not_found", $"ClaimDefinition {id} not found"); return; } await redb.DeleteAsync(new RedbObject { id = id }); exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new SuccessResponse(); } private static ClaimDefinitionResponse MapToResponse(RedbObject obj) => new() { Id = obj.Id, ClaimName = obj.Props.ClaimName, DisplayName = obj.Props.DisplayName, Description = obj.Props.Description, Type = obj.Props.Type, Required = obj.Props.Required, DefaultValue = obj.Props.DefaultValue, ValidationPattern = obj.Props.ValidationPattern, Scope = obj.Props.Scope, ApplicationId = obj.Props.ApplicationId, EmitOnIdToken = obj.Props.EmitOnIdToken, EmitOnAccessToken = obj.Props.EmitOnAccessToken, CreatedAt = obj.date_create, ModifiedAt = obj.date_modify, }; private static void SetError(IExchange exchange, string code, string description) { exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new ErrorResponse { Error = code, ErrorDescription = description }; } } Path: redb-identity/src/redb.Identity.Core/Routes/Processors/ClaimMapperManagementProcessor.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/Routes/Processors/ClaimMapperManagementProcessor.cs ---- using Microsoft.Extensions.DependencyInjection; using redb.Core; using redb.Core.Models.Entities; using redb.Core.Services; using redb.Identity.Contracts.ClaimMappers; using redb.Identity.Contracts.Common; using redb.Identity.Core.Models; using redb.Identity.Core.Module; using redb.Identity.Core.Services; using redb.Route.Abstractions; using redb.Route.RedbCore.Extensions; using redb.Identity.Contracts.Routes; namespace redb.Identity.Core.Routes.Processors; /// /// H5 (v1.0 DoD §5): CRUD management processor for declarative claim mapping rules /// (). Operations dispatched on the operation header: /// create | read | update | delete | list. list accepts an optional /// owner filter ("global", "application:{id}", "scope:{id}", /// or omitted for all). /// internal sealed class ClaimMapperManagementProcessor : IProcessor { private readonly IRouteContext _context; private readonly string? _redbName; public ClaimMapperManagementProcessor(IRouteContext context, string? redbName = null) { _context = context; _redbName = redbName; } public async Task Process(IExchange exchange, CancellationToken ct = default) { var redb = _context.GetRedbService(_redbName, exchange); var operation = exchange.In.GetHeader("operation") ?? throw new InvalidOperationException("Missing 'operation' header"); switch (operation) { case "create": await Create(redb, exchange, ct); break; case "read": await Read(redb, exchange, ct); break; case "update": await Update(redb, exchange, ct); break; case "delete": await Delete(redb, exchange, ct); break; case "list": await List(redb, exchange, ct); break; default: exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new ErrorResponse { Error = "invalid_operation", ErrorDescription = $"Unknown operation: {operation}" }; break; } } private static async Task Create(IRedbService redb, IExchange exchange, CancellationToken ct) { var request = exchange.In.Body as CreateClaimMapperRequest; if (request is null) { SetError(exchange, "validation_error", "Request body is required"); return; } var err = IdentityProcessorHelpers.ValidateDisplayName(request.Name, "Name"); if (err != null) { SetError(exchange, "validation_error", err); return; } if (string.IsNullOrWhiteSpace(request.ClaimType)) { SetError(exchange, "validation_error", "ClaimType is required"); return; } var sourceErr = ValidateSource(request.SourceKind, request.SourcePath, request.ConstantValue); if (sourceErr != null) { SetError(exchange, "validation_error", sourceErr); return; } long? parentId; try { parentId = ParseOwner(request.Owner); } catch (FormatException ex) { SetError(exchange, "validation_error", ex.Message); return; } // Verify parent exists when not global if (parentId is long pid) { var parentExists = await redb.LoadAsync(pid).ConfigureAwait(false) is not null || await redb.LoadAsync(pid).ConfigureAwait(false) is not null; if (!parentExists) { SetError(exchange, "not_found", $"Owner object {pid} not found (must be Application or ClaimScope)"); return; } } var obj = new RedbObject(new ClaimMapperProps { ClaimType = request.ClaimType.Trim(), SourceKind = request.SourceKind.Trim(), SourcePath = request.SourcePath, ConstantValue = request.ConstantValue, RequiredScopes = request.RequiredScopes, Destinations = request.Destinations, Required = request.Required, Order = request.Order, Enabled = request.Enabled, Description = request.Description, }); obj.Name = request.Name; obj.ParentId = parentId; await redb.SaveAsync(obj).ConfigureAwait(false); exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = MapToResponse(obj); exchange.Properties["identity-event-type"] = IdentityAuditEventIds.ClaimMapperCreated; exchange.Properties["identity-event-data"] = new { Id = obj.Id, request.ClaimType, Owner = OwnerString(parentId) }; } private static async Task Read(IRedbService redb, IExchange exchange, CancellationToken ct) { if (exchange.In.Body is not Dictionary dict || !dict.TryGetValue("id", out var idVal) || idVal == null || !long.TryParse(idVal.ToString(), out var id) || id <= 0) { SetError(exchange, "validation_error", "Id is required"); return; } var obj = await redb.LoadAsync(id).ConfigureAwait(false); if (obj is null) { SetError(exchange, "not_found", $"ClaimMapper {id} not found"); return; } exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = MapToResponse(obj); } private static async Task Update(IRedbService redb, IExchange exchange, CancellationToken ct) { var request = exchange.In.Body as UpdateClaimMapperRequest; if (request is null || !long.TryParse(request.Id, out var id) || id <= 0) { SetError(exchange, "validation_error", "Id is required"); return; } var obj = await redb.LoadAsync(id).ConfigureAwait(false); if (obj is null) { SetError(exchange, "not_found", $"ClaimMapper {id} not found"); return; } if (request.Name != null) obj.Name = request.Name; if (request.ClaimType != null) { if (string.IsNullOrWhiteSpace(request.ClaimType)) { SetError(exchange, "validation_error", "ClaimType cannot be empty"); return; } obj.Props.ClaimType = request.ClaimType.Trim(); } var nextSourceKind = request.SourceKind ?? obj.Props.SourceKind; var nextSourcePath = request.SourcePath ?? obj.Props.SourcePath; var nextConstantValue = request.ConstantValue ?? obj.Props.ConstantValue; if (request.SourceKind != null || request.SourcePath != null || request.ConstantValue != null) { var srcErr = ValidateSource(nextSourceKind, nextSourcePath, nextConstantValue); if (srcErr != null) { SetError(exchange, "validation_error", srcErr); return; } obj.Props.SourceKind = nextSourceKind; obj.Props.SourcePath = nextSourcePath; obj.Props.ConstantValue = nextConstantValue; } if (request.RequiredScopes != null) obj.Props.RequiredScopes = request.RequiredScopes; if (request.Destinations != null) obj.Props.Destinations = request.Destinations; if (request.Required.HasValue) obj.Props.Required = request.Required.Value; if (request.Order.HasValue) obj.Props.Order = request.Order.Value; if (request.Enabled.HasValue) obj.Props.Enabled = request.Enabled.Value; if (request.Description != null) obj.Props.Description = request.Description; await redb.SaveAsync(obj).ConfigureAwait(false); exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = MapToResponse(obj); exchange.Properties["identity-event-type"] = IdentityAuditEventIds.ClaimMapperUpdated; exchange.Properties["identity-event-data"] = new { Id = id, obj.Props.ClaimType }; } private async Task Delete(IRedbService redb, IExchange exchange, CancellationToken ct) { if (exchange.In.Body is not Dictionary dict || !dict.TryGetValue("id", out var idVal) || idVal == null || !long.TryParse(idVal.ToString(), out var id) || id <= 0) { SetError(exchange, "validation_error", "Id is required"); return; } var bg = _context.GetIdentityServiceOrDefault(exchange); // Delete only a record of this resource: the typed load answers null for an unknown id // and for the id of a record of another resource alike. if (await redb.LoadAsync(id).ConfigureAwait(false) is null) { SetError(exchange, "not_found", $"ClaimMapper {id} not found"); return; } await IdentityDeletionHelper.DeleteAsync(redb, bg, id).ConfigureAwait(false); exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new SuccessResponse(); exchange.Properties["identity-event-type"] = IdentityAuditEventIds.ClaimMapperDeleted; exchange.Properties["identity-event-data"] = new { Id = id }; } private static async Task List(IRedbService redb, IExchange exchange, CancellationToken ct) { var request = exchange.In.Body as ListRequest ?? new ListRequest(); // owner filter via header OR body extra-field var owner = exchange.In.GetHeader("owner"); if (string.IsNullOrEmpty(owner) && exchange.In.Body is Dictionary bodyDict && bodyDict.TryGetValue("owner", out var ownerVal) && ownerVal is string s) owner = s; var query = redb.Query(); if (!string.IsNullOrEmpty(owner)) { long? parentFilter; try { parentFilter = ParseOwner(owner); } catch (FormatException ex) { SetError(exchange, "validation_error", ex.Message); return; } if (parentFilter is null) query = query.WhereRedb(o => o.ParentId == null); else { var pid = parentFilter.Value; query = query.WhereRedb(o => o.ParentId == pid); } } query = query.OrderByRedb(o => o.Id); var total = await query.CountAsync().ConfigureAwait(false); var count = Math.Min(request.Count, 100); var items = await query.Skip(request.Offset).Take(count).ToListAsync().ConfigureAwait(false); exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new PagedResult { Items = items.Select(MapToResponse).ToList(), Total = total, Offset = request.Offset, Count = request.Count, }; } private static void SetError(IExchange exchange, string error, string description) => IdentityProcessorHelpers.SetError(exchange, error, description); private static string? ValidateSource(string? kind, string? path, string? constantValue) => kind switch { "Constant" => string.IsNullOrEmpty(constantValue) ? "ConstantValue is required when SourceKind=Constant" : null, "CustomClaim" or "UserProps" => string.IsNullOrEmpty(path) ? "SourcePath is required when SourceKind=CustomClaim or UserProps" : null, null or "" => "SourceKind is required", _ => $"Unknown SourceKind '{kind}' (expected: Constant | CustomClaim | UserProps)" }; /// /// Parses the owner string into a parent_id value. /// /// null / empty / "global" → null (global rule) /// application:{id} → application object id /// scope:{id} → ClaimScope object id /// /// private static long? ParseOwner(string? owner) { if (string.IsNullOrWhiteSpace(owner) || owner.Equals("global", StringComparison.OrdinalIgnoreCase)) return null; var sep = owner.IndexOf(':'); if (sep <= 0) throw new FormatException($"Owner '{owner}' must be 'global', 'application:{{id}}' or 'scope:{{id}}'"); var prefix = owner[..sep].Trim().ToLowerInvariant(); var rest = owner[(sep + 1)..].Trim(); if (prefix is not ("application" or "scope")) throw new FormatException($"Unknown owner prefix '{prefix}' (expected: application | scope)"); if (!long.TryParse(rest, out var id) || id <= 0) throw new FormatException($"Owner id '{rest}' is not a positive integer"); return id; } private static string OwnerString(long? parentId) => parentId is null ? "global" : $"id:{parentId.Value}"; private static ClaimMapperResponse MapToResponse(RedbObject obj) => new() { Id = obj.Id.ToString(), Name = obj.Name, ClaimType = obj.Props.ClaimType, SourceKind = obj.Props.SourceKind, SourcePath = obj.Props.SourcePath, ConstantValue = obj.Props.ConstantValue, RequiredScopes = obj.Props.RequiredScopes, Destinations = obj.Props.Destinations, Required = obj.Props.Required, Order = obj.Props.Order, Enabled = obj.Props.Enabled, Description = obj.Props.Description, Owner = obj.ParentId is null ? "global" : $"id:{obj.ParentId.Value}", }; } Path: redb-identity/src/redb.Identity.Core/Routes/Processors/ClaimScopeManagementProcessor.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/Routes/Processors/ClaimScopeManagementProcessor.cs ---- using Microsoft.Extensions.DependencyInjection; using redb.Core; using redb.Core.Models.Entities; using redb.Core.Services; using redb.Identity.Contracts.ClaimMappers; using redb.Identity.Contracts.Common; using redb.Identity.Core.Models; using redb.Identity.Core.Module; using redb.Identity.Core.Services; using redb.Route.Abstractions; using redb.Route.RedbCore.Extensions; using redb.Identity.Contracts.Routes; namespace redb.Identity.Core.Routes.Processors; /// /// H5 (v1.0 DoD §5): CRUD management processor for reusable Client Scopes /// () AND for Application↔Scope assignments /// (). /// /// Operations dispatched on the operation header: /// /// Scope CRUD: create | read | update | delete | list. /// Assignments: assign | unassign | list-assignments /// (the latter requires header applicationId). /// /// /// internal sealed class ClaimScopeManagementProcessor : IProcessor { private readonly IRouteContext _context; private readonly string? _redbName; public ClaimScopeManagementProcessor(IRouteContext context, string? redbName = null) { _context = context; _redbName = redbName; } public async Task Process(IExchange exchange, CancellationToken ct = default) { var redb = _context.GetRedbService(_redbName, exchange); var operation = exchange.In.GetHeader("operation") ?? throw new InvalidOperationException("Missing 'operation' header"); switch (operation) { case "create": await CreateScope(redb, exchange); break; case "read": await ReadScope(redb, exchange); break; case "update": await UpdateScope(redb, exchange); break; case "delete": await DeleteScope(redb, exchange); break; case "list": await ListScopes(redb, exchange); break; case "assign": await Assign(redb, exchange); break; case "unassign": await Unassign(redb, exchange); break; case "list-assignments": await ListAssignments(redb, exchange); break; default: exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new ErrorResponse { Error = "invalid_operation", ErrorDescription = $"Unknown operation: {operation}" }; break; } } // ── Scope CRUD ── private async Task CreateScope(IRedbService redb, IExchange exchange) { var request = exchange.In.Body as CreateClaimScopeRequest; if (request is null) { SetError(exchange, "validation_error", "Request body is required"); return; } var err = IdentityProcessorHelpers.ValidateIdentifier(request.Name, "Name"); if (err != null) { SetError(exchange, "validation_error", err); return; } err = IdentityProcessorHelpers.ValidateDisplayName(request.DisplayName, "DisplayName"); if (err != null) { SetError(exchange, "validation_error", err); return; } err = IdentityProcessorHelpers.ValidateDescription(request.Description, "Description"); if (err != null) { SetError(exchange, "validation_error", err); return; } var existing = await redb.GetByUniqueAsync(p => p.ScopeName, request.Name) .ConfigureAwait(false); if (existing != null) { SetError(exchange, "duplicate", $"ClaimScope '{request.Name}' already exists"); return; } var obj = new RedbObject(new ClaimScopeProps { ScopeName = request.Name, Description = request.Description, Enabled = request.Enabled, }); obj.Name = request.DisplayName ?? request.Name; try { await redb.SaveAsync(obj).ConfigureAwait(false); } catch (redb.Core.Exceptions.RedbUniqueViolationException violation) { IdentityProcessorHelpers.CountUniqueViolation(_context, exchange, violation); SetError(exchange, "duplicate", $"ClaimScope '{request.Name}' already exists"); return; } exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = MapScope(obj); exchange.Properties["identity-event-type"] = IdentityAuditEventIds.ClaimScopeCreated; exchange.Properties["identity-event-data"] = new { Id = obj.Id, Name = request.Name }; } private static async Task ReadScope(IRedbService redb, IExchange exchange) { RedbObject? scope = null; if (exchange.In.Body is Dictionary dict) { if (dict.TryGetValue("id", out var idVal) && idVal != null && long.TryParse(idVal.ToString(), out var id) && id > 0) scope = (await redb.LoadAsync(id).ConfigureAwait(false)); else if (dict.TryGetValue("name", out var nVal) && nVal is string name && !string.IsNullOrEmpty(name)) scope = await redb.GetByUniqueAsync(p => p.ScopeName, name).ConfigureAwait(false); else { SetError(exchange, "validation_error", "Either 'id' or 'name' required"); return; } } else { SetError(exchange, "validation_error", "Expected body with 'id' or 'name'"); return; } if (scope is null) { SetError(exchange, "not_found", "ClaimScope not found"); return; } exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = MapScope(scope); } private static async Task UpdateScope(IRedbService redb, IExchange exchange) { var request = exchange.In.Body as UpdateClaimScopeRequest; if (request is null || !long.TryParse(request.Id, out var id) || id <= 0) { SetError(exchange, "validation_error", "Id is required"); return; } var scope = (await redb.LoadAsync(id).ConfigureAwait(false)); if (scope is null) { SetError(exchange, "not_found", $"ClaimScope {id} not found"); return; } if (request.DisplayName != null) { var err = IdentityProcessorHelpers.ValidateDisplayName(request.DisplayName, "DisplayName"); if (err != null) { SetError(exchange, "validation_error", err); return; } scope.Name = request.DisplayName; } if (request.Description != null) { var err = IdentityProcessorHelpers.ValidateDescription(request.Description, "Description"); if (err != null) { SetError(exchange, "validation_error", err); return; } scope.Props.Description = request.Description; } if (request.Enabled.HasValue) scope.Props.Enabled = request.Enabled.Value; await redb.SaveAsync(scope).ConfigureAwait(false); exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = MapScope(scope); exchange.Properties["identity-event-type"] = IdentityAuditEventIds.ClaimScopeUpdated; exchange.Properties["identity-event-data"] = new { Id = id, scope.Props.ScopeName }; } private async Task DeleteScope(IRedbService redb, IExchange exchange) { if (exchange.In.Body is not Dictionary dict || !dict.TryGetValue("id", out var idVal) || idVal == null || !long.TryParse(idVal.ToString(), out var id) || id <= 0) { SetError(exchange, "validation_error", "Id is required"); return; } // Delete only a record of this resource: the typed load answers null for an unknown id // and for the id of a record of another resource alike. if (await redb.LoadAsync(id).ConfigureAwait(false) is null) { SetError(exchange, "not_found", "ClaimScope not found"); return; } // Cascade: delete all assignments referencing this scope, plus all mapper rules under it. var assignments = await redb.Query() .WhereRedb(o => o.Key == id).ToListAsync().ConfigureAwait(false); // (assignments use `key=ApplicationId` for the index; assigned ScopeId is in props) assignments.AddRange(await redb.Query() .Where(p => p.ScopeId == id).ToListAsync().ConfigureAwait(false)); var bg = _context.GetIdentityServiceOrDefault(exchange); var assignmentIds = assignments.Select(a => a.Id).Distinct().ToList(); foreach (var aid in assignmentIds) await IdentityDeletionHelper.DeleteAsync(redb, bg, aid).ConfigureAwait(false); var childMappers = await redb.Query() .WhereRedb(o => o.ParentId == id).ToListAsync().ConfigureAwait(false); foreach (var cm in childMappers) await IdentityDeletionHelper.DeleteAsync(redb, bg, cm.Id).ConfigureAwait(false); await IdentityDeletionHelper.DeleteAsync(redb, bg, id).ConfigureAwait(false); exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new ClaimScopeDeletedResponse { CascadedAssignments = assignmentIds.Count, CascadedMappers = childMappers.Count }; exchange.Properties["identity-event-type"] = IdentityAuditEventIds.ClaimScopeDeleted; exchange.Properties["identity-event-data"] = new { Id = id }; } private static async Task ListScopes(IRedbService redb, IExchange exchange) { var request = exchange.In.Body as ListRequest ?? new ListRequest(); var query = redb.Query().OrderByRedb(o => o.Id); var total = await query.CountAsync().ConfigureAwait(false); var count = Math.Min(request.Count, 100); var items = await query.Skip(request.Offset).Take(count).ToListAsync().ConfigureAwait(false); exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new PagedResult { Items = items.Select(MapScope).ToList(), Total = total, Offset = request.Offset, Count = request.Count, }; } // ── Assignments ── private static async Task Assign(IRedbService redb, IExchange exchange) { var request = exchange.In.Body as AssignClaimScopeRequest; if (request is null) { SetError(exchange, "validation_error", "Request body is required"); return; } if (!long.TryParse(request.ApplicationId, out var appId) || appId <= 0) { SetError(exchange, "validation_error", "applicationId must be a positive integer"); return; } if (!long.TryParse(request.ScopeId, out var scopeId) || scopeId <= 0) { SetError(exchange, "validation_error", "scopeId must be a positive integer"); return; } var app = await redb.LoadAsync(appId).ConfigureAwait(false); if (app is null) { SetError(exchange, "not_found", $"Application {appId} not found"); return; } var scope = await redb.LoadAsync(scopeId).ConfigureAwait(false); if (scope is null) { SetError(exchange, "not_found", $"ClaimScope {scopeId} not found"); return; } // Idempotent: if assignment already exists, return it var existing = await redb.Query() .WhereRedb(o => o.Key == appId) .Where(p => p.ScopeId == scopeId) .FirstOrDefaultAsync().ConfigureAwait(false); if (existing is not null) { exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = MapAssignment(existing, scope); return; } var now = DateTimeOffset.UtcNow; var assignment = new RedbObject(new ClaimScopeAssignmentProps { ApplicationId = appId, ScopeId = scopeId, AssignedAt = now, }); assignment.Name = $"{appId}::{scopeId}"; assignment.key = appId; await redb.SaveAsync(assignment).ConfigureAwait(false); exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = MapAssignment(assignment, scope); exchange.Properties["identity-event-type"] = IdentityAuditEventIds.ClaimScopeAssigned; exchange.Properties["identity-event-data"] = new { ApplicationId = appId, ScopeId = scopeId }; } private async Task Unassign(IRedbService redb, IExchange exchange) { if (exchange.In.Body is not Dictionary dict) { SetError(exchange, "validation_error", "Body required"); return; } long appId = 0, scopeId = 0, assignmentId = 0; if (dict.TryGetValue("id", out var idVal) && idVal != null && long.TryParse(idVal.ToString(), out var aid) && aid > 0) assignmentId = aid; if (dict.TryGetValue("applicationId", out var appVal) && appVal != null && long.TryParse(appVal.ToString(), out var av) && av > 0) appId = av; if (dict.TryGetValue("scopeId", out var sv) && sv != null && long.TryParse(sv.ToString(), out var svv) && svv > 0) scopeId = svv; if (assignmentId == 0) { if (appId == 0 || scopeId == 0) { SetError(exchange, "validation_error", "Either id, or both applicationId+scopeId required"); return; } var existing = await redb.Query() .WhereRedb(o => o.Key == appId) .Where(p => p.ScopeId == scopeId) .FirstOrDefaultAsync().ConfigureAwait(false); if (existing is null) { SetError(exchange, "not_found", "Assignment not found"); return; } assignmentId = existing.Id; appId = existing.Props.ApplicationId; scopeId = existing.Props.ScopeId; } else { var existing = await redb.LoadAsync(assignmentId).ConfigureAwait(false); if (existing is null) { SetError(exchange, "not_found", "Assignment not found"); return; } appId = existing.Props.ApplicationId; scopeId = existing.Props.ScopeId; } var bg = _context.GetIdentityServiceOrDefault(exchange); await IdentityDeletionHelper.DeleteAsync(redb, bg, assignmentId).ConfigureAwait(false); exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new SuccessResponse(); exchange.Properties["identity-event-type"] = IdentityAuditEventIds.ClaimScopeUnassigned; exchange.Properties["identity-event-data"] = new { ApplicationId = appId, ScopeId = scopeId }; } private static async Task ListAssignments(IRedbService redb, IExchange exchange) { var appHeader = exchange.In.GetHeader("applicationId"); if (string.IsNullOrEmpty(appHeader) && exchange.In.Body is Dictionary bodyDict && bodyDict.TryGetValue("applicationId", out var appVal) && appVal != null) appHeader = appVal.ToString(); if (string.IsNullOrEmpty(appHeader) || !long.TryParse(appHeader, out var appId) || appId <= 0) { SetError(exchange, "validation_error", "applicationId (positive integer) is required"); return; } var assignments = await redb.Query() .WhereRedb(o => o.Key == appId).ToListAsync().ConfigureAwait(false); var scopeIds = assignments.Select(a => a.Props.ScopeId).Distinct().ToList(); var scopes = scopeIds.Count == 0 ? new List>() : await redb.Query() .WhereInRedb(o => o.Id, scopeIds).ToListAsync().ConfigureAwait(false); var scopeMap = scopes.ToDictionary(s => s.Id); exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new PagedResult { Items = assignments .Select(a => MapAssignment(a, scopeMap.GetValueOrDefault(a.Props.ScopeId))) .ToList(), Total = assignments.Count, Offset = 0, Count = assignments.Count, }; } // ── helpers ── private static void SetError(IExchange exchange, string error, string description) => IdentityProcessorHelpers.SetError(exchange, error, description); private static ClaimScopeResponse MapScope(RedbObject obj) => new() { Id = obj.Id.ToString(), Name = obj.Props.ScopeName, DisplayName = obj.Name, Description = obj.Props.Description, Enabled = obj.Props.Enabled, }; private static ClaimScopeAssignmentResponse MapAssignment( RedbObject obj, RedbObject? scope) => new() { Id = obj.Id.ToString(), ApplicationId = obj.Props.ApplicationId.ToString(), ScopeId = obj.Props.ScopeId.ToString(), ScopeName = scope?.Props.ScopeName, AssignedAt = obj.Props.AssignedAt, AssignedBy = obj.Props.AssignedBy?.ToString(), }; } Path: redb-identity/src/redb.Identity.Core/Routes/Processors/ClientRegistrationManagementProcessor.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/Routes/Processors/ClientRegistrationManagementProcessor.cs ---- using System.Security.Cryptography; using System.Text; using System.Text.Json; using Microsoft.Extensions.DependencyInjection; using OpenIddict.Abstractions; using redb.Core; using redb.Core.Models.Entities; using redb.Identity.Contracts.Registration; using redb.Identity.Core.Models; using redb.Identity.Core.Module; using redb.Route.Abstractions; using redb.Route.RedbCore.Extensions; using redb.Identity.Contracts.Routes; namespace redb.Identity.Core.Routes.Processors; /// /// Z2 (RFC 7592): Client configuration endpoint — GET/PUT/DELETE /connect/register/{client_id}. /// /// Dispatches on the operation header (read, update, delete). The /// client_id header is populated by the HTTP facade from the route segment. Authorizes /// via the bearer registration_access_token issued at DCR time and stored as SHA-256 /// hash on . /// /// /// Returns RFC 7592-compliant errors: invalid_token (401), invalid_client_id (404), /// invalid_client_metadata (400). /// /// internal sealed class ClientRegistrationManagementProcessor : IProcessor { private readonly IRouteContext _context; private readonly string? _redbName; private readonly redb.Identity.Core.Configuration.RedbIdentityOptions _options; public ClientRegistrationManagementProcessor( IRouteContext context, string? redbName = null, redb.Identity.Core.Configuration.RedbIdentityOptions? options = null) { _context = context; _redbName = redbName; _options = options ?? new redb.Identity.Core.Configuration.RedbIdentityOptions(); } public async Task Process(IExchange exchange, CancellationToken ct = default) { var operation = exchange.In.GetHeader("operation"); var clientId = exchange.In.GetHeader("client_id"); if (string.IsNullOrEmpty(clientId)) { SetError(exchange, "invalid_request", "Missing client_id", 400); return; } // Resolve bearer RAT from request. Headers are stripped by ExtractBearerToken upstream; // direct-vm tests may pass raw Authorization. var presentedToken = exchange.In.GetHeader("access_token"); if (string.IsNullOrEmpty(presentedToken)) { var auth = exchange.In.GetHeader("Authorization"); if (auth is not null && auth.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase)) presentedToken = auth[7..]; } if (string.IsNullOrEmpty(presentedToken)) { SetError(exchange, "invalid_token", "Missing registration_access_token", 401); return; } var manager = _context.GetIdentityService(exchange); var app = await manager.FindByClientIdAsync(clientId, ct) as RedbObject; if (app is null) { SetError(exchange, "invalid_client_id", "Unknown client_id", 404); return; } var storedHash = app.Props.RegistrationAccessTokenHash; if (string.IsNullOrEmpty(storedHash)) { // Client was created via admin API, not DCR — RFC 7592 §3 mgmt endpoint does not apply. SetError(exchange, "invalid_token", "Client not eligible for registration management", 401); return; } var presentedHash = ComputeSha256Hex(presentedToken); if (!FixedTimeHexEquals(presentedHash, storedHash)) { SetError(exchange, "invalid_token", "Registration access token mismatch", 401); return; } switch (operation) { case "read": await Read(app, exchange); break; case "update": await Update(manager, app, exchange, ct); break; case "delete": await Delete(manager, app, exchange, ct); break; default: SetError(exchange, "invalid_request", $"Unsupported operation '{operation}'", 400); break; } } private static Task Read(RedbObject app, IExchange exchange) { var response = MapToResponse(app); exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = SerializeResponse(response); exchange.Out.Headers["redbHttp.ResponseCode"] = 200; return Task.CompletedTask; } private async Task Update( IOpenIddictApplicationManager manager, RedbObject app, IExchange exchange, CancellationToken ct) { if (exchange.In.Body is not DynamicRegistrationRequest request) { // Mirror DCR processor — also accept JSON bytes / string bodies from HTTP facade. DynamicRegistrationRequest? parsed = null; try { parsed = exchange.In.Body switch { byte[] bytes => JsonSerializer.Deserialize(bytes), string json => JsonSerializer.Deserialize(json), _ => null }; } catch (JsonException) { parsed = null; } if (parsed is null) { SetError(exchange, "invalid_client_metadata", "Request body must be a JSON registration object", 400); return; } request = parsed; } // Apply mutable metadata fields — identity (client_id, client_secret, RAT hash) is untouched. if (request.ClientName is not null) app.name = request.ClientName; if (request.RedirectUris is { Length: > 0 }) app.Props.RedirectUris = request.RedirectUris; if (request.PostLogoutRedirectUris is { Length: > 0 }) app.Props.PostLogoutRedirectUris = request.PostLogoutRedirectUris; if (request.RequestUris is { Length: > 0 }) { var uriErr = IdentityProcessorHelpers.ValidateRequestUris(request.RequestUris); if (uriErr is not null) { SetError(exchange, "invalid_client_metadata", uriErr, 400); return; } app.Props.RequestUris = request.RequestUris.Distinct(StringComparer.Ordinal).ToArray(); } // Keys and the request object algorithm: read as at registration, stored, and answered from storage. if (request.JsonWebKeySet is not null || !string.IsNullOrWhiteSpace(request.JsonWebKeySetUri)) { var (keysError, keys) = await DcrClientMetadata.ReadKeysAsync(request, _options.ClientKeys, ct).ConfigureAwait(false); if (keysError is not null) { SetError(exchange, "invalid_client_metadata", keysError, 400); return; } // One source at a time: the new one replaces the other. app.Props.JsonWebKeySet = keys.JwksJson; app.Props.JwksUri = keys.JwksUri; } if (request.RequestObjectSigningAlg is not null) { var algError = DcrClientMetadata.ValidateRequestObjectSigningAlg(request.RequestObjectSigningAlg, _options.Jar); if (algError is not null) { SetError(exchange, "invalid_client_metadata", algError, 400); return; } app.Props.RequestObjectSigningAlg = request.RequestObjectSigningAlg; } var redb = _context.GetRedbService(_redbName, exchange); await redb.SaveAsync(app).ConfigureAwait(false); exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = SerializeResponse(MapToResponse(app)); exchange.Out.Headers["redbHttp.ResponseCode"] = 200; exchange.Properties["identity-event-type"] = IdentityAuditEventIds.ClientUpdated; exchange.Properties["identity-event-data"] = new { ClientId = app.Props.ClientId, Source = "dynamic_registration" }; } private async Task Delete( IOpenIddictApplicationManager manager, RedbObject app, IExchange exchange, CancellationToken ct) { // The client's tokens stop working with it (the resource side checks the stored entry). if (_context.GetIdentityServiceOrDefault(exchange) is { } tokens) await tokens.RevokeByApplicationIdAsync(app.id.ToString(System.Globalization.CultureInfo.InvariantCulture), ct); await manager.DeleteAsync(app, ct); exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Headers["redbHttp.ResponseCode"] = 204; exchange.Properties["identity-event-type"] = IdentityAuditEventIds.ClientDeleted; exchange.Properties["identity-event-data"] = new { ClientId = app.Props.ClientId, Source = "dynamic_registration" }; } private static DynamicRegistrationResponse MapToResponse(RedbObject app) { var perms = app.Props.Permissions ?? Array.Empty(); var grantTypes = perms.Where(p => p.StartsWith("gt:", StringComparison.Ordinal)) .Select(p => p[3..]).ToArray(); var responseTypes = perms.Where(p => p.StartsWith("rst:", StringComparison.Ordinal)) .Select(p => p[4..]).ToArray(); var scopes = perms.Where(p => p.StartsWith("scp:", StringComparison.Ordinal)) .Select(p => p[4..]).ToArray(); return new DynamicRegistrationResponse { ClientId = app.Props.ClientId ?? "", ClientName = app.name, RedirectUris = app.Props.RedirectUris, PostLogoutRedirectUris = app.Props.PostLogoutRedirectUris, RequestUris = app.Props.RequestUris, ApplicationType = app.Props.ApplicationType, TokenEndpointAuthMethod = AuthMethodOf(app.Props), JsonWebKeySet = string.IsNullOrWhiteSpace(app.Props.JsonWebKeySet) ? null : System.Text.Json.JsonDocument.Parse(app.Props.JsonWebKeySet).RootElement.Clone(), JsonWebKeySetUri = app.Props.JwksUri, RequestObjectSigningAlg = app.Props.RequestObjectSigningAlg, GrantTypes = grantTypes.Length > 0 ? grantTypes : null, ResponseTypes = responseTypes.Length > 0 ? responseTypes : null, Scope = scopes.Length > 0 ? string.Join(' ', scopes) : null // client_secret / registration_access_token are NEVER returned in GET — they were one-time at creation. }; } /// /// The method the client authenticates with, as the server will check it: none for a public client, /// client_secret_basic when it holds a secret, private_key_jwt when it holds keys and no secret. /// private static string AuthMethodOf(ApplicationProps props) => props.ClientType == "public" ? "none" : string.IsNullOrEmpty(props.ClientSecret) && (!string.IsNullOrWhiteSpace(props.JsonWebKeySet) || !string.IsNullOrWhiteSpace(props.JwksUri)) ? "private_key_jwt" : "client_secret_basic"; private static IDictionary SerializeResponse(DynamicRegistrationResponse response) { // Round-trip through the same JSON options as the DCR processor to guarantee // RFC 7591/7592 snake_case wire format and to drop null/empty fields. var opts = new JsonSerializerOptions { DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull }; var json = JsonSerializer.Serialize(response, opts); return JsonSerializer.Deserialize>(json)!; } private static void SetError(IExchange exchange, string error, string description, int statusCode) { exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new Dictionary { ["error"] = error, ["error_description"] = description }; exchange.Out.Headers["redbHttp.ResponseCode"] = statusCode; } private static string ComputeSha256Hex(string plaintext) { var bytes = SHA256.HashData(Encoding.UTF8.GetBytes(plaintext)); var sb = new StringBuilder(bytes.Length * 2); foreach (var b in bytes) sb.Append(b.ToString("x2")); return sb.ToString(); } /// Fixed-time equality for hex strings — defeats timing side-channels on RAT verification. private static bool FixedTimeHexEquals(string a, string b) { if (a.Length != b.Length) return false; return CryptographicOperations.FixedTimeEquals( Encoding.ASCII.GetBytes(a), Encoding.ASCII.GetBytes(b)); } } Path: redb-identity/src/redb.Identity.Core/Routes/Processors/ConsentGrantProcessor.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/Routes/Processors/ConsentGrantProcessor.cs ---- using redb.Identity.Core.Services; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.RedbCore.Extensions; using redb.Identity.Contracts.Routes; namespace redb.Identity.Core.Routes.Processors; /// /// Processes user consent approval. Expects body with: userId, clientId, scopes (space-separated). /// Grants consent via and signals success. /// internal sealed class ConsentGrantProcessor : IProcessor { private readonly IRouteContext _context; private readonly string? _redbName; public ConsentGrantProcessor(IRouteContext context, string? redbName = null) { _context = context; _redbName = redbName; } public async Task Process(IExchange exchange, CancellationToken ct = default) { var redb = _context.GetRedbService(_redbName, exchange); var body = exchange.In.Body as IDictionary; if (body is null) { IdentityProcessorHelpers.SetError(exchange, "invalid_request", "Request body is required"); return; } var userId = IdentityProcessorHelpers.ExtractLong( body as Dictionary ?? new(body), "userId") ?? 0; body.TryGetValue("clientId", out var cidObj); var clientId = cidObj?.ToString(); body.TryGetValue("scopes", out var scopesObj); var scopesStr = scopesObj?.ToString() ?? ""; if (userId <= 0) { IdentityProcessorHelpers.SetError(exchange, "invalid_request", "userId is required"); return; } if (string.IsNullOrEmpty(clientId)) { IdentityProcessorHelpers.SetError(exchange, "invalid_request", "clientId is required"); return; } var consentService = new ConsentService(redb); var appId = await consentService.FindApplicationIdAsync(clientId).ConfigureAwait(false); if (appId is null or <= 0) { IdentityProcessorHelpers.SetError(exchange, "invalid_client", "Unknown client_id"); return; } var scopes = scopesStr.Split(' ', StringSplitOptions.RemoveEmptyEntries); await consentService.GrantAsync(userId, appId.Value, scopes).ConfigureAwait(false); exchange.Out = new Message(); exchange.Out.Body = new Dictionary { ["success"] = true, ["userId"] = userId, ["clientId"] = clientId, ["scopes"] = scopesStr }; exchange.Properties["identity-event-type"] = IdentityAuditEventIds.ConsentGranted; exchange.Properties["identity-event-data"] = new { UserId = userId, ClientId = clientId, Scopes = scopesStr }; } } Path: redb-identity/src/redb.Identity.Core/Routes/Processors/ConsentManagementProcessor.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/Routes/Processors/ConsentManagementProcessor.cs ---- using redb.Identity.Contracts.Consents; using redb.Identity.Contracts.Common; using redb.Identity.Core.Services; using redb.Route.Abstractions; using redb.Route.RedbCore.Extensions; using redb.Identity.Contracts.Routes; namespace redb.Identity.Core.Routes.Processors; /// /// Management processor for user consents. /// Dispatches on the "operation" header: list, revoke, revoke-all. /// internal sealed class ConsentManagementProcessor : IProcessor { private readonly IRouteContext _context; private readonly string? _redbName; public ConsentManagementProcessor(IRouteContext context, string? redbName = null) { _context = context; _redbName = redbName; } public async Task Process(IExchange exchange, CancellationToken ct = default) { var redb = _context.GetRedbService(_redbName, exchange); var consent = new ConsentService(redb); var operation = exchange.In.GetHeader("operation") ?? throw new InvalidOperationException("Missing 'operation' header"); switch (operation) { case "list": await List(consent, exchange, ct); break; case "revoke": await Revoke(consent, exchange, ct); break; case "revoke-all": await RevokeAll(consent, exchange, ct); break; default: exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new ErrorResponse { Error = "invalid_operation", ErrorDescription = $"Unknown operation: {operation}" }; break; } } private static async Task List(ConsentService consent, IExchange exchange, CancellationToken ct) { var userId = IdentityProcessorHelpers.ExtractRequiredLong(exchange, "userId"); var consents = await consent.ListAsync(userId, ct); exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = consents.Select(c => new ConsentResponse { Id = c.Id, UserId = c.UserId, ApplicationId = c.ApplicationId, ClientId = c.ClientId, ApplicationName = c.ApplicationName, Scopes = c.Scopes, Status = "valid", CreatedAt = c.CreatedAt }).ToList(); } private static async Task Revoke(ConsentService consent, IExchange exchange, CancellationToken ct) { var dict = exchange.In.Body as Dictionary ?? throw new InvalidOperationException("Body is required"); var userId = IdentityProcessorHelpers.ExtractRequiredLong(exchange, "userId"); var appId = IdentityProcessorHelpers.ExtractLong(dict, "applicationId") ?? throw new InvalidOperationException("applicationId is required"); var revoked = await consent.RevokeAsync(userId, appId, ct); exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new SuccessResponse { Revoked = revoked }; exchange.Properties["identity-event-type"] = IdentityAuditEventIds.ConsentRevoked; exchange.Properties["identity-event-data"] = new { UserId = userId, ApplicationId = appId }; } private static async Task RevokeAll(ConsentService consent, IExchange exchange, CancellationToken ct) { var userId = IdentityProcessorHelpers.ExtractRequiredLong(exchange, "userId"); var revoked = await consent.RevokeAllAsync(userId, ct); exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new SuccessResponse { Revoked = revoked }; exchange.Properties["identity-event-type"] = IdentityAuditEventIds.AllConsentsRevoked; exchange.Properties["identity-event-data"] = new { UserId = userId }; } } Path: redb-identity/src/redb.Identity.Core/Routes/Processors/CrossContextQueryProcessors.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/Routes/Processors/CrossContextQueryProcessors.cs ---- using Microsoft.Extensions.DependencyInjection; using OpenIddict.Abstractions; using redb.Identity.Contracts.Cors; using redb.Identity.Contracts.Endpoints; using redb.Identity.Contracts.Mfa; using redb.Identity.Core.Services; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Identity.Core.Routes.Processors; /// /// Phase 9d cross-context broker processors. Serve direct-vm://identity-cors-check, /// direct-vm://identity-validate-post-logout and direct-vm://identity-mfa-methods-from-state /// — all read-only queries the HTTP transport facade issues from its own RouteContext. /// /// Each processor accepts either the strongly-typed Contracts DTO directly or an /// with the same property names. The broker on /// the Http side serializes via the Route default body convertor, which preserves the /// dictionary form when going through direct-vm. /// /// internal sealed class CorsCheckProcessor : IProcessor { private readonly IServiceProvider _sp; public CorsCheckProcessor(IServiceProvider sp) => _sp = sp; public async Task Process(IExchange exchange, CancellationToken ct = default) { var origin = ExtractOrigin(exchange.In.Body); bool allowed = false; if (!string.IsNullOrEmpty(origin)) { using var scope = _sp.CreateScope(); var registry = scope.ServiceProvider.GetService(); if (registry is not null) allowed = await registry.IsAllowedAsync(origin, ct).ConfigureAwait(false); } exchange.Out = new Message(new CorsCheckResponse { Allowed = allowed }); } private static string? ExtractOrigin(object? body) => body switch { CorsCheckRequest typed => typed.Origin, IDictionary dict when dict.TryGetValue("Origin", out var v) => v?.ToString(), IDictionary dict when dict.TryGetValue("origin", out var v) => v?.ToString(), _ => null, }; } internal sealed class ValidatePostLogoutRedirectProcessor : IProcessor { private readonly IServiceProvider _sp; public ValidatePostLogoutRedirectProcessor(IServiceProvider sp) => _sp = sp; public async Task Process(IExchange exchange, CancellationToken ct = default) { var uri = ExtractUri(exchange.In.Body); bool allowed = false; if (!string.IsNullOrEmpty(uri)) { using var scope = _sp.CreateScope(); var manager = scope.ServiceProvider.GetService(); if (manager is not null) { await foreach (var _ in manager.FindByPostLogoutRedirectUriAsync(uri, ct).ConfigureAwait(false)) { allowed = true; break; } } } exchange.Out = new Message(new ValidatePostLogoutRedirectResponse { Allowed = allowed }); } private static string? ExtractUri(object? body) => body switch { ValidatePostLogoutRedirectRequest typed => typed.RedirectUri, IDictionary dict when dict.TryGetValue("RedirectUri", out var v) => v?.ToString(), IDictionary dict when dict.TryGetValue("redirect_uri", out var v) => v?.ToString(), _ => null, }; } internal sealed class MfaMethodsFromStateProcessor : IProcessor { private readonly IServiceProvider _sp; public MfaMethodsFromStateProcessor(IServiceProvider sp) => _sp = sp; public Task Process(IExchange exchange, CancellationToken ct = default) { var token = ExtractState(exchange.In.Body); var response = new MfaMethodsFromStateResponse(); if (!string.IsNullOrEmpty(token)) { using var scope = _sp.CreateScope(); var protector = scope.ServiceProvider.GetService(); var state = protector?.Unprotect(token); if (state is not null && state.Methods is { Length: > 0 } m) { response.Success = true; response.Methods = m; } } exchange.Out = new Message(response); return Task.CompletedTask; } private static string? ExtractState(object? body) => body switch { MfaMethodsFromStateRequest typed => typed.MfaState, IDictionary dict when dict.TryGetValue("MfaState", out var v) => v?.ToString(), IDictionary dict when dict.TryGetValue("mfa_state", out var v) => v?.ToString(), _ => null, }; } Path: redb-identity/src/redb.Identity.Core/Routes/Processors/DcrClientMetadata.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/Routes/Processors/DcrClientMetadata.cs ---- using redb.Identity.Contracts.Registration; using redb.Identity.Core.Configuration; using redb.Identity.Core.Services; namespace redb.Identity.Core.Routes.Processors; /// /// The key and request-object metadata of a dynamic registration (RFC 7591 §2, OIDC Dynamic Client Registration /// 1.0 §2), read the same way by the registration and by its RFC 7592 update. What this accepts is stored, and the /// answer is built from what was stored. /// internal static class DcrClientMetadata { /// The client's keys as registered: an inline set or an address, never both. internal readonly record struct Keys(string? JwksJson, string? JwksUri); /// /// Reads jwks and jwks_uri. Both at once are refused (RFC 7591 §2: they MUST NOT both be present). /// jwks must be a key set with at least one key; jwks_uri an address the key fetch would accept /// under , checked here as an early refusal and again before every fetch. /// Returns the error text, or null with the keys. /// internal static async Task<(string? Error, Keys Keys)> ReadKeysAsync( DynamicRegistrationRequest request, ClientKeysOptions options, CancellationToken ct) { var hasInline = request.JsonWebKeySet is { ValueKind: not System.Text.Json.JsonValueKind.Null }; var uri = request.JsonWebKeySetUri?.Trim(); var hasUri = !string.IsNullOrEmpty(uri); if (hasInline && hasUri) return ("`jwks` and `jwks_uri` must not both be present.", default); string? json = null; if (hasInline) { try { var raw = request.JsonWebKeySet!.Value.GetRawText(); if (Microsoft.IdentityModel.Tokens.JsonWebKeySet.Create(raw).Keys.Count == 0) return ("`jwks` must contain at least one public key in `keys`.", default); json = raw; } catch (Exception ex) { return ($"`jwks` is not a valid JSON Web Key Set: {ex.Message}", default); } } if (hasUri) { if (uri!.Length > IdentityProcessorHelpers.MaxRequestUriLength) return ($"`jwks_uri` must have at most {IdentityProcessorHelpers.MaxRequestUriLength} characters.", default); var rejection = await OutboundUrlGuard.ValidateAsync( uri, options.RequireHttps, options.AllowPrivateNetworkTargets, ct).ConfigureAwait(false); if (rejection != OutboundUrlGuard.Rejection.None) return ($"`jwks_uri` is not accepted: {OutboundUrlGuard.Describe(rejection)}.", default); } return (null, new Keys(json, hasUri ? uri : null)); } /// /// Reads request_object_signing_alg: one of /// (none is never among them). Returns the error text, or null. /// internal static string? ValidateRequestObjectSigningAlg(string? alg, JarOptions options) { if (alg is null) return null; if (string.Equals(alg, "none", StringComparison.OrdinalIgnoreCase) || !options.AllowedSigningAlgorithms.Contains(alg, StringComparer.Ordinal)) return $"`request_object_signing_alg` must be one of: {string.Join(", ", options.AllowedSigningAlgorithms)}."; return null; } } Path: redb-identity/src/redb.Identity.Core/Routes/Processors/DynamicRegistrationProcessor.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/Routes/Processors/DynamicRegistrationProcessor.cs ---- using System.Diagnostics; using System.Security.Cryptography; using System.Text; using System.Text.Json; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using OpenIddict.Abstractions; using redb.Core; using redb.Core.Models.Entities; using redb.Identity.Contracts.Registration; using redb.Identity.Core.Configuration; using redb.Identity.Core.Models; using redb.Identity.Core.Module; using redb.Identity.Core.Serialization; using redb.Route.Abstractions; using redb.Route.RedbCore.Extensions; using redb.Identity.Contracts.Routes; namespace redb.Identity.Core.Routes.Processors; /// /// RFC 7591 Dynamic Client Registration endpoint processor. /// Accepts a JSON registration request and creates a new OAuth application. /// internal sealed class DynamicRegistrationProcessor : IProcessor { private readonly IRouteContext _context; private readonly RedbIdentityOptions _options; private readonly TimeProvider _timeProvider; private readonly ILogger? _logger; // Default grant types per RFC 7591 §2 private static readonly string[] DefaultGrantTypes = ["authorization_code"]; private static readonly string[] DefaultResponseTypes = ["code"]; public DynamicRegistrationProcessor( IRouteContext context, IOptions options, TimeProvider? timeProvider = null, ILoggerFactory? loggerFactory = null) { _context = context; _options = options.Value; _timeProvider = timeProvider ?? TimeProvider.System; _logger = loggerFactory?.CreateLogger("DynamicRegistrationProcessor"); } /// /// The initial access token this deployment requires, or null when none is configured. An empty or /// whitespace value is not a token: it counts as not configured, so registration is open and the floor for /// anonymous registrants below applies, whatever a request carries in its Authorization header. /// private string? ConfiguredInitialAccessToken => string.IsNullOrWhiteSpace(_options.DynamicRegistrationInitialAccessToken) ? null : _options.DynamicRegistrationInitialAccessToken; public async Task Process(IExchange exchange, CancellationToken ct = default) { var swTotal = Stopwatch.StartNew(); // Validate initial access token if configured (RFC 7591 §1.2) var expectedToken = ConfiguredInitialAccessToken; if (expectedToken is not null) { // access_token header is set by ExtractBearerToken (already stripped "Bearer " prefix) var tokenValue = exchange.In.GetHeader("access_token"); if (tokenValue is null) { // Fallback: check raw Authorization header (direct-vm tests, non-HTTP transports) var authHeader = exchange.In.GetHeader("Authorization"); if (authHeader?.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase) == true) tokenValue = authHeader[7..]; } if (tokenValue is null || !CryptographicOperations.FixedTimeEquals( System.Text.Encoding.UTF8.GetBytes(tokenValue), System.Text.Encoding.UTF8.GetBytes(expectedToken))) { SetError(exchange, "invalid_token", "A valid initial access token is required", 401); return; } } // Deserialize the request body DynamicRegistrationRequest? request; try { request = exchange.In.Body switch { DynamicRegistrationRequest typed => typed, byte[] bytes => JsonSerializer.Deserialize(bytes), string json => JsonSerializer.Deserialize(json), _ => null }; } catch (JsonException) { request = null; } if (request is null) { SetError(exchange, "invalid_client_metadata", "Invalid or missing request body"); return; } // Resolve grant types (RFC 7591 §2: default = authorization_code) var grantTypes = request.GrantTypes is { Length: > 0 } ? request.GrantTypes : DefaultGrantTypes; // Validate grant types against policy var disallowed = grantTypes.Except(_options.DynamicRegistrationAllowedGrantTypes).ToArray(); if (disallowed.Length > 0) { SetError(exchange, "invalid_client_metadata", $"Grant type(s) not allowed: {string.Join(", ", disallowed)}"); return; } // Resolve response types (RFC 7591 §2: default = code) var responseTypes = request.ResponseTypes is { Length: > 0 } ? request.ResponseTypes : DefaultResponseTypes; // Validate scopes against policy var requestedScopes = ParseScopes(request.Scope); var disallowedScopes = requestedScopes.Except(_options.DynamicRegistrationAllowedScopes).ToArray(); if (disallowedScopes.Length > 0) { SetError(exchange, "invalid_client_metadata", $"Scope(s) not allowed: {string.Join(", ", disallowedScopes)}"); return; } // An anonymous caller cannot register a client that administers this server. // // RFC 7591 §1.2 offers two modes: open registration and protected registration behind an // initial access token. Under open registration the only limit above is // DynamicRegistrationAllowedScopes, and a deployment whose list contains administrative // scopes hands full administration to anyone who can reach the endpoint: register a // client_credentials client asking for identity:users:write, take a token, delete users. // No role, no password, no operator involved. The scope gate on user-bound grants cannot // help here - this grant has no user to entitle, so the client's own permissions are the // whole of it, and those permissions are precisely what is being handed out. // // So the floor is below policy: while registration is open, a scope this deployment counts // as administrative is refused no matter what the allow-list says. An operator who wants // administrative clients registered dynamically sets DynamicRegistrationInitialAccessToken to a // non-blank value // - then every registration carries a credential the deployment issued, and the allow-list // governs as before. Which scopes count is Identity:AdminScopeEntitlement, the same // definition the issuance gate uses, including any the operator added; its Enabled switch // is not consulted, because that switch exists to recover a locked-out administrator and // must not quietly reopen anonymous registration of administrative clients. if (expectedToken is null) { var administrative = requestedScopes.Where(_options.AdminScopeEntitlement.IsGated).ToArray(); if (administrative.Length > 0) { _logger?.LogWarning( "DynamicRegistration: refused anonymous registration of '{ClientName}' requesting administrative scope(s) {Scopes}; " + "set Identity:DynamicRegistrationInitialAccessToken to allow registering administrative clients", request.ClientName ?? "", string.Join(",", administrative)); SetError(exchange, "invalid_client_metadata", $"Scope(s) require an authenticated registration: {string.Join(", ", administrative)}"); return; } } // Validate redirect URIs (required for authorization_code / implicit) if (grantTypes.Contains("authorization_code") || grantTypes.Contains("implicit")) { if (request.RedirectUris is not { Length: > 0 }) { SetError(exchange, "invalid_redirect_uri", "redirect_uris is required for authorization_code / implicit grant types"); return; } var uriErr = IdentityProcessorHelpers.ValidateUris(request.RedirectUris, "redirect URI"); if (uriErr is not null) { SetError(exchange, "invalid_redirect_uri", uriErr); return; } } if (request.PostLogoutRedirectUris is { Length: > 0 }) { var uriErr = IdentityProcessorHelpers.ValidateUris(request.PostLogoutRedirectUris, "post-logout redirect URI"); if (uriErr is not null) { SetError(exchange, "invalid_client_metadata", uriErr); return; } } if (!string.IsNullOrWhiteSpace(request.BackchannelLogoutUri)) { var bclErr = await IdentityProcessorHelpers.ValidateBackchannelLogoutUriAsync( request.BackchannelLogoutUri.Trim(), _options.BackchannelLogout, ct).ConfigureAwait(false); if (bclErr is not null) { SetError(exchange, "invalid_client_metadata", bclErr); return; } } if (request.RequestUris is { Length: > 0 }) { var uriErr = IdentityProcessorHelpers.ValidateRequestUris(request.RequestUris); if (uriErr is not null) { SetError(exchange, "invalid_client_metadata", uriErr); return; } } // Determine client type from token_endpoint_auth_method (RFC 7591 §2) var authMethod = request.TokenEndpointAuthMethod ?? "client_secret_basic"; string clientType; string? plainSecret = null; var (keysError, keys) = await DcrClientMetadata.ReadKeysAsync(request, _options.ClientKeys, ct).ConfigureAwait(false); if (keysError is not null) { SetError(exchange, "invalid_client_metadata", keysError); return; } var jwksJson = keys.JwksJson; var algError = DcrClientMetadata.ValidateRequestObjectSigningAlg(request.RequestObjectSigningAlg, _options.Jar); if (algError is not null) { SetError(exchange, "invalid_client_metadata", algError); return; } if (authMethod == "none") { clientType = "public"; } else if (authMethod is "client_secret_basic" or "client_secret_post") { clientType = "confidential"; plainSecret = GenerateClientSecret(); } else if (authMethod == "private_key_jwt") { // RFC 7521 §6.2 / RFC 7523 §2.2 — clients authenticating with a JWT bearer // assertion are confidential clients (they hold a private signing key) but // do NOT carry a server-issued client_secret. clientType = "confidential"; // RFC 7591 §2: the client publishes its keys as `jwks` or at `jwks_uri` (read above for every // auth method). The store hands either to OpenIddict when it verifies the client assertion. if (keys.JwksJson is null && keys.JwksUri is null) { SetError(exchange, "invalid_client_metadata", "private_key_jwt requires `jwks` or `jwks_uri` with the client's public keys."); return; } } else { SetError(exchange, "invalid_client_metadata", $"Unsupported token_endpoint_auth_method: {authMethod}"); return; } // Application type (RFC 7591 §2: default = web) var applicationType = request.ApplicationType ?? "web"; if (applicationType is not ("web" or "native")) { SetError(exchange, "invalid_client_metadata", "application_type must be 'web' or 'native'"); return; } // Build permissions array (OpenIddict format) var permissions = BuildPermissions(grantTypes, responseTypes, requestedScopes); // Build requirements. Force PKCE per-client ONLY when the server mandates it // (RedbIdentityOptions.RequirePkce, default true = OAuth 2.1 hardening). When PKCE is // optional (RequirePkce=false), authorization_code clients register WITHOUT the ft:pkce // requirement — they may still use PKCE, but it is not mandated — so the per-client policy // matches the server policy (e.g. lets the OpenID Basic OP non-PKCE tests register a client). var requirements = new List(); if (_options.RequirePkce && grantTypes.Contains("authorization_code")) requirements.Add("ft:pkce"); // Generate unique client_id var clientId = Guid.NewGuid().ToString("D"); // Use OpenIddict ApplicationManager to create the client. // This ensures the secret is hashed using OpenIddict's built-in mechanism (BCrypt), // which is consistent with how ValidateClientSecretAsync verifies credentials. var manager = _context.GetIdentityService(exchange); var descriptor = new OpenIddictApplicationDescriptor { ClientId = clientId, ClientSecret = plainSecret, ClientType = clientType, ConsentType = OpenIddictConstants.ConsentTypes.Implicit, DisplayName = request.ClientName ?? clientId, }; if (applicationType == "native") descriptor.ApplicationType = OpenIddictConstants.ApplicationTypes.Native; // RFC 7523 §3 — surface the inline JWKS on the descriptor so PopulateAsync // routes it through IOpenIddictApplicationStore.SetJsonWebKeySetAsync (which // persists into ApplicationProps.JsonWebKeySet). OpenIddict's built-in // private_key_jwt validator on /connect/token et al. then resolves the keys // via GetJsonWebKeySetAsync at validation time. if (jwksJson is not null) descriptor.JsonWebKeySet = Microsoft.IdentityModel.Tokens.JsonWebKeySet.Create(jwksJson); if (request.RedirectUris is { Length: > 0 }) foreach (var uri in request.RedirectUris) descriptor.RedirectUris.Add(new Uri(uri)); if (request.PostLogoutRedirectUris is { Length: > 0 }) foreach (var uri in request.PostLogoutRedirectUris) descriptor.PostLogoutRedirectUris.Add(new Uri(uri)); // OIDC Back-Channel Logout 1.0 §2.2 — store as custom properties so // BackchannelLogoutDispatcher can read them at logout time. if (!string.IsNullOrWhiteSpace(request.BackchannelLogoutUri)) { descriptor.Properties["backchannel_logout_uri"] = JsonDocument.Parse(JsonSerializer.Serialize(request.BackchannelLogoutUri)).RootElement.Clone(); descriptor.Properties["backchannel_logout_session_required"] = JsonDocument.Parse((request.BackchannelLogoutSessionRequired ?? true) ? "true" : "false").RootElement.Clone(); } foreach (var p in permissions) descriptor.Permissions.Add(p); foreach (var r in requirements) descriptor.Requirements.Add(r); // Z2 (RFC 7592 §3): generate the registration_access_token and persist its hash // so that GET/PUT/DELETE /connect/register/{client_id} can authenticate the caller. // The plaintext RAT is returned ONCE in the registration response; after that, only // the SHA-256 hex hash lives in PROPS (defense-in-depth against DB dumps). var registrationAccessToken = GenerateUrlSafeToken(32); var ratHash = ComputeSha256Hex(registrationAccessToken); // Split the manager.CreateAsync(descriptor) pipeline manually so the RAT hash // is written in the SAME redb roundtrip as the rest of the application: // instantiate → PopulateAsync (without secret) → mutate Props → CreateAsync(app, secret). // Pull the plaintext secret out of the descriptor BEFORE Populate, otherwise // PopulateAsync stamps the plaintext into Props.ClientSecret and the 2-arg // CreateAsync(app, ct) overload's "hash already set" guard rejects it. var localSecret = descriptor.ClientSecret; descriptor.ClientSecret = null; var swPopulate = Stopwatch.StartNew(); var app = new RedbObject { Props = new ApplicationProps() }; await manager.PopulateAsync(app, descriptor, ct).ConfigureAwait(false); swPopulate.Stop(); app.Props.RegistrationAccessTokenHash = ratHash; // OIDC Back-Channel Logout 1.0 §2.2 — PopulateAsync ignores descriptor.Properties[] // (those are OpenIddict's per-store custom-properties bag, not redb Props), so the // strongly-typed Props field has to be written manually after Populate. if (!string.IsNullOrWhiteSpace(request.BackchannelLogoutUri)) { app.Props.BackchannelLogoutUri = request.BackchannelLogoutUri; app.Props.BackchannelLogoutSessionRequired = request.BackchannelLogoutSessionRequired ?? true; } // RFC 9126 §5 — per-client PAR enforcement. Stored on Props directly so // ValidateAuthorizeRequestHandler can read it without lifting the OpenIddict // descriptor.Properties bag into Props. if (request.RequirePushedAuthorizationRequests == true) app.Props.RequirePushedAuthorizationRequests = true; // N-4 (Session C/E) — per-client landing-URL whitelists for the password-recovery, // verify-email, and change-email flows. Without these the flows are disabled even // when the server-side feature toggle is on; persisting them on Props at DCR time // is the only way a self-registered client can opt in (admin Update is the other path). if (request.PasswordResetUris is { Length: > 0 }) app.Props.PasswordResetUris = request.PasswordResetUris; if (request.EmailVerifyUris is { Length: > 0 }) app.Props.EmailVerifyUris = request.EmailVerifyUris; if (request.ChangeEmailUris is { Length: > 0 }) app.Props.ChangeEmailUris = request.ChangeEmailUris; // OIDC DCR §2 request_uris: the JAR request_uri values this client may use, matched exactly. if (request.RequestUris is { Length: > 0 }) app.Props.RequestUris = request.RequestUris.Distinct(StringComparer.Ordinal).ToArray(); // RFC 7591 §2 jwks_uri and OIDC DCR §2 request_object_signing_alg, as read above. if (keys.JwksUri is not null) app.Props.JwksUri = keys.JwksUri; if (request.RequestObjectSigningAlg is not null) app.Props.RequestObjectSigningAlg = request.RequestObjectSigningAlg; var swCreate = Stopwatch.StartNew(); if (localSecret is not null) await manager.CreateAsync(app, localSecret, ct).ConfigureAwait(false); else await manager.CreateAsync(app, ct).ConfigureAwait(false); swCreate.Stop(); _logger?.LogDebug( "DCR_TIMING populate={PopulateMs}ms create={CreateMs}ms total={TotalMs}ms hasSecret={HasSecret} grants=[{Grants}] scopes=[{Scopes}] redirectUris={UriCount}", swPopulate.ElapsedMilliseconds, swCreate.ElapsedMilliseconds, swTotal.ElapsedMilliseconds, localSecret is not null, string.Join(",", grantTypes), string.Join(",", requestedScopes), request.RedirectUris?.Length ?? 0); // Build registration_client_uri from the configured issuer. var registrationClientUri = BuildRegistrationClientUri(clientId); // Build response (RFC 7591 §3.2.1) var now = _timeProvider.GetUtcNow(); var response = new DynamicRegistrationResponse { ClientId = clientId, ClientSecret = plainSecret, ClientSecretExpiresAt = plainSecret is not null ? 0 : null, // 0 = never expires ClientIdIssuedAt = now.ToUnixTimeSeconds(), RedirectUris = request.RedirectUris, TokenEndpointAuthMethod = authMethod, GrantTypes = grantTypes, ResponseTypes = responseTypes, ClientName = request.ClientName, ClientUri = request.ClientUri, LogoUri = request.LogoUri, Scope = requestedScopes.Length > 0 ? string.Join(' ', requestedScopes) : request.Scope, Contacts = request.Contacts, SoftwareId = request.SoftwareId, SoftwareVersion = request.SoftwareVersion, ApplicationType = applicationType, PostLogoutRedirectUris = request.PostLogoutRedirectUris, // Only what was stored: the inline set (stored for every auth method) and the address. JsonWebKeySet = jwksJson is not null ? request.JsonWebKeySet : null, JsonWebKeySetUri = app.Props.JwksUri, RequestObjectSigningAlg = app.Props.RequestObjectSigningAlg, RegistrationAccessToken = registrationAccessToken, RegistrationClientUri = registrationClientUri, RequirePushedAuthorizationRequests = request.RequirePushedAuthorizationRequests, PasswordResetUris = app.Props.PasswordResetUris, EmailVerifyUris = app.Props.EmailVerifyUris, ChangeEmailUris = app.Props.ChangeEmailUris, RequestUris = app.Props.RequestUris }; exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = SerializeResponse(response); exchange.Out.Headers["redbHttp.ResponseCode"] = 201; exchange.Properties["identity-event-type"] = IdentityAuditEventIds.ClientRegistered; exchange.Properties["identity-event-data"] = new { ClientId = clientId, Source = "dynamic_registration" }; } // ── Helpers ── private static string[] ParseScopes(string? scope) { if (string.IsNullOrWhiteSpace(scope)) return []; return scope.Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); } private static List BuildPermissions(string[] grantTypes, string[] responseTypes, string[] scopes) { var perms = new List(); // Endpoint permissions. We always grant token + introspection + revocation so that // dynamically-registered clients can manage their own tokens (RFC 7662 / RFC 7009); // OpenIddict refuses these endpoints without explicit permission, which would // otherwise return 'unauthorized_client' for the very first introspect call. perms.Add("ept:token"); perms.Add("ept:introspection"); perms.Add("ept:revocation"); if (grantTypes.Contains("authorization_code") || grantTypes.Contains("implicit")) { perms.Add("ept:authorization"); if (grantTypes.Contains("authorization_code")) perms.Add("ept:pushed_authorization"); // RFC 9126 PAR endpoint } if (grantTypes.Contains("refresh_token")) perms.Add("ept:token"); // already added, dedup below if (grantTypes.Contains("urn:ietf:params:oauth:grant-type:device_code")) perms.Add("ept:device_authorization"); // Grant type permissions foreach (var gt in grantTypes) perms.Add($"gt:{gt}"); // Response type permissions foreach (var rt in responseTypes) perms.Add($"rst:{rt}"); // Scope permissions foreach (var s in scopes) perms.Add($"scp:{s}"); return perms.Distinct().ToList(); } private static string GenerateClientSecret() { var bytes = RandomNumberGenerator.GetBytes(32); return Convert.ToBase64String(bytes).TrimEnd('='); } /// /// Z2: generates a URL-safe registration_access_token using . /// Uses base64url without padding so the value can travel in an Authorization: Bearer header. /// internal static string GenerateUrlSafeToken(int entropyBytes) { Span buf = stackalloc byte[Math.Max(entropyBytes, 16)]; RandomNumberGenerator.Fill(buf); return Convert.ToBase64String(buf) .TrimEnd('=') .Replace('+', '-') .Replace('/', '_'); } /// SHA-256 hex (lowercase) of the provided plaintext. Used for RAT verification. internal static string ComputeSha256Hex(string plaintext) { var bytes = SHA256.HashData(Encoding.UTF8.GetBytes(plaintext)); var sb = new StringBuilder(bytes.Length * 2); foreach (var b in bytes) sb.Append(b.ToString("x2")); return sb.ToString(); } private string BuildRegistrationClientUri(string clientId) { // Issuer is guaranteed non-null by RedbIdentityOptions validation. var issuer = _options.Issuer.AbsoluteUri.TrimEnd('/'); return $"{issuer}/connect/register/{Uri.EscapeDataString(clientId)}"; } private static IDictionary SerializeResponse(DynamicRegistrationResponse response) { // RFC 7591 §3.2 — DCR response uses snake_case names defined by the spec // (redirect_uris, grant_types, client_id_issued_at, …). Apply the locked OAuth // profile via SerializeToElement so the resulting Dictionary already carries the // canonical names; transport facades serialise the typed payload themselves. // We deliberately avoid SerializeToUtf8Bytes / Serialize->string here: those // are wire-encoding APIs and would tie core to a single transport format. var element = JsonSerializer.SerializeToElement(response, IdentityCodecProfiles.OAuthOptions); var dict = new Dictionary(StringComparer.Ordinal); foreach (var prop in element.EnumerateObject()) dict[prop.Name] = prop.Value.Clone(); return dict; } private static void SetError(IExchange exchange, string error, string description, int statusCode = 400) { exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new Dictionary { ["error"] = error, ["error_description"] = description }; exchange.Out.Headers["redbHttp.ResponseCode"] = statusCode; } } Path: redb-identity/src/redb.Identity.Core/Routes/Processors/EmailVerifyConfirmProcessor.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/Routes/Processors/EmailVerifyConfirmProcessor.cs ---- using System; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Core; using redb.Core.Models.Entities; using redb.Identity.Contracts.Routes; using redb.Identity.Contracts.Users; using redb.Identity.Core.EmailVerification; using redb.Identity.Core.Models; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.RedbCore.Extensions; namespace redb.Identity.Core.Routes.Processors; /// /// N-4 (Session C, sub-step N4-6): anonymous e-mail-verification confirmation backing /// direct-vm://identity-email-verify-confirm. /// /// Verifies + atomically consumes the single-use token via /// . On success it loads /// the user, ensures the user's current e-mail still matches the snapshot captured at /// issue time (double-change race protection), then flips /// to true in the OIDC props extension. /// /// /// All failure modes return the generic OAuth-style invalid_token error — the /// granular reason from the store (or email_changed) is only persisted to audit /// () so an anonymous caller /// cannot enumerate which jti values exist. /// /// internal sealed class EmailVerifyConfirmProcessor : IProcessor { private readonly IRouteContext _context; private readonly IServiceProvider _sp; private readonly string? _redbName; public EmailVerifyConfirmProcessor(IRouteContext context, IServiceProvider sp, string? redbName = null) { _context = context; _sp = sp; _redbName = redbName; } public async Task Process(IExchange exchange, CancellationToken ct = default) { var request = exchange.In.Body as EmailVerifyConfirmRequest; if (request is null || string.IsNullOrWhiteSpace(request.Jti) || string.IsNullOrWhiteSpace(request.Token)) { Reject(exchange, 400, "validation_error", "Jti and Token are required."); return; } if (!Guid.TryParseExact(request.Jti, "N", out var jti) && !Guid.TryParse(request.Jti, out jti)) { EmitFailureAudit(exchange, "bad_jti_format", userId: 0); Reject(exchange, 400, "invalid_token", "The verification token is invalid or has expired."); return; } var logger = _sp.GetService()?.CreateLogger("EmailVerifyConfirmProcessor"); var store = _sp.GetRequiredService(); var verify = await store.VerifyAndConsumeAsync(jti, request.Token, ct).ConfigureAwait(false); if (!verify.Success) { EmitFailureAudit(exchange, verify.Reason, verify.UserId); Reject(exchange, 400, "invalid_token", "The verification token is invalid or has expired."); return; } var redb = _context.GetRedbService(_redbName, exchange); var user = await redb.UserProvider.GetUserByIdAsync(verify.UserId).ConfigureAwait(false); if (user is null) { EmitFailureAudit(exchange, "user_not_found", verify.UserId); Reject(exchange, 400, "invalid_token", "The verification token is invalid or has expired."); return; } // Double-change race guard: the token vouches for the e-mail value that was bound // at issue time. If the user has since changed their e-mail, this token must NOT // promote the new value to "verified". var currentEmail = (user.Email ?? string.Empty).Trim().ToLowerInvariant(); if (!string.Equals(currentEmail, verify.Email, StringComparison.Ordinal)) { EmitFailureAudit(exchange, "email_changed", user.Id); Reject(exchange, 400, "invalid_token", "The verification token is invalid or has expired."); return; } // Flip OIDC EmailVerified flag. Load (or create) the props extension. var oidcObj = await MeProcessorHelpers.LoadOidcProps(redb, user.Id).ConfigureAwait(false); if (oidcObj is null) { oidcObj = new RedbObject(new UserProps { EmailVerified = true, UserId = user.Id }); oidcObj.name = user.Login; oidcObj.key = user.Id; oidcObj.value_guid = Guid.NewGuid(); } else { oidcObj.Props.EmailVerified = true; } await redb.SaveAsync(oidcObj).ConfigureAwait(false); exchange.Out ??= new Message(); exchange.Out.Body = new EmailVerifyConfirmResponse { Success = true }; exchange.Properties["identity-event-type"] = IdentityAuditEventIds.EmailVerificationCompleted; exchange.Properties["identity-event-data"] = new { UserId = user.Id, Login = user.Login, Email = verify.Email, Jti = jti.ToString("N"), }; } private static void EmitFailureAudit(IExchange exchange, string reason, long userId) { exchange.Properties["identity-event-type"] = IdentityAuditEventIds.EmailVerificationFailed; exchange.Properties["identity-event-data"] = new { Reason = reason, UserId = userId }; } private static void Reject(IExchange exchange, int status, string error, string description) { exchange.Out ??= new Message(); exchange.Out.Headers["redbHttp.ResponseCode"] = status; exchange.Out.Body = new EmailVerifyConfirmResponse { Success = false, Error = error, ErrorDescription = description, }; } } Path: redb-identity/src/redb.Identity.Core/Routes/Processors/EmailVerifySendProcessor.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/Routes/Processors/EmailVerifySendProcessor.cs ---- using System; using System.Collections.Generic; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using redb.Core; using redb.Core.Query; using redb.Identity.Contracts.Routes; using redb.Identity.Contracts.Users; using redb.Identity.Core.Configuration; using redb.Identity.Core.EmailVerification; using redb.Identity.Core.Models; using redb.Identity.Core.Services; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.RedbCore.Extensions; namespace redb.Identity.Core.Routes.Processors; /// /// N-4 (Session C, sub-step N4-6): authenticated self-service e-mail-verification dispatch /// backing direct-vm://identity-me-email-verify-send. /// /// Caller user + target e-mail are derived from the access-token subject (via /// ); the body only carries /// ClientId + CallerVerifyUrl. The URL must match the client's /// ApplicationProps.EmailVerifyUris whitelist exactly (string compare); a mismatch /// or unknown client returns a generic 400 (no anti-enumeration concern — caller is /// already authenticated). /// /// /// The issued token is bound to the user's current e-mail snapshot via /// so the confirm step can detect a /// double-change race (token issued for value A, e-mail moved to B before confirm). /// /// internal sealed class EmailVerifySendProcessor : IProcessor { private readonly IRouteContext _context; private readonly IServiceProvider _sp; private readonly string? _redbName; public EmailVerifySendProcessor(IRouteContext context, IServiceProvider sp, string? redbName = null) { _context = context; _sp = sp; _redbName = redbName; } public async Task Process(IExchange exchange, CancellationToken ct = default) { var request = exchange.In.Body as EmailVerifySendRequest; if (request is null || string.IsNullOrWhiteSpace(request.ClientId) || string.IsNullOrWhiteSpace(request.CallerVerifyUrl)) { MeProcessorHelpers.Reject(exchange, 400, "validation_error", "ClientId and CallerVerifyUrl are required."); return; } var callerUserId = MeProcessorHelpers.TryGetCallerUserId(exchange); if (callerUserId is null) { MeProcessorHelpers.Reject(exchange, 401, "unauthorized", "Caller subject missing or invalid."); return; } var redb = _context.GetRedbService(_redbName, exchange); var logger = _sp.GetService()?.CreateLogger("EmailVerifySendProcessor"); var user = await redb.UserProvider.GetUserByIdAsync(callerUserId.Value).ConfigureAwait(false); if (user is null || string.IsNullOrEmpty(user.Email)) { MeProcessorHelpers.Reject(exchange, 400, "invalid_request", "Caller has no e-mail on file."); return; } // ── Gate: client whitelist ──────────────────────────────────────────────── var app = await redb.GetByUniqueAsync(p => p.ClientId, request.ClientId) .ConfigureAwait(false); if (app is null) { MeProcessorHelpers.Reject(exchange, 400, "invalid_client", "Unknown client_id."); return; } var whitelist = app.Props.EmailVerifyUris; if (whitelist is null || whitelist.Length == 0) { MeProcessorHelpers.Reject(exchange, 400, "invalid_request", "E-mail verification is not enabled for this client."); return; } var allowed = false; for (var i = 0; i < whitelist.Length; i++) { if (string.Equals(whitelist[i], request.CallerVerifyUrl, StringComparison.Ordinal)) { allowed = true; break; } } if (!allowed) { MeProcessorHelpers.Reject(exchange, 400, "invalid_request", "CallerVerifyUrl is not whitelisted for this client."); return; } // ── Issue + dispatch ────────────────────────────────────────────────────── var store = _sp.GetRequiredService(); var emailChannel = _sp.GetService(); if (emailChannel is null) { logger?.LogError( "EmailVerify-send: no IEmailNotificationChannel registered \u2014 dropping (host misconfiguration)"); MeProcessorHelpers.Reject(exchange, 503, "service_unavailable", "E-mail channel unavailable."); return; } var ttl = _sp.GetRequiredService>().Value.EmailVerification.TokenTtl; var issued = await store.IssueAsync(user.Id, user.Email, request.CallerVerifyUrl, ttl, ct) .ConfigureAwait(false); var verifyLink = BuildVerifyLink(request.CallerVerifyUrl, issued.Jti, issued.PlaintextToken); var vars = new Dictionary(StringComparer.Ordinal) { ["userName"] = user.Name ?? user.Login, ["verifyLink"] = verifyLink, ["ttlHours"] = ((int)ttl.TotalHours).ToString(System.Globalization.CultureInfo.InvariantCulture), }; try { await emailChannel.SendTemplateAsync(user.Email, IdentityEmailTemplates.EmailVerification, vars, ct) .ConfigureAwait(false); } catch (Exception ex) { logger?.LogError(ex, "EmailVerify-send: e-mail delivery failed for user {UserId}", user.Id); MeProcessorHelpers.Reject(exchange, 502, "delivery_failed", "Could not dispatch verification e-mail."); return; } exchange.Out ??= new Message(); exchange.Out.Body = new EmailVerifySendResponse { Success = true }; exchange.Properties["identity-event-type"] = IdentityAuditEventIds.EmailVerificationSent; exchange.Properties["identity-event-data"] = new { UserId = user.Id, Login = user.Login, ClientId = request.ClientId, Email = user.Email.ToLowerInvariant(), Jti = issued.Jti.ToString("N"), ExpiresAt = issued.ExpiresAt, }; } private static string BuildVerifyLink(string callerVerifyUrl, Guid jti, string plaintextToken) { var sep = callerVerifyUrl.Contains('?') ? '&' : '?'; var sb = new StringBuilder(callerVerifyUrl.Length + 128); sb.Append(callerVerifyUrl); sb.Append(sep); sb.Append("token="); sb.Append(Uri.EscapeDataString(plaintextToken)); sb.Append("&jti="); sb.Append(jti.ToString("N")); return sb.ToString(); } } Path: redb-identity/src/redb.Identity.Core/Routes/Processors/EndpointProcessors.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/Routes/Processors/EndpointProcessors.cs ---- using OpenIddict.Server; using redb.Identity.Core.OpenIddict; using redb.Identity.Core.OpenIddict.Handlers; using redb.Route.Abstractions; using redb.Identity.Contracts.Routes; namespace redb.Identity.Core.Routes.Processors; /// /// Discovery endpoint (OpenID Connect Configuration). /// internal sealed class DiscoveryEndpointProcessor : IProcessor { private readonly RedbRouteOpenIddictServerHandler _handler; public DiscoveryEndpointProcessor(RedbRouteOpenIddictServerHandler handler) => _handler = handler; public async Task Process(IExchange exchange, CancellationToken ct = default) { await _handler.ProcessAsync(exchange, OpenIddictServerEndpointType.Configuration, ct); // D1/D2: discovery doc is bounded-mutable (claims, scopes, endpoints rarely change). // RFC 8414 doesn't mandate a cache header, but RFC 7234 §5.2 says clients SHOULD // cache. Five minutes is small enough to roll forward after a config push, large // enough to cut request volume on cold-start spikes. if (exchange.HasOut) { exchange.Out!.Headers["Cache-Control"] = "public, max-age=300"; exchange.Out!.Headers.TryAdd("Vary", "Accept"); } } } /// /// JWKS endpoint (JSON Web Key Set). /// internal sealed class JwksEndpointProcessor : IProcessor { private readonly RedbRouteOpenIddictServerHandler _handler; public JwksEndpointProcessor(RedbRouteOpenIddictServerHandler handler) => _handler = handler; public async Task Process(IExchange exchange, CancellationToken ct = default) { await _handler.ProcessAsync(exchange, OpenIddictServerEndpointType.JsonWebKeySet, ct); // D2: JWKS rotation overlap — RPs MUST cache (OIDC Core §10.1.1) but a too-long // TTL delays detecting a newly-rotated key. One hour matches Microsoft / Google / // Auth0 conventions and is well within the typical 24-72h overlap window. if (exchange.HasOut) { exchange.Out!.Headers["Cache-Control"] = "public, max-age=3600"; exchange.Out!.Headers.TryAdd("Vary", "Accept"); } } } /// /// Token introspection endpoint (RFC 7662). /// internal sealed class IntrospectionEndpointProcessor : IProcessor { private readonly RedbRouteOpenIddictServerHandler _handler; public IntrospectionEndpointProcessor(RedbRouteOpenIddictServerHandler handler) => _handler = handler; public async Task Process(IExchange exchange, CancellationToken ct = default) { await _handler.ProcessAsync(exchange, OpenIddictServerEndpointType.Introspection, ct); // H6 (RFC 7662): emit audit for every well-formed introspection (not for invalid_request // — protocol-level wire errors are noise, not security signals). var body = (exchange.HasOut ? exchange.Out!.Body : exchange.In.Body) as IDictionary; var isInvalidRequest = body?.TryGetValue("error", out var err) == true && err?.ToString() == "invalid_request"; if (isInvalidRequest) return; var active = body?.TryGetValue("active", out var a) == true && a is bool b && b; exchange.Properties["identity-event-type"] = IdentityAuditEventIds.TokenIntrospected; exchange.Properties["identity-event-data"] = new { ClientId = exchange.In.GetHeader("client_id"), Active = active }; } } /// /// Token revocation endpoint (RFC 7009). /// internal sealed class RevocationEndpointProcessor : IProcessor { private readonly RedbRouteOpenIddictServerHandler _handler; private readonly TimeProvider _timeProvider; public RevocationEndpointProcessor(RedbRouteOpenIddictServerHandler handler, TimeProvider? timeProvider = null) { _handler = handler; _timeProvider = timeProvider ?? TimeProvider.System; } public async Task Process(IExchange exchange, CancellationToken ct = default) { await _handler.ProcessAsync(exchange, OpenIddictServerEndpointType.Revocation, ct); // Only suppress TokenRevoked event for malformed requests (e.g. missing token parameter). // Per RFC 7009, the server SHOULD return 200 even for invalid/unknown tokens, // so we fire the event for all well-formed requests. var body = (exchange.HasOut ? exchange.Out!.Body : exchange.In.Body) as IDictionary; var isInvalidRequest = body?.TryGetValue("error", out var err) == true && err?.ToString() == "invalid_request"; if (!isInvalidRequest) { exchange.Properties["identity-event-type"] = IdentityAuditEventIds.TokenRevoked; exchange.Properties["identity-event-data"] = new { ClientId = exchange.In.GetHeader("client_id"), // The owner of the revoked token (CaptureRevokedTokenUserHandler); null for a client // token or a token Identity does not know. UserId = exchange.Properties.TryGetValue(CaptureRevokedTokenUserHandler.ExchangeProperty, out var userId) ? userId as string : null, Timestamp = _timeProvider.GetUtcNow() }; } } } /// /// Pushed Authorization Request endpoint (RFC 9126 / Z6). The caller pushes the /// authorization parameters (client_id, redirect_uri, scope, state, code_challenge, /// …) over a back-channel POST to /connect/par and receives a one-time /// request_uri to be included on the next user-agent redirect to /connect/authorize. /// All validation — client auth, PKCE, scope, redirect_uri — is handled by OpenIddict. /// internal sealed class PushedAuthorizationEndpointProcessor : IProcessor { private readonly RedbRouteOpenIddictServerHandler _handler; public PushedAuthorizationEndpointProcessor(RedbRouteOpenIddictServerHandler handler) => _handler = handler; public async Task Process(IExchange exchange, CancellationToken ct = default) { await _handler.ProcessAsync(exchange, OpenIddictServerEndpointType.PushedAuthorization, ct); // Audit: success when body contains request_uri (per RFC 9126 §2.2), // failure when body contains "error". var body = (exchange.HasOut ? exchange.Out!.Body : exchange.In.Body) as IDictionary; if (body is null) return; if (body.ContainsKey("request_uri")) { exchange.Properties["identity-event-type"] = redb.Identity.Contracts.Routes.IdentityAuditEventIds.ParRequestAccepted; exchange.Properties["identity-event-data"] = new { ClientId = exchange.In.GetHeader("client_id"), }; } else if (body.TryGetValue("error", out var err)) { exchange.Properties["identity-event-type"] = redb.Identity.Contracts.Routes.IdentityAuditEventIds.ParRequestRejected; exchange.Properties["identity-event-data"] = new { ClientId = exchange.In.GetHeader("client_id"), Error = err?.ToString() }; } } } /// /// Device authorization endpoint (RFC 8628). /// internal sealed class DeviceEndpointProcessor : IProcessor { private readonly RedbRouteOpenIddictServerHandler _handler; public DeviceEndpointProcessor(RedbRouteOpenIddictServerHandler handler) => _handler = handler; public async Task Process(IExchange exchange, CancellationToken ct = default) { await _handler.ProcessAsync(exchange, OpenIddictServerEndpointType.DeviceAuthorization, ct); // H7 (RFC 8628): emit DeviceCodeIssued only on success (presence of device_code in body). var body = (exchange.HasOut ? exchange.Out!.Body : exchange.In.Body) as IDictionary; if (body?.ContainsKey("device_code") == true) { exchange.Properties["identity-event-type"] = IdentityAuditEventIds.DeviceCodeIssued; exchange.Properties["identity-event-data"] = new { ClientId = exchange.In.GetHeader("client_id"), }; } } } /// /// End-user verification endpoint (RFC 8628 §3.3). /// The user enters the user_code and authenticates to approve the device. /// internal sealed class VerificationEndpointProcessor : IProcessor { private readonly RedbRouteOpenIddictServerHandler _handler; public VerificationEndpointProcessor(RedbRouteOpenIddictServerHandler handler) => _handler = handler; public async Task Process(IExchange exchange, CancellationToken ct = default) { await _handler.ProcessAsync(exchange, OpenIddictServerEndpointType.EndUserVerification, ct); exchange.Properties["identity-event-type"] = IdentityAuditEventIds.DeviceCodeVerified; } } Path: redb-identity/src/redb.Identity.Core/Routes/Processors/EventDispatchProcessor.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/Routes/Processors/EventDispatchProcessor.cs ---- using System.Reflection; using System.Text.Json; using Microsoft.Extensions.Logging; using redb.Identity.Contracts.Events; using redb.Identity.Core.Configuration; using redb.Route.Abstractions; namespace redb.Identity.Core.Routes.Processors; /// /// Receives WireTap copies from mutating endpoints. /// Reads event properties set by upstream processors, creates typed , /// applies the audit filter, and prepares headers for downstream audit targets (SQL param binding, etc.). /// internal sealed class EventDispatchProcessor : IProcessor { private readonly ILogger _logger; private readonly HashSet? _allowedEventTypes; private readonly TimeProvider _timeProvider; public EventDispatchProcessor(ILogger logger, IdentityAuditOptions? auditOptions = null, TimeProvider? timeProvider = null) { _logger = logger; _timeProvider = timeProvider ?? TimeProvider.System; if (auditOptions is { Enabled: true, Filter: not ("*" or "" or null) }) { _allowedEventTypes = new HashSet( auditOptions.Filter.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries), StringComparer.OrdinalIgnoreCase); } } public Task Process(IExchange exchange, CancellationToken ct = default) { // The exchange is the WireTap copy of the originating request: its In carries that request's // headers (Authorization, client_secret and the other form fields, cookies, redbHttp.*), its body // and attachments, and its Out the response. None of it may reach the audit sink, the webhook // delivery or the audit targets. An exchange that yields no event goes no further; one that does // leaves this step carrying the event and its own headers only. var eventType = exchange.GetProperty("identity-event-type"); if (string.IsNullOrEmpty(eventType)) { exchange.Stop(); return Task.CompletedTask; } // Apply filter — skip events not in whitelist if (_allowedEventTypes is not null && !_allowedEventTypes.Contains(eventType)) { exchange.Stop(); return Task.CompletedTask; } var detailsDict = exchange.GetProperty("identity-event-data") switch { Dictionary d => d, null => null, { } obj => obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance) .ToDictionary(p => p.Name, p => (object?)p.GetValue(obj)) }; // A management call carries the validated token (ManagementBearerAuthProcessor): its client and subject // are who made the change. Only the subject and the client id are read, never the token. var actor = exchange.GetProperty("identity:management-principal"); var actorClientId = actor?.FindFirst(global::OpenIddict.Abstractions.OpenIddictConstants.Claims.ClientId)?.Value; var actorSubject = actor?.FindFirst(global::OpenIddict.Abstractions.OpenIddictConstants.Claims.Subject)?.Value; var identityEvent = new IdentityEvent { EventType = eventType, Timestamp = _timeProvider.GetUtcNow(), ClientId = exchange.In.GetHeader("client_id") ?? actorClientId, ActorSubject = actorSubject, // user_id resolution order: explicit header (top priority) → // UserId field on the identity-event-data payload (the common // shape — most emitters stamp it). Keeps per-user audit filters // hitting the indexed user_id column instead of falling back to // the wider login OR-clause on every query. UserId = exchange.In.GetHeader("user_id") ?? ExtractStringFromDetails(detailsDict, "UserId"), // ip_address / user_agent are internal names an HTTP client can no longer supply // (the facade strips them on ingress); for HTTP-originated events fall back to the // transport-owned, proxy-sanitized remote address and the real User-Agent header. IpAddress = exchange.In.GetHeader("ip_address") ?? exchange.In.GetHeader("redbHttp.RemoteAddress"), UserAgent = exchange.In.GetHeader("user_agent") ?? exchange.In.GetHeader("User-Agent"), Details = detailsDict }; _logger.LogDebug("Identity event: {EventType}", eventType); // Prepare exchange for downstream audit targets. // Body carries the typed IdentityEvent + ContentType="application/json" — the OAuth/OIDC // domain is RFC-defined in JSON shape, but each downstream transport (Kafka/Elasticsearch/ // RabbitMQ/log) is responsible for its own wire encoding via IDataFormatRegistry, or the // route DSL inserts an explicit .Marshal() step at the boundary. Core MUST NOT pre-serialise // to string/bytes here: that would lock every sink to JSON and break proto/avro/CBOR sinks. // Fresh messages on both sides: the pipeline merges Out headers into In, so the request's In must // go, and a response already on Out must not be reused. exchange.In = new redb.Route.Core.Message(); exchange.Out = new redb.Route.Core.Message(); exchange.Out.Body = identityEvent; exchange.Out.ContentType = "application/json"; exchange.Out.Headers["event-type"] = eventType; // Headers for SQL param binding (auto-bind by parameter name from exchange.In.Headers) exchange.Out.Headers["event_id"] = Guid.Parse(identityEvent.EventId); exchange.Out.Headers["event_type"] = identityEvent.EventType; exchange.Out.Headers["timestamp"] = identityEvent.Timestamp; exchange.Out.Headers["user_id"] = identityEvent.UserId ?? (object)DBNull.Value; exchange.Out.Headers["client_id"] = identityEvent.ClientId ?? (object)DBNull.Value; exchange.Out.Headers["actor_subject"] = identityEvent.ActorSubject ?? (object)DBNull.Value; exchange.Out.Headers["ip_address"] = identityEvent.IpAddress ?? (object)DBNull.Value; exchange.Out.Headers["user_agent"] = identityEvent.UserAgent ?? (object)DBNull.Value; // Typed details — the PROPS sink owns its own persistence encoding (DetailsJson column). // Wire-encoding for external transports happens at the boundary via .Marshal(...) in the DSL. // The header carries the JSON string only because it doubles as an SQL bind parameter for // jsonb columns (Npgsql parameters require ground-typed values, not arbitrary objects). // This is a persistence-binding contract for headers, NOT a wire encoding for Body. exchange.Out.Headers["details"] = identityEvent.Details is { Count: > 0 } detailsMap ? JsonSerializer.Serialize(detailsMap) : (object)DBNull.Value; return Task.CompletedTask; } /// /// Pull a string field off the (anonymous-object-shaped or Dictionary-shaped) /// identity-event-data payload. Used as a fallback to surface canonical /// audit columns (UserId, Login, ...) when the emitter put them on the /// payload but not on the exchange header. /// private static string? ExtractStringFromDetails(Dictionary? details, string key) { if (details is null) return null; if (!details.TryGetValue(key, out var v) || v is null) return null; return v switch { string s => string.IsNullOrEmpty(s) ? null : s, long l => l.ToString(System.Globalization.CultureInfo.InvariantCulture), int i => i.ToString(System.Globalization.CultureInfo.InvariantCulture), Guid g => g.ToString("D"), _ => v.ToString() }; } } Path: redb-identity/src/redb.Identity.Core/Routes/Processors/FederationCallbackProcessor.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/Routes/Processors/FederationCallbackProcessor.cs ---- using Microsoft.Extensions.DependencyInjection; using redb.Core; using redb.Identity.Core.Services; using redb.Route.Abstractions; using redb.Route.Core; using redb.Identity.Contracts.Routes; namespace redb.Identity.Core.Routes.Processors; /// /// Core route processor for the Federation Callback endpoint. /// Handles the IdP redirect: decrypts state, exchanges authorization code for tokens, /// resolves/provisions local user, creates session, and returns redirect data. /// internal sealed class FederationCallbackProcessor : IProcessor { private readonly IServiceProvider _sp; public FederationCallbackProcessor(IServiceProvider sp) => _sp = sp; public async Task Process(IExchange exchange, CancellationToken ct = default) { var body = exchange.In.Body as IDictionary; var code = body?.TryGetValue("code", out var c) == true ? c?.ToString() : null; var stateParam = body?.TryGetValue("state", out var s) == true ? s?.ToString() : null; var errorParam = body?.TryGetValue("error", out var ep) == true ? ep?.ToString() : null; var callbackUrl = body?.TryGetValue("callbackUrl", out var cb) == true ? cb?.ToString() : null; // IdP returned an error (user denied consent, etc.) if (!string.IsNullOrEmpty(errorParam)) { var errorDesc = body?.TryGetValue("error_description", out var ed) == true ? ed?.ToString() : null; exchange.Out = new Message(); exchange.Out.Body = new Dictionary { ["success"] = false, ["error"] = errorParam, ["error_description"] = errorDesc ?? "External authentication failed." }; return; } if (string.IsNullOrEmpty(code) || string.IsNullOrEmpty(stateParam)) { exchange.Out = new Message(); exchange.Out.Body = new Dictionary { ["success"] = false, ["error"] = "invalid_request", ["error_description"] = "Missing 'code' or 'state' parameter." }; return; } // Decrypt and validate state (CSRF + replay protection via TTL + one-time-use jti + optional browser-binding) var stateProtector = _sp.GetRequiredService(); var bindingSecret = exchange.Properties.TryGetValue("federation-binding-secret", out var bs) ? bs?.ToString() : null; var timeProvider = _sp.GetService() ?? TimeProvider.System; var (state, failure) = await stateProtector.UnprotectAsync(stateParam, bindingSecret, ct).ConfigureAwait(false); if (state is null) { var error = failure switch { FederationStateValidationFailure.Expired => "invalid_state", FederationStateValidationFailure.AlreadyUsed => "invalid_state", FederationStateValidationFailure.BindingMismatch => "invalid_state", _ => "invalid_state", }; var description = failure switch { FederationStateValidationFailure.Expired => "State parameter is expired.", FederationStateValidationFailure.AlreadyUsed => "State parameter has already been used.", FederationStateValidationFailure.BindingMismatch => "Browser-binding cookie missing or mismatched.", _ => "State parameter is invalid or expired.", }; exchange.Properties["identity-event-type"] = IdentityAuditEventIds.FederationStateValidationFailed; exchange.Properties["identity-event-data"] = new { Reason = failure.ToString(), Timestamp = timeProvider.GetUtcNow(), }; exchange.Out = new Message(); exchange.Out.Body = new Dictionary { ["success"] = false, ["error"] = error, ["error_description"] = description, }; return; } // Find the federation provider var providers = _sp.GetServices(); var provider = providers.FirstOrDefault(p => p.ProviderId == state.ProviderId); if (provider is null) { exchange.Out = new Message(); exchange.Out.Body = new Dictionary { ["success"] = false, ["error"] = "invalid_request", ["error_description"] = $"Unknown federation provider '{state.ProviderId}'." }; return; } // Exchange authorization code for tokens + validate id_token var extResult = await provider.HandleCallbackAsync( code, callbackUrl ?? "", state.CodeVerifier, state.Nonce, ct).ConfigureAwait(false); if (extResult is null || !extResult.Succeeded) { exchange.Out = new Message(); exchange.Out.Body = new Dictionary { ["success"] = false, ["error"] = "access_denied", ["error_description"] = extResult?.ErrorMessage ?? "Token exchange or validation failed." }; return; } // Resolve or provision user via LoginService (reverse lookup by value_string) using var scope = _sp.CreateScope(); var loginService = scope.ServiceProvider.GetRequiredService(); // H8 (DoD §4 gap (b)): link mode — when the challenge embedded a LinkUserId, // the callback adds the federated identity to the already-known user instead of // performing a login. The link must NOT mint a session; it just records the link // and returns success metadata to the front-end. if (state.LinkUserId is long linkUserId) { try { await loginService.LinkFederatedIdentityAsync(linkUserId, state.ProviderId, extResult, ct) .ConfigureAwait(false); } catch (InvalidOperationException ex) { exchange.Out = new Message(); exchange.Out.Body = new Dictionary { ["success"] = false, ["error"] = "link_conflict", ["error_description"] = ex.Message, ["providerId"] = state.ProviderId, }; return; } exchange.Out = new Message(); exchange.Out.Body = new Dictionary { ["success"] = true, ["linked"] = true, ["userId"] = linkUserId, ["providerId"] = state.ProviderId, ["externalSub"] = extResult.ExternalId, ["returnUrl"] = state.ReturnUrl, }; exchange.Properties["identity-event-type"] = IdentityAuditEventIds.FederatedIdentityLinked; exchange.Properties["identity-event-data"] = new { UserId = linkUserId, ProviderId = state.ProviderId, ExternalSub = extResult.ExternalId, Email = extResult.Email, Timestamp = timeProvider.GetUtcNow() }; return; } var loginResult = await loginService.ResolveFederatedUserAsync( state.ProviderId, extResult, ct).ConfigureAwait(false); if (!loginResult.Succeeded) { // H8 (DoD §4 gap (c)): explicit email-conflict path emits a distinct error // code so the front-end can route to a "log in locally and link your social // account" page instead of showing a generic access_denied message. if (loginResult.IsEmailConflict) { exchange.Out = new Message(); exchange.Out.Body = new Dictionary { ["success"] = false, ["error"] = "email_conflict", ["error_description"] = loginResult.ErrorMessage, ["conflictEmail"] = loginResult.ConflictEmail, ["providerId"] = loginResult.ConflictProviderId, ["externalSub"] = loginResult.ConflictExternalSub, ["returnUrl"] = state.ReturnUrl, }; exchange.Properties["identity-event-type"] = IdentityAuditEventIds.FederatedEmailConflict; exchange.Properties["identity-event-data"] = new { ProviderId = loginResult.ConflictProviderId, ExternalSub = loginResult.ConflictExternalSub, Email = loginResult.ConflictEmail, Timestamp = timeProvider.GetUtcNow() }; return; } exchange.Out = new Message(); exchange.Out.Body = new Dictionary { ["success"] = false, ["error"] = "access_denied", ["error_description"] = loginResult.ErrorMessage }; return; } // Create session (same pattern as LoginProcessor) long sessionId = 0; var redb = scope.ServiceProvider.GetService(); if (redb is not null) { var sessionService = new SessionService(redb, timeProvider); var uaParser = scope.ServiceProvider.GetService(); var device = DeviceMetadataExtractor.Extract(exchange, uaParser); var session = await sessionService.CreateAsync( loginResult.UserId, applicationObjectId: 0, ipAddress: device.IpAddress, userAgent: device.UserAgent, deviceLabel: device.DeviceLabel, ct: ct); sessionId = session.id; } exchange.Out = new Message(); exchange.Out.Body = new Dictionary { ["success"] = true, ["userId"] = loginResult.UserId, ["username"] = loginResult.Username, ["sessionId"] = sessionId, ["returnUrl"] = state.ReturnUrl }; exchange.Properties["identity-event-type"] = IdentityAuditEventIds.FederatedUserLoggedIn; exchange.Properties["identity-event-data"] = new { UserId = loginResult.UserId, Username = loginResult.Username, ProviderId = state.ProviderId, Timestamp = timeProvider.GetUtcNow() }; } } Path: redb-identity/src/redb.Identity.Core/Routes/Processors/FederationChallengeProcessor.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/Routes/Processors/FederationChallengeProcessor.cs ---- using Microsoft.Extensions.DependencyInjection; using redb.Identity.Core.Configuration; using redb.Identity.Core.Services; using redb.Route.Abstractions; using redb.Route.Core; using redb.Identity.Contracts.Routes; namespace redb.Identity.Core.Routes.Processors; /// /// Core route processor for the Federation Challenge endpoint. /// Resolves the requested provider, generates an authorization redirect (PKCE + nonce), /// encrypts state via , and returns a 302 redirect. /// internal sealed class FederationChallengeProcessor : IProcessor { private readonly IServiceProvider _sp; public FederationChallengeProcessor(IServiceProvider sp) => _sp = sp; public async Task Process(IExchange exchange, CancellationToken ct = default) { var body = exchange.In.Body as IDictionary; var providerId = body?.TryGetValue("provider", out var p) == true ? p?.ToString() : null; var returnUrl = body?.TryGetValue("returnUrl", out var r) == true ? r?.ToString() : null; var callbackUrl = body?.TryGetValue("callbackUrl", out var cb) == true ? cb?.ToString() : null; if (string.IsNullOrEmpty(providerId)) { exchange.Out = new Message(); exchange.Out.Body = new Dictionary { ["error"] = "invalid_request", ["error_description"] = "Missing 'provider' parameter." }; return; } // Find the requested federation provider var providers = _sp.GetServices(); var provider = providers.FirstOrDefault(p => p.ProviderId == providerId); if (provider is null) { exchange.Out = new Message(); exchange.Out.Body = new Dictionary { ["error"] = "invalid_request", ["error_description"] = $"Unknown federation provider '{providerId}'." }; return; } if (string.IsNullOrEmpty(callbackUrl)) { exchange.Out = new Message(); exchange.Out.Body = new Dictionary { ["error"] = "server_error", ["error_description"] = "Callback URL not configured." }; return; } // Generate challenge (PKCE + nonce + auth URL) var challenge = await provider.CreateChallengeAsync(callbackUrl, returnUrl ?? "/", ct) .ConfigureAwait(false); // C6: optionally mint per-flow browser-binding secret. The HTTP transport // converts `federation-binding-secret` into a Secure HttpOnly SameSite=Lax cookie. var fedOptions = _sp.GetService()?.FederationState ?? new FederationStateOptions(); string? bindingSecret = null; string? bindingHash = null; if (fedOptions.RequireBrowserBinding) { var raw = new byte[32]; System.Security.Cryptography.RandomNumberGenerator.Fill(raw); bindingSecret = Convert.ToBase64String(raw); bindingHash = FederationStateProtector.ComputeBindingHash(bindingSecret); } // Encrypt state with DataProtection (contains providerId, returnUrl, nonce, codeVerifier, jti, optional bindingHash) var stateProtector = _sp.GetRequiredService(); var protectedState = stateProtector.Protect(new FederationState { ProviderId = providerId, ReturnUrl = returnUrl, Nonce = challenge.Nonce, CodeVerifier = challenge.CodeVerifier, BindingHash = bindingHash, }); // Replace the provider's opaque state with our encrypted state in the redirect URL var redirectUri = challenge.RedirectUri.Replace( Uri.EscapeDataString(challenge.State), Uri.EscapeDataString(protectedState)); exchange.Out = new Message(); exchange.Out.Body = new Dictionary { ["redirect_uri"] = redirectUri }; if (bindingSecret is not null) { exchange.Properties["federation-binding-secret"] = bindingSecret; exchange.Properties["federation-binding-cookie-name"] = fedOptions.BindingCookieName; } exchange.Properties["identity-event-type"] = IdentityAuditEventIds.FederationChallengeInitiated; var timeProvider = _sp.GetService() ?? TimeProvider.System; exchange.Properties["identity-event-data"] = new { ProviderId = providerId, Timestamp = timeProvider.GetUtcNow() }; } } Path: redb-identity/src/redb.Identity.Core/Routes/Processors/FederationProviderManagementProcessor.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/Routes/Processors/FederationProviderManagementProcessor.cs ---- using Microsoft.Extensions.DependencyInjection; using redb.Core; using redb.Core.Models.Entities; using redb.Core.Query; using redb.Core.Services; using redb.Identity.Contracts.Common; using redb.Identity.Contracts.Federation; using redb.Identity.Core.Models; using redb.Identity.Core.Module; using redb.Identity.Core.Services; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.RedbCore.Extensions; using redb.Identity.Contracts.Routes; namespace redb.Identity.Core.Routes.Processors; /// /// H8 (v1.0 DoD §4 gap (e)): admin CRUD over PROPS-stored /// . Operations dispatched on the operation /// header: create | read | update | delete | list. Client secrets are encrypted /// at rest via and never returned in /// responses (only is exposed). /// /// PROPS-stored providers complement (and override) the /// RedbIdentityOptions.FederationProviders list loaded from appsettings.json: /// runtime resolution prefers PROPS when both define the same ProviderId, so existing /// deployments keep working until they migrate to the database. /// /// internal sealed class FederationProviderManagementProcessor : IProcessor { private readonly IRouteContext _context; private readonly string? _redbName; public FederationProviderManagementProcessor(IRouteContext context, string? redbName = null) { _context = context; _redbName = redbName; } public async Task Process(IExchange exchange, CancellationToken ct = default) { var redb = _context.GetRedbService(_redbName, exchange); var protector = _context.GetIdentityService(exchange); var operation = exchange.In.GetHeader("operation") ?? throw new InvalidOperationException("Missing 'operation' header"); switch (operation) { case "create": await Create(redb, protector, exchange, ct); break; case "read": await Read(redb, exchange, ct); break; case "update": await Update(redb, protector, exchange, ct); break; case "delete": await Delete(redb, exchange, ct); break; case "list": await List(redb, exchange, ct); break; default: SetError(exchange, "invalid_operation", $"Unknown operation: {operation}"); break; } } private static async Task Create( IRedbService redb, FederationProviderSecretProtector protector, IExchange exchange, CancellationToken ct) { var request = exchange.In.Body as CreateFederationProviderRequest; if (request is null) { SetError(exchange, "validation_error", "Request body is required"); return; } if (RefuseBlankSecret(exchange, request.ClientSecret)) return; var providerId = request.ProviderId.Trim().ToLowerInvariant(); // Reject duplicates: ProviderId is [RedbUnique] (V4-UNIQUE) so a concurrent insert // would fail at the DB level anyway, but a friendly error here avoids exposing // raw constraint names to the API consumer. var dup = await redb.GetByUniqueAsync(p => p.ProviderId, providerId) .ConfigureAwait(false); if (dup is not null) { SetError(exchange, "duplicate", $"Federation provider '{providerId}' already exists."); return; } var obj = new RedbObject(new FederationProviderProps { ProviderId = providerId, Kind = request.Kind.Trim().ToLowerInvariant(), DisplayName = request.DisplayName.Trim(), Authority = request.Authority, ClientId = request.ClientId.Trim(), EncryptedClientSecret = protector.Protect(request.ClientSecret), Scopes = request.Scopes ?? ["openid", "profile", "email"], AutoProvision = request.AutoProvision, Enabled = request.Enabled, Priority = request.Priority, ClaimMappings = request.ClaimMappings, }); obj.name = providerId; await redb.SaveAsync(obj).ConfigureAwait(false); exchange.Out ??= new Message(); exchange.Out.Body = MapToResponse(obj); exchange.Properties["identity-event-type"] = IdentityAuditEventIds.FederationProviderCreated; exchange.Properties["identity-event-data"] = new { Id = obj.Id, ProviderId = providerId, obj.Props.Kind, obj.Props.Enabled, }; } private static async Task Read(IRedbService redb, IExchange exchange, CancellationToken ct) { var id = TryParseId(exchange); if (id is null) { SetError(exchange, "validation_error", "Id is required"); return; } var obj = await redb.LoadAsync(id.Value).ConfigureAwait(false); if (obj is null) { SetError(exchange, "not_found", $"Federation provider {id} not found"); return; } // Props is the source of truth (V4-UNIQUE); value_string covers legacy rows. if (obj.Props.ProviderId.Length == 0) obj.Props.ProviderId = obj.value_string ?? string.Empty; exchange.Out ??= new Message(); exchange.Out.Body = MapToResponse(obj); } private static async Task Update( IRedbService redb, FederationProviderSecretProtector protector, IExchange exchange, CancellationToken ct) { var request = exchange.In.Body as UpdateFederationProviderRequest; if (request is null || !long.TryParse(request.Id, out var id) || id <= 0) { SetError(exchange, "validation_error", "Id is required"); return; } if (RefuseBlankSecret(exchange, request.ClientSecret)) return; var obj = await redb.LoadAsync(id).ConfigureAwait(false); if (obj is null) { SetError(exchange, "not_found", $"Federation provider {id} not found"); return; } if (obj.Props.ProviderId.Length == 0) obj.Props.ProviderId = obj.value_string ?? string.Empty; // legacy row if (request.Kind != null) obj.Props.Kind = request.Kind.Trim().ToLowerInvariant(); if (request.DisplayName != null) obj.Props.DisplayName = request.DisplayName.Trim(); if (request.Authority != null) obj.Props.Authority = request.Authority; if (request.ClientId != null) obj.Props.ClientId = request.ClientId.Trim(); if (request.ClientSecret != null) { // Empty string ⇒ clear; non-empty ⇒ rotate. Null was already filtered above. obj.Props.EncryptedClientSecret = string.IsNullOrEmpty(request.ClientSecret) ? null : protector.Protect(request.ClientSecret); } if (request.Scopes != null) obj.Props.Scopes = request.Scopes; if (request.AutoProvision.HasValue) obj.Props.AutoProvision = request.AutoProvision.Value; if (request.Enabled.HasValue) obj.Props.Enabled = request.Enabled.Value; if (request.Priority.HasValue) obj.Props.Priority = request.Priority.Value; if (request.ClaimMappings != null) obj.Props.ClaimMappings = request.ClaimMappings; await redb.SaveAsync(obj).ConfigureAwait(false); exchange.Out ??= new Message(); exchange.Out.Body = MapToResponse(obj); exchange.Properties["identity-event-type"] = IdentityAuditEventIds.FederationProviderUpdated; exchange.Properties["identity-event-data"] = new { Id = id, obj.Props.ProviderId }; } private async Task Delete(IRedbService redb, IExchange exchange, CancellationToken ct) { var id = TryParseId(exchange); if (id is null) { SetError(exchange, "validation_error", "Id is required"); return; } var obj = await redb.LoadAsync(id.Value).ConfigureAwait(false); if (obj is null) { SetError(exchange, "not_found", $"Federation provider {id} not found"); return; } // Props is the source of truth; value_string covers not-yet-backfilled legacy rows. var providerId = obj.Props.ProviderId is { Length: > 0 } pid ? pid : obj.value_string ?? string.Empty; // Note: deleting a provider does NOT cascade-delete user FederatedIdentityProps // links — those become "orphaned" but the user can still log in if the same // ProviderId is re-created or remains in appsettings. This matches Keycloak's // behavior (provider deletion does not log users out). var bg = _context.GetIdentityServiceOrDefault(exchange); await IdentityDeletionHelper.DeleteAsync(redb, bg, id.Value).ConfigureAwait(false); exchange.Out ??= new Message(); exchange.Out.Body = new SuccessResponse(); exchange.Properties["identity-event-type"] = IdentityAuditEventIds.FederationProviderDeleted; exchange.Properties["identity-event-data"] = new { Id = id, ProviderId = providerId }; } private static async Task List(IRedbService redb, IExchange exchange, CancellationToken ct) { var request = exchange.In.Body as ListRequest ?? new ListRequest(); var query = redb.Query().OrderByRedb(o => o.Id); var total = await query.CountAsync().ConfigureAwait(false); var count = Math.Min(request.Count, 100); var items = await query.Skip(request.Offset).Take(count).ToListAsync().ConfigureAwait(false); // Props is the source of truth (V4-UNIQUE); value_string covers legacy rows. foreach (var item in items) if (item.Props.ProviderId.Length == 0) item.Props.ProviderId = item.value_string ?? string.Empty; exchange.Out ??= new Message(); exchange.Out.Body = new PagedResult { Items = items.Select(MapToResponse).ToList(), Total = total, Offset = request.Offset, Count = request.Count, }; } /// /// One rule for create and update: null or the empty string means no secret (on update, null leaves the stored /// one alone and the empty string clears it); a value of white space only is refused, because no provider issues /// such a secret and storing it would only fail later at the provider's token endpoint. /// private static bool RefuseBlankSecret(IExchange exchange, string? clientSecret) { if (string.IsNullOrEmpty(clientSecret) || !string.IsNullOrWhiteSpace(clientSecret)) return false; SetError(exchange, "validation_error", "ClientSecret must not be white space only; send an empty string or omit it for no secret."); return true; } private static long? TryParseId(IExchange exchange) { if (exchange.In.Body is not Dictionary dict || !dict.TryGetValue("id", out var idVal) || idVal == null || !long.TryParse(idVal.ToString(), out var id) || id <= 0) return null; return id; } private static void SetError(IExchange exchange, string error, string description) => IdentityProcessorHelpers.SetError(exchange, error, description); private static FederationProviderResponse MapToResponse(RedbObject obj) => new() { Id = obj.Id.ToString(), ProviderId = obj.Props.ProviderId, Kind = obj.Props.Kind, DisplayName = obj.Props.DisplayName, Authority = obj.Props.Authority, ClientId = obj.Props.ClientId, HasSecret = !string.IsNullOrEmpty(obj.Props.EncryptedClientSecret), Scopes = obj.Props.Scopes, AutoProvision = obj.Props.AutoProvision, Enabled = obj.Props.Enabled, Priority = obj.Props.Priority, ClaimMappings = obj.Props.ClaimMappings, }; } Path: redb-identity/src/redb.Identity.Core/Routes/Processors/GroupManagementProcessor.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/Routes/Processors/GroupManagementProcessor.cs ---- using redb.Core.Services; using redb.Identity.Core.Models; using redb.Identity.Core.Services; using redb.Route.Abstractions; using redb.Route.RedbCore.Extensions; using redb.Identity.Contracts.Routes; using redb.Identity.Contracts.Common; using redb.Identity.Contracts.Groups; namespace redb.Identity.Core.Routes.Processors; /// /// Group management processor — dispatches on "operation" header. /// Operations: list, read, create, create-child, update, delete, move, /// tree, path, children, list-members, add-member, update-member, remove-member, /// user-groups, is-member. /// internal sealed class GroupManagementProcessor : IProcessor { private readonly IRouteContext _context; private readonly string? _redbName; private readonly IBackgroundDeletionService? _backgroundDeletion; public GroupManagementProcessor(IRouteContext context, string? redbName = null, IBackgroundDeletionService? backgroundDeletion = null) { _context = context; _redbName = redbName; _backgroundDeletion = backgroundDeletion; } public async Task Process(IExchange exchange, CancellationToken ct = default) { var redb = _context.GetRedbService(_redbName, exchange); var svc = new GroupService(redb, _backgroundDeletion); var operation = exchange.In.GetHeader("operation") ?? throw new InvalidOperationException("Missing 'operation' header"); switch (operation) { case "list": await ListRoots(svc, exchange, ct); break; case "search": await Search(svc, exchange, ct); break; case "read": await Read(svc, exchange, ct); break; case "create": await Create(svc, exchange, ct); break; case "create-child": await CreateChild(svc, exchange, ct); break; case "update": await Update(svc, exchange, ct); break; case "delete": await Delete(svc, exchange, ct); break; case "move": await Move(svc, exchange, ct); break; case "tree": await Tree(svc, exchange, ct); break; case "path": await Path(svc, exchange, ct); break; case "list-members": await ListMembers(svc, exchange, ct); break; case "add-member": await AddMember(svc, exchange, ct); break; case "update-member": await UpdateMember(svc, exchange, ct); break; case "remove-member": await RemoveMember(svc, exchange, ct); break; case "children": await Children(svc, exchange, ct); break; case "is-member": await IsMember(svc, exchange, ct); break; case "user-groups": await UserGroups(svc, exchange, ct); break; default: SetError(exchange, "invalid_operation", $"Unknown operation: {operation}"); break; } } // ── Group CRUD ────────────────────────────────────────────── private static async Task ListRoots(IGroupService svc, IExchange exchange, CancellationToken ct) { var groups = await svc.ListRootGroupsAsync(ct); SetResult(exchange, groups.Select(g => MapGroup(g)).ToList()); } private static async Task Search(IGroupService svc, IExchange exchange, CancellationToken ct) { var dict = exchange.In.Body as Dictionary ?? new(); string? query = dict.TryGetValue("query", out var q) ? q?.ToString() : null; string? groupType = dict.TryGetValue("groupType", out var t) ? t?.ToString() : null; var offset = 0; var count = 25; if (dict.TryGetValue("offset", out var oVal) && int.TryParse(oVal?.ToString(), out var parsedOff)) offset = Math.Max(0, parsedOff); if (dict.TryGetValue("count", out var cVal) && int.TryParse(cVal?.ToString(), out var parsedCount)) count = Math.Clamp(parsedCount, 1, 200); var (items, total) = await svc.SearchGroupsAsync( string.IsNullOrWhiteSpace(query) ? null : query, string.IsNullOrWhiteSpace(groupType) ? null : groupType, offset, count, ct).ConfigureAwait(false); // One bulk member-count query for every visible row (vs N round-trips // if the UI did "list then count each"). var counts = await svc.CountMembersByGroupAsync(items.Select(i => i.Id), ct).ConfigureAwait(false); SetResult(exchange, new PagedResult { Items = items.Select(g => MapGroup(g, counts.GetValueOrDefault(g.Id, 0))).ToList(), Total = total, Offset = offset, Count = count }); } private static async Task Read(IGroupService svc, IExchange exchange, CancellationToken ct) { var id = IdentityProcessorHelpers.ExtractRequiredLong(exchange, "groupId"); var group = await svc.GetGroupAsync(id, ct); if (group is null) { SetError(exchange, "not_found", $"Group {id} not found"); return; } SetResult(exchange, MapGroup(group)); } private static async Task Create(IGroupService svc, IExchange exchange, CancellationToken ct) { var dict = RequireBody(exchange); var name = dict.GetValueOrDefault("name")?.ToString() ?? throw new InvalidOperationException("name is required"); var groupType = dict.GetValueOrDefault("groupType")?.ToString(); var description = dict.GetValueOrDefault("description")?.ToString(); var group = await svc.CreateGroupAsync(name, groupType, description, ct); SetResult(exchange, MapGroup(group)); exchange.Properties["identity-event-type"] = IdentityAuditEventIds.GroupCreated; exchange.Properties["identity-event-data"] = new { GroupId = group.id, Name = name }; } private static async Task CreateChild(IGroupService svc, IExchange exchange, CancellationToken ct) { var dict = RequireBody(exchange); var parentId = IdentityProcessorHelpers.ExtractLong(dict, "parentGroupId") ?? throw new InvalidOperationException("parentGroupId is required"); var name = dict.GetValueOrDefault("name")?.ToString() ?? throw new InvalidOperationException("name is required"); var groupType = dict.GetValueOrDefault("groupType")?.ToString(); var description = dict.GetValueOrDefault("description")?.ToString(); if (!await ExistsAsync(svc, exchange, parentId, "Parent group", ct)) return; var group = await svc.CreateChildGroupAsync(parentId, name, groupType, description, ct); SetResult(exchange, MapGroup(group)); exchange.Properties["identity-event-type"] = IdentityAuditEventIds.GroupCreated; exchange.Properties["identity-event-data"] = new { GroupId = group.id, ParentGroupId = parentId, Name = name }; } private static async Task Update(IGroupService svc, IExchange exchange, CancellationToken ct) { var dict = RequireBody(exchange); var id = IdentityProcessorHelpers.ExtractLong(dict, "groupId") ?? IdentityProcessorHelpers.ExtractRequiredLong(exchange, "groupId"); var name = dict.GetValueOrDefault("name")?.ToString(); var groupType = dict.GetValueOrDefault("groupType")?.ToString(); var description = dict.GetValueOrDefault("description")?.ToString(); if (!await ExistsAsync(svc, exchange, id, "Group", ct)) return; await svc.UpdateGroupAsync(id, name, groupType, description, ct); SetResult(exchange, new GroupChangedResponse { GroupId = id }); exchange.Properties["identity-event-type"] = IdentityAuditEventIds.GroupUpdated; exchange.Properties["identity-event-data"] = new { GroupId = id }; } private static async Task Delete(IGroupService svc, IExchange exchange, CancellationToken ct) { var id = IdentityProcessorHelpers.ExtractRequiredLong(exchange, "groupId"); if (!await ExistsAsync(svc, exchange, id, "Group", ct)) return; await svc.DeleteGroupAsync(id, ct); SetResult(exchange, new GroupChangedResponse { GroupId = id }); exchange.Properties["identity-event-type"] = IdentityAuditEventIds.GroupDeleted; exchange.Properties["identity-event-data"] = new { GroupId = id }; } // ── Tree operations ───────────────────────────────────────── private static async Task Move(IGroupService svc, IExchange exchange, CancellationToken ct) { var dict = RequireBody(exchange); var id = IdentityProcessorHelpers.ExtractLong(dict, "groupId") ?? IdentityProcessorHelpers.ExtractRequiredLong(exchange, "groupId"); var newParentId = IdentityProcessorHelpers.ExtractLong(dict, "newParentGroupId") ?? throw new InvalidOperationException("newParentGroupId is required"); if (!await ExistsAsync(svc, exchange, id, "Group", ct)) return; if (!await ExistsAsync(svc, exchange, newParentId, "Target parent group", ct)) return; await svc.MoveGroupAsync(id, newParentId, ct); SetResult(exchange, new GroupMovedResponse { GroupId = id, NewParentGroupId = newParentId }); exchange.Properties["identity-event-type"] = IdentityAuditEventIds.GroupMoved; exchange.Properties["identity-event-data"] = new { GroupId = id, NewParentGroupId = newParentId }; } private static async Task Tree(IGroupService svc, IExchange exchange, CancellationToken ct) { var id = IdentityProcessorHelpers.ExtractRequiredLong(exchange, "groupId"); int? maxDepth = null; if (exchange.In.Body is Dictionary dict && dict.TryGetValue("maxDepth", out var md) && md is not null && int.TryParse(md.ToString(), out var d)) maxDepth = d; if (!await ExistsAsync(svc, exchange, id, "Group", ct)) return; var tree = await svc.LoadTreeAsync(id, maxDepth, ct); SetResult(exchange, MapTreeNode(tree)); } private static async Task Path(IGroupService svc, IExchange exchange, CancellationToken ct) { var id = IdentityProcessorHelpers.ExtractRequiredLong(exchange, "groupId"); if (!await ExistsAsync(svc, exchange, id, "Group", ct)) return; var path = await svc.GetPathToRootAsync(id, ct); SetResult(exchange, path.Select(g => MapGroup(g)).ToList()); } // ── Membership ────────────────────────────────────────────── private static async Task ListMembers(IGroupService svc, IExchange exchange, CancellationToken ct) { var groupId = IdentityProcessorHelpers.ExtractRequiredLong(exchange, "groupId"); if (!await ExistsAsync(svc, exchange, groupId, "Group", ct)) return; var members = await svc.GetMembersAsync(groupId, ct); SetResult(exchange, members); } private static async Task AddMember(IGroupService svc, IExchange exchange, CancellationToken ct) { var dict = RequireBody(exchange); var groupId = IdentityProcessorHelpers.ExtractLong(dict, "groupId") ?? IdentityProcessorHelpers.ExtractRequiredLong(exchange, "groupId"); var userId = IdentityProcessorHelpers.ExtractLong(dict, "userId") ?? throw new InvalidOperationException("userId is required"); var role = dict.GetValueOrDefault("role")?.ToString() ?? "member"; DateTimeOffset? expiresAt = null; if (dict.TryGetValue("expiresAt", out var ea) && ea is not null && DateTimeOffset.TryParse(ea.ToString(), out var parsed)) expiresAt = parsed; if (!await ExistsAsync(svc, exchange, groupId, "Group", ct)) return; var member = await svc.AddMemberAsync(groupId, userId, role, expiresAt, ct); SetResult(exchange, new GroupMemberAddedResponse { MembershipId = member.id, GroupId = groupId, UserId = userId, Role = role }); exchange.Properties["identity-event-type"] = IdentityAuditEventIds.MemberAdded; exchange.Properties["identity-event-data"] = new { GroupId = groupId, UserId = userId, Role = role }; } private static async Task UpdateMember(IGroupService svc, IExchange exchange, CancellationToken ct) { var dict = RequireBody(exchange); var groupId = IdentityProcessorHelpers.ExtractLong(dict, "groupId") ?? IdentityProcessorHelpers.ExtractRequiredLong(exchange, "groupId"); var userId = IdentityProcessorHelpers.ExtractLong(dict, "userId") ?? throw new InvalidOperationException("userId is required"); var role = dict.GetValueOrDefault("role")?.ToString() ?? throw new InvalidOperationException("role is required"); if (!await MembershipExistsAsync(svc, exchange, groupId, userId, ct)) return; await svc.UpdateMemberRoleAsync(groupId, userId, role, ct); SetResult(exchange, new GroupMemberChangedResponse { GroupId = groupId, UserId = userId, Role = role }); exchange.Properties["identity-event-type"] = IdentityAuditEventIds.MemberUpdated; exchange.Properties["identity-event-data"] = new { GroupId = groupId, UserId = userId, Role = role }; } private static async Task RemoveMember(IGroupService svc, IExchange exchange, CancellationToken ct) { var dict = RequireBody(exchange); var groupId = IdentityProcessorHelpers.ExtractLong(dict, "groupId") ?? IdentityProcessorHelpers.ExtractRequiredLong(exchange, "groupId"); var userId = IdentityProcessorHelpers.ExtractLong(dict, "userId") ?? throw new InvalidOperationException("userId is required"); if (!await MembershipExistsAsync(svc, exchange, groupId, userId, ct)) return; await svc.RemoveMemberAsync(groupId, userId, ct); SetResult(exchange, new GroupMemberRemovedResponse { GroupId = groupId, UserId = userId }); exchange.Properties["identity-event-type"] = IdentityAuditEventIds.MemberRemoved; exchange.Properties["identity-event-data"] = new { GroupId = groupId, UserId = userId }; } private static async Task UserGroups(IGroupService svc, IExchange exchange, CancellationToken ct) { var userId = IdentityProcessorHelpers.ExtractRequiredLong(exchange, "userId"); var groups = await svc.GetUserGroupsAsync(userId, ct); SetResult(exchange, groups); } private static async Task Children(IGroupService svc, IExchange exchange, CancellationToken ct) { var groupId = IdentityProcessorHelpers.ExtractRequiredLong(exchange, "groupId"); if (!await ExistsAsync(svc, exchange, groupId, "Group", ct)) return; var children = await svc.GetChildGroupsAsync(groupId, ct); SetResult(exchange, children.Select(g => MapGroup(g)).ToList()); } private static async Task IsMember(IGroupService svc, IExchange exchange, CancellationToken ct) { var dict = RequireBody(exchange); var groupId = IdentityProcessorHelpers.ExtractLong(dict, "groupId") ?? IdentityProcessorHelpers.ExtractRequiredLong(exchange, "groupId"); var userId = IdentityProcessorHelpers.ExtractLong(dict, "userId") ?? throw new InvalidOperationException("userId is required"); if (!await ExistsAsync(svc, exchange, groupId, "Group", ct)) return; var result = await svc.IsMemberAsync(groupId, userId, ct); SetResult(exchange, new GroupMembershipCheckResponse { IsMember = result, GroupId = groupId, UserId = userId }); } // ── Helpers ───────────────────────────────────────────────── private static Dictionary RequireBody(IExchange exchange) => exchange.In.Body as Dictionary ?? throw new InvalidOperationException("Body is required"); /// /// Answers "not found" for a group that does not exist and says whether the operation may go on. /// The group service reports a missing group with an InvalidOperationException; left to reach the /// route it was answered as a server error, about a record the caller merely named wrongly. /// private static async Task ExistsAsync( IGroupService svc, IExchange exchange, long groupId, string what, CancellationToken ct) { if (await svc.GetGroupAsync(groupId, ct) is not null) return true; SetError(exchange, "not_found", $"{what} {groupId} not found"); return false; } /// /// Answers "not found" when the user has no membership record in the group (which covers a group /// that does not exist) and says whether the operation may go on. The question is the record the /// update and the removal act on, expired or not, and not IsMemberAsync: that one would /// refuse an expired membership, which must stay removable, and accept one inherited from an /// ancestor group, for which there is no record here to change. /// private static async Task MembershipExistsAsync( IGroupService svc, IExchange exchange, long groupId, long userId, CancellationToken ct) { if (await svc.HasMembershipRecordAsync(groupId, userId, ct)) return true; SetError(exchange, "not_found", $"User {userId} has no membership in group {groupId}"); return false; } private static void SetResult(IExchange exchange, object body) { exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = body; } private static void SetError(IExchange exchange, string error, string description) => IdentityProcessorHelpers.SetError(exchange, error, description); // A group created with a name only has no props rows and loads with Props null. private static GroupResponse MapGroup(redb.Core.Models.Entities.RedbObject g, int? memberCount = null) => new() { Id = g.id, Name = g.name, ParentId = g.parent_id, GroupType = g.Props?.GroupType, Description = g.Props?.Description, CreatedAt = g.date_create, ModifiedAt = g.date_modify, MemberCount = memberCount }; private static GroupTreeNodeResponse MapTreeNode(redb.Core.Models.Entities.TreeRedbObject node) => new() { Id = node.id, Name = node.name, ParentId = node.parent_id, GroupType = node.Props?.GroupType, Description = node.Props?.Description, Level = node.Level, Children = node.Children .OfType>() .Select(c => MapTreeNode(c)) .ToList() }; } Path: redb-identity/src/redb.Identity.Core/Routes/Processors/IdempotencyKeyHash.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/Routes/Processors/IdempotencyKeyHash.cs ---- using System.Security.Cryptography; using System.Text; namespace redb.Identity.Core.Routes.Processors; /// /// The idempotency-record unique key /// is _objects._value_unique = SHA-256 of the composite name, hex-lowercase (64 chars, /// always under the 440-char ValueUnique limit — the raw composite /// idem:{scope}:{operation}:{caller}:{key} is unbounded because caller subject and the /// client-chosen Idempotency-Key are). The readable composite stays in _objects._name /// exactly as before; only the enforced key is hashed. Collisions are negligible for this /// small, TTL-reaped table, and the defensive Props equality check in the processor guards /// the replay path regardless. /// internal static class IdempotencyKeyHash { public static string Sha256Hex(string composite) => Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(composite))).ToLowerInvariant(); } Path: redb-identity/src/redb.Identity.Core/Routes/Processors/IdempotencyProcessor.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/Routes/Processors/IdempotencyProcessor.cs ---- using System.Text.Json; using Microsoft.Extensions.Logging; using redb.Core; using redb.Core.Models.Entities; using redb.Identity.Contracts.Common; using redb.Identity.Core.Configuration; using redb.Identity.Core.Models; using redb.Route.Abstractions; using redb.Route.RedbCore.Extensions; namespace redb.Identity.Core.Routes.Processors; // Internal property keys shared between the PRE / POST processors. internal static class IdempotencyProperties { public const string Name = "__idempotency:name"; public const string Scope = "__idempotency:scope"; public const string Method = "__idempotency:method"; public const string Operation = "__idempotency:operation"; public const string Caller = "__idempotency:caller"; public const string Key = "__idempotency:key"; public const string CacheHit = "idempotency:cache-hit"; } /// /// E2 — pre-step that consults the idempotency cache. /// /// If no Idempotency-Key header is present (or it is too long), /// the processor is a no-op. /// On a cache hit (matching record whose date_complete is in the /// future), the cached body and HTTP status are written to exchange.Out (or, for a record /// kept without its body because the answer carried a one-time secret, a /// with that status) and the /// route is short-circuited via — downstream business /// processors and WireTap do NOT run, so no audit event is emitted for the /// replayed response (intended: the original event was emitted on first execution). /// On a cache miss, request metadata is stashed in /// for the paired /// to consume after the business step completes. /// /// internal sealed class IdempotencyProcessor : IProcessor { private readonly IRouteContext _context; private readonly string? _redbName; private readonly string _scope; private readonly IdempotencyOptions _options; private readonly TimeProvider _timeProvider; private readonly ILogger? _logger; public IdempotencyProcessor( IRouteContext context, string? redbName, string scope, IdempotencyOptions options, TimeProvider? timeProvider = null, ILogger? logger = null) { _context = context; _redbName = redbName; _scope = scope; _options = options; _timeProvider = timeProvider ?? TimeProvider.System; _logger = logger; } public async Task Process(IExchange exchange, CancellationToken ct = default) { if (!_options.Enabled) return; // Headers dictionary is OrdinalIgnoreCase — single lookup is enough. var key = exchange.In.GetHeader("Idempotency-Key"); if (string.IsNullOrWhiteSpace(key)) return; if (key.Length > _options.MaxKeyLength) return; var operation = exchange.In.GetHeader("operation") ?? "default"; var method = exchange.In.GetHeader("redbHttp.Method") ?? string.Empty; var caller = ResolveCaller(exchange); var name = ComposeName(_scope, operation, caller, key); // Stash for the capture processor BEFORE we attempt the lookup so that a transient // read failure still allows the business step to run (capture will then write a // fresh record on completion). exchange.Properties[IdempotencyProperties.Name] = name; exchange.Properties[IdempotencyProperties.Scope] = _scope; exchange.Properties[IdempotencyProperties.Method] = method; exchange.Properties[IdempotencyProperties.Operation] = operation; exchange.Properties[IdempotencyProperties.Caller] = caller; exchange.Properties[IdempotencyProperties.Key] = key; try { var redb = _context.GetRedbService(_redbName, exchange); var now = _timeProvider.GetUtcNow(); // V4-UNIQUE: the enforced key is // ValueUnique = SHA-256(name) — a probe of the core unique index; the Name // lookup covers legacy rows written before the upgrade (they fade with the TTL). var keyHash = IdempotencyKeyHash.Sha256Hex(name); var matches = await redb.Query() .WhereRedb(o => o.ValueUnique == keyHash) .ToListAsync() .ConfigureAwait(false); if (matches.Count == 0) matches = await redb.Query() .WhereRedb(o => o.Name == name) .ToListAsync() .ConfigureAwait(false); // Defensive equality check on Props guards against any name collision from a // foreign scheme that happens to share the composite name format. var hit = matches.FirstOrDefault(m => m.Props.Scope == _scope && m.Props.Operation == operation && m.Props.CallerSubject == caller && m.Props.IdempotencyKey == key && m.date_complete is { } dc && dc > now); if (hit is null) return; exchange.Out ??= new redb.Route.Core.Message(); // As JSON, like every replayed body, so each transport writes it the way it writes a replay today. exchange.Out.Body = hit.Props.SecretWithheld ? WithheldReplayBody : DeserializeBody(hit.Props.ResponseBody); exchange.Out.Headers["redbHttp.ResponseCode"] = hit.Props.StatusCode; exchange.Out.Headers["Idempotency-Replayed"] = "true"; exchange.Properties[IdempotencyProperties.CacheHit] = true; _logger?.LogDebug( "Idempotency cache hit for scope={Scope} operation={Operation} caller={Caller}.", _scope, operation, caller); exchange.Stop(); } catch (Exception ex) { // Cache lookup failures must NOT prevent the business operation from running. // Worst case the client sees the response twice — same as today. _logger?.LogWarning(ex, "Idempotency lookup failed; proceeding without cache."); } } private static readonly JsonElement WithheldReplayBody = JsonSerializer.SerializeToElement(new SecretWithheldReplayResponse()); internal static string ComposeName(string scope, string operation, string caller, string key) => $"idem:{scope}:{operation}:{caller}:{key}"; internal static string ResolveCaller(IExchange exchange) { if (exchange.Properties.TryGetValue("identity:management-subject", out var s) && s is string sub && !string.IsNullOrEmpty(sub)) return sub; return "anon"; } internal static object? DeserializeBody(string? json) { if (string.IsNullOrEmpty(json)) return null; try { // JsonElement round-trips identically through System.Text.Json on the next write. using var doc = JsonDocument.Parse(json); return doc.RootElement.Clone(); } catch { return json; } } } /// /// E2 — post-step that captures the response into the idempotency cache when the paired /// stashed metadata for a cache miss. /// /// Runs inside the same redb transaction as the business step, so a failed mutation that /// rolls back also rolls back the cache write — clients can safely retry a failed request /// without being permanently stuck on the failure response. /// /// internal sealed class IdempotencyCaptureProcessor : IProcessor { private readonly IRouteContext _context; private readonly string? _redbName; private readonly IdempotencyOptions _options; private readonly TimeProvider _timeProvider; private readonly ILogger? _logger; public IdempotencyCaptureProcessor( IRouteContext context, string? redbName, IdempotencyOptions options, TimeProvider? timeProvider = null, ILogger? logger = null) { _context = context; _redbName = redbName; _options = options; _timeProvider = timeProvider ?? TimeProvider.System; _logger = logger; } public async Task Process(IExchange exchange, CancellationToken ct = default) { if (!_options.Enabled) return; if (!exchange.Properties.TryGetValue(IdempotencyProperties.Name, out var nameObj) || nameObj is not string name) return; if (exchange.Properties.TryGetValue(IdempotencyProperties.CacheHit, out var hit) && hit is true) return; // Identity convention follows Camel canon: the response is exchange.Out ?? exchange.In. // PipelineProcessor merges business.Out into In before invoking this terminal step, // so In.Body holds whatever the business processor wrote. Callers downstream must also // read via `Out ?? In` — we do NOT synthesise Out here (that would be redundant: the // outer PipelineProcessor would re-merge it back into In on the next step anyway). var responseSource = exchange.Out ?? exchange.In; if (responseSource?.Body is null) return; // Skip caching error responses (4xx/5xx). RFC-style idempotency only protects // successful state changes; a transient 5xx must be retriable. var status = ResolveStatus(exchange); if (status >= 400) return; var method = exchange.Properties.TryGetValue(IdempotencyProperties.Method, out var m) ? m as string ?? string.Empty : string.Empty; var operation = exchange.Properties.TryGetValue(IdempotencyProperties.Operation, out var o) ? o as string ?? string.Empty : string.Empty; var caller = exchange.Properties.TryGetValue(IdempotencyProperties.Caller, out var c) ? c as string ?? "anon" : "anon"; var key = exchange.Properties.TryGetValue(IdempotencyProperties.Key, out var k) ? k as string ?? string.Empty : string.Empty; try { var redb = _context.GetRedbService(_redbName, exchange); var now = _timeProvider.GetUtcNow(); // Re-check (TOCTOU): a concurrent request with the same key may have already // stored a record between the PRE-lookup and now. Keep the first writer's record // to give callers stable replay semantics. var keyHash = IdempotencyKeyHash.Sha256Hex(name); var existing = await redb.Query() .WhereRedb(obj => obj.ValueUnique == keyHash) .ToListAsync() .ConfigureAwait(false); if (existing.Count == 0) existing = await redb.Query() .WhereRedb(obj => obj.Name == name) .ToListAsync() .ConfigureAwait(false); if (existing.Any(e => e.Props.IdempotencyKey == key && e.Props.CallerSubject == caller && e.date_complete is { } dc && dc > now)) { return; } var scope = exchange.Properties.TryGetValue(IdempotencyProperties.Scope, out var sc) ? sc as string : null; // An answer with a one-time secret is recorded without its body: the record still stops a repeat // from running the operation again, and the repeat is told the secret is not shown again. var secretWithheld = OneTimeSecrets.Carries(responseSource.Body); var record = new RedbObject { name = name, // readable composite, exactly as before ValueUnique = keyHash, // V4-UNIQUE R5(v): the DB-enforced key date_complete = now.Add(_options.Ttl), Props = new IdempotencyRecordProps { Method = method, Scope = scope, Operation = operation, CallerSubject = caller, IdempotencyKey = key, StatusCode = status, ResponseBody = secretWithheld ? null : SerializeBody(responseSource.Body), SecretWithheld = secretWithheld, } }; await redb.SaveAsync(record).ConfigureAwait(false); } catch (redb.Core.Exceptions.RedbUniqueViolationException) { // Concurrent capture won the race — the core ValueUnique index rejected this // insert (V4-UNIQUE, R5(v): the key is the SHA-256 of the composite name). // The other writer already persisted the authoritative response, so silently // drop this attempt: the client still gets its 2xx from the business step, // and future retries will hit the cached copy. _logger?.LogDebug( "Idempotency capture race — another writer already stored name={Name}.", name); } catch (Exception ex) { // Cache write failure must NOT fail the user's request — they already got the // real response from the business step. Log and move on; next retry simply won't // be deduplicated. _logger?.LogWarning(ex, "Idempotency capture failed for name={Name}.", name); } } private static int ResolveStatus(IExchange exchange) { var src = exchange.Out ?? exchange.In; if (src is null) return 200; if (src.Headers.TryGetValue("redbHttp.ResponseCode", out var rc)) { if (rc is int i) return i; if (rc is string s && int.TryParse(s, out var p)) return p; } return 200; } private static string? SerializeBody(object? body) { if (body is null) return null; try { return JsonSerializer.Serialize(body); } catch { return null; } } } Path: redb-identity/src/redb.Identity.Core/Routes/Processors/IdempotencyRecordCleanupProcessor.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/Routes/Processors/IdempotencyRecordCleanupProcessor.cs ---- using Microsoft.Extensions.Options; using redb.Core; using redb.Core.Services; using redb.Identity.Contracts.Common; using redb.Identity.Contracts.Routes; using redb.Identity.Core.Configuration; using redb.Identity.Core.Models; using redb.Identity.Core.Services; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.RedbCore.Extensions; namespace redb.Identity.Core.Routes.Processors; /// /// Deletes the idempotency records whose time to live has ended (date_complete in the past). The cache /// already ignores them; without this cleanup they would stay in the database for good, answers and all. Runs /// leader-only on the timer registered in , batch after batch of /// until no expired record is left. Deletes through /// , like the other cleanups. A body {"dryRun":true} counts the expired /// records and changes nothing. /// internal sealed class IdempotencyRecordCleanupProcessor : IProcessor { private readonly IRouteContext _context; private readonly string? _redbName; private readonly RedbIdentityOptions _options; private readonly IBackgroundDeletionService? _backgroundDeletion; private readonly TimeProvider _timeProvider; public IdempotencyRecordCleanupProcessor( IRouteContext context, IOptions options, string? redbName = null, IBackgroundDeletionService? backgroundDeletion = null, TimeProvider? timeProvider = null) { _context = context; _redbName = redbName; _options = options.Value; _backgroundDeletion = backgroundDeletion; _timeProvider = timeProvider ?? TimeProvider.System; } public async Task Process(IExchange exchange, CancellationToken ct = default) { var redb = _context.GetRedbService(_redbName, exchange); var now = _timeProvider.GetUtcNow(); var batchSize = Math.Max(1, _options.IdempotencyCleanupBatchSize); if (exchange.In.Body is Dictionary body && body.TryGetValue("dryRun", out var raw) && (raw is true || (raw is string s && bool.TryParse(s, out var parsed) && parsed))) { var expired = await redb.Query() .WhereRedb(o => o.DateComplete < now) .CountAsync() .ConfigureAwait(false); exchange.Out ??= new Message(); exchange.Out.Body = new IdempotencyRecordPrunePreview { WouldPruneIdempotencyRecords = expired, Threshold = now }; exchange.Properties["identity-event-type"] = IdentityAuditEventIds.IdempotencyRecordsPrunePreviewed; exchange.Properties["identity-event-data"] = new { Count = expired, Threshold = now }; return; } var pruned = 0; while (true) { ct.ThrowIfCancellationRequested(); var ids = await redb.Query() .WhereRedb(o => o.DateComplete < now) .Take(batchSize) .Select(o => o.Id) .ToListAsync() .ConfigureAwait(false); if (ids.Count == 0) break; await IdentityDeletionHelper.DeleteAsync(redb, _backgroundDeletion, ids).ConfigureAwait(false); pruned += ids.Count; if (ids.Count < batchSize) break; } exchange.Out ??= new Message(); exchange.Out.Body = new IdempotencyRecordPruneResult { PrunedIdempotencyRecords = pruned }; exchange.Properties["identity-event-type"] = IdentityAuditEventIds.IdempotencyRecordsPruned; exchange.Properties["identity-event-data"] = new { Count = pruned, Threshold = now }; } } Path: redb-identity/src/redb.Identity.Core/Routes/Processors/IdentityProcessorHelpers.UniqueViolation.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/Routes/Processors/IdentityProcessorHelpers.UniqueViolation.cs ---- using System.Data.Common; namespace redb.Identity.Core.Routes.Processors; internal static partial class IdentityProcessorHelpers { /// /// Returns true if — or any exception in its inner /// chain — is a database unique-constraint violation. /// /// PostgreSQL (Npgsql): SQLSTATE 23505. /// SQL Server: errors 2601 (unique index) and 2627 (unique/PK constraint). /// /// V4-UNIQUE: the scheme-key catches moved to the typed /// RedbUniqueViolationException. This duck-typed recognizer SURVIVES for the two /// places a raw driver violation can still reach Identity code: /// /// the UX_users_email index on the core _users table (owner /// decision R1 — not a redb scheme key, the core never wraps it), reached through the /// route-level generic 409 mapping in IdentityCoreRouteBuilder; /// UX_route_idempotent_entry_name on redb.Route's scheme (R2 interim, /// until the Route-side fix ships). /// /// A typed RedbUniqueViolationException also satisfies this predicate — the /// driver exception rides its inner chain. That does not bring it to the route-level /// DbException handler, though: the handler is chosen by the closest type over the /// chain, and on PostgreSQL the typed exception lands in the catch-all. It has its own /// handler in IdentityCoreRouteBuilder, with the same 409 answer. /// public static bool IsUniqueViolation(Exception? ex) { for (var e = ex; e is not null; e = e.InnerException) { if (e is DbException db) { // Npgsql: SqlState populated for every backend error. "23505" is the // unique-violation SQLSTATE for all indexed and constraint-backed // uniqueness checks. if (string.Equals(db.SqlState, "23505", StringComparison.Ordinal)) return true; // Microsoft.Data.SqlClient exposes the concrete error number via the // ErrorCode-less "Number" property on SqlException. Probe via reflection // to avoid a hard dependency on Microsoft.Data.SqlClient from this // module (which already references both Npgsql and SqlClient only // transitively through the redb connectors). var numberProp = e.GetType().GetProperty("Number"); if (numberProp?.GetValue(e) is int number && (number == 2601 || number == 2627)) return true; } // SqlException inherits DbException but older surfaces may wrap messages. var msg = e.Message; if (msg is not null && (msg.Contains("duplicate key", StringComparison.OrdinalIgnoreCase) || msg.Contains("UNIQUE KEY constraint", StringComparison.OrdinalIgnoreCase) || msg.Contains("UNIQUE constraint", StringComparison.OrdinalIgnoreCase))) { return true; } } return false; } /// /// Returns true when a unique violation on the _users table is the one of the /// e-mail index rather than of the login. PostgreSQL and SQL Server name the index /// (UX_users_email) in the driver message; SQLite names the column /// (_users._email). Meaningful only after said yes. /// public static bool IsEmailUniqueViolation(Exception? ex) { for (var e = ex; e is not null; e = e.InnerException) { var msg = e.Message; if (msg is not null && (msg.Contains("UX_users_email", StringComparison.OrdinalIgnoreCase) || msg.Contains("_users._email", StringComparison.OrdinalIgnoreCase))) { return true; } } return false; } /// /// Adds one to identity.unique_violation for a violation that is being turned into an /// answer, tagged with what collided when the exception says so: scheme and property of a typed /// RedbUniqueViolationException, _users / _email for the e-mail index of the /// users table, unknown otherwise (a driver violation that names neither). /// public static void CountUniqueViolation(Metrics.IdentityMetrics? metrics, Exception? ex) { if (metrics is null) return; var scheme = "unknown"; var column = "unknown"; redb.Core.Exceptions.RedbUniqueViolationException? typed = null; for (var e = ex; e is not null && typed is null; e = e.InnerException) typed = e as redb.Core.Exceptions.RedbUniqueViolationException; if (typed is not null) { scheme = typed.SchemeName ?? scheme; column = typed.PropertyName ?? column; } else if (IsEmailUniqueViolation(ex)) { scheme = "_users"; column = "_email"; } metrics.UniqueViolations.Add(1, new KeyValuePair("scheme", scheme), new KeyValuePair("column", column)); } /// /// The same count for a processor that catches the violation itself and answers with its own /// text: the metric must see those too, or it would report only the violations nobody expected. /// public static void CountUniqueViolation( redb.Route.Abstractions.IRouteContext context, redb.Route.Abstractions.IExchange exchange, Exception ex) => CountUniqueViolation( redb.Identity.Core.Module.IdentityRouteContextExtensions .GetIdentityServiceOrDefault(context, exchange), ex); } Path: redb-identity/src/redb.Identity.Core/Routes/Processors/IdentityProcessorHelpers.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/Routes/Processors/IdentityProcessorHelpers.cs ---- using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Core; using redb.Core.Models.Entities; using redb.Core.Security; using redb.Identity.Contracts.Common; using redb.Identity.Core.Configuration; using redb.Identity.Core.Models; using redb.Identity.Core.Module; using redb.Identity.Core.Security; using redb.Route.Abstractions; namespace redb.Identity.Core.Routes.Processors; /// /// Shared extraction and validation helpers used by identity management processors. /// internal static partial class IdentityProcessorHelpers { // ── Limits (defaults; configurable via Configure(IdentityValidationOptions)) ── public static int MaxIdentifierLength { get; private set; } = 128; public static int MaxDisplayNameLength { get; private set; } = 256; public static int MaxDescriptionLength { get; private set; } = 1024; public static int MinPasswordLength { get; private set; } = 8; public static int MaxPasswordLength { get; private set; } = 512; // Active regex (defaults = source-generated; overridable via Configure()). private static Regex _identifierRegex = DefaultIdentifierRegex(); private static Regex _emailRegex = DefaultEmailRegex(); private static Regex _phoneRegex = DefaultE164Regex(); /// /// Applies length limits and regex overrides from configuration. Called once during /// Identity server bootstrap (see AddRedbIdentityServer). Idempotent; null input /// is a no-op. Invalid override patterns fall back to defaults. /// public static void Configure(IdentityValidationOptions? options) { if (options is null) return; MaxIdentifierLength = options.MaxIdentifierLength; MaxDisplayNameLength = options.MaxDisplayNameLength; MaxDescriptionLength = options.MaxDescriptionLength; MinPasswordLength = options.MinPasswordLength; MaxPasswordLength = options.MaxPasswordLength; _identifierRegex = Compile(options.IdentifierPattern, DefaultIdentifierRegex()); _emailRegex = Compile(options.EmailPattern, DefaultEmailRegex()); _phoneRegex = Compile(options.PhonePattern, DefaultE164Regex()); } private static Regex Compile(string? pattern, Regex fallback) { if (string.IsNullOrWhiteSpace(pattern)) return fallback; try { return new Regex(pattern, RegexOptions.Compiled | RegexOptions.CultureInvariant); } catch (ArgumentException) { return fallback; } } // ── Regex (source-generated defaults) ── [GeneratedRegex(@"^[a-zA-Z0-9\-_.]+$")] private static partial Regex DefaultIdentifierRegex(); [GeneratedRegex(@"^[^@\s]+@[^@\s]+\.[^@\s]+$")] private static partial Regex DefaultEmailRegex(); [GeneratedRegex(@"^\+[1-9]\d{1,14}$")] private static partial Regex DefaultE164Regex(); // ── Error helper ── public static void SetError(IExchange exchange, string error, string description) { exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new ErrorResponse { Error = error, ErrorDescription = description }; } // ── Validation helpers (return error message or null) ── public static string? ValidateIdentifier(string? value, string fieldName) { if (string.IsNullOrEmpty(value)) return $"{fieldName} is required"; if (value.Length > MaxIdentifierLength) return $"{fieldName} must not exceed {MaxIdentifierLength} characters"; if (!_identifierRegex.IsMatch(value)) return $"{fieldName} contains invalid characters (allowed: a-z, 0-9, '-', '_', '.')"; return null; } public static string? ValidateDisplayName(string? value, string fieldName) { if (value is not null && value.Length > MaxDisplayNameLength) return $"{fieldName} must not exceed {MaxDisplayNameLength} characters"; return null; } public static string? ValidateDescription(string? value, string fieldName) { if (value is not null && value.Length > MaxDescriptionLength) return $"{fieldName} must not exceed {MaxDescriptionLength} characters"; return null; } public static string? ValidatePassword(string? value, string fieldName = "Password") { if (string.IsNullOrEmpty(value)) return $"{fieldName} is required"; if (value.Length < MinPasswordLength) return $"{fieldName} must be at least {MinPasswordLength} characters"; if (value.Length > MaxPasswordLength) return $"{fieldName} must not exceed {MaxPasswordLength} characters"; return null; } /// /// H10 — full password policy gate (length + composition + history + breach). /// Resolves from the current request scope /// (preferred) or the route-context root provider; falls back to the legacy /// length-only when no validator is /// registered (unit-test paths without a full DI container). Returns null on /// success or a single-line joined error message suitable for /// error_description fields. /// public static ValueTask ValidatePasswordPolicyAsync( IExchange exchange, IRouteContext context, string? password, long? userId, string fieldName = "Password", CancellationToken ct = default) => ValidatePasswordPolicyAsync(exchange, context, redb: null, password, userId, fieldName, ct); /// /// The same gate for a processor on a transacted route: the history lookup runs through /// , the exchange's , instead of a scope of the store's own. /// A second connection inside the route's transaction promotes it to a distributed one, which PostgreSQL /// refuses unless max_prepared_transactions is set. /// public static async ValueTask ValidatePasswordPolicyAsync( IExchange exchange, IRouteContext context, IRedbService? redb, string? password, long? userId, string fieldName = "Password", CancellationToken ct = default) { // The validator is registered in the Identity child SP — under tpkg deployment // exchange.ServiceProvider is a per-exchange scope of the HOST root, not the child. // GetIdentityServiceOrDefault bridges the two SPs (cf. IdentityRouteContextExtensions); // without this, the policy validator silently misses and we fall back to the // legacy length-only check, swallowing composition rules (digit/upper/lower). var validator = context?.GetIdentityServiceOrDefault(exchange); if (validator is null) { var sp = exchange?.ServiceProvider ?? context?.GetServiceProvider(); validator = sp?.GetService(); } if (validator is null) return ValidatePassword(password, fieldName); var result = redb is null ? await validator.ValidateAsync(password, userId, ct).ConfigureAwait(false) : await validator.ValidateAsync(password, userId, redb, ct).ConfigureAwait(false); return result.IsValid ? null : result.ToErrorMessage(); } /// /// H10 Phase 2 — record the just-set password in the per-user history (via the /// registered ) so future change attempts can /// reject reuse. Best-effort: if no store is registered or /// is 0, this is a /// no-op. Failures are logged but never propagate — the password change has already /// succeeded at this point and the user must not be rolled back over a history I/O. /// public static async ValueTask RecordPasswordHistoryAsync( IExchange exchange, IRouteContext context, long userId, string password, CancellationToken ct = default) => await RecordPasswordHistoryAsync(exchange, context, redb: null, userId, password, ct).ConfigureAwait(false); /// /// PERF overload: callers that already hold the in-tx /// (everyone inside a WithRedbTx-wrapped processor) pass it in here. We reuse /// that instance for the history write and the PasswordChangedAt stamp, avoiding /// the historic 30 s deadlock where opening a fresh scope acquired an independent /// connection that blocked on the un-committed outer tx until /// TransactionPolicy.Timeout elapsed. /// public static async ValueTask RecordPasswordHistoryAsync( IExchange exchange, IRouteContext context, IRedbService? redb, long userId, string password, CancellationToken ct = default) { if (userId <= 0 || string.IsNullOrEmpty(password)) return; var sp = exchange?.ServiceProvider ?? context?.GetServiceProvider(); if (sp is null) return; var policy = sp.GetService(); var keep = policy?.HistoryCount ?? 0; if (keep > 0) { try { if (redb is not null) { // Fast path — caller's IRedbService is enlisted in the outer tx. await RecordPasswordHistoryWithRedbAsync(sp, redb, userId, password, keep, ct).ConfigureAwait(false); } else { // Out-of-exchange fallback (unit tests / cleanup hooks). var store = sp.GetService(); if (store is not null) await store.RecordAsync(userId, password, keep, ct).ConfigureAwait(false); } } catch { // Swallow: history recording must not fail an otherwise-successful password // change. Underlying store has its own logging. } } // H10 Phase 3 — stamp PasswordChangedAt on the user's OIDC props so future logins // can enforce MaxAge expiration. Always done, even when history is disabled. if (redb is not null) { // Use the in-tx IRedbService directly — same anti-deadlock reasoning as above. await UpdatePasswordChangedAtWithRedbAsync(sp, redb, userId, ct).ConfigureAwait(false); } else { await UpdatePasswordChangedAtAsync(sp, exchange, userId, ct).ConfigureAwait(false); } } /// /// PERF inline of that runs against the /// supplied exchange's /. Same /// logic as the store; lives here so it doesn't need to be wired through a new method on /// . The trimming branch swallows failures so the /// password-change write succeeds even when the trim query throws. /// private static async Task RecordPasswordHistoryWithRedbAsync( IServiceProvider sp, IRedbService redb, long userId, string password, int keep, CancellationToken ct) { var hasher = sp.GetRequiredService(); var timeProvider = sp.GetService() ?? TimeProvider.System; var now = timeProvider.GetUtcNow(); var entry = new RedbObject(new PasswordHistoryProps { UserId = userId, HashedPassword = hasher.HashPassword(password), CreatedAt = now, }) { name = $"pwhist:{userId}:{now.ToUnixTimeMilliseconds()}", }; await redb.SaveAsync(entry).ConfigureAwait(false); try { var staleIds = await redb.Query() .Where(o => o.UserId == userId) .OrderByDescending(o => o.CreatedAt) .Skip(keep) .Select(o => o.id) .ToListAsync() .ConfigureAwait(false); if (staleIds.Count > 0) await redb.SoftDeleteAsync(staleIds).ConfigureAwait(false); } catch { // Trim is advisory — failures must not block password change. } } /// /// H10 Phase 3 — upsert /// to the current UTC time for . Creates the OIDC props row /// if missing (covers users created before H10). Best-effort. /// /// PERF: when an exchange is supplied we prefer its /// because it shares the in-flight IRedbService already enlisted in the route's /// transaction (cf. WithRedbTx). Opening a separate scope here used to acquire a /// fresh DB connection that immediately blocked on the still-open outer tx, and only /// returned when the connection pool's TransactionPolicy.Timeout (30 s default) /// expired — admin POST /users and SCIM POST /scim/v2/Users were both /// observed taking ~30 s/op for that reason. The exchange-SP path is now the fast path /// for in-route callers; the scope-factory fallback remains for code that runs outside /// an exchange (e.g. unit tests). /// /// /// /// PERF fast path mirroring /// but using the supplied directly so the upsert lands inside /// the caller's in-flight transaction. /// private static async Task UpdatePasswordChangedAtWithRedbAsync( IServiceProvider sp, IRedbService redb, long userId, CancellationToken ct) { try { var timeProvider = sp.GetService() ?? TimeProvider.System; var existing = await redb.Query() .WhereRedb(o => o.Key == userId) .FirstOrDefaultAsync() .ConfigureAwait(false); var now = timeProvider.GetUtcNow(); if (existing is not null) { existing.Props.PasswordChangedAt = now; existing.Props.HasUserPassword = true; await redb.SaveAsync(existing).ConfigureAwait(false); } else { var fresh = new redb.Core.Models.Entities.RedbObject( new Models.UserProps { PasswordChangedAt = now, HasUserPassword = true, UserId = userId }) { key = userId, }; await redb.SaveAsync(fresh).ConfigureAwait(false); } } catch { // Advisory — same swallow contract as the scope-factory variant. } } private static async Task UpdatePasswordChangedAtAsync( IServiceProvider sp, IExchange? exchange, long userId, CancellationToken ct) { try { redb.Core.IRedbService redbService; IServiceScope? scope = null; if (exchange?.ServiceProvider is { } exSp) { // Fast path: reuse the exchange's scope (same outer tx, same connection). redbService = exSp.GetRequiredService(); } else { // Out-of-exchange path: open a fresh scope. var scopeFactory = sp.GetService(); if (scopeFactory is not null) { scope = scopeFactory.CreateScope(); redbService = scope.ServiceProvider.GetRequiredService(); } else { redbService = sp.GetRequiredService(); } } try { var timeProvider = sp.GetService() ?? TimeProvider.System; var existing = await redbService.Query() .WhereRedb(o => o.Key == userId) .FirstOrDefaultAsync() .ConfigureAwait(false); var now = timeProvider.GetUtcNow(); if (existing is not null) { existing.Props.PasswordChangedAt = now; // H8 (DoD §4 gap (d)): mark that the user has set their own password. // Used by MeFederatedIdentitiesProcessor to refuse unlinking the last // social provider when no local password exists. existing.Props.HasUserPassword = true; await redbService.SaveAsync(existing).ConfigureAwait(false); } else { var fresh = new redb.Core.Models.Entities.RedbObject( new Models.UserProps { PasswordChangedAt = now, HasUserPassword = true, UserId = userId }) { key = userId, }; await redbService.SaveAsync(fresh).ConfigureAwait(false); } } finally { scope?.Dispose(); } } catch { // Swallow: stamping is advisory; failure must not roll back the password // change that has already been persisted in _users. } } public static string? ValidateEmail(string? value) { if (value is not null && !_emailRegex.IsMatch(value)) return "Invalid email format"; return null; } public static string? ValidatePhoneNumber(string? value) { if (value is not null && !_phoneRegex.IsMatch(value)) return "Phone number must be in E.164 format (e.g. +12345678901)"; return null; } public static string? ValidateUris(IEnumerable? uris, string fieldName) { if (uris is null) return null; foreach (var u in uris) { if (!Uri.IsWellFormedUriString(u, UriKind.Absolute)) return $"Invalid {fieldName} format: {u}"; // OAuth 2.1 / RFC 6749 §3.1.2: redirect URIs MUST NOT contain wildcards, // and MUST NOT include a fragment component. Server-side matching is exact. if (u.Contains('*')) return $"Wildcards are not allowed in {fieldName}: {u}"; if (u.Contains('#')) return $"Fragment component is not allowed in {fieldName}: {u}"; } return null; } /// /// Checks a backchannel_logout_uri by the outbound guard under /// (https and private targets), the same check the dispatcher makes before every POST. Returns the error text, /// or null when the address is accepted. /// public static async Task ValidateBackchannelLogoutUriAsync( string uri, Configuration.BackchannelLogoutOptions options, CancellationToken ct) { if (uri.Length > MaxRequestUriLength) return $"The back-channel logout URI must have at most {MaxRequestUriLength} characters"; if (uri.Contains('#')) return "Fragment component is not allowed in the back-channel logout URI"; var rejection = await Services.OutboundUrlGuard.ValidateAsync( uri, options.RequireHttps, options.AllowPrivateNetworkTargets, ct).ConfigureAwait(false); return rejection == Services.OutboundUrlGuard.Rejection.None ? null : $"The back-channel logout URI is not accepted: {Services.OutboundUrlGuard.Describe(rejection)}"; } /// At most this many request_uris per client. public const int MaxRequestUris = 20; /// At most this many characters per request_uris value. public const int MaxRequestUriLength = 2048; /// /// Validates a client's registered request_uris (OIDC Dynamic Client Registration 1.0 §2): absolute /// http or https URIs without user info or wildcards, at most values of /// at most characters. A fragment is allowed: the standard puts the base64url /// SHA-256 of the request object there. Whether http may be fetched is decided at fetch time by /// Jar.RequestUriRequireHttps. Returns the error text, or null when the list is valid. /// public static string? ValidateRequestUris(IReadOnlyCollection? uris) { if (uris is null) return null; if (uris.Count > MaxRequestUris) return $"At most {MaxRequestUris} request URIs are allowed"; foreach (var u in uris) { if (string.IsNullOrEmpty(u) || u.Length > MaxRequestUriLength) return $"A request URI must have 1 to {MaxRequestUriLength} characters"; if (!Uri.TryCreate(u, UriKind.Absolute, out var parsed) || !Uri.IsWellFormedUriString(u, UriKind.Absolute)) return $"Invalid request URI format: {u}"; if (parsed.Scheme is not ("https" or "http")) return $"A request URI must use https or http: {u}"; if (parsed.UserInfo.Length > 0) return $"User info is not allowed in a request URI: {u}"; if (u.Contains('*')) return $"Wildcards are not allowed in a request URI: {u}"; } return null; } public static long ExtractRequiredLong(IExchange exchange, string key) { if (exchange.In.Body is Dictionary dict) return ExtractLong(dict, key) ?? throw new InvalidOperationException($"{key} is required"); throw new InvalidOperationException($"{key} is required"); } public static long? ExtractLong(Dictionary dict, string key) { if (dict.TryGetValue(key, out var val) && val is not null && long.TryParse(val.ToString(), out var result) && result > 0) return result; return null; } } Path: redb-identity/src/redb.Identity.Core/Routes/Processors/ImpersonationManagementProcessor.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/Routes/Processors/ImpersonationManagementProcessor.cs ---- using redb.Identity.Contracts.Routes; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.RedbCore.Extensions; using redb.Identity.Contracts.Common; using redb.Identity.Contracts.Users; namespace redb.Identity.Core.Routes.Processors; /// /// N7-3 — admin impersonation overlay. /// /// Does NOT mint a token. The BFF tracks the impersonation target in its own session /// cookie; this processor only validates the target user exists and emits an audit /// event so the action is permanently recorded against the admin's sub. /// /// /// Operations on the operation header: /// /// start — body { userId, reason? }; returns { targetUserId, targetLogin }. /// stop — body { userId }; returns { stopped: true }. /// /// /// internal sealed class ImpersonationManagementProcessor : IProcessor { private readonly IRouteContext _context; private readonly string? _redbName; public ImpersonationManagementProcessor(IRouteContext context, string? redbName = null) { _context = context; _redbName = redbName; } public async Task Process(IExchange exchange, CancellationToken ct = default) { var operation = exchange.In.GetHeader("operation") ?? throw new InvalidOperationException("Missing 'operation' header"); var redb = _context.GetRedbService(_redbName, exchange); switch (operation) { case "start": await Start(redb, exchange, ct); break; case "stop": await Stop(redb, exchange, ct); break; default: exchange.Out ??= new Message(); exchange.Out.Body = new ErrorResponse { Error = "invalid_operation", ErrorDescription = $"Unknown operation: {operation}" }; break; } } private static async Task Start(redb.Core.IRedbService redb, IExchange exchange, CancellationToken ct) { var targetId = IdentityProcessorHelpers.ExtractRequiredLong(exchange, "userId"); var reason = (exchange.In.Body as Dictionary) is { } dict ? dict.TryGetValue("reason", out var r) ? r as string : null : null; var target = await redb.UserProvider.GetUserByIdAsync(targetId); if (target is null) { exchange.Out ??= new Message(); exchange.Out.Body = new ErrorResponse { Error = "not_found", ErrorDescription = $"User {targetId} not found" }; return; } var adminSubject = exchange.Properties.TryGetValue("identity:management-subject", out var s) ? s as string : null; exchange.Out ??= new Message(); exchange.Out.Body = new ImpersonationStartedResponse { TargetUserId = target.Id, TargetLogin = target.Login }; exchange.Properties["identity-event-type"] = IdentityAuditEventIds.UserImpersonationStarted; exchange.Properties["identity-event-data"] = new { AdminSubject = adminSubject, TargetUserId = target.Id, TargetLogin = target.Login, Reason = reason }; } private static Task Stop(redb.Core.IRedbService redb, IExchange exchange, CancellationToken ct) { var targetId = IdentityProcessorHelpers.ExtractRequiredLong(exchange, "userId"); var adminSubject = exchange.Properties.TryGetValue("identity:management-subject", out var s) ? s as string : null; exchange.Out ??= new Message(); exchange.Out.Body = new ImpersonationStoppedResponse(); exchange.Properties["identity-event-type"] = IdentityAuditEventIds.UserImpersonationStopped; exchange.Properties["identity-event-data"] = new { AdminSubject = adminSubject, TargetUserId = targetId }; return Task.CompletedTask; } } Path: redb-identity/src/redb.Identity.Core/Routes/Processors/LiveJwksProcessor.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/Routes/Processors/LiveJwksProcessor.cs ---- using System.Text.Json; using Microsoft.IdentityModel.Tokens; using redb.Identity.Core.Keys; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Identity.Core.Routes.Processors; /// /// JWKS endpoint that reads keys live from on every request, /// bypassing the static OpenIddictServerOptions.SigningCredentials list (which is /// frozen at process start). Wired in place of the default JwksEndpointProcessor /// when is enabled, /// so admin /signing-keys/rotate and /signing-keys/{kid}/retire reflect on /// the JWKS immediately without any process restart. /// /// Caveat: OpenIddict still picks the signing credential for NEW tokens from its frozen /// options list. RPs cache the live JWKS (Cache-Control: max-age=3600) and will validate /// in-flight tokens against whichever kid is present. New-token-kid follows new-key only /// after the OpenIddict cache refreshes (process restart or future IOptionsMonitor wiring). /// /// internal sealed class LiveJwksProcessor : IProcessor { private readonly ISigningKeyStore _store; public LiveJwksProcessor(ISigningKeyStore store) { _store = store ?? throw new ArgumentNullException(nameof(store)); } public async Task Process(IExchange exchange, CancellationToken ct = default) { var keys = await _store.GetAllAsync(ct).ConfigureAwait(false); // Convert each stored SecurityKey to its public JWK form (no private material). // Filter to signing-kind only; encryption keys live in a separate part of the spec // (`use=enc`) and we currently advertise sign-only on this endpoint. var jwks = new List(keys.Length); foreach (var m in keys) { if (!string.Equals(m.KeyKind, "signing", StringComparison.OrdinalIgnoreCase)) continue; var jwk = JsonWebKeyConverter.ConvertFromSecurityKey(m.SecurityKey); // ConvertFromSecurityKey copies the private components for RSA keys; strip them // before serialising so the public JWKS doesn't leak `d`, `p`, `q`, `dp`, `dq`, `qi`. jwk.D = null; jwk.P = null; jwk.Q = null; jwk.DP = null; jwk.DQ = null; jwk.QI = null; jwk.K = null; jwk.Kid = m.Kid; jwk.Use = "sig"; jwk.Alg = m.Algorithm; jwks.Add(new { kty = jwk.Kty, use = jwk.Use, alg = jwk.Alg, kid = jwk.Kid, n = jwk.N, e = jwk.E, }); } var body = JsonSerializer.SerializeToUtf8Bytes(new { keys = jwks }); var msg = new Message(body) { ContentType = "application/json", }; msg.Headers["redbHttp.ResponseCode"] = 200; msg.Headers["redbHttp.ResponseContentType"] = "application/json"; // D2: 1-hour cache matches Microsoft / Google / Auth0 conventions and is well // within the typical 24-72h rotation grace window. With the live store, RPs that // miss-cache after rotation see the new kid on the next refresh; in-flight tokens // still validate as long as their kid is in the store's NotAfter window. msg.Headers["Cache-Control"] = "public, max-age=3600"; msg.Headers["Vary"] = "Accept"; exchange.Out = msg; } } Path: redb-identity/src/redb.Identity.Core/Routes/Processors/LoginFailureRecorderProcessor.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/Routes/Processors/LoginFailureRecorderProcessor.cs ---- using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using redb.Identity.Core.Configuration; using redb.Identity.Core.Metrics; using redb.Identity.Core.Services; using redb.Route.Abstractions; namespace redb.Identity.Core.Routes.Processors; /// /// C1 — Per-(IP+username) failure counter. Runs AFTER and /// inspects exchange.Out.Body to decide: /// /// success=true → resets the failure bucket so a single /// legitimate sign-in clears the tally. /// success=false (any reason: bad password, MFA challenge, /// any error) → increments the bucket; if the limit is breached, replaces the response /// with HTTP 429 + Retry-After. /// /// internal sealed class LoginFailureRecorderProcessor : IProcessor { private readonly IServiceProvider _sp; private readonly ILogger _logger; public LoginFailureRecorderProcessor(IServiceProvider sp, ILogger? logger = null) { _sp = sp; _logger = logger ?? NullLogger.Instance; } public async Task Process(IExchange exchange, CancellationToken ct = default) { var store = _sp.GetService(); var optsAccessor = _sp.GetService>(); if (store is null || optsAccessor is null) return; var rl = optsAccessor.Value.RateLimit; if (!rl.Enabled) return; var inBody = exchange.In.Body as IDictionary; var username = inBody?.TryGetValue("username", out var u) == true ? u?.ToString() : null; if (string.IsNullOrWhiteSpace(username)) return; var ip = exchange.In.Headers.TryGetValue("redbHttp.RemoteAddress", out var v) ? v?.ToString() : null; if (string.IsNullOrEmpty(ip)) return; var key = $"ipuser:login:{ip}:{username.ToLowerInvariant()}"; var outBody = exchange.Out?.Body as IDictionary; var succeeded = outBody is not null && outBody.TryGetValue("success", out var s) && s is bool b && b; if (succeeded) { await store.ResetAsync(key, ct); return; } var decision = await store.TryIncrementAsync(key, rl.PerIpUsernameFailures, rl.PerIpUsernameWindow, ct); System.Diagnostics.Debug.WriteLine($"[RATE-LIMIT] key={key} allowed={decision.Allowed} count={decision.Count} limit={rl.PerIpUsernameFailures}"); if (!decision.Allowed) { _logger.LogWarning( "Per-(IP+username) failure ceiling reached: ip={Ip} username={User} count={Count}", ip, username, decision.Count); // F3 + G4: emit `identity.rate_limit.rejections` with key_dimension=ip_user tag // — distinguishes credential-stuffing block-outs from generic per-IP throttle. _sp.GetService()?.RateLimitRejections.Add( 1, new KeyValuePair("key_dimension", "ip_user"), new KeyValuePair("endpoint", "login")); RateLimitProcessor.EmitTooManyRequests(exchange, decision.RetryAfter, rl.DefaultRetryAfterSeconds); } } } Path: redb-identity/src/redb.Identity.Core/Routes/Processors/LoginProcessor.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/Routes/Processors/LoginProcessor.cs ---- using Microsoft.Extensions.DependencyInjection; using redb.Core; using redb.Identity.Core.Models; using redb.Identity.Core.Services; using redb.Route.Abstractions; using redb.Route.Core; using redb.Identity.Contracts.Routes; namespace redb.Identity.Core.Routes.Processors; /// /// Core route processor for the Login endpoint. /// Verifies credentials and returns userId + username in the response /// (the HTTP facade converts this to a session cookie). /// internal sealed class LoginProcessor : IProcessor { private readonly IServiceProvider _sp; public LoginProcessor(IServiceProvider sp) => _sp = sp; public async Task Process(IExchange exchange, CancellationToken ct = default) { var body = exchange.In.Body as IDictionary; var username = body?.TryGetValue("username", out var u) == true ? u?.ToString() : null; var password = body?.TryGetValue("password", out var p) == true ? p?.ToString() : null; var returnUrl = body?.TryGetValue("returnUrl", out var r) == true ? r?.ToString() : null; using var scope = _sp.CreateScope(); var timeProvider = scope.ServiceProvider.GetService() ?? TimeProvider.System; var loginService = scope.ServiceProvider.GetRequiredService(); var result = await loginService.AuthenticateAsync(username ?? "", password ?? "", ct); exchange.Out = new Message(); if (result.MfaRequired) { // Password verified but MFA needed — encrypt state, no session var stateProtector = scope.ServiceProvider.GetRequiredService(); var mfaState = stateProtector.Protect(new MfaState { Jti = Guid.NewGuid(), UserId = result.UserId, Username = result.Username, Methods = result.MfaMethods!, ReturnUrl = returnUrl }); exchange.Out.Body = new Dictionary { ["success"] = false, ["mfa_required"] = true, // B9 / BUG-9: do NOT echo the configured MFA methods back to a caller who // has only just proved knowledge of the password. The methods are still // embedded inside the encrypted mfa_state and can be obtained with a // gated round-trip to /mfa/methods (Auth0-style). This avoids leaking // factor-mix information to callers who might be probing accounts. ["mfa_state"] = mfaState }; return; } // H10 — password verified but expired. Surface a dedicated flag so the HTTP // facade can redirect the browser to the password-change page; we deliberately // do NOT create a session here — the user must change the password first. if (result.MustChangePassword) { exchange.Out.Body = new Dictionary { ["success"] = false, ["password_expired"] = true, ["userId"] = result.UserId, ["username"] = result.Username, ["returnUrl"] = returnUrl, ["error"] = "password_expired", ["error_description"] = "Password has expired and must be changed before signing in." }; return; } if (result.Succeeded) { // Create session record at login time (1 session = 1 browser login) long sessionId = 0; var redb = scope.ServiceProvider.GetService(); if (redb is not null) { var sessionService = new SessionService(redb, timeProvider); var uaParser = scope.ServiceProvider.GetService(); var device = DeviceMetadataExtractor.Extract(exchange, uaParser); var session = await sessionService.CreateAsync( result.UserId, applicationObjectId: 0, ipAddress: device.IpAddress, userAgent: device.UserAgent, deviceLabel: device.DeviceLabel, ct: ct); sessionId = session.id; } exchange.Out.Body = new Dictionary { ["success"] = true, ["userId"] = result.UserId, ["username"] = result.Username, ["sessionId"] = sessionId, ["returnUrl"] = returnUrl }; exchange.Properties["identity-event-type"] = IdentityAuditEventIds.UserLoggedIn; exchange.Properties["identity-event-data"] = new { UserId = result.UserId, Username = result.Username, Timestamp = timeProvider.GetUtcNow() }; } else { // C14 / SEC-A20: do NOT echo provider-specific error text back to the caller. // ResolveExternalUser may have produced a richer message (e.g. "Account locked // by external IdP"), but exposing it here lets an attacker enumerate accounts // and probe for state. The actual message is preserved in server logs by // LoginService for operator triage. exchange.Out.Body = new Dictionary { ["success"] = false, ["error"] = "access_denied", ["error_description"] = "Invalid credentials." }; } } } Path: redb-identity/src/redb.Identity.Core/Routes/Processors/LogoutProcessor.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/Routes/Processors/LogoutProcessor.cs ---- using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Microsoft.IdentityModel.JsonWebTokens; using Microsoft.IdentityModel.Tokens; using OpenIddict.Server; using redb.Core; using redb.Core.Models.Entities; using redb.Identity.Core.Models; using redb.Identity.Core.Module; using redb.Identity.Core.Services; using redb.Route.Abstractions; using redb.Route.RedbCore.Extensions; using redb.Identity.Contracts.Routes; namespace redb.Identity.Core.Routes.Processors; /// /// Logout processor: acts on the browser's own OP session (the user and session ids that /// ReadSessionCookie decoded from the session cookie), validates an optional id_token_hint /// (OIDC RP-Initiated Logout 1.0) and revokes sessions via SessionService. Without a session the request /// completes and ends nothing. /// internal sealed class LogoutProcessor : IProcessor { private readonly IRouteContext _context; private readonly string? _redbName; private readonly ILogger? _logger; private readonly IOptionsMonitor _serverOptions; private readonly LogoutConfirmationProtector _confirmation; private static readonly JsonWebTokenHandler _tokenHandler = new(); public LogoutProcessor( IRouteContext context, IOptionsMonitor serverOptions, LogoutConfirmationProtector confirmation, string? redbName = null, ILogger? logger = null) { ArgumentNullException.ThrowIfNull(confirmation); _context = context; _serverOptions = serverOptions; _confirmation = confirmation; _redbName = redbName; _logger = logger; } public async Task Process(IExchange exchange, CancellationToken ct = default) { var redb = _context.GetRedbService(_redbName, exchange); // The subject of a logout is the browser's own OP session: the user and session ids that // ReadSessionCookie decoded from the verified session ticket into the exchange headers (the facade // strips those header names off the request first, so they are ours). Nothing in the request body // chooses the user. This endpoint is reachable only through the public HTTP facade, where a body // value is the caller's word; reading "userId" from it let an anonymous POST sign any user out of // every session and notify every relying party. Signing another user out is an operator action and // goes through ManageSessions ("logout"), behind the management gate. var userId = HeaderLong(exchange, "session_user_id"); var sessionId = HeaderLong(exchange, "session_id"); var idTokenHint = BodyString(exchange, "id_token_hint"); if (userId <= 0) { // No OP session in this browser (no cookie, or a ticket that did not verify). RP-Initiated // Logout 1.0 §2 still has the OP complete the request — the RP's post_logout_redirect_uri is // handled after this processor — so this is a logout that ended nothing, not an error. A hint, // if any, names a user, but the request does not come from that user's browser and acts on nobody. _logger?.LogInformation( "Logout without an OP session: nothing to end (id_token_hint present: {HasHint})", !string.IsNullOrEmpty(idTokenHint)); exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new Dictionary { ["success"] = true, ["sessions_revoked"] = 0, ["backchannel_delivered"] = 0 }; return; } // The user's public subject: the sub of every token issued for them, hence what an id_token_hint // carries and what a relying party matches a logout token against. Not the core user id the session // ticket carries. var subject = await ResolveSubjectAsync(redb, userId).ConfigureAwait(false); // OIDC RP-Initiated Logout: process id_token_hint if present. A hint that verifies and names the // session's user is the relying party's proof of intent — the request came from an RP that holds // this user's id_token, not from a page the user happened to visit. var intentProven = false; if (!string.IsNullOrEmpty(idTokenHint)) { var (hintSub, hintAud) = await ValidateIdTokenHintAsync(idTokenHint); if (hintSub is null) { // Signature invalid or missing sub — treat as no hint (already logged inside) } else if (subject == Guid.Empty || !Guid.TryParse(hintSub, out var hintSubject) || hintSubject != subject) { // OIDC RP-Initiated Logout §2: sub mismatch → MUST treat as if hint not provided _logger?.LogWarning( "id_token_hint sub '{HintSub}' does not match session user {UserId} — ignoring hint", hintSub, userId); } else { intentProven = true; // Valid hint, sub matches — safe to use aud for post_logout_redirect_uri scoping if (hintAud is not null) exchange.Properties["logout_client_id"] = hintAud; } } // Without that proof, the request has to carry the confirmation state from the page this server // showed for this very session (LogoutConfirmationProtector). The session cookie alone proves // nothing about intent: a cross-site top-level navigation carries it too, and a link on any page // could otherwise end the visitor's OP session. The facade renders the page from this answer; // the request's own RP parameters travel with it so the redirect back still happens. if (!intentProven && !_confirmation.Accepts(BodyString(exchange, "logout_state"), userId, sessionId)) { exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new Dictionary { ["confirm_required"] = true, ["logout_state"] = _confirmation.Issue(userId, sessionId), ["post_logout_redirect_uri"] = BodyString(exchange, "post_logout_redirect_uri"), ["state"] = BodyString(exchange, "state"), ["client_id"] = BodyString(exchange, "client_id"), }; exchange.Properties["logout_confirm_required"] = true; return; } var session = new SessionService(redb); int sessionsRevoked; // Whom to tell, collected BEFORE anything is revoked (revocation flips the rows this reads). var targets = await CollectBackchannelTargetsAsync(redb, userId, sessionId, subject, ct).ConfigureAwait(false); if (sessionId > 0) { // Per-session logout ends this OP session and tells the relying parties that signed in through // it (back-channel below). It deliberately leaves the user's grants alone: refresh tokens exist // only with offline_access, which OIDC Core §11 defines as access while the End-User is not // logged in, so signing out of one browser must not sign the user's other applications out. // Keycloak keeps offline tokens across a session logout and Duende revokes nothing on logout for // the same reason. Ending every grant is the full logout (password change or reset, operator, // SCIM deactivation): SessionService.LogoutAsync. sessionsRevoked = await session.RevokeAsync(sessionId, ct); } else { // A ticket without a session id (legacy): end every session of the user. sessionsRevoked = await session.LogoutAsync(userId, ct); } // Best-effort backchannel logout fan-out. Failures are logged but never break logout. // BackchannelLogoutDispatcher is registered in the Identity child container — resolve // through the IRouteContext scope helper, NOT exchange.ServiceProvider (that's the // *host* container, where the dispatcher is not registered). var dispatcher = _context.GetIdentityServiceOrDefault(exchange); int backchannelDelivered = 0; if (dispatcher is not null && subject != Guid.Empty) { foreach (var (sid, applications) in targets) { try { backchannelDelivered += await dispatcher.DispatchAsync( redb, subject, sid, applications, ct).ConfigureAwait(false); } catch (Exception ex) { _logger?.LogWarning(ex, "BackchannelLogoutDispatcher.DispatchAsync threw for session {SessionId} — logout flow continues.", sid); } } } var backchannelTargets = targets.SelectMany(t => t.Applications).Distinct().Count(); exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new Dictionary { ["success"] = true, ["sessions_revoked"] = sessionsRevoked, ["backchannel_delivered"] = backchannelDelivered }; exchange.Properties["identity-event-type"] = IdentityAuditEventIds.UserLoggedOut; exchange.Properties["identity-event-data"] = new { UserId = userId, SessionsRevoked = sessionsRevoked, BackchannelDelivered = backchannelDelivered, BackchannelTargets = backchannelTargets }; } /// /// Whom the back-channel logout goes to, grouped by the session whose id the logout token carries as /// sid (Back-Channel Logout 1.0 §2.1: the OP notifies the relying parties the End-User logged in /// to through the session being ended). For the session being ended: the relying parties that obtained /// tokens through it (, bound at the authorization /// endpoint) and the application the session was opened for, if any. For a logout of every session (a /// ticket without a session id): each active session's relying parties with that session's id, and, /// with no sid, the relying parties that hold live authorizations or tokens for the user outside /// any browser session (ROPC, device flow) — they have no session to match, so sub is all the /// token can say. /// private static async Task Applications)>> CollectBackchannelTargetsAsync( IRedbService redb, long userId, long sessionId, Guid subject, CancellationToken ct) { var targets = new List<(long SessionId, IReadOnlyCollection Applications)>(); if (sessionId > 0) { var current = await redb.LoadAsync(sessionId).ConfigureAwait(false); if (current is not null && current.Props.Status != "revoked") { var applications = ApplicationsOf(current); if (applications.Count > 0) targets.Add((sessionId, applications)); } return targets; } // Sessions use Key == userId (long). var sessions = await redb.Query() .WhereRedb(o => o.Key == userId) .Where(p => p.Status == "active") .ToListAsync() .ConfigureAwait(false); var covered = new HashSet(); foreach (var s in sessions) { var applications = ApplicationsOf(s); if (applications.Count == 0) continue; targets.Add((s.id, applications)); covered.UnionWith(applications); } if (subject == Guid.Empty) return targets; // Authorizations and tokens are written by OpenIddict stores via SetSubjectAsync, which keys // them by the public subject (_objects.value_guid), not by Key. var sessionless = new HashSet(); var auths = await redb.Query() .WhereRedb(o => o.ValueGuid == subject) .Where(p => p.Status != "revoked") .ToListAsync() .ConfigureAwait(false); foreach (var a in auths) if (a.Props.ApplicationObjectId > 0 && !covered.Contains(a.Props.ApplicationObjectId)) sessionless.Add(a.Props.ApplicationObjectId); // ROPC and other non-interactive grants emit access/refresh tokens without creating an // authorization row; tokens always carry ApplicationObjectId. var tokens = await redb.Query() .WhereRedb(o => o.ValueGuid == subject) .Where(p => p.Status != "revoked") .ToListAsync() .ConfigureAwait(false); foreach (var t in tokens) if (t.Props.ApplicationObjectId > 0 && !covered.Contains(t.Props.ApplicationObjectId)) sessionless.Add(t.Props.ApplicationObjectId); if (sessionless.Count > 0) targets.Add((0, sessionless)); return targets; } private static IReadOnlyCollection ApplicationsOf(RedbObject session) { var applications = new HashSet(session.Props.ClientApplicationIds ?? []); if (session.Props.ApplicationObjectId > 0) applications.Add(session.Props.ApplicationObjectId); return applications; } private static long HeaderLong(IExchange exchange, string name) { if (!exchange.In.Headers.TryGetValue(name, out var raw)) return 0; return raw switch { long value => value, string text when long.TryParse(text, out var parsed) => parsed, _ => 0, }; } private static string? BodyString(IExchange exchange, string name) => exchange.In.Body switch { Dictionary dict when dict.TryGetValue(name, out var value) => value?.ToString(), Dictionary sdict when sdict.TryGetValue(name, out var value) => value, _ => null, }; /// /// The user's public subject GUID — the sub of every token and the value_guid OpenIddict's /// stores key authorizations and tokens by. It lives on the UserProps "oidc" sibling object /// (Key == coreUser.Id), not on the core-user object itself. when the /// user has no such object. /// private static async Task ResolveSubjectAsync(IRedbService redb, long userId) { var userProps = await redb.Query() .WhereRedb(o => o.Key == userId) .FirstOrDefaultAsync() .ConfigureAwait(false); return userProps?.value_guid ?? Guid.Empty; } /// /// Validates the id_token_hint JWT signature using our own signing keys and extracts /// sub and aud claims. Returns (null, null) if validation fails. /// private async Task<(string? sub, string? aud)> ValidateIdTokenHintAsync(string jwt) { try { var opts = _serverOptions.CurrentValue; var signingKeys = opts.SigningCredentials .Select(c => c.Key) .ToList(); if (signingKeys.Count == 0) { _logger?.LogWarning("No signing keys configured — cannot validate id_token_hint"); return (null, null); } // Microsoft.IdentityModel does STRICT-STRING issuer comparison — no URI // normalisation. OpenIddict mints id_tokens with iss=opts.Issuer.AbsoluteUri // which always carries a trailing slash (Uri normalises path "" → "/"). If we // pass only the TrimEnd('/') form here, validation fails with IDX10205 // ("Issuer: 'http://host:5002/'. Did not match: ValidIssuer 'http://host:5002'") // on every logout that supplies an id_token_hint signed by ourselves. Accept // both forms so admin-configured Issuer values with/without a trailing slash // both work end-to-end. var issuerWithSlash = opts.Issuer?.ToString(); var issuerNoSlash = issuerWithSlash?.TrimEnd('/'); var validationParams = new TokenValidationParameters { ValidIssuers = opts.Issuer is null ? null : new[] { issuerWithSlash!, issuerNoSlash! }, ValidateIssuer = opts.Issuer is not null, ValidateAudience = false, // we just need sub + aud claims, audience was our client ValidateLifetime = false, // logout should work even with expired tokens IssuerSigningKeys = signingKeys, ValidateIssuerSigningKey = true, ClockSkew = TimeSpan.FromMinutes(5) }; var result = await _tokenHandler.ValidateTokenAsync(jwt, validationParams) .ConfigureAwait(false); if (!result.IsValid) { _logger?.LogWarning("id_token_hint signature validation failed: {Error}", result.Exception?.Message); return (null, null); } var sub = result.ClaimsIdentity.FindFirst("sub")?.Value; var aud = result.ClaimsIdentity.FindFirst("aud")?.Value; return (sub, aud); } catch (Exception ex) { _logger?.LogWarning(ex, "Failed to validate id_token_hint"); return (null, null); } } } Path: redb-identity/src/redb.Identity.Core/Routes/Processors/ManagementBearerAuthProcessor.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/Routes/Processors/ManagementBearerAuthProcessor.cs ---- using System.Security.Claims; using Microsoft.Extensions.DependencyInjection; using OpenIddict.Abstractions; using OpenIddict.Validation; using redb.Identity.Core.OpenIddict.Handlers; using redb.Identity.Core.Serialization; using redb.Identity.Core.Services; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Identity.Core.Routes.Processors; /// /// Validates management API requests using OAuth2 Bearer token authentication. /// Uses OpenIddict Validation (server-local, no network round-trip) to validate tokens /// and checks for the required management scope. /// internal sealed class ManagementBearerAuthProcessor : IProcessor { /// /// Transaction property key used to pass the bearer token to the OpenIddict Validation pipeline. /// internal const string TokenPropertyKey = "__mgmt_bearer_token"; // The validation services are resolved in a scope of their own for every request: the token and application // stores are scoped and cache what they read for one request, so a scope that outlived a request would keep // answering from the first read of a token (a revoked token would stay valid). private readonly IServiceScopeFactory _scopes; private readonly string[] _acceptableScopes; private readonly string[] _anonymousPathPrefixes; /// /// Constructs the processor with a single required scope. The token must carry exactly /// this scope. /// public ManagementBearerAuthProcessor( IServiceScopeFactory scopes, string requiredScope, IEnumerable? anonymousPathPrefixes = null) : this(scopes, new[] { requiredScope ?? throw new ArgumentNullException(nameof(requiredScope)) }, anonymousPathPrefixes) { } /// /// Constructs the processor with a set of acceptable scopes. The token must carry AT LEAST /// ONE of these scopes (any-of). Used to admit both administrator (e.g. identity:manage) /// and self-service (e.g. identity:account) callers; the subsequent /// enforces the actual self-vs-admin rule. /// /// /// N-4 (Session C): optional list of URL path prefixes (matched against redbHttp.Path, /// case-insensitive) that bypass bearer-token validation entirely. Used for genuinely /// anonymous self-service endpoints (e.g. /api/v1/identity/password/forgot, /// /api/v1/identity/password/reset) that must be reachable without any prior /// authentication. When a request matches, the processor short-circuits without /// reading the Authorization header and without populating any /// identity:management-* properties — downstream processors MUST tolerate the /// absence of a principal. /// public ManagementBearerAuthProcessor( IServiceScopeFactory scopes, IEnumerable acceptableScopes, IEnumerable? anonymousPathPrefixes = null) { _scopes = scopes ?? throw new ArgumentNullException(nameof(scopes)); if (acceptableScopes is null) throw new ArgumentNullException(nameof(acceptableScopes)); _acceptableScopes = acceptableScopes.Where(s => !string.IsNullOrEmpty(s)).Distinct(StringComparer.Ordinal).ToArray(); if (_acceptableScopes.Length == 0) throw new ArgumentException("At least one acceptable scope must be provided.", nameof(acceptableScopes)); _anonymousPathPrefixes = (anonymousPathPrefixes ?? Array.Empty()) .Where(s => !string.IsNullOrWhiteSpace(s)) .Select(s => s!) .ToArray(); } public async Task Process(IExchange exchange, CancellationToken ct = default) { // N-4 (Session C): anonymous-prefix short-circuit. Genuinely public endpoints // (password-recovery flows) must be reachable without any Authorization header // at all — they live under the same /api/v1/identity/ root for URL stability // and dispatch through the same controller registry, but skip bearer validation // entirely here. Downstream processors / controllers MUST tolerate the absence // of `identity:management-principal`. if (_anonymousPathPrefixes.Length > 0) { var path = exchange.In.GetHeader("redbHttp.Path"); if (!string.IsNullOrEmpty(path)) { System.Diagnostics.Debug.WriteLine($"[SCIM-AUTH] Path: {path}, Prefixes: {string.Join(", ", _anonymousPathPrefixes)}"); foreach (var prefix in _anonymousPathPrefixes) { if (path!.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) { System.Diagnostics.Debug.WriteLine($"[SCIM-AUTH] MATCH: {path} starts with {prefix}"); exchange.Properties["identity:management-anonymous"] = true; return; } } System.Diagnostics.Debug.WriteLine($"[SCIM-AUTH] NO MATCH for {path}"); } else { System.Diagnostics.Debug.WriteLine($"[SCIM-AUTH] redbHttp.Path is empty/null"); } } // 1. Extract bearer token from Authorization header. // D6: per RFC 6750 §2.1 the scheme token is case-insensitive ("Bearer", "bearer", // "BEARER" all valid) and per RFC 7230 §3.2.4 one-or-more SP / OWS is permitted // between the scheme and the credentials. // A DPoP-bound token comes under the DPoP scheme (RFC 9449 §7.1); whether the scheme fits the // token, and the proof, are checked by DpopConfirmationValidationPassThroughHandler. var authorization = exchange.In.GetHeader("Authorization"); var scheme = DpopConfirmationPassThrough.DpopScheme; var token = TryExtractToken(authorization, scheme); if (token is null) { scheme = "Bearer"; token = TryExtractBearerToken(authorization); } if (token is null) { Reject(exchange, 401, "missing_token", "Authorization header with a Bearer or DPoP token is required."); return; } if (token.Length == 0) { Reject(exchange, 401, "invalid_token", "The access token is empty."); return; } // 2. Validate token via OpenIddict Validation (server-local) await using var scope = _scopes.CreateAsyncScope(); var factory = scope.ServiceProvider.GetRequiredService(); var dispatcher = scope.ServiceProvider.GetRequiredService(); var transaction = await factory.CreateTransactionAsync(); transaction.Properties[TokenPropertyKey] = token; transaction.Properties[DpopConfirmationPassThrough.SchemeProperty] = scheme; transaction.Properties[DpopConfirmationPassThrough.ProofProperty] = exchange.In.GetHeader("DPoP"); transaction.Properties[DpopConfirmationPassThrough.MethodProperty] = exchange.In.GetHeader("redbHttp.Method"); transaction.Properties[DpopConfirmationPassThrough.UrlProperty] = exchange.In.GetHeader("redbHttp.Url"); transaction.CancellationToken = ct; var context = new OpenIddictValidationEvents.ProcessAuthenticationContext(transaction); await dispatcher.DispatchAsync(context); if (context.IsRejected || context.AccessTokenPrincipal is null) { Reject(exchange, 401, context.Error ?? "invalid_token", context.ErrorDescription ?? "The access token is not valid.", transaction.Properties.TryGetValue(DpopConfirmationPassThrough.ChallengeProperty, out var challenge) ? challenge as string : null); return; } // 3. Check required scope var principal = context.AccessTokenPrincipal; var scopes = principal.GetScopes(); if (!_acceptableScopes.Any(s => scopes.Contains(s, StringComparer.Ordinal))) { Reject(exchange, 403, "insufficient_scope", $"The access token does not have any of the required scopes: {string.Join(", ", _acceptableScopes)}."); return; } // 4. Store validated principal for downstream processors exchange.Properties["identity:management-principal"] = principal; exchange.Properties["identity:management-subject"] = principal.GetClaim(OpenIddictConstants.Claims.Subject); // Mirror the internal bigint user id (if present — only end-user grants emit it, // client_credentials tokens carry only the public string sub). Self-service // processors read this property instead of long-parsing the GUID sub. var internalUid = principal.GetClaim(IdentityPrincipalBuilder.InternalUserIdClaim); if (!string.IsNullOrEmpty(internalUid) && long.TryParse(internalUid, out var uid) && uid > 0) exchange.Properties["identity:management-user-id"] = uid; // B8: surface the granted scopes so RequireSelfOrAdminProcessor can pick admin vs self. exchange.Properties["identity:management-scopes"] = scopes.ToArray(); // H3-SSO: surface the "sid" claim (OIDC session id, written by // AttachSessionPrincipalHandler) so /me/sessions revoke-current can map the // current access token back to its owning session without trusting the body. // Only present on tokens issued via the OIDC session flow; client_credentials // and other grants won't have it — that's fine, revoke-current is a no-op for them. var sid = principal.GetClaim("sid"); if (!string.IsNullOrEmpty(sid)) exchange.Properties["identity:management-sid"] = sid; } private static void Reject(IExchange exchange, int statusCode, string error, string description, string? challenge = null) { // RFC 6749 §5.2 — OAuth 2.0 error response: application/json with snake_case // members "error", "error_description". RFC 6750 §3 mandates the same envelope // on protected-resource 401/403 responses so external OAuth clients (that a user // might point at our identity server as a drop-in replacement) can parse it. // // Going through the locked OAuthJson IMessageSerializer facade (rather than // raw JsonSerializer) keeps the wire format observably identical to what the // codec registry would produce, while guaranteeing that no app-level // `ConfigureJsonCodec(...)` can reshape this RFC-mandated payload — the OAuth // profile is intentionally NOT registered into IDataFormatRegistry. var body = IdentityCodecProfiles.OAuthJson.Serialize(new Dictionary { ["error"] = error, ["error_description"] = description }); exchange.Out = new Message(body); // Core-level content type keeps the value transport-agnostic for Rabbit/Kafka façades. exchange.Out.ContentType = IdentityCodecProfiles.OAuthMediaType; exchange.Out.Headers["redbHttp.ResponseCode"] = statusCode; exchange.Out.Headers["redbHttp.ResponseContentType"] = IdentityCodecProfiles.OAuthMediaType; // D6: RFC 6750 §3.1 — challenge MUST be returned on 401 and SHOULD be returned // on 403 (insufficient_scope). The realm parameter helps clients distinguish // protected resources behind the same hostname. if (statusCode is 401 or 403) { exchange.Out.Headers["WWW-Authenticate"] = challenge ?? BuildChallenge(error, description); } exchange.Exception = new UnauthorizedAccessException(description); exchange.ExceptionHandled = true; exchange.Stop(); } private static string BuildChallenge(string error, string description) { // RFC 6750 §3 quoted-string syntax: backslash and double quotes must be escaped. var safeDesc = description.Replace("\\", "\\\\").Replace("\"", "\\\""); var safeError = error.Replace("\\", "\\\\").Replace("\"", "\\\""); return $"Bearer realm=\"identity\", error=\"{safeError}\", error_description=\"{safeDesc}\""; } /// /// Parses a single Authorization: Bearer <token> header tolerantly per /// RFC 6750 §2.1 + RFC 7230 §3.2.4. Returns the raw token (possibly empty), or /// null when the header is absent / does not use the Bearer scheme. /// internal static string? TryExtractBearerToken(string? authorizationHeader) => TryExtractToken(authorizationHeader, "Bearer"); /// /// Same tolerant parsing as for the given . /// internal static string? TryExtractToken(string? authorizationHeader, string scheme) { if (string.IsNullOrEmpty(authorizationHeader)) return null; var span = authorizationHeader.AsSpan().TrimStart(); if (span.Length < scheme.Length || !span[..scheme.Length].Equals(scheme.AsSpan(), StringComparison.OrdinalIgnoreCase)) return null; var after = span[scheme.Length..]; // Must be at least one whitespace separator (or empty rest, which we treat // as empty token below). if (after.Length > 0 && after[0] != ' ' && after[0] != '\t') return null; return after.Trim().ToString(); } } Path: redb-identity/src/redb.Identity.Core/Routes/Processors/ManagementProblem.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/Routes/Processors/ManagementProblem.cs ---- using redb.Identity.Core.Serialization; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Identity.Core.Routes.Processors; /// /// The one refusal every authorization gate on the management surface produces. /// /// A single generic 403 Problem Details answer (RFC 9457) with the stable machine-readable /// code not_authorized. Every gate uses the same shape on purpose: the answer must not /// tell the caller whether the target exists, which rule refused, or whether a context was missing or /// merely insufficient — B8 (IDOR) rests on that. This is an application-level authorization rule, not /// an RFC 6750 scope challenge: the 6750 challenge, when there is one, was already issued upstream by /// . /// /// internal static class ManagementProblem { public const string Code = "not_authorized"; /// Refuses the exchange: 403 problem body, handled exception, route stopped. public static void Forbidden(IExchange exchange, string detail) { var problem = new Dictionary { ["type"] = "https://redb.local/problems/authorization-denied", ["title"] = "Forbidden", ["status"] = 403, ["detail"] = detail, ["code"] = Code, }; // Serialize through the locked Problem profile facade: the same wire format a registry lookup // for "application/problem+json" returns (IdentityCodecProfilesConfigurator); the gates have no // route context to look it up with, and the profile is an Identity-owned, RFC-locked artifact. var body = IdentityCodecProfiles.Problem.Serialize(problem); exchange.Out = new Message(body); // Core-level content type keeps the value transport-agnostic for the Rabbit/Kafka facades. exchange.Out.ContentType = IdentityCodecProfiles.ProblemMediaType; exchange.Out.Headers["redbHttp.ResponseCode"] = 403; exchange.Out.Headers["redbHttp.ResponseContentType"] = IdentityCodecProfiles.ProblemMediaType; exchange.Exception = new UnauthorizedAccessException(detail); exchange.ExceptionHandled = true; exchange.Stop(); } } Path: redb-identity/src/redb.Identity.Core/Routes/Processors/MeConsentsProcessor.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/Routes/Processors/MeConsentsProcessor.cs ---- using redb.Identity.Contracts.Consents; using redb.Identity.Core.Services; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.RedbCore.Extensions; using redb.Identity.Contracts.Routes; namespace redb.Identity.Core.Routes.Processors; /// /// H3 (v1.0 DoD §6): self-service consent management backing /// GET /me/consents and DELETE /me/consents/{clientId}. Returns the /// caller's own valid permanent OAuth/OIDC consent grants and lets them revoke a /// specific grant by client_id. Caller id is taken from the access token — /// the request body never carries a userId. /// internal sealed class MeConsentsProcessor : IProcessor { private readonly IRouteContext _context; private readonly string? _redbName; public MeConsentsProcessor(IRouteContext context, string? redbName = null) { _context = context; _redbName = redbName; } public async Task Process(IExchange exchange, CancellationToken ct = default) { var callerId = MeProcessorHelpers.TryGetCallerUserId(exchange); if (callerId is null) { MeProcessorHelpers.Reject(exchange, 401, "invalid_token", $"The access token does not carry a numeric subject claim required for self-service APIs (got subject={MeProcessorHelpers.GetRawCallerSubject(exchange) ?? ""})."); return; } var operation = exchange.In.GetHeader("operation") ?? throw new InvalidOperationException("Missing 'operation' header"); // Lazy resolution: input-validation paths (e.g. grant with empty clientId/scopes) // must reject before any IRouteContext access so they can be unit-tested without DI. ConsentService? consentService = null; ConsentService GetConsents() => consentService ??= new ConsentService(_context.GetRedbService(_redbName, exchange)); switch (operation) { case "list": await List(GetConsents(), exchange, callerId.Value, ct); break; case "revoke": await Revoke(GetConsents(), exchange, callerId.Value, ct); break; case "grant": await Grant(GetConsents, exchange, callerId.Value, ct); break; default: MeProcessorHelpers.Reject(exchange, 400, "invalid_operation", $"Unknown operation: {operation}"); break; } } private static async Task Grant( Func consentsFactory, IExchange exchange, long userId, CancellationToken ct) { // Body shape: typed GrantMyConsentRequest from the controller, or a route-supplied // dictionary with clientId + scopes (string[] or space-separated string) for direct-vm callers. string? clientId = null; IReadOnlyCollection? scopes = null; switch (exchange.In.Body) { case GrantMyConsentRequest req: clientId = req.ClientId; scopes = req.Scopes; break; case IDictionary dict: if (dict.TryGetValue("clientId", out var cid)) clientId = cid?.ToString(); if (dict.TryGetValue("scopes", out var sc)) { scopes = sc switch { string[] arr => arr, IEnumerable en => en.Select(x => x?.ToString() ?? "") .Where(s => !string.IsNullOrWhiteSpace(s)).ToArray(), string spaceSep => spaceSep.Split(' ', StringSplitOptions.RemoveEmptyEntries), _ => null }; } break; } if (string.IsNullOrWhiteSpace(clientId)) { MeProcessorHelpers.Reject(exchange, 400, "validation_error", "ClientId is required"); return; } if (scopes is null || scopes.Count == 0) { MeProcessorHelpers.Reject(exchange, 400, "validation_error", "At least one scope is required"); return; } var consents = consentsFactory(); var applicationId = await consents.FindApplicationIdAsync(clientId, ct); if (applicationId is null) { MeProcessorHelpers.Reject(exchange, 404, "not_found", $"Application with ClientId='{clientId}' not found."); return; } var auth = await consents.GrantAsync(userId, applicationId.Value, scopes, ct); exchange.Out ??= new Message(); exchange.Out.Body = new MyConsentGrantedResponse { Id = auth.id, UserId = userId, ClientId = clientId, ApplicationId = applicationId.Value, Scopes = auth.Props.Scopes ?? Array.Empty() }; exchange.Properties["identity-event-type"] = IdentityAuditEventIds.ConsentGranted; exchange.Properties["identity-event-data"] = new { UserId = userId, ClientId = clientId, ApplicationId = applicationId.Value, Scopes = string.Join(' ', scopes), SelfService = true }; } private static async Task List( ConsentService consents, IExchange exchange, long userId, CancellationToken ct) { var grants = await consents.ListAsync(userId, ct); var response = grants.Select(c => new ConsentResponse { Id = c.Id, UserId = c.UserId, ApplicationId = c.ApplicationId, ClientId = c.ClientId, ApplicationName = c.ApplicationName, Scopes = c.Scopes, Status = "valid", CreatedAt = c.CreatedAt }).ToList(); exchange.Out ??= new Message(); exchange.Out.Body = response; } private static async Task Revoke( ConsentService consents, IExchange exchange, long userId, CancellationToken ct) { // Body shape: either MeRevokeConsentRequest, or a route-supplied dict with "clientId" // (the controller path-segment is mapped into the body for direct-vm dispatch). string? clientId = null; switch (exchange.In.Body) { case MeRevokeConsentRequest req: clientId = req.ClientId; break; case IDictionary dict when dict.TryGetValue("clientId", out var cid): clientId = cid?.ToString(); break; } if (string.IsNullOrWhiteSpace(clientId)) { MeProcessorHelpers.Reject(exchange, 400, "validation_error", "ClientId is required"); return; } var applicationId = await consents.FindApplicationIdAsync(clientId, ct); if (applicationId is null) { MeProcessorHelpers.Reject(exchange, 404, "not_found", $"Application with ClientId='{clientId}' not found."); return; } var revoked = await consents.RevokeAsync(userId, applicationId.Value, ct); exchange.Out ??= new Message(); exchange.Out.Body = new MyConsentRevokedResponse { Revoked = revoked }; exchange.Properties["identity-event-type"] = IdentityAuditEventIds.ConsentRevoked; exchange.Properties["identity-event-data"] = new { UserId = userId, ClientId = clientId, ApplicationId = applicationId.Value, Count = revoked, SelfService = true }; } } Path: redb-identity/src/redb.Identity.Core/Routes/Processors/MeFederatedIdentitiesProcessor.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/Routes/Processors/MeFederatedIdentitiesProcessor.cs ---- using Microsoft.Extensions.DependencyInjection; using redb.Core; using redb.Core.Query; using redb.Identity.Contracts.Federation; using redb.Identity.Core.Configuration; using redb.Identity.Core.Models; using redb.Identity.Core.Services; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.RedbCore.Extensions; using redb.Identity.Contracts.Routes; namespace redb.Identity.Core.Routes.Processors; /// /// H8 (DoD §4 gap (b)/(d)): self-service federated identity management backing /// /me/federated-identities. Lets a logged-in user list, add (link) or remove /// (unlink) federated identities tied to their own account. Operations: /// /// list — returns all rows for the /// caller's user id. /// link-challenge — starts an OIDC dance for an additional provider; the /// encrypted state carries the caller's user id, so the existing /// FederationCallbackProcessor performs a link instead of a login. /// unlink — removes a single (provider) link. Refuses when the link is /// the user's last credential method (no other federated link AND no local password) /// to prevent the user from locking themselves out (gap (d)). /// /// internal sealed class MeFederatedIdentitiesProcessor : IProcessor { private readonly IRouteContext _context; private readonly IServiceProvider _sp; private readonly string? _redbName; public MeFederatedIdentitiesProcessor(IRouteContext context, IServiceProvider sp, string? redbName = null) { _context = context; _sp = sp; _redbName = redbName; } public async Task Process(IExchange exchange, CancellationToken ct = default) { var callerId = MeProcessorHelpers.TryGetCallerUserId(exchange); if (callerId is null) { MeProcessorHelpers.Reject(exchange, 401, "invalid_token", $"The access token does not carry a numeric subject claim required for self-service APIs (got subject={MeProcessorHelpers.GetRawCallerSubject(exchange) ?? ""})."); return; } var operation = exchange.In.GetHeader("operation") ?? throw new InvalidOperationException("Missing 'operation' header"); var redb = _context.GetRedbService(_redbName, exchange); switch (operation) { case "list": await List(redb, exchange, callerId.Value, ct); break; case "link-challenge": await LinkChallenge(exchange, callerId.Value, ct); break; case "unlink": await Unlink(redb, exchange, callerId.Value, ct); break; default: MeProcessorHelpers.Reject(exchange, 400, "invalid_operation", $"Unknown operation: {operation}"); break; } } private static async Task List( IRedbService redb, IExchange exchange, long userId, CancellationToken ct) { var links = await redb.Query() .WhereRedb(o => o.Key == userId) .OrderBy(o => o.ProviderId) .ToListAsync() .ConfigureAwait(false); var response = links .Select(o => new FederatedIdentityResponse { ProviderId = o.Props.ProviderId, ExternalSub = o.Props.ExternalSub, ExternalEmail = o.Props.ExternalEmail, ExternalDisplayName = o.Props.ExternalDisplayName, LinkedAt = o.Props.LinkedAt, LastLoginAt = o.Props.LastLoginAt, }) .ToList(); exchange.Out ??= new Message(); exchange.Out.Body = response; } private async Task LinkChallenge(IExchange exchange, long userId, CancellationToken ct) { // Body shape: contracted DTO from controller, or dict for direct-vm dispatch. string? providerId = null; string? returnUrl = null; string? callbackUrl = null; switch (exchange.In.Body) { case LinkFederatedIdentityRequest req: providerId = req.ProviderId; returnUrl = req.ReturnUrl; break; case IDictionary dict: providerId = dict.TryGetValue("providerId", out var p) ? p?.ToString() : null; returnUrl = dict.TryGetValue("returnUrl", out var r) ? r?.ToString() : null; callbackUrl = dict.TryGetValue("callbackUrl", out var cb) ? cb?.ToString() : null; break; } // The callbackUrl is normally injected by the HTTP transport (it knows the public // base URL). Direct-vm callers must supply it explicitly in the body dict. if (string.IsNullOrWhiteSpace(providerId)) { MeProcessorHelpers.Reject(exchange, 400, "validation_error", "ProviderId is required"); return; } if (string.IsNullOrWhiteSpace(callbackUrl)) { // Fallback: compute from the server's configured Issuer + the standard // /connect/federation/callback path. Closes the gap where the HTTP-facing // controller resolves IdentityTransportOptions through a Route-context SP // that doesn't have the IOptions binding wired and returns the default // https://localhost/ (causing mock IdPs to redirect to an unreachable URL). // Same shape as the static /connect/federation/callback route registered in // HttpFacadeRouteBuilder, so the existing FederationCallbackProcessor handles it. // RedbIdentityOptions lives in DI as IOptions, not as the raw type — same // gotcha that bit the controller-side resolution. var identityOpts = _sp.GetService>()?.Value; var issuer = identityOpts?.Issuer?.AbsoluteUri?.TrimEnd('/'); if (!string.IsNullOrWhiteSpace(issuer)) { callbackUrl = $"{issuer}/connect/federation/callback"; } } if (string.IsNullOrWhiteSpace(callbackUrl)) { MeProcessorHelpers.Reject(exchange, 500, "server_error", "Federation callback URL is not configured."); return; } var providers = _sp.GetServices(); var provider = providers.FirstOrDefault(p => string.Equals(p.ProviderId, providerId, StringComparison.OrdinalIgnoreCase)); if (provider is null) { MeProcessorHelpers.Reject(exchange, 400, "invalid_request", $"Unknown federation provider '{providerId}'."); return; } var challenge = await provider.CreateChallengeAsync(callbackUrl, returnUrl ?? "/", ct) .ConfigureAwait(false); // C6 parity with FederationChallengeProcessor: optionally mint per-flow // browser-binding secret. The HTTP transport converts the property into a Secure // HttpOnly SameSite=Lax cookie that the callback validates. var fedOptions = _sp.GetService()?.FederationState ?? new FederationStateOptions(); string? bindingSecret = null; string? bindingHash = null; if (fedOptions.RequireBrowserBinding) { var raw = new byte[32]; System.Security.Cryptography.RandomNumberGenerator.Fill(raw); bindingSecret = Convert.ToBase64String(raw); bindingHash = FederationStateProtector.ComputeBindingHash(bindingSecret); } // Encrypt state with LinkUserId set — the callback will treat this as a link op. var stateProtector = _sp.GetRequiredService(); var protectedState = stateProtector.Protect(new FederationState { ProviderId = providerId, ReturnUrl = returnUrl, Nonce = challenge.Nonce, CodeVerifier = challenge.CodeVerifier, LinkUserId = userId, BindingHash = bindingHash, }); var redirectUri = challenge.RedirectUri.Replace( Uri.EscapeDataString(challenge.State), Uri.EscapeDataString(protectedState)); exchange.Out ??= new Message(); exchange.Out.Body = new LinkFederatedIdentityChallengeResponse { RedirectUri = redirectUri }; if (bindingSecret is not null) { exchange.Properties["federation-binding-secret"] = bindingSecret; exchange.Properties["federation-binding-cookie-name"] = fedOptions.BindingCookieName; } } private static async Task Unlink( IRedbService redb, IExchange exchange, long userId, CancellationToken ct) { // Body shape: route-supplied dict with "providerId" path segment. string? providerId = null; switch (exchange.In.Body) { case IDictionary dict when dict.TryGetValue("providerId", out var p): providerId = p?.ToString(); break; } if (string.IsNullOrWhiteSpace(providerId)) { MeProcessorHelpers.Reject(exchange, 400, "validation_error", "ProviderId is required"); return; } // Load the full set of federations to determine whether removing this one would // leave the user without any usable credential. var allLinks = await redb.Query() .WhereRedb(o => o.Key == userId) .ToListAsync() .ConfigureAwait(false); var match = allLinks.FirstOrDefault(o => string.Equals(o.Props.ProviderId, providerId, StringComparison.OrdinalIgnoreCase)); if (match is null) { MeProcessorHelpers.Reject(exchange, 404, "not_found", $"No linked federated identity from provider '{providerId}' for the current user."); return; } // Last-credential guard (gap (d)): if this is the only link AND the user never // set their own password, reject with a structured error so the caller can show a // helpful message ("set a password first"). if (allLinks.Count == 1) { var props = await redb.Query() .WhereRedb(o => o.Key == userId) .FirstOrDefaultAsync() .ConfigureAwait(false); var hasPassword = props?.Props.HasUserPassword == true; if (!hasPassword) { MeProcessorHelpers.Reject(exchange, 409, "last_credential_method", "This is your last sign-in method. Set a local password before removing this link."); return; } } await redb.DeleteAsync(match).ConfigureAwait(false); // Mirror to denormalized cache on UserProps. var oidcObj = await redb.Query() .WhereRedb(o => o.Key == userId) .FirstOrDefaultAsync() .ConfigureAwait(false); if (oidcObj?.Props.ExternalIdentities is { } map && map.Remove(providerId)) await redb.SaveAsync(oidcObj).ConfigureAwait(false); exchange.Out ??= new Message(); exchange.Out.Body = new FederatedIdentityUnlinkedResponse { ProviderId = providerId }; exchange.Properties["identity-event-type"] = IdentityAuditEventIds.FederatedIdentityUnlinked; exchange.Properties["identity-event-data"] = new { UserId = userId, ProviderId = providerId, SelfService = true, }; } } Path: redb-identity/src/redb.Identity.Core/Routes/Processors/MeMfaProcessor.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/Routes/Processors/MeMfaProcessor.cs ---- using System.Text.Json; using Microsoft.Extensions.DependencyInjection; using redb.Identity.Contracts.Common; using redb.Identity.Contracts.Mfa; using redb.Identity.Core.Services; using redb.Route.Abstractions; using redb.Route.Core; using redb.Identity.Contracts.Routes; namespace redb.Identity.Core.Routes.Processors; /// /// H3 (v1.0 DoD §6): self-service MFA management backing /me/mfa/*. Mirrors /// operation-by-operation but injects the caller's /// user id from identity:management-subject instead of reading it from the /// request body — under no circumstances may a user enroll, confirm, disable, or /// regenerate codes for someone else's account through this surface. Admin parity /// remains under with body.userId. /// internal sealed class MeMfaProcessor : IProcessor { private readonly IServiceProvider _sp; public MeMfaProcessor(IServiceProvider sp) => _sp = sp; public async Task Process(IExchange exchange, CancellationToken ct = default) { var callerId = MeProcessorHelpers.TryGetCallerUserId(exchange); if (callerId is null) { MeProcessorHelpers.Reject(exchange, 401, "invalid_token", $"The access token does not carry a numeric subject claim required for self-service APIs (got subject={MeProcessorHelpers.GetRawCallerSubject(exchange) ?? ""})."); return; } var operation = exchange.In.GetHeader("operation") ?? throw new InvalidOperationException("Missing 'operation' header"); exchange.Out = new Message(); using var scope = _sp.CreateScope(); var mfaService = scope.ServiceProvider.GetRequiredService(); var body = exchange.In.Body as IDictionary; switch (operation) { case "status": await Status(mfaService, callerId.Value, exchange, ct); break; case "setup": await Setup(mfaService, callerId.Value, body, exchange, ct); break; case "confirm": await Confirm(mfaService, callerId.Value, body, exchange, ct); break; case "disable": await Disable(mfaService, callerId.Value, body, exchange, ct); break; case "regenerate-recovery": await RegenerateRecovery(mfaService, callerId.Value, exchange, ct); break; case "download-recovery": await DownloadRecovery(mfaService, callerId.Value, exchange, ct); break; default: exchange.Out.Body = Error("invalid_operation", $"Unknown MFA operation: {operation}"); break; } // For self-service, audit events carry the caller id explicitly. if (operation == "download-recovery" && exchange.Out!.Body is byte[]) { // Download-recovery body is plaintext bytes (the file payload) — emit the // dedicated audit event so the audit sink categorizes it under Mfa rather // than the generic MfaSelfService:* fallback. exchange.Properties["identity-event-type"] = redb.Identity.Contracts.Routes.IdentityAuditEventIds.MfaRecoveryCodesDownloaded; exchange.Properties["identity-event-data"] = new { UserId = callerId.Value }; } else if (exchange.Out!.Body is not ErrorResponse) { exchange.Properties["identity-event-type"] = $"MfaSelfService:{operation}"; exchange.Properties["identity-event-data"] = new { UserId = callerId.Value, Operation = operation }; } } private static string? GetString(IDictionary? body, string key) { if (body is null) return null; return body.TryGetValue(key, out var v) ? v?.ToString() : null; } private static async Task Status(MfaService mfaService, long userId, IExchange exchange, CancellationToken ct) { var status = await mfaService.GetStatusAsync(userId, ct); exchange.Out!.Body = new MfaStatusResponse { Enabled = status.Enabled, Methods = status.Methods, RecoveryCodesRemaining = status.RecoveryCodesRemaining }; } private static async Task Setup( MfaService mfaService, long userId, IDictionary? body, IExchange exchange, CancellationToken ct) { var method = GetString(body, "method") ?? "totp"; var username = GetString(body, "username") ?? ""; var destination = GetString(body, "destination"); var result = await mfaService.SetupAsync(userId, method, username, destination, ct); if (result.Extra is not null && result.Extra.TryGetValue("error", out var err) && err is string errStr) { var errCode = result.Extra.TryGetValue("error_code", out var code) && code is string c ? c : "invalid_request"; exchange.Out!.Body = Error(errCode, errStr); return; } exchange.Out!.Body = new MfaSetupResponse { Method = result.MethodId, SecretBase32 = result.SecretBase32, QrUri = result.QrUri, SetupToken = result.SetupToken, Extra = result.Extra }; } private static async Task Confirm( MfaService mfaService, long userId, IDictionary? body, IExchange exchange, CancellationToken ct) { var method = GetString(body, "method") ?? "totp"; var code = GetString(body, "code"); var setupToken = GetString(body, "setup_token"); var protectedState = GetString(body, "mfa_state"); if (string.IsNullOrEmpty(code)) { exchange.Out!.Body = Error("invalid_request", "Missing code"); return; } if (string.IsNullOrEmpty(setupToken)) { exchange.Out!.Body = Error("invalid_request", "Missing setup_token"); return; } Models.MfaState? state = null; if (!string.IsNullOrEmpty(protectedState)) state = mfaService.UnprotectState(protectedState); var recoveryCodes = await mfaService.ConfirmSetupAsync(userId, method, code, setupToken, state, ct); if (recoveryCodes is null) { exchange.Out!.Body = Error("invalid_code", "Invalid verification code"); return; } exchange.Out!.Body = new MfaConfirmedResponse { RecoveryCodes = recoveryCodes }; } private static async Task Disable( MfaService mfaService, long userId, IDictionary? body, IExchange exchange, CancellationToken ct) { var method = GetString(body, "method") ?? "totp"; await mfaService.DisableAsync(userId, method, ct); exchange.Out!.Body = new MfaDisabledResponse(); } private static async Task RegenerateRecovery( MfaService mfaService, long userId, IExchange exchange, CancellationToken ct) { var codes = await mfaService.RegenerateRecoveryCodesAsync(userId, ct); if (codes is null) { exchange.Out!.Body = Error("mfa_not_enabled", "MFA is not enabled for this user"); return; } exchange.Out!.Body = new MfaRecoveryCodesResponse { RecoveryCodes = codes }; } /// /// MFA backup-codes download UX: regenerates the recovery codes (atomically invalidates /// the previous set in the same way as regenerate-recovery) and returns the fresh /// codes as a text/plain attachment so the user can save the file. Recovery codes /// are stored only as salted hashes — there is no other moment they exist in plaintext /// on the server, so download is necessarily destructive (mirrors Google / GitHub / /// Auth0 behaviour: every "download backup codes" click invalidates the prior batch). /// private static async Task DownloadRecovery( MfaService mfaService, long userId, IExchange exchange, CancellationToken ct) { var codes = await mfaService.RegenerateRecoveryCodesAsync(userId, ct); if (codes is null) { exchange.Out!.Body = Error("mfa_not_enabled", "MFA is not enabled for this user"); return; } // Plain-text body: one code per line + a header banner identifying the issuer and // the timestamp so a downloaded file is self-describing if the user revisits it years // later. UTF-8 BOM not added — plain ASCII codes only, BOM would confuse some editors. var now = DateTimeOffset.UtcNow.ToString("yyyy-MM-dd HH:mm:ss 'UTC'"); var sb = new System.Text.StringBuilder(); sb.Append("# redb.Identity MFA recovery codes\r\n"); sb.Append("# Generated: ").Append(now).Append("\r\n"); sb.Append("# Each code may be used exactly once. Store this file in a secure location.\r\n"); sb.Append("# Downloading a new batch invalidates this one.\r\n"); sb.Append("\r\n"); foreach (var code in codes) sb.Append(code).Append("\r\n"); exchange.Out!.Body = System.Text.Encoding.UTF8.GetBytes(sb.ToString()); exchange.Out!.Headers["Content-Type"] = "text/plain; charset=utf-8"; exchange.Out!.Headers["redbHttp.ResponseContentType"] = "text/plain; charset=utf-8"; exchange.Out!.Headers["Content-Disposition"] = "attachment; filename=\"redb-recovery-codes.txt\""; // Disable any cache between client and server — the file contains plaintext // recovery secrets, never cache it anywhere. exchange.Out!.Headers["Cache-Control"] = "no-store, max-age=0"; exchange.Out!.Headers["Pragma"] = "no-cache"; } private static ErrorResponse Error(string error, string description) => new() { Error = error, ErrorDescription = description }; } Path: redb-identity/src/redb.Identity.Core/Routes/Processors/MePasswordProcessor.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/Routes/Processors/MePasswordProcessor.cs ---- using redb.Core; using redb.Identity.Contracts.Users; using redb.Identity.Core.Services; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.RedbCore.Extensions; using redb.Identity.Contracts.Routes; using redb.Identity.Contracts.Common; namespace redb.Identity.Core.Routes.Processors; /// /// H3 (v1.0 DoD §6): self-service password change backing PUT /me/password. /// Caller id is derived from the access-token subject — the request body is the /// old+new password pair, no Id field. Enforces the same password policy as /// and revokes ALL of the /// caller's sessions on success (OWASP Session Management C7). Returns /// invalid_password (400) when the old password does not match — no lockout /// of its own; per-IP login-failure rate-limit covers brute-force attempts upstream. /// internal sealed class MePasswordProcessor : IProcessor { private readonly IRouteContext _context; private readonly string? _redbName; public MePasswordProcessor(IRouteContext context, string? redbName = null) { _context = context; _redbName = redbName; } public async Task Process(IExchange exchange, CancellationToken ct = default) { var callerId = MeProcessorHelpers.TryGetCallerUserId(exchange); if (callerId is null) { MeProcessorHelpers.Reject(exchange, 401, "invalid_token", $"The access token does not carry a numeric subject claim required for self-service APIs (got subject={MeProcessorHelpers.GetRawCallerSubject(exchange) ?? ""})."); return; } var request = exchange.In.Body as MeChangePasswordRequest; if (request is null) { MeProcessorHelpers.Reject(exchange, 400, "validation_error", "Body must be a MeChangePasswordRequest."); return; } if (string.IsNullOrEmpty(request.OldPassword)) { MeProcessorHelpers.Reject(exchange, 400, "validation_error", "OldPassword is required"); return; } var err = await IdentityProcessorHelpers.ValidatePasswordPolicyAsync( exchange, _context, request.NewPassword, callerId.Value, "NewPassword", ct); if (err != null) { MeProcessorHelpers.Reject(exchange, 400, "validation_error", err); return; } if (request.OldPassword == request.NewPassword) { MeProcessorHelpers.Reject(exchange, 400, "validation_error", "NewPassword must differ from OldPassword"); return; } var redb = _context.GetRedbService(_redbName, exchange); var coreUser = await redb.UserProvider.GetUserByIdAsync(callerId.Value); if (coreUser is null) { MeProcessorHelpers.Reject(exchange, 404, "not_found", "User not found."); return; } bool changed; try { changed = await redb.UserProvider.ChangePasswordAsync( coreUser, request.OldPassword, request.NewPassword); } catch (UnauthorizedAccessException) { // The core UserProvider raises this for wrong-old-password instead of // returning false. Honour the documented processor contract (400 invalid_password) // so the rejection lands in the same shape regardless of which provider // (in-memory test fixture vs redb-pg) is in use. MeProcessorHelpers.Reject(exchange, 400, "invalid_password", "Old password is incorrect"); return; } if (!changed) { MeProcessorHelpers.Reject(exchange, 400, "invalid_password", "Old password is incorrect"); return; } // H10 — record the new password in history (post-success). await IdentityProcessorHelpers.RecordPasswordHistoryAsync( exchange, _context, redb, coreUser.Id, request.NewPassword, ct); // C7 (OWASP Session Management): invalidate every session authenticated with the // old password, including the caller's current session. User must re-auth. var sessionsRevoked = await new SessionService(redb).LogoutAsync(coreUser.Id, ct); exchange.Out ??= new Message(); exchange.Out.Body = new SuccessResponse { SessionsRevoked = sessionsRevoked }; exchange.Properties["identity-event-type"] = IdentityAuditEventIds.PasswordChanged; exchange.Properties["identity-event-data"] = new { Login = coreUser.Login, SessionsRevoked = sessionsRevoked, SelfService = true }; } } Path: redb-identity/src/redb.Identity.Core/Routes/Processors/MeProcessorHelpers.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/Routes/Processors/MeProcessorHelpers.cs ---- using redb.Core; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Core.Query; using redb.Identity.Contracts.Users; using redb.Identity.Core.Models; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Identity.Core.Routes.Processors; /// /// Shared helpers for self-service /me/* processors: extracts the caller user id /// from the bearer-auth context (populated upstream by /// ), loads the OIDC profile extension, and /// projects core user + OIDC props into the public DTO used /// by both admin and self-service endpoints. /// internal static class MeProcessorHelpers { /// /// Extracts the internal numeric caller id from the auth context populated by /// . The public sub claim is now a /// GUID, so the bigint _users._id is mirrored in the /// identity:management-user-id exchange property (sourced from the /// redb:user_id access-token claim). Returns null when the property is /// absent — e.g., client_credentials tokens or genuinely anonymous endpoints — so /// callers can decide whether to reject or treat as anonymous. /// public static long? TryGetCallerUserId(IExchange exchange) { if (!exchange.Properties.TryGetValue("identity:management-user-id", out var raw)) return null; return raw switch { long l when l > 0 => l, int i when i > 0 => i, string s when long.TryParse(s, out var id) && id > 0 => id, _ => null }; } /// /// Diagnostic accessor: returns the raw identity:management-subject value /// (or null if the property is not set). Used by /me/* processors to /// surface the actual subject in the rejection message so misconfigured hosts can /// be debugged without enabling trace logging. /// public static string? GetRawCallerSubject(IExchange exchange) => exchange.Properties.TryGetValue("identity:management-subject", out var raw) && raw is string s ? s : null; /// /// Halts the exchange with a structured error body and an HTTP-status hint. Mirrors /// MeSessionsProcessor.Reject so every /me/* processor reports failures /// identically — including the exchange.Stop() that ensures downstream /// processors on the same route do not execute. /// public static void Reject(IExchange exchange, int statusCode, string error, string description) { exchange.Out = new Message(new Dictionary { ["error"] = error, ["error_description"] = description }); exchange.Out.Headers["redbHttp.ResponseCode"] = statusCode; exchange.Exception = new InvalidOperationException(description); exchange.ExceptionHandled = true; exchange.Stop(); } /// Loads the OIDC extension linked via key=userId. public static Task?> LoadOidcProps(IRedbService redb, long userId) => redb.Query() .WhereRedb(o => o.Key == userId) .FirstOrDefaultAsync(); /// /// Projects a Core user + OIDC extension into the public /// DTO. Mirrors UserManagementProcessor.MapToResponse; both paths return the /// same wire shape so that admin and self-service clients can reuse a single model. /// public static UserResponse MapToResponse( IRedbUser user, UserProps? oidc, DateTimeOffset? createdAt, DateTimeOffset? modifiedAt) => new() { Id = user.Id, Login = user.Login, DisplayName = user.Name, Status = user.Enabled ? "active" : "blocked", Email = user.Email, EmailVerified = oidc?.EmailVerified ?? false, PhoneNumber = user.Phone, PhoneNumberVerified = oidc?.PhoneNumberVerified ?? false, GivenName = oidc?.GivenName, FamilyName = oidc?.FamilyName, MiddleName = oidc?.MiddleName, Nickname = oidc?.Nickname, PreferredUsername = oidc?.PreferredUsername ?? user.Login, Profile = oidc?.Profile, Picture = oidc?.Picture, Website = oidc?.Website, Gender = oidc?.Gender, Birthdate = oidc?.Birthdate, ZoneInfo = oidc?.ZoneInfo, Locale = oidc?.Locale, Address = oidc?.Address is { } addr ? new AddressDto { StreetAddress = addr.StreetAddress, Locality = addr.Locality, Region = addr.Region, PostalCode = addr.PostalCode, Country = addr.Country, Formatted = addr.Formatted } : null, CustomClaims = oidc?.CustomClaims, ExternalIdentities = oidc?.ExternalIdentities is { Count: > 0 } extIds ? extIds.ToDictionary( kvp => kvp.Key, kvp => new ExternalIdentityDto { Sub = kvp.Value.Sub, LinkedAt = kvp.Value.LinkedAt }) : null, CreatedAt = createdAt ?? user.DateRegister, ModifiedAt = modifiedAt ?? user.DateRegister }; } Path: redb-identity/src/redb.Identity.Core/Routes/Processors/MeProfileProcessor.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/Routes/Processors/MeProfileProcessor.cs ---- using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using redb.Core; using redb.Core.Models.Entities; using redb.Identity.Contracts.Users; using redb.Identity.Core.Configuration; using redb.Identity.Core.Models; using redb.Identity.Core.Module; using redb.Identity.Core.Services; using redb.Core.Services; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.RedbCore.Extensions; using CoreUpdateUserRequest = redb.Core.Models.Users.UpdateUserRequest; using redb.Identity.Contracts.Routes; using redb.Identity.Contracts.Common; namespace redb.Identity.Core.Routes.Processors; /// /// H3 (v1.0 DoD §6): self-service profile endpoint backing GET /me and /// PUT /me. Caller identity is derived from the authenticated access-token /// subject (identity:management-subject) — the request body has no Id /// field and admin-only properties (Status, EmailVerified, /// PhoneNumberVerified) are intentionally absent from /// . Users cannot grant themselves verified flags /// or flip their own account status; those changes remain admin-only via /// . /// internal sealed class MeProfileProcessor : IProcessor { private readonly IRouteContext _context; private readonly string? _redbName; public MeProfileProcessor(IRouteContext context, string? redbName = null) { _context = context; _redbName = redbName; } public async Task Process(IExchange exchange, CancellationToken ct = default) { var callerId = MeProcessorHelpers.TryGetCallerUserId(exchange); if (callerId is null) { MeProcessorHelpers.Reject(exchange, 401, "invalid_token", $"The access token does not carry a numeric subject claim required for self-service APIs (got subject={MeProcessorHelpers.GetRawCallerSubject(exchange) ?? ""})."); return; } var operation = exchange.In.GetHeader("operation") ?? throw new InvalidOperationException("Missing 'operation' header"); var redb = _context.GetRedbService(_redbName, exchange); switch (operation) { case "read": await Read(redb, exchange, callerId.Value); break; case "update": await Update(redb, exchange, callerId.Value); break; case "delete": await Delete(redb, exchange, callerId.Value, ct); break; default: MeProcessorHelpers.Reject(exchange, 400, "invalid_operation", $"Unknown operation: {operation}"); break; } } /// /// Self-service account deletion. Follows the exact same cascade as the admin /// .Delete path: revoke all sessions (kills /// OpenIddict authorizations and the access/refresh tokens linked to them), /// soft-delete the _users row (login STAYS as-is — immutable per the /// protect_system_users trigger; name is tombstoned), then soft-delete the /// OIDC props object via so it disappears /// from queries. Re-registration with the same login is blocked while the /// soft-deleted row exists. /// private async Task Delete(IRedbService redb, IExchange exchange, long callerId, CancellationToken ct) { var coreUser = await redb.UserProvider.GetUserByIdAsync(callerId); if (coreUser is null) { // Token said the subject existed but the underlying row is gone — treat as // already-deleted (idempotent self-service). Don't surface as 404 because // the caller's view of "deleted" already matches. exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new SuccessResponse { AlreadyAbsent = true }; return; } var sessionsRevoked = await new redb.Identity.Core.Services.SessionService(redb).LogoutAsync(coreUser.Id, ct); await redb.UserProvider.DeleteUserAsync(coreUser); var oidcObj = await MeProcessorHelpers.LoadOidcProps(redb, callerId); if (oidcObj is not null) { var bg = _context.GetIdentityServiceOrDefault(exchange); await IdentityDeletionHelper.DeleteAsync(redb, bg, oidcObj.id); } exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new SuccessResponse { SessionsRevoked = sessionsRevoked }; exchange.Properties["identity-event-type"] = IdentityAuditEventIds.UserDeleted; exchange.Properties["identity-event-data"] = new { Id = callerId, SessionsRevoked = sessionsRevoked, SelfService = true }; } /// /// N4-6: returns true when RedbIdentityOptions.EmailVerification.AutoResetOnChange /// is set (default). Caller flips UserProps.EmailVerified back to false after /// any /me e-mail change so a stale-verified flag never vouches for a fresh address. /// private bool ShouldResetEmailVerifiedOnChange(IExchange exchange) { var opts = _context.GetIdentityServiceOrDefault>(exchange)?.Value; return opts?.EmailVerification.AutoResetOnChange ?? true; } /// /// N-4 (N4-7): returns true when RedbIdentityOptions.ChangeEmail.RejectSoftEmailChange /// is set. When enabled, /me/profile refuses any e-mail mutation so the only /// path to change an address is the strict verify-then-commit flow exposed by /// ChangeEmailRequestProcessor / ChangeEmailConfirmProcessor. /// private bool RejectSoftEmailChange(IExchange exchange) { var opts = _context.GetIdentityServiceOrDefault>(exchange)?.Value; return opts?.ChangeEmail.RejectSoftEmailChange ?? false; } private static async Task Read(IRedbService redb, IExchange exchange, long callerId) { var coreUser = await redb.UserProvider.GetUserByIdAsync(callerId); if (coreUser is null) { MeProcessorHelpers.Reject(exchange, 404, "not_found", "User not found."); return; } var oidcObj = await MeProcessorHelpers.LoadOidcProps(redb, callerId); exchange.Out ??= new Message(); exchange.Out.Body = MeProcessorHelpers.MapToResponse( coreUser, oidcObj?.Props, oidcObj?.DateCreate, oidcObj?.DateModify); } private async Task Update(IRedbService redb, IExchange exchange, long callerId) { var request = exchange.In.Body as MeUpdateProfileRequest; if (request is null) { MeProcessorHelpers.Reject(exchange, 400, "validation_error", "Body must be a MeUpdateProfileRequest."); return; } var coreUser = await redb.UserProvider.GetUserByIdAsync(callerId); if (coreUser is null) { MeProcessorHelpers.Reject(exchange, 404, "not_found", "User not found."); return; } // --- Update _users fields via Core (same validation rules as admin route) --- var coreUpdate = new CoreUpdateUserRequest(); bool coreChanged = false; bool emailChanged = false; if (request.DisplayName != null) { var err = IdentityProcessorHelpers.ValidateDisplayName(request.DisplayName, "DisplayName"); if (err != null) { MeProcessorHelpers.Reject(exchange, 400, "validation_error", err); return; } coreUpdate.Name = request.DisplayName; coreChanged = true; } if (request.Email != null) { var err = IdentityProcessorHelpers.ValidateEmail(request.Email); if (err != null) { MeProcessorHelpers.Reject(exchange, 400, "validation_error", err); return; } // N4-6: detect actual value change (case-insensitive) so we can clear the // OIDC EmailVerified flag below — a stale-verified flag must never vouch // for a freshly adopted address. emailChanged = !string.Equals(coreUser.Email, request.Email, StringComparison.OrdinalIgnoreCase); // N-4 (N4-7): when the host enables strict change-email, reject any soft // mutation of the e-mail through /me/profile so every address change flows // through the verify-then-commit pipeline (IChangeEmailTokenStore + // ChangeEmailConfirmProcessor) — otherwise an attacker who hijacks a session // could silently rebind the account to an inbox they own. if (emailChanged && RejectSoftEmailChange(exchange)) { MeProcessorHelpers.Reject(exchange, 400, "use_change_email_flow", "Direct e-mail change via /me/profile is disabled by host policy. Use /me/change-email/request to start the strict verification flow."); return; } coreUpdate.Email = request.Email; coreChanged = true; } if (request.PhoneNumber != null) { var err = IdentityProcessorHelpers.ValidatePhoneNumber(request.PhoneNumber); if (err != null) { MeProcessorHelpers.Reject(exchange, 400, "validation_error", err); return; } coreUpdate.Phone = request.PhoneNumber; coreChanged = true; } if (coreChanged) coreUser = await redb.UserProvider.UpdateUserAsync(coreUser, coreUpdate); // --- Update OIDC extension --- var oidcObj = await MeProcessorHelpers.LoadOidcProps(redb, callerId); bool oidcChanged = false; // N4-6: lazily materialize the OIDC row when we need to flip EmailVerified=false // on an e-mail change, even if the request carried no other OIDC fields. var resetEmailVerified = emailChanged && ShouldResetEmailVerifiedOnChange(exchange); if (oidcObj is null && (resetEmailVerified || request.GivenName != null || request.FamilyName != null || request.MiddleName != null || request.Nickname != null || request.PreferredUsername != null || request.Profile != null || request.Picture != null || request.Website != null || request.Gender != null || request.Birthdate != null || request.ZoneInfo != null || request.Locale != null || request.Address != null || request.CustomClaims is { Count: > 0 })) { oidcObj = new RedbObject(new UserProps { UserId = coreUser.Id }); oidcObj.name = coreUser.Login; oidcObj.key = coreUser.Id; oidcObj.value_guid = Guid.NewGuid(); } if (oidcObj is not null) { if (resetEmailVerified && oidcObj.Props.EmailVerified) { oidcObj.Props.EmailVerified = false; oidcChanged = true; } // OIDC Core §5.1 `profile` claims — the full set, so userinfo can return it. if (request.GivenName != null) { oidcObj.Props.GivenName = request.GivenName; oidcChanged = true; } if (request.FamilyName != null) { oidcObj.Props.FamilyName = request.FamilyName; oidcChanged = true; } if (request.MiddleName != null) { oidcObj.Props.MiddleName = request.MiddleName; oidcChanged = true; } if (request.Nickname != null) { oidcObj.Props.Nickname = request.Nickname; oidcChanged = true; } if (request.PreferredUsername != null) { oidcObj.Props.PreferredUsername = request.PreferredUsername; oidcChanged = true; } if (request.Profile != null) { oidcObj.Props.Profile = request.Profile; oidcChanged = true; } if (request.Picture != null) { oidcObj.Props.Picture = request.Picture; oidcChanged = true; } if (request.Website != null) { oidcObj.Props.Website = request.Website; oidcChanged = true; } if (request.Gender != null) { oidcObj.Props.Gender = request.Gender; oidcChanged = true; } if (request.Birthdate != null) { oidcObj.Props.Birthdate = request.Birthdate; oidcChanged = true; } if (request.ZoneInfo != null) { oidcObj.Props.ZoneInfo = request.ZoneInfo; oidcChanged = true; } if (request.Locale != null) { oidcObj.Props.Locale = request.Locale; oidcChanged = true; } if (request.Address != null) { oidcObj.Props.Address = new AddressClaim { StreetAddress = request.Address.StreetAddress, Locality = request.Address.Locality, Region = request.Address.Region, PostalCode = request.Address.PostalCode, Country = request.Address.Country, Formatted = request.Address.Formatted }; oidcChanged = true; } if (request.CustomClaims is { Count: > 0 }) { oidcObj.Props.CustomClaims ??= new Dictionary(); foreach (var (key, value) in request.CustomClaims) oidcObj.Props.CustomClaims[key] = value; oidcChanged = true; } if (oidcChanged) { // Backs the OIDC `updated_at` claim (userinfo, profile scope). oidcObj.Props.UpdatedAt = DateTimeOffset.UtcNow; await redb.SaveAsync(oidcObj); } } exchange.Out ??= new Message(); exchange.Out.Body = MeProcessorHelpers.MapToResponse( coreUser, oidcObj?.Props, oidcObj?.DateCreate, oidcObj?.DateModify); exchange.Properties["identity-event-type"] = IdentityAuditEventIds.UserUpdated; exchange.Properties["identity-event-data"] = new { UserId = coreUser.Id.ToString(), Login = coreUser.Login, SelfService = true }; } } Path: redb-identity/src/redb.Identity.Core/Routes/Processors/MeSessionsProcessor.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/Routes/Processors/MeSessionsProcessor.cs ---- using redb.Core.Models.Entities; using redb.Identity.Contracts.Common; using redb.Identity.Contracts.Sessions; using redb.Identity.Core.Models; using redb.Identity.Core.Services; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.RedbCore.Extensions; using redb.Identity.Contracts.Routes; namespace redb.Identity.Core.Routes.Processors; /// /// H3-SSO (v1.0 DoD §6 scoped-subset): self-service session endpoint. /// Caller targets only their own sessions — userId is derived from the /// authenticated token subject (identity:management-subject), never from the /// request body. Supports four operations: /// /// list — list caller's active sessions. /// revoke — revoke a single session by id; verifies the target /// session belongs to the caller before revoking. /// revoke-current — revoke the session the caller's access /// token was issued for. The session id is taken from the sid claim carried /// by the bearer token (surfaced as identity:management-sid); the request body /// is ignored. Returns 400 if the token has no sid claim (e.g. client_credentials /// grant or other non-session-backed tokens). /// revoke-others — revoke all of the caller's sessions except /// the one identified by the sid claim. If sid is absent, all sessions /// are revoked. Used by the account console "Sign out other devices" action. /// /// Unlike , this processor does NOT support /// admin-scoped revoke-all / logout for arbitrary users. /// /// Authorization. The upstream /// validates the Bearer token and populates identity:management-subject with /// the sub claim. This processor requires that property to be present and /// numerically parseable; otherwise it rejects with 401. For non-numeric subjects /// (e.g. UUID-issuing hosts) the self-service path is unavailable by design — /// callers must use the admin scope. /// /// /// Revoke ownership check. Before revoking a session we load it and verify /// that session.key == caller. A caller attempting to revoke another user's /// session receives 404 (not 403) to avoid leaking existence of other sessions. /// /// internal sealed class MeSessionsProcessor : IProcessor { private readonly IRouteContext _context; private readonly string? _redbName; public MeSessionsProcessor(IRouteContext context, string? redbName = null) { _context = context; _redbName = redbName; } public async Task Process(IExchange exchange, CancellationToken ct = default) { var callerId = TryGetCallerUserId(exchange); if (callerId is null) { Reject(exchange, 401, "invalid_token", $"The access token does not carry a numeric subject claim required for self-service session APIs (got subject={MeProcessorHelpers.GetRawCallerSubject(exchange) ?? ""})."); return; } var operation = exchange.In.GetHeader("operation") ?? throw new InvalidOperationException("Missing 'operation' header"); // Pre-validate revoke-current's sid precondition BEFORE touching IRouteContext, // so tokens without a session binding are rejected cheaply and the unit-test // surface stays free of redb-service wiring. // For revoke-others the sid is optional — if absent all sessions are revoked. long? currentSessionId = null; if (operation is "revoke-current" or "revoke-others") { currentSessionId = TryGetSessionId(exchange); if (currentSessionId is null && operation == "revoke-current") { Reject(exchange, 400, "sid_unavailable", "The access token has no session binding (sid claim). revoke-current is only available for tokens issued via the OIDC session flow."); return; } } var redb = _context.GetRedbService(_redbName!, exchange); var session = new SessionService(redb); switch (operation) { case "list": await List(session, exchange, callerId.Value, ct).ConfigureAwait(false); break; case "revoke": await Revoke(session, redb, exchange, callerId.Value, ct).ConfigureAwait(false); break; case "revoke-current": await RevokeIfOwned(session, redb, exchange, callerId.Value, currentSessionId!.Value, selfCurrent: true, ct).ConfigureAwait(false); break; case "revoke-others": await RevokeOthers(session, exchange, callerId.Value, currentSessionId, ct).ConfigureAwait(false); break; default: Reject(exchange, 400, "invalid_operation", $"Unknown operation: {operation}"); break; } } private static async Task List(SessionService session, IExchange exchange, long callerId, CancellationToken ct) { var sessions = await session.ListAsync(callerId, ct).ConfigureAwait(false); exchange.Out ??= new Message(); exchange.Out.Body = sessions.Select(s => new SessionResponse { SessionId = s.SessionId, UserId = s.UserId, ApplicationId = s.ApplicationObjectId, ClientId = s.ClientId, ApplicationName = s.ApplicationName, Status = s.Status, CreatedAt = s.CreatedAt, IpAddress = s.IpAddress, UserAgent = s.UserAgent, DeviceLabel = s.DeviceLabel }).ToList(); } private static async Task Revoke( SessionService session, redb.Core.IRedbService redb, IExchange exchange, long callerId, CancellationToken ct) { var dict = exchange.In.Body as Dictionary ?? throw new InvalidOperationException("Body is required"); var sessionId = IdentityProcessorHelpers.ExtractLong(dict, "sessionId") ?? throw new InvalidOperationException("sessionId is required"); await RevokeIfOwned(session, redb, exchange, callerId, sessionId, selfCurrent: false, ct).ConfigureAwait(false); } /// /// Revokes all of the caller's sessions except . /// When is null (token has no sid /// claim) all sessions are revoked. /// private static async Task RevokeOthers( SessionService session, IExchange exchange, long callerId, long? exceptSessionId, CancellationToken ct) { var sessions = await session.ListAsync(callerId, ct).ConfigureAwait(false); var revoked = 0; foreach (var s in sessions) { if (exceptSessionId is not null && s.SessionId == exceptSessionId.Value) continue; revoked += await session.RevokeAsync(s.SessionId, ct).ConfigureAwait(false); } exchange.Out ??= new Message(); exchange.Out.Body = new SuccessResponse { Revoked = revoked }; exchange.Properties["identity-event-type"] = IdentityAuditEventIds.SessionRevoked; exchange.Properties["identity-event-data"] = new { SelfService = true, SelfCurrent = false, Count = revoked }; } /// /// Extracts the session id from the sid claim surfaced by /// . Returns null when the /// claim is absent (e.g. client_credentials grant) or not a positive integer. /// private static long? TryGetSessionId(IExchange exchange) { if (!exchange.Properties.TryGetValue("identity:management-sid", out var raw) || raw is not string sidStr || string.IsNullOrEmpty(sidStr)) { return null; } return long.TryParse(sidStr, out var id) && id > 0 ? id : null; } private static async Task RevokeIfOwned( SessionService session, redb.Core.IRedbService redb, IExchange exchange, long callerId, long sessionId, bool selfCurrent, CancellationToken ct) { // Ownership check: load the session and verify it belongs to the caller. // 404 (not 403) on mismatch/not-found — callers must not learn about other // users' sessions by probing IDs. var target = await redb.LoadAsync(sessionId).ConfigureAwait(false); if (target is null || target.key != callerId) { Reject(exchange, 404, "not_found", "Session not found."); return; } var revoked = await session.RevokeAsync(sessionId, ct).ConfigureAwait(false); exchange.Out ??= new Message(); exchange.Out.Body = new SuccessResponse { Revoked = revoked }; // Emit audit event via the existing WireTap on the route. exchange.Properties["identity-event-type"] = IdentityAuditEventIds.SessionRevoked; exchange.Properties["identity-event-data"] = new { SessionId = sessionId, SelfService = true, SelfCurrent = selfCurrent }; } /// /// Extracts the internal numeric caller id from identity:management-user-id /// (mirrored from the redb:user_id access-token claim by /// ; the public sub is now a GUID). /// private static long? TryGetCallerUserId(IExchange exchange) { if (!exchange.Properties.TryGetValue("identity:management-user-id", out var raw)) return null; return raw switch { long l when l > 0 => l, int i when i > 0 => i, string s when long.TryParse(s, out var id) && id > 0 => id, _ => null }; } private static void Reject(IExchange exchange, int statusCode, string error, string description) { exchange.Out = new Message(new ErrorResponse { Error = error, ErrorDescription = description }); exchange.Out.Headers["redbHttp.ResponseCode"] = statusCode; exchange.Exception = new InvalidOperationException(description); exchange.ExceptionHandled = true; exchange.Stop(); } } Path: redb-identity/src/redb.Identity.Core/Routes/Processors/MeWebAuthnProcessor.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/Routes/Processors/MeWebAuthnProcessor.cs ---- using System.Text.Json; using Fido2NetLib; using Microsoft.Extensions.DependencyInjection; using redb.Core; using redb.Identity.Contracts.Common; using redb.Identity.Contracts.Mfa; using redb.Identity.Contracts.Routes; using redb.Identity.Core.Services; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Identity.Core.Routes.Processors; /// /// MFA-3: self-service WebAuthn management backing /me/webauthn/*. Operations: /// /// status \u2014 list whether WebAuthn is enabled (any registered credentials). /// register-begin \u2014 issue CredentialCreateOptions + setup_token. /// register-complete \u2014 verify attestation, persist credential, return recovery codes (first method only). /// credentials \u2014 list all credentials of the caller. /// credential-rename \u2014 change the friendly label. /// credential-delete \u2014 remove a credential by key. /// /// /// Caller user id is always derived from identity:management-subject \u2014 never from /// the request body \u2014 mirroring . /// /// internal sealed class MeWebAuthnProcessor : IProcessor { private readonly IServiceProvider _sp; private static readonly JsonSerializerOptions s_json = new() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase, DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull, }; public MeWebAuthnProcessor(IServiceProvider sp) => _sp = sp; public async Task Process(IExchange exchange, CancellationToken ct = default) { var callerId = MeProcessorHelpers.TryGetCallerUserId(exchange); if (callerId is null) { MeProcessorHelpers.Reject(exchange, 401, "invalid_token", $"The access token does not carry a numeric subject claim required for self-service APIs (got subject={MeProcessorHelpers.GetRawCallerSubject(exchange) ?? ""})."); return; } var operation = exchange.In.GetHeader("operation") ?? throw new InvalidOperationException("Missing 'operation' header"); exchange.Out = new Message(); using var scope = _sp.CreateScope(); var mfa = scope.ServiceProvider.GetRequiredService(); var redb = scope.ServiceProvider.GetRequiredService(); var body = exchange.In.Body as IDictionary; switch (operation) { case "status": await Status(mfa, callerId.Value, exchange, ct); break; case "register-begin": await RegisterBegin(mfa, redb, callerId.Value, body, exchange, ct); break; case "register-complete": await RegisterComplete(mfa, redb, callerId.Value, body, exchange, ct); break; case "credentials": await ListCredentials(mfa, callerId.Value, exchange, ct); break; case "credential-rename": await Rename(mfa, callerId.Value, body, exchange, ct); break; case "credential-delete": await Delete(mfa, callerId.Value, body, exchange, ct); break; default: exchange.Out.Body = Error("invalid_operation", $"Unknown WebAuthn operation: {operation}"); break; } // The generic self-service event only when the operation recorded none of its own: register-complete and // credential-delete write MfaWebAuthnRegistered / MfaWebAuthnRevoked, which must reach the audit as they are. if (exchange.Out!.Body is not ErrorResponse && !exchange.Properties.ContainsKey("identity-event-type")) { exchange.Properties["identity-event-type"] = $"MfaSelfService:webauthn:{operation}"; exchange.Properties["identity-event-data"] = new { UserId = callerId.Value, Operation = operation }; } } private static async Task Status(MfaService mfa, long userId, IExchange exchange, CancellationToken ct) { var creds = await mfa.ListWebAuthnCredentialsAsync(userId, ct); exchange.Out!.Body = new WebAuthnStatusResponse { Enabled = creds.Count > 0, CredentialsCount = creds.Count }; } private static async Task RegisterBegin( MfaService mfa, IRedbService redb, long userId, IDictionary? body, IExchange exchange, CancellationToken ct) { var username = GetString(body, "username") ?? ""; var displayName = GetString(body, "display_name") ?? username; // Forward to the orchestrator. The challenge + serialized options are bound into the // returned setup_token and round-tripped to the client opaque-style. var (options, setupToken) = await mfa.BeginWebAuthnRegistrationAsync(userId, username, displayName, ct); exchange.Out!.Body = new WebAuthnRegistrationOptionsResponse { Options = JsonSerializer.SerializeToElement(options, s_json), SetupToken = setupToken, }; } private static async Task RegisterComplete( MfaService mfa, IRedbService redb, long userId, IDictionary? body, IExchange exchange, CancellationToken ct) { var setupToken = GetString(body, "setup_token"); var attestationRaw = body is not null && body.TryGetValue("attestation", out var att) ? att : null; var displayName = GetString(body, "display_name"); if (string.IsNullOrEmpty(setupToken) || attestationRaw is null) { exchange.Out!.Body = Error("invalid_request", "Missing setup_token or attestation"); return; } AuthenticatorAttestationRawResponse? attestation; try { var json = JsonSerializer.Serialize(attestationRaw, s_json); attestation = JsonSerializer.Deserialize(json, s_json); } catch (JsonException ex) { exchange.Out!.Body = Error("invalid_request", $"Malformed attestation: {ex.Message}"); return; } if (attestation is null) { exchange.Out!.Body = Error("invalid_request", "attestation could not be parsed"); return; } // Atomic complete: SELECT ... FOR UPDATE on user's MFA props row, then run the full // verification + persistence inside the same TX. Mirrors MfaVerifyProcessor. var mfaObjId = await mfa.GetMfaObjectIdAsync(userId, ct); (bool ok, string[]? recovery, string? key, string? error) result; await using (var tx = await redb.Context.BeginTransactionAsync()) { if (mfaObjId != 0) await redb.LockForUpdateAsync(mfaObjId); result = await mfa.CompleteWebAuthnRegistrationAsync( userId, attestation, setupToken!, displayName, ct); await tx.CommitAsync(); } if (!result.ok) { exchange.Out!.Body = Error(result.error ?? "register_failed", "WebAuthn registration failed"); return; } exchange.Out!.Body = new WebAuthnRegisteredResponse { CredentialKey = result.key!, RecoveryCodes = result.recovery ?? Array.Empty(), }; exchange.Properties["identity-event-type"] = IdentityAuditEventIds.MfaWebAuthnRegistered; exchange.Properties["identity-event-data"] = new { UserId = userId, CredentialKey = result.key, }; } private static async Task ListCredentials(MfaService mfa, long userId, IExchange exchange, CancellationToken ct) { var creds = await mfa.ListWebAuthnCredentialsAsync(userId, ct); exchange.Out!.Body = new WebAuthnCredentialList { Credentials = creds.Select(c => new WebAuthnCredentialResponse { Key = c.Key, DisplayName = c.DisplayName, Aaguid = c.Aaguid, RegisteredAt = c.RegisteredAt, LastUsedAt = c.LastUsedAt, UserVerified = c.UserVerified, BackupEligible = c.BackupEligible, BackupState = c.BackupState, }).ToList(), }; } private static async Task Rename(MfaService mfa, long userId, IDictionary? body, IExchange exchange, CancellationToken ct) { var key = GetString(body, "key") ?? GetString(body, "credential_key"); var name = GetString(body, "display_name"); if (string.IsNullOrEmpty(key)) { exchange.Out!.Body = Error("invalid_request", "Missing key"); return; } var ok = await mfa.RenameWebAuthnCredentialAsync(userId, key!, name, ct); if (!ok) { exchange.Out!.Body = Error("not_found", "Credential not found"); return; } exchange.Out!.Body = new WebAuthnRenamedResponse(); } private static async Task Delete(MfaService mfa, long userId, IDictionary? body, IExchange exchange, CancellationToken ct) { var key = GetString(body, "key") ?? GetString(body, "credential_key"); if (string.IsNullOrEmpty(key)) { exchange.Out!.Body = Error("invalid_request", "Missing key"); return; } var ok = await mfa.DeleteWebAuthnCredentialAsync(userId, key!, ct); if (!ok) { exchange.Out!.Body = Error("not_found", "Credential not found"); return; } exchange.Out!.Body = new WebAuthnDeletedResponse(); exchange.Properties["identity-event-type"] = IdentityAuditEventIds.MfaWebAuthnRevoked; exchange.Properties["identity-event-data"] = new { UserId = userId, CredentialKey = key, }; } private static string? GetString(IDictionary? body, string key) => body is not null && body.TryGetValue(key, out var v) ? v?.ToString() : null; private static ErrorResponse Error(string error, string description) => new() { Error = error, ErrorDescription = description }; } Path: redb-identity/src/redb.Identity.Core/Routes/Processors/MfaChallengeProcessor.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/Routes/Processors/MfaChallengeProcessor.cs ---- using Microsoft.Extensions.DependencyInjection; using redb.Identity.Core.Services; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Identity.Core.Routes.Processors; /// /// Core route processor for MFA challenge dispatch (SMS/Email). /// Accepts encrypted mfa_state + method ("sms" or "email"), /// generates a fresh OTP code, sends it via the registered , /// and returns a NEW encrypted state with the OTP embedded for the verify step. /// internal sealed class MfaChallengeProcessor : IProcessor { private readonly IServiceProvider _sp; public MfaChallengeProcessor(IServiceProvider sp) => _sp = sp; public async Task Process(IExchange exchange, CancellationToken ct = default) { var body = exchange.In.Body as IDictionary; var mfaStateToken = body?.TryGetValue("mfa_state", out var s) == true ? s?.ToString() : null; var method = body?.TryGetValue("method", out var m) == true ? m?.ToString() : null; exchange.Out = new Message(); if (string.IsNullOrEmpty(mfaStateToken) || string.IsNullOrEmpty(method)) { exchange.Out.Body = new Dictionary { ["success"] = false, ["error"] = "invalid_request", ["error_description"] = "Missing mfa_state or method" }; return; } using var scope = _sp.CreateScope(); var mfaService = scope.ServiceProvider.GetRequiredService(); var state = mfaService.UnprotectState(mfaStateToken); if (state is null) { exchange.Out.Body = new Dictionary { ["success"] = false, ["error"] = "invalid_grant", ["error_description"] = "MFA session expired or invalid" }; return; } var result = await mfaService.CreateChallengeAsync( state.UserId, state.Username ?? "", method, state.ReturnUrl, knownMethods: state.Methods, ct).ConfigureAwait(false); if (!result.Success) { var resp = new Dictionary { ["success"] = false, ["error"] = result.Error }; if (result.RetryAfterSeconds is { } retry) resp["retry_after"] = retry; exchange.Out.Body = resp; return; } exchange.Out.Body = new Dictionary { ["success"] = true, ["mfa_state"] = result.MfaState, ["masked_destination"] = result.MaskedDestination, ["method"] = result.Method }; } } Path: redb-identity/src/redb.Identity.Core/Routes/Processors/MfaListMethodsProcessor.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/Routes/Processors/MfaListMethodsProcessor.cs ---- using Microsoft.Extensions.DependencyInjection; using redb.Identity.Core.Services; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Identity.Core.Routes.Processors; /// /// B9 / BUG-9 — Auth0-style gated enumeration of the calling user's MFA methods. /// Accepts an encrypted mfa_state token (issued by ) /// and returns the methods embedded in that state. Possession of a valid state proves /// the caller has already passed first-factor authentication and is therefore allowed /// to discover which factors are configured for the account. /// /// On invalid / expired state returns {"success":false,"error":"invalid_grant"} /// without distinguishing «no such session» from «session expired». /// /// internal sealed class MfaListMethodsProcessor : IProcessor { private readonly IServiceProvider _sp; public MfaListMethodsProcessor(IServiceProvider sp) => _sp = sp; public Task Process(IExchange exchange, CancellationToken ct = default) { var body = exchange.In.Body as IDictionary; var mfaStateToken = body?.TryGetValue("mfa_state", out var s) == true ? s?.ToString() : null; exchange.Out = new Message(); if (string.IsNullOrEmpty(mfaStateToken)) { exchange.Out.Body = new Dictionary { ["success"] = false, ["error"] = "invalid_request", ["error_description"] = "Missing mfa_state" }; return Task.CompletedTask; } using var scope = _sp.CreateScope(); var mfaService = scope.ServiceProvider.GetRequiredService(); var state = mfaService.UnprotectState(mfaStateToken); if (state is null || state.Methods is null) { exchange.Out.Body = new Dictionary { ["success"] = false, ["error"] = "invalid_grant", ["error_description"] = "MFA session expired or invalid" }; return Task.CompletedTask; } exchange.Out.Body = new Dictionary { ["success"] = true, ["methods"] = state.Methods }; return Task.CompletedTask; } } Path: redb-identity/src/redb.Identity.Core/Routes/Processors/MfaOtpCleanupProcessor.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/Routes/Processors/MfaOtpCleanupProcessor.cs ---- using Microsoft.Extensions.Options; using redb.Core; using redb.Core.Services; using redb.Identity.Core.Configuration; using redb.Identity.Core.Models; using redb.Identity.Core.Services; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.RedbCore.Extensions; using redb.Identity.Contracts.Routes; using redb.Identity.Contracts.Common; namespace redb.Identity.Core.Routes.Processors; /// /// B3: periodic cleanup of rows whose /// is in the past. Mirrors — uses /// claim-pattern soft delete when available, /// falls back to direct hard delete otherwise. /// /// Verify requests with expired rows already fail with Reason = "expired" inside /// PropsServerSideOtpStore.VerifyAndConsumeAsync, so the cleanup route is purely a /// storage-size hygiene measure — it does NOT guard against replay (single-use is enforced /// at verify time under LockForUpdate). /// /// internal sealed class MfaOtpCleanupProcessor : IProcessor { private readonly IRouteContext _context; private readonly string? _redbName; private readonly IBackgroundDeletionService? _backgroundDeletion; private readonly TimeProvider _timeProvider; public MfaOtpCleanupProcessor( IRouteContext context, string? redbName = null, IBackgroundDeletionService? backgroundDeletion = null, TimeProvider? timeProvider = null) { _context = context; _redbName = redbName; _backgroundDeletion = backgroundDeletion; _timeProvider = timeProvider ?? TimeProvider.System; } public async Task Process(IExchange exchange, CancellationToken ct = default) { var redb = _context.GetRedbService(_redbName, exchange); var now = _timeProvider.GetUtcNow(); const int batchSize = 500; var expiredIds = await redb.Query() .Where(o => o.ExpiresAt < now) .Take(batchSize) .Select(o => o.Id) .ToListAsync(); if (expiredIds.Count > 0) { await SoftDeleteAsync(redb, expiredIds); } exchange.Out ??= new Message(); exchange.Out.Body = new MfaOtpPruneResult { PrunedMfaOtp = expiredIds.Count }; exchange.Properties["identity-event-type"] = IdentityAuditEventIds.MfaOtpPruned; exchange.Properties["identity-event-data"] = new { RowCount = expiredIds.Count, Threshold = now }; } private Task SoftDeleteAsync(IRedbService redb, List ids) => IdentityDeletionHelper.DeleteAsync(redb, _backgroundDeletion, ids); } Path: redb-identity/src/redb.Identity.Core/Routes/Processors/MfaRecoveryProcessor.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/Routes/Processors/MfaRecoveryProcessor.cs ---- using Microsoft.Extensions.DependencyInjection; using redb.Core; using redb.Identity.Core.Services; using redb.Route.Abstractions; using redb.Route.Core; using redb.Identity.Contracts.Routes; namespace redb.Identity.Core.Routes.Processors; /// /// Core route processor for MFA recovery code verification. /// Accepts encrypted mfa_state + one-time recovery_code, /// verifies via , creates session. /// The recovery code is consumed (deleted) on success. /// internal sealed class MfaRecoveryProcessor : IProcessor { private readonly IServiceProvider _sp; public MfaRecoveryProcessor(IServiceProvider sp) => _sp = sp; public async Task Process(IExchange exchange, CancellationToken ct = default) { var body = exchange.In.Body as IDictionary; var mfaStateToken = body?.TryGetValue("mfa_state", out var s) == true ? s?.ToString() : null; var recoveryCode = body?.TryGetValue("recovery_code", out var c) == true ? c?.ToString() : null; exchange.Out = new Message(); if (string.IsNullOrEmpty(mfaStateToken) || string.IsNullOrEmpty(recoveryCode)) { exchange.Out.Body = new Dictionary { ["success"] = false, ["error"] = "invalid_request", ["error_description"] = "Missing mfa_state or recovery_code" }; return; } using var scope = _sp.CreateScope(); var timeProvider = scope.ServiceProvider.GetService() ?? TimeProvider.System; var mfaService = scope.ServiceProvider.GetRequiredService(); var metrics = scope.ServiceProvider.GetService(); var state = mfaService.UnprotectState(mfaStateToken); if (state is null) { exchange.Out.Body = new Dictionary { ["success"] = false, ["error"] = "invalid_grant", ["error_description"] = "MFA session expired or invalid" }; return; } // Atomic consume (B1-recovery): mirrors MfaVerifyProcessor — SELECT ... FOR UPDATE on // the MFA row, then verify+consume+persist under one tx. Without this, two concurrent // verifies of the same recovery code both read the same RecoveryCodes list, both find // the match, both call SaveAsync → last write wins and a single code is "used" twice. // The IRedbService resolved here is the same scoped instance used by mfaService, so // the lock and the internal SaveAsync share connection/transaction. var redb = scope.ServiceProvider.GetRequiredService(); var mfaObjId = await mfaService.GetMfaObjectIdAsync(state.UserId, ct).ConfigureAwait(false); bool verified; await using (var tx = await redb.Context.BeginTransactionAsync().ConfigureAwait(false)) { if (mfaObjId != 0) await redb.LockForUpdateAsync(mfaObjId).ConfigureAwait(false); verified = await mfaService.VerifyRecoveryCodeAsync(state.UserId, recoveryCode, ct).ConfigureAwait(false); await tx.CommitAsync().ConfigureAwait(false); } if (!verified) { metrics?.MfaVerifications.Add(1, new KeyValuePair("method", "recovery"), new KeyValuePair("result", "fail")); exchange.Out.Body = new Dictionary { ["success"] = false, ["error"] = "invalid_code", ["error_description"] = "Invalid recovery code", ["mfa_state"] = mfaStateToken }; return; } // Recovery code verified and consumed — create session long sessionId = 0; { var sessionService = new SessionService(redb, timeProvider); var uaParser = scope.ServiceProvider.GetService(); var device = DeviceMetadataExtractor.Extract(exchange, uaParser); var session = await sessionService.CreateAsync( state.UserId, applicationObjectId: 0, mfaVerified: true, mfaMethod: "recovery", ipAddress: device.IpAddress, userAgent: device.UserAgent, deviceLabel: device.DeviceLabel, ct: ct); sessionId = session.id; } metrics?.MfaVerifications.Add(1, new KeyValuePair("method", "recovery"), new KeyValuePair("result", "success")); exchange.Out.Body = new Dictionary { ["success"] = true, ["userId"] = state.UserId, ["username"] = state.Username, ["sessionId"] = sessionId, ["returnUrl"] = state.ReturnUrl }; exchange.Properties["identity-event-type"] = IdentityAuditEventIds.UserLoggedIn; exchange.Properties["identity-event-data"] = new { UserId = state.UserId, Username = state.Username, MfaMethod = "recovery", Timestamp = timeProvider.GetUtcNow() }; } } Path: redb-identity/src/redb.Identity.Core/Routes/Processors/MfaSetupProcessor.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/Routes/Processors/MfaSetupProcessor.cs ---- using System.Text.Json; using Microsoft.Extensions.DependencyInjection; using redb.Identity.Contracts.Common; using redb.Identity.Contracts.Mfa; using redb.Identity.Core.Services; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Identity.Core.Routes.Processors; /// /// Core route processor for MFA management operations (setup, confirm, disable, status, regenerate). /// Dispatches by operation header, same pattern as . /// internal sealed class MfaSetupProcessor : IProcessor { private readonly IServiceProvider _sp; public MfaSetupProcessor(IServiceProvider sp) => _sp = sp; public async Task Process(IExchange exchange, CancellationToken ct = default) { var operation = exchange.In.GetHeader("operation") ?? throw new InvalidOperationException("Missing 'operation' header"); exchange.Out = new Message(); using var scope = _sp.CreateScope(); var mfaService = scope.ServiceProvider.GetRequiredService(); var body = exchange.In.Body as IDictionary; switch (operation) { case "status": await Status(mfaService, body, exchange, ct); break; case "setup": await Setup(mfaService, body, exchange, ct); break; case "confirm": await Confirm(mfaService, body, exchange, ct); break; case "disable": await Disable(mfaService, body, exchange, ct); break; case "regenerate-recovery": await RegenerateRecovery(mfaService, body, exchange, ct); break; default: exchange.Out.Body = Error("invalid_operation", $"Unknown MFA operation: {operation}"); break; } } private static long GetUserId(IDictionary? body) { if (body is null) return 0; if (!body.TryGetValue("userId", out var v) || v is null) return 0; return v switch { long id => id, int intId => intId, double d => (long)d, decimal dec => (long)dec, JsonElement je when je.TryGetInt64(out var jid) => jid, string s when long.TryParse(s, out var parsed) => parsed, _ => 0 }; } private static string? GetString(IDictionary? body, string key) { if (body is null) return null; return body.TryGetValue(key, out var v) ? v?.ToString() : null; } private static async Task Status( MfaService mfaService, IDictionary? body, IExchange exchange, CancellationToken ct) { var userId = GetUserId(body); if (userId <= 0) { exchange.Out!.Body = Error("invalid_request", "Missing userId"); return; } var status = await mfaService.GetStatusAsync(userId, ct); exchange.Out!.Body = new MfaStatusResponse { Enabled = status.Enabled, Methods = status.Methods, RecoveryCodesRemaining = status.RecoveryCodesRemaining }; } private static async Task Setup( MfaService mfaService, IDictionary? body, IExchange exchange, CancellationToken ct) { var userId = GetUserId(body); var method = GetString(body, "method") ?? "totp"; var username = GetString(body, "username") ?? ""; var destination = GetString(body, "destination"); if (userId <= 0) { exchange.Out!.Body = Error("invalid_request", "Missing userId"); return; } var result = await mfaService.SetupAsync(userId, method, username, destination, ct); // Surface setup error from the method (e.g. invalid phone/email). if (result.Extra is not null && result.Extra.TryGetValue("error", out var err) && err is string errStr) { var errCode = result.Extra.TryGetValue("error_code", out var code) && code is string c ? c : "invalid_request"; exchange.Out!.Body = Error(errCode, errStr); return; } exchange.Out!.Body = new MfaSetupResponse { Method = result.MethodId, SecretBase32 = result.SecretBase32, QrUri = result.QrUri, // B5: opaque encrypted setup token; client MUST send it back in the confirm call. SetupToken = result.SetupToken, Extra = result.Extra }; } private static async Task Confirm( MfaService mfaService, IDictionary? body, IExchange exchange, CancellationToken ct) { var userId = GetUserId(body); var method = GetString(body, "method") ?? "totp"; var code = GetString(body, "code"); var setupToken = GetString(body, "setup_token"); var protectedState = GetString(body, "mfa_state"); if (userId <= 0 || string.IsNullOrEmpty(code)) { exchange.Out!.Body = Error("invalid_request", "Missing userId or code"); return; } if (string.IsNullOrEmpty(setupToken)) { exchange.Out!.Body = Error("invalid_request", "Missing setup_token"); return; } // For SMS/Email confirmation, the OTP code lives inside the encrypted state from CreateChallengeAsync. Models.MfaState? state = null; if (!string.IsNullOrEmpty(protectedState)) state = mfaService.UnprotectState(protectedState); var recoveryCodes = await mfaService.ConfirmSetupAsync(userId, method, code, setupToken, state, ct); if (recoveryCodes is null) { exchange.Out!.Body = Error("invalid_code", "Invalid verification code"); return; } exchange.Out!.Body = new MfaConfirmedResponse { RecoveryCodes = recoveryCodes }; } private static async Task Disable( MfaService mfaService, IDictionary? body, IExchange exchange, CancellationToken ct) { var userId = GetUserId(body); var method = GetString(body, "method") ?? "totp"; if (userId <= 0) { exchange.Out!.Body = Error("invalid_request", "Missing userId"); return; } await mfaService.DisableAsync(userId, method, ct); exchange.Out!.Body = new MfaDisabledResponse(); } private static async Task RegenerateRecovery( MfaService mfaService, IDictionary? body, IExchange exchange, CancellationToken ct) { var userId = GetUserId(body); if (userId <= 0) { exchange.Out!.Body = Error("invalid_request", "Missing userId"); return; } var codes = await mfaService.RegenerateRecoveryCodesAsync(userId, ct); if (codes is null) { exchange.Out!.Body = Error("mfa_not_enabled", "MFA is not enabled for this user"); return; } exchange.Out!.Body = new MfaRecoveryCodesResponse { RecoveryCodes = codes }; } private static ErrorResponse Error(string error, string description) => new() { Error = error, ErrorDescription = description }; } Path: redb-identity/src/redb.Identity.Core/Routes/Processors/MfaVerifyProcessor.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/Routes/Processors/MfaVerifyProcessor.cs ---- using Microsoft.Extensions.DependencyInjection; using redb.Core; using redb.Identity.Core.Services; using redb.Route.Abstractions; using redb.Route.Core; using redb.Identity.Contracts.Routes; namespace redb.Identity.Core.Routes.Processors; /// /// Core route processor for MFA TOTP verification. /// Accepts encrypted mfa_state + TOTP code, /// verifies via , creates session with mfaVerified=true. /// internal sealed class MfaVerifyProcessor : IProcessor { private readonly IServiceProvider _sp; public MfaVerifyProcessor(IServiceProvider sp) => _sp = sp; public async Task Process(IExchange exchange, CancellationToken ct = default) { var body = exchange.In.Body as IDictionary; var mfaStateToken = body?.TryGetValue("mfa_state", out var s) == true ? s?.ToString() : null; var code = body?.TryGetValue("code", out var c) == true ? c?.ToString() : null; exchange.Out = new Message(); if (string.IsNullOrEmpty(mfaStateToken) || string.IsNullOrEmpty(code)) { exchange.Out.Body = new Dictionary { ["success"] = false, ["error"] = "invalid_request", ["error_description"] = "Missing mfa_state or code" }; return; } using var scope = _sp.CreateScope(); var timeProvider = scope.ServiceProvider.GetService() ?? TimeProvider.System; var mfaService = scope.ServiceProvider.GetRequiredService(); var metrics = scope.ServiceProvider.GetService(); // Decrypt and validate MFA state (includes TTL check) var state = mfaService.UnprotectState(mfaStateToken); if (state is null) { exchange.Out.Body = new Dictionary { ["success"] = false, ["error"] = "invalid_grant", ["error_description"] = "MFA session expired or invalid" }; return; } // Dispatch by method: SMS/Email use the OTP code embedded in state; TOTP verifies against stored secret. var methodId = string.IsNullOrEmpty(state.OtpMethod) ? "totp" : state.OtpMethod!; // Atomic verify (B1): // SELECT ... FOR UPDATE on the MFA row, then verify + persist FailedAttempts/Lockout under // the same transaction. Serializes concurrent verify attempts for the same user → prevents // lost-update of FailedAttempts and bypass of the lockout threshold. // The IRedbService used by mfaService is the same scoped instance resolved here, so // the lock and any SaveAsync inside VerifyAsync share the same connection/transaction. var redb = scope.ServiceProvider.GetRequiredService(); var mfaObjId = await mfaService.GetMfaObjectIdAsync(state.UserId, ct).ConfigureAwait(false); bool verified; await using (var tx = await redb.Context.BeginTransactionAsync().ConfigureAwait(false)) { if (mfaObjId != 0) await redb.LockForUpdateAsync(mfaObjId).ConfigureAwait(false); verified = await mfaService.VerifyAsync(state.UserId, methodId, code, state, ct).ConfigureAwait(false); // Commit either way: success path persists LastVerifiedAt; failure path persists // FailedAttempts++ / LockedUntil. Throwing exceptions still rollback via dispose. await tx.CommitAsync().ConfigureAwait(false); } if (!verified) { metrics?.MfaVerifications.Add(1, new KeyValuePair("method", methodId), new KeyValuePair("result", "fail")); // Re-encrypt state so the user can retry (state is still valid within TTL) exchange.Out.Body = new Dictionary { ["success"] = false, ["error"] = "invalid_code", ["error_description"] = "Invalid or expired verification code", ["mfa_state"] = mfaStateToken }; return; } // MFA passed — create session long sessionId = 0; var sessionService = new SessionService(redb, timeProvider); var uaParser = scope.ServiceProvider.GetService(); var device = DeviceMetadataExtractor.Extract(exchange, uaParser); var session = await sessionService.CreateAsync( state.UserId, applicationObjectId: 0, mfaVerified: true, mfaMethod: methodId, ipAddress: device.IpAddress, userAgent: device.UserAgent, deviceLabel: device.DeviceLabel, ct: ct); sessionId = session.id; metrics?.MfaVerifications.Add(1, new KeyValuePair("method", methodId), new KeyValuePair("result", "success")); exchange.Out.Body = new Dictionary { ["success"] = true, ["userId"] = state.UserId, ["username"] = state.Username, ["sessionId"] = sessionId, ["returnUrl"] = state.ReturnUrl }; exchange.Properties["identity-event-type"] = IdentityAuditEventIds.UserLoggedIn; exchange.Properties["identity-event-data"] = new { UserId = state.UserId, Username = state.Username, MfaMethod = methodId, Timestamp = timeProvider.GetUtcNow() }; } } Path: redb-identity/src/redb.Identity.Core/Routes/Processors/OneTimeSecrets.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/Routes/Processors/OneTimeSecrets.cs ---- using System.Collections; using System.Collections.Concurrent; using System.Reflection; using redb.Identity.Contracts.Common; namespace redb.Identity.Core.Routes.Processors; /// /// Tells whether a result carries a one-time secret: a member marked /// that is set, on the result itself or on a result type of redb.Identity.Contracts it holds, directly or in a /// collection. The idempotency capture keeps such an answer out of its cache. The declaration is the marker on /// the type; no route or operation is named here. /// internal static class OneTimeSecrets { private const int MaxDepth = 8; private static readonly Assembly ContractsAssembly = typeof(OneTimeSecretAttribute).Assembly; private static readonly ConcurrentDictionary Members = new(); private readonly record struct Member(PropertyInfo Property, bool Secret); /// true when holds a set member marked as a one-time secret. public static bool Carries(object? result) => CarriesAt(result, 0); private static bool CarriesAt(object? value, int depth) { if (value is null || depth > MaxDepth) return false; if (value is string) return false; if (value is IEnumerable items) { foreach (var item in items) if (CarriesAt(item, depth + 1)) return true; return false; } var type = value.GetType(); if (type.Assembly != ContractsAssembly) return false; foreach (var member in Members.GetOrAdd(type, Describe)) { var memberValue = member.Property.GetValue(value); if (member.Secret ? IsSet(memberValue) : CarriesAt(memberValue, depth + 1)) return true; } return false; } private static bool IsSet(object? value) => value switch { null => false, string s => s.Length > 0, IEnumerable items => items.GetEnumerator().MoveNext(), _ => true, }; private static Member[] Describe(Type type) => type .GetProperties(BindingFlags.Public | BindingFlags.Instance) .Where(p => p.CanRead && p.GetIndexParameters().Length == 0) .Select(p => new Member(p, p.IsDefined(typeof(OneTimeSecretAttribute), inherit: true))) .Where(m => m.Secret || MayHoldResults(m.Property.PropertyType)) .ToArray(); // A member is looked into when its type is a Contracts type or a collection or an object that may hold one. private static bool MayHoldResults(Type type) => type != typeof(string) && !type.IsPrimitive && !type.IsEnum && (type.Assembly == ContractsAssembly || type == typeof(object) || typeof(IEnumerable).IsAssignableFrom(type) || (type.IsGenericType && type.GetGenericArguments().Any(a => a.Assembly == ContractsAssembly))); } Path: redb-identity/src/redb.Identity.Core/Routes/Processors/OutboxCleanupProcessor.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/Routes/Processors/OutboxCleanupProcessor.cs ---- using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Core; using redb.Core.Query; using redb.Identity.Core.Configuration; using redb.Identity.Core.Events; using redb.Route.Abstractions; namespace redb.Identity.Core.Routes.Processors; /// /// Deletes finished outbox rows past their retention (, /// ) in batches of . /// Runs on a timer route marked .Cluster(true). A pending row is never deleted, however old. /// internal sealed class OutboxCleanupProcessor : IProcessor { // A run stops after this many batches; what is left goes at the next run. private const int MaxBatchesPerRun = 100; private readonly IServiceProvider _sp; private readonly DeliveryOptions _options; private readonly ILogger _logger; public OutboxCleanupProcessor(IServiceProvider sp, DeliveryOptions options, ILogger logger) { _sp = sp; _options = options; _logger = logger; } public Task Process(IExchange exchange, CancellationToken ct = default) => RunAsync(ct); /// One cleanup run; returns the number of rows deleted. internal async Task RunAsync(CancellationToken ct = default) { var batch = Math.Max(1, _options.CleanupBatchSize); var total = 0; try { for (var i = 0; i < MaxBatchesPerRun; i++) { await using var scope = _sp.CreateAsyncScope(); var store = new IdentityEventStore( scope.ServiceProvider.GetRequiredService(), scope.ServiceProvider.GetRequiredService()); var deleted = await store.CleanupAsync(_options.DeliveredRetention, _options.FailedRetention, batch, ct) .ConfigureAwait(false); total += deleted; if (deleted < batch) break; } } catch (Exception ex) when (ex is not OperationCanceledException) { _logger.LogWarning(ex, "Outbox cleanup stopped after {Deleted} row(s); it continues at the next run.", total); } if (total > 0) _logger.LogInformation("Outbox cleanup deleted {Deleted} finished row(s).", total); return total; } } Path: redb-identity/src/redb.Identity.Core/Routes/Processors/PasswordForgotProcessor.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/Routes/Processors/PasswordForgotProcessor.cs ---- using System; using System.Collections.Generic; using System.Security.Cryptography; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using redb.Core; using redb.Core.Models.Users; using redb.Core.Query; using redb.Identity.Contracts.Routes; using redb.Identity.Contracts.Users; using redb.Identity.Core.Configuration; using redb.Identity.Core.Models; using redb.Identity.Core.PasswordReset; using redb.Identity.Core.Services; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.RedbCore.Extensions; using redb.Identity.Contracts.Common; namespace redb.Identity.Core.Routes.Processors; /// /// N-4 (Session C): anonymous password-recovery initiation backing /// direct-vm://identity-password-forgot. /// /// Strict anti-enumeration contract: always writes a 200/success response and /// emits a audit event, even /// when the e-mail does not resolve to a user, the client is unknown, or the /// callerResetUrl is not on the per-client ApplicationProps.PasswordResetUris /// whitelist. Only when all three gates pass does the processor issue a single-use reset /// token via and dispatch the e-mail /// through (audit event /// ). /// /// internal sealed class PasswordForgotProcessor : IProcessor { private readonly IRouteContext _context; private readonly IServiceProvider _sp; private readonly string? _redbName; public PasswordForgotProcessor(IRouteContext context, IServiceProvider sp, string? redbName = null) { _context = context; _sp = sp; _redbName = redbName; } public async Task Process(IExchange exchange, CancellationToken ct = default) { var request = exchange.In.Body as PasswordForgotRequest; if (request is null || string.IsNullOrWhiteSpace(request.Email) || string.IsNullOrWhiteSpace(request.ClientId) || string.IsNullOrWhiteSpace(request.CallerResetUrl)) { // Hard validation error — body shape is not a legitimate user submission. // This branch is NOT covered by anti-enumeration: malformed bodies must be // visible to API callers / SDKs. Reject(exchange, 400, "validation_error", "Email, ClientId and CallerResetUrl are required."); return; } // Always respond success — set up before any branching so silent-drop paths still // emit the standard envelope. exchange.Out ??= new Message(); exchange.Out.Body = new PasswordForgotResponse { Success = true }; // Always emit the "requested" audit event so abuse telemetry can trace volume per // IP / email even when the request is silently dropped. exchange.Properties["identity-event-type"] = IdentityAuditEventIds.PasswordResetRequested; exchange.Properties["identity-event-data"] = new { EmailHash = HashEmailForAudit(request.Email), ClientId = request.ClientId, CallerResetUrl = request.CallerResetUrl }; var redb = _context.GetRedbService(_redbName, exchange); var logger = _sp.GetService()?.CreateLogger("PasswordForgotProcessor"); // ── Gate 1: client + whitelist check (per C.6 / variant A) ──────────────── var app = await redb.GetByUniqueAsync(p => p.ClientId, request.ClientId) .ConfigureAwait(false); if (app is null) { logger?.LogInformation("Password-forgot silently dropped: unknown client_id"); return; } var whitelist = app.Props.PasswordResetUris; if (whitelist is null || whitelist.Length == 0) { logger?.LogInformation( "Password-forgot silently dropped: client {ClientId} has no PasswordResetUris configured (feature disabled)", request.ClientId); return; } var allowed = false; for (var i = 0; i < whitelist.Length; i++) { if (string.Equals(whitelist[i], request.CallerResetUrl, StringComparison.Ordinal)) { allowed = true; break; } } if (!allowed) { logger?.LogWarning( "Password-forgot silently dropped: CallerResetUrl not whitelisted for client {ClientId}", request.ClientId); return; } // ── Gate 2: user lookup by email (exact, case-insensitive at storage level) ── var usersAny = await redb.UserProvider.GetUsersAsync(new UserSearchCriteria { EmailExact = request.Email, // Enabled NOT set — list every match so the dropped-on-Enabled case is observable. }).ConfigureAwait(false); var users = await redb.UserProvider.GetUsersAsync(new UserSearchCriteria { EmailExact = request.Email, Enabled = true, }).ConfigureAwait(false); if (usersAny is not null && usersAny.Count > 0) { for (int i = 0; i < usersAny.Count; i++) { var u = usersAny[i]; } } if (users is null || users.Count == 0) { logger?.LogInformation("Password-forgot silently dropped: no enabled user for supplied email"); return; } var user = users[0]; if (string.IsNullOrEmpty(user.Email)) { // Should not happen given EmailExact matched, but guard anyway. return; } // ── Issue token + send e-mail ───────────────────────────────────────────── var store = _sp.GetRequiredService(); var emailChannel = _sp.GetService(); if (emailChannel is null) { logger?.LogError( "Password-forgot: no IEmailNotificationChannel registered — silently dropping (host misconfiguration)"); return; } var ttl = _sp.GetRequiredService>().Value.PasswordRecovery.TokenTtl; var issued = await store.IssueAsync(user.Id, request.CallerResetUrl, ttl, ct) .ConfigureAwait(false); var resetLink = BuildResetLink(request.CallerResetUrl, issued.Jti, issued.PlaintextToken); var vars = new Dictionary(StringComparer.Ordinal) { ["userName"] = user.Name ?? user.Login, ["resetLink"] = resetLink, ["ttlMinutes"] = ((int)ttl.TotalMinutes).ToString(System.Globalization.CultureInfo.InvariantCulture), }; try { await emailChannel.SendTemplateAsync(user.Email, IdentityEmailTemplates.PasswordReset, vars, ct) .ConfigureAwait(false); } catch (Exception ex) { // Anti-enumeration: never bubble e-mail failures to the caller. Log + audit only. logger?.LogError(ex, "Password-forgot: e-mail delivery failed for user {UserId} — request remains acknowledged", user.Id); return; } // Upgrade audit envelope: the request actually produced a token + e-mail. exchange.Properties["identity-event-type"] = IdentityAuditEventIds.PasswordResetTokenIssued; exchange.Properties["identity-event-data"] = new { UserId = user.Id, Login = user.Login, ClientId = request.ClientId, Jti = issued.Jti.ToString("N"), ExpiresAt = issued.ExpiresAt, }; } /// /// Composes the final reset link the user clicks on in the e-mail. URL-encodes both /// the plaintext token (base64url chars are URL-safe, but encoding is defence-in-depth) /// and the jti. Preserves any existing query string the caller's URL may already have. /// private static string BuildResetLink(string callerResetUrl, Guid jti, string plaintextToken) { var sep = callerResetUrl.Contains('?') ? '&' : '?'; var sb = new StringBuilder(callerResetUrl.Length + 128); sb.Append(callerResetUrl); sb.Append(sep); sb.Append("token="); sb.Append(Uri.EscapeDataString(plaintextToken)); sb.Append("&jti="); sb.Append(jti.ToString("N")); return sb.ToString(); } /// /// Hashes the supplied e-mail for audit storage (SHA-256 hex). We do not store the /// plaintext e-mail of a NON-matching request — leaving it un-hashed would let an /// attacker who later compromises the audit log enumerate every e-mail an attacker /// has ever tried against the system. /// private static string HashEmailForAudit(string email) { var bytes = SHA256.HashData(Encoding.UTF8.GetBytes(email.Trim().ToLowerInvariant())); return Convert.ToHexString(bytes); } private static void Reject(IExchange exchange, int status, string error, string description) { exchange.Out ??= new Message(); exchange.Out.Headers["redbHttp.ResponseCode"] = status; exchange.Out.Body = new ErrorResponse { Error = error, ErrorDescription = description }; } } Path: redb-identity/src/redb.Identity.Core/Routes/Processors/PasswordResetProcessor.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/Routes/Processors/PasswordResetProcessor.cs ---- using System; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Core; using redb.Identity.Contracts.Routes; using redb.Identity.Contracts.Users; using redb.Identity.Core.PasswordReset; using redb.Identity.Core.Services; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.RedbCore.Extensions; namespace redb.Identity.Core.Routes.Processors; /// /// N-4 (Session C): anonymous password-recovery completion backing /// direct-vm://identity-password-reset. /// /// Verifies + atomically consumes the single-use reset token via /// , validates the new /// password against the policy, persists it through /// (which bypasses the /// old-password check), records the change in password history, and revokes every /// active session for the user (OWASP Session Management C7). /// /// /// Error responses are intentionally generic (invalid_token / /// validation_error) — the granular Reason from the store is recorded only /// in the audit log () so an /// online attacker cannot tell "bad token" from "expired" from "already consumed". /// /// internal sealed class PasswordResetProcessor : IProcessor { private readonly IRouteContext _context; private readonly IServiceProvider _sp; private readonly string? _redbName; public PasswordResetProcessor(IRouteContext context, IServiceProvider sp, string? redbName = null) { _context = context; _sp = sp; _redbName = redbName; } public async Task Process(IExchange exchange, CancellationToken ct = default) { var request = exchange.In.Body as PasswordResetRequest; if (request is null || string.IsNullOrWhiteSpace(request.Jti) || string.IsNullOrWhiteSpace(request.Token) || string.IsNullOrWhiteSpace(request.NewPassword)) { Reject(exchange, 400, "validation_error", "Jti, Token and NewPassword are required."); return; } if (!Guid.TryParseExact(request.Jti, "N", out var jti) && !Guid.TryParse(request.Jti, out jti)) { // Malformed jti — treat as bad token (audit + generic response). await EmitFailureAuditAsync(exchange, "bad_jti_format", userId: 0).ConfigureAwait(false); Reject(exchange, 400, "invalid_token", "The reset token is invalid or has expired."); return; } var logger = _sp.GetService()?.CreateLogger("PasswordResetProcessor"); var store = _sp.GetRequiredService(); var verify = await store.VerifyAndConsumeAsync(jti, request.Token, ct).ConfigureAwait(false); if (!verify.Success) { await EmitFailureAuditAsync(exchange, verify.Reason, userId: verify.UserId).ConfigureAwait(false); Reject(exchange, 400, "invalid_token", "The reset token is invalid or has expired."); return; } var redb = _context.GetRedbService(_redbName, exchange); var user = await redb.UserProvider.GetUserByIdAsync(verify.UserId).ConfigureAwait(false); if (user is null) { // Token consumed but user vanished — extremely rare race (admin delete between // issue + reset). Treat as failure; the consumed token is already non-replayable. await EmitFailureAuditAsync(exchange, "user_not_found", verify.UserId).ConfigureAwait(false); Reject(exchange, 400, "invalid_token", "The reset token is invalid or has expired."); return; } // Validate new password against the registered policy (length, history, etc.). var err = await IdentityProcessorHelpers.ValidatePasswordPolicyAsync( exchange, _context, request.NewPassword, user.Id, "NewPassword", ct).ConfigureAwait(false); if (err is not null) { await EmitFailureAuditAsync(exchange, "policy_violation", user.Id).ConfigureAwait(false); Reject(exchange, 400, "validation_error", err); return; } // SetPasswordAsync bypasses the old-password check (admin/reset path). var ok = await redb.UserProvider.SetPasswordAsync(user, request.NewPassword).ConfigureAwait(false); if (!ok) { logger?.LogError( "Password reset: SetPasswordAsync returned false for user {UserId} — unexpected after policy check passed", user.Id); await EmitFailureAuditAsync(exchange, "set_password_failed", user.Id).ConfigureAwait(false); Reject(exchange, 500, "server_error", "Failed to persist the new password."); return; } // H10 — record in history so future change attempts can reject reuse. await IdentityProcessorHelpers.RecordPasswordHistoryAsync( exchange, _context, redb, user.Id, request.NewPassword, ct).ConfigureAwait(false); // C7 (OWASP Session Management): every active session must be invalidated, since // the user may not even be the legitimate one who initiated recovery. var sessionsRevoked = await new SessionService(redb).LogoutAsync(user.Id, ct).ConfigureAwait(false); exchange.Out ??= new Message(); exchange.Out.Body = new PasswordResetResponse { Success = true, SessionsRevoked = sessionsRevoked, }; exchange.Properties["identity-event-type"] = IdentityAuditEventIds.PasswordResetCompleted; exchange.Properties["identity-event-data"] = new { UserId = user.Id, Login = user.Login, Jti = jti.ToString("N"), SessionsRevoked = sessionsRevoked, }; } private static Task EmitFailureAuditAsync(IExchange exchange, string reason, long userId) { exchange.Properties["identity-event-type"] = IdentityAuditEventIds.PasswordResetFailed; exchange.Properties["identity-event-data"] = new { Reason = reason, UserId = userId, }; return Task.CompletedTask; } private static void Reject(IExchange exchange, int status, string error, string description) { exchange.Out ??= new Message(); exchange.Out.Headers["redbHttp.ResponseCode"] = status; exchange.Out.Body = new PasswordResetResponse { Success = false, Error = error, ErrorDescription = description, }; } } Path: redb-identity/src/redb.Identity.Core/Routes/Processors/PepperUsageReportProcessor.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/Routes/Processors/PepperUsageReportProcessor.cs ---- using Microsoft.Extensions.Logging; using redb.Core.Query; using redb.Identity.Core.Models; using redb.Identity.Core.Services; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.RedbCore.Extensions; namespace redb.Identity.Core.Routes.Processors; /// /// Pepper rotation: tells the operator when a previous pepper can go. Recovery codes have no expiry, so a value in /// stays needed while users hold codes /// hashed with it. Logs, per previous pepper id, how many users hold such codes, and how many hold codes without a /// pepper id (issued before 4.8.0, pepper unknown). Only ids and counts, never a pepper value or a user. /// Runs on the leader once after start and then daily; registered only while previous peppers are configured. /// internal sealed class PepperUsageReportProcessor : IProcessor { private readonly IRouteContext _context; private readonly string? _redbName; private readonly Func _peppers; private readonly ILogger _logger; public PepperUsageReportProcessor( IRouteContext context, string? redbName, Func peppers, ILogger logger) { _context = context; _redbName = redbName; _peppers = peppers; _logger = logger; } public async Task Process(IExchange exchange, CancellationToken ct = default) { var redb = _context.GetRedbService(_redbName, exchange); foreach (var id in _peppers().PreviousPepperIds) { var users = await redb.Query() .Where(p => p.RecoveryCodesPepperId == id && p.RecoveryCodes!.Any()) .CountAsync(); _logger.LogInformation( "Pepper rotation: {Users} user(s) hold recovery codes hashed with previous pepper {PepperId}.", users, id); } var unknown = await redb.Query() .Where(p => p.RecoveryCodesPepperId == null && p.RecoveryCodes!.Any()) .CountAsync(); _logger.LogInformation( "Pepper rotation: {Users} user(s) hold recovery codes issued before 4.8.0, without a pepper id; they are " + "checked with the current pepper, then the previous ones.", unknown); } } Path: redb-identity/src/redb.Identity.Core/Routes/Processors/ProtocolProcessors.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/Routes/Processors/ProtocolProcessors.cs ---- using OpenIddict.Server; using redb.Identity.Core.OpenIddict; using redb.Route.Abstractions; using redb.Identity.Contracts.Routes; namespace redb.Identity.Core.Routes.Processors; /// /// Token endpoint processor. Delegates to the OpenIddict pipeline via /// . /// internal sealed class TokenEndpointProcessor : IProcessor { private readonly RedbRouteOpenIddictServerHandler _handler; private readonly TimeProvider _timeProvider; public TokenEndpointProcessor(RedbRouteOpenIddictServerHandler handler, TimeProvider? timeProvider = null) { _handler = handler; _timeProvider = timeProvider ?? TimeProvider.System; } public async Task Process(IExchange exchange, CancellationToken ct = default) { await _handler.ProcessAsync(exchange, OpenIddictServerEndpointType.Token, ct); // Only emit event if token issuance succeeded (no error in response) var body = exchange.Out?.Body; if (body is Dictionary dict && dict.ContainsKey("error")) return; exchange.Properties["identity-event-type"] = IdentityAuditEventIds.TokenIssued; exchange.Properties["identity-event-data"] = new { ClientId = exchange.In.GetHeader("client_id"), GrantType = exchange.In.GetHeader("grant_type"), Timestamp = _timeProvider.GetUtcNow() }; } } /// /// Authorization endpoint processor. Delegates to the OpenIddict pipeline. /// internal sealed class AuthorizeEndpointProcessor : IProcessor { private readonly RedbRouteOpenIddictServerHandler _handler; public AuthorizeEndpointProcessor(RedbRouteOpenIddictServerHandler handler) => _handler = handler; public async Task Process(IExchange exchange, CancellationToken ct = default) { await _handler.ProcessAsync(exchange, OpenIddictServerEndpointType.Authorization, ct); exchange.Properties["identity-event-type"] = IdentityAuditEventIds.AuthorizationGranted; } } /// /// Userinfo endpoint processor. Delegates to the OpenIddict pipeline. /// internal sealed class UserinfoEndpointProcessor : IProcessor { private readonly RedbRouteOpenIddictServerHandler _handler; public UserinfoEndpointProcessor(RedbRouteOpenIddictServerHandler handler) => _handler = handler; public Task Process(IExchange exchange, CancellationToken ct = default) => _handler.ProcessAsync(exchange, OpenIddictServerEndpointType.UserInfo, ct); } Path: redb-identity/src/redb.Identity.Core/Routes/Processors/RateLimitProcessor.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/Routes/Processors/RateLimitProcessor.cs ---- using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using redb.Identity.Core.Configuration; using redb.Identity.Core.Metrics; using redb.Identity.Core.Services; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Identity.Core.Routes.Processors; /// /// C1 — Per-IP rate-limit guard. Reads the (already trust-resolved by C2) client IP from /// redbHttp.RemoteAddress and consults . On limit /// breach, short-circuits the pipeline with an HTTP 429 + Retry-After response and /// stops further processors from running. /// internal sealed class RateLimitProcessor : IProcessor { private readonly IServiceProvider _sp; private readonly string _bucketTag; private readonly Func _limitSelector; private readonly Func _windowSelector; private readonly ILogger _logger; public RateLimitProcessor( IServiceProvider sp, string bucketTag, Func limitSelector, Func windowSelector, ILogger? logger = null) { _sp = sp; _bucketTag = bucketTag; _limitSelector = limitSelector; _windowSelector = windowSelector; _logger = logger ?? NullLogger.Instance; } public async Task Process(IExchange exchange, CancellationToken ct = default) { var store = _sp.GetService(); var optsAccessor = _sp.GetService>(); if (store is null || optsAccessor is null) return; // Misconfigured — fail open rather than block legitimate traffic. var rl = optsAccessor.Value.RateLimit; if (!rl.Enabled) return; var ip = ResolveClientIp(exchange); if (string.IsNullOrEmpty(ip)) return; // No IP (e.g. internal direct-vm caller) — skip. var key = $"ip:{_bucketTag}:{ip}"; var decision = await store.TryIncrementAsync(key, _limitSelector(rl), _windowSelector(rl), ct); if (!decision.Allowed) { _logger.LogWarning( "RateLimit triggered: bucket={Bucket} ip={Ip} count={Count} retryAfter={RetryAfterSec}s", _bucketTag, ip, decision.Count, (int)decision.RetryAfter.TotalSeconds); // F3 + G4: emit `identity.rate_limit.rejections` with key_dimension=ip tag so // SRE dashboards can slice per-IP throttle activity from per-(IP+user) activity. _sp.GetService()?.RateLimitRejections.Add( 1, new KeyValuePair("key_dimension", "ip"), new KeyValuePair("bucket", _bucketTag)); EmitTooManyRequests(exchange, decision.RetryAfter, rl.DefaultRetryAfterSeconds); } } private static string? ResolveClientIp(IExchange exchange) { if (exchange.In.Headers.TryGetValue("redbHttp.RemoteAddress", out var v) && v is not null) return v.ToString(); return null; } internal static void EmitTooManyRequests(IExchange exchange, TimeSpan retryAfter, int defaultRetryAfterSeconds) { var seconds = retryAfter > TimeSpan.Zero ? (int)Math.Ceiling(retryAfter.TotalSeconds) : defaultRetryAfterSeconds; exchange.Out = new Message { Body = new Dictionary { ["success"] = false, ["error"] = "rate_limited", ["error_description"] = "Too many requests. Please retry later." } }; exchange.Out.Headers["redbHttp.ResponseCode"] = 429; exchange.Out.Headers["redbHttp.ResponseContentType"] = "application/json"; exchange.Out.Headers["Retry-After"] = seconds.ToString(System.Globalization.CultureInfo.InvariantCulture); // Mark as handled so downstream processors don't keep running. exchange.Exception = new RateLimitedException(); exchange.ExceptionHandled = true; exchange.Stop(); } } /// Marker exception used to short-circuit the route pipeline when a rate limit fires. internal sealed class RateLimitedException : Exception { public RateLimitedException() : base("Rate limit exceeded") { } } Path: redb-identity/src/redb.Identity.Core/Routes/Processors/RequireManagementContextProcessor.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/Routes/Processors/RequireManagementContextProcessor.cs ---- using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using redb.Identity.Contracts.Routes; using redb.Route.Abstractions; namespace redb.Identity.Core.Routes.Processors; /// /// The gate at the entrance of every management, self-service and SCIM route: the exchange carries the /// management context a facade attaches after validating a bearer, or it is refused. /// /// The core routes are transport-agnostic and never see a token themselves. The HTTP, gRPC and SOAP /// facades all take the same path: validate the bearer on /// (), which leaves identity:management-scopes and /// its siblings on the exchange, then forward. direct-vm is a transport like the others, not a /// trust level: in a Tsak worker the registry is shared by every module in the process, so an exchange /// that arrives without the context is not "internal and trusted" — nobody authenticated it. It is /// refused here, before any business processor, idempotency cache or transaction sees it. /// /// /// There is deliberately no in-process bypass and no option to declare one. A module that needs the /// management surface obtains a context the way the facades do: a token (client credentials with the /// scopes it needs) validated on . Trust is a property /// of the exchange, established by that hop — never inferred from the transport, and never from the /// absence of something. /// /// /// The refusal is — the same generic 403 every gate on this /// surface produces — plus a warning on the security log naming the route and the operation, so a /// caller reaching the core without a context is visible instead of silently admitted. /// /// internal sealed class RequireManagementContextProcessor : IProcessor { /// Set by from the validated token's scopes. internal const string ScopesProperty = "identity:management-scopes"; private readonly ILogger _logger; public RequireManagementContextProcessor(ILogger? logger = null) => _logger = logger ?? NullLogger.Instance; public Task Process(IExchange exchange, CancellationToken ct = default) { // Each operation starts without an event. An in-process caller may send one exchange to several // management routes in a row; the event a previous operation left in the properties would // otherwise reach this route's WireTap again, raised by an operation that did not cause it. exchange.Properties.Remove("identity-event-type"); exchange.Properties.Remove("identity-event-data"); if (exchange.Properties.TryGetValue(ScopesProperty, out var raw) && raw is string[] { Length: > 0 }) return Task.CompletedTask; exchange.In.Headers.TryGetValue("operation", out var operation); _logger.LogWarning( "Management route reached without a management context and refused: route={RouteId} operation={Operation}. " + "The caller did not come through a facade. In-process callers obtain a context the same way the facades do: " + "validate a bearer on {AuthHop}.", exchange.RouteId, operation, IdentityEndpoints.AuthManagement); ManagementProblem.Forbidden(exchange, "The request carries no management authorization."); return Task.CompletedTask; } } Path: redb-identity/src/redb.Identity.Core/Routes/Processors/RequireSelfOrAdminProcessor.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/Routes/Processors/RequireSelfOrAdminProcessor.cs ---- using System.Text.Json; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using redb.Route.Abstractions; namespace redb.Identity.Core.Routes.Processors; /// /// B8 — IDOR fix. Enforces the «self vs admin» authorization rule on management-API /// routes that take a userId from the request body. /// /// Caller is admitted in one of two cases: /// /// token carries the configured admin scope (typically /// identity:manage) — may target any user; /// token carries the configured self scope (typically /// identity:account) AND the body userId equals the token's /// sub claim — may target only the calling user. /// /// On any other combination (missing scope, mismatched subject, missing userId in body, /// no management context at all) the request is rejected with HTTP 403 and a single /// generic error message — never distinguishing «user does not exist» from «not /// authorized», to avoid information leakage. /// /// /// No management context is a refusal, not a bypass. This processor used to admit an /// exchange without identity:management-scopes as an "internal trusted" caller, on the /// reasoning that direct-vm is not network-reachable. In a Tsak worker the direct-vm /// registry is shared by every module in the process, so that reasoning granted any module /// admin rights over users' MFA. The gate at the route entrance /// () refuses such exchanges first; this processor /// refuses them too, so the rule holds even if it is ever placed on a route without the gate. /// /// /// The granular scopes of the surface admit as admin too. With given, a token /// carrying the surface's write scope (for MFA identity:mfa:write) may target any user with any operation, /// and one carrying its read scope (identity:mfa:read) may target any user with a read operation (the /// operation header is one of ). That is the rule the scope /// table of applies to every management surface; before, this gate /// admitted only the master scope, and the granular MFA scopes passed the table only to be refused here. /// /// internal sealed class RequireSelfOrAdminProcessor : IProcessor { /// /// The granular scopes of the surface this processor guards: admits every /// operation, the operations named in . /// public sealed record SurfaceScopes(string WriteScope, string ReadScope, IReadOnlySet ReadOperations); private readonly string _adminScope; private readonly string _accountScope; private readonly SurfaceScopes? _surface; private readonly ILogger _logger; public RequireSelfOrAdminProcessor( string adminScope, string accountScope, ILogger? logger = null, SurfaceScopes? surface = null) { _adminScope = adminScope ?? throw new ArgumentNullException(nameof(adminScope)); _accountScope = accountScope ?? throw new ArgumentNullException(nameof(accountScope)); _surface = surface; _logger = logger ?? NullLogger.Instance; } private bool HasSurfaceAdmin(IExchange exchange, string[] scopes) { if (_surface is null) return false; if (Array.IndexOf(scopes, _surface.WriteScope) >= 0) return true; if (Array.IndexOf(scopes, _surface.ReadScope) < 0) return false; var operation = exchange.In.GetHeader("operation"); return operation is not null && _surface.ReadOperations.Contains(operation); } public Task Process(IExchange exchange, CancellationToken ct = default) { if (!exchange.Properties.TryGetValue(RequireManagementContextProcessor.ScopesProperty, out var scopesObj) || scopesObj is not string[] scopes) { // Nobody authenticated this caller. Not a trusted internal one — see the class docs. _logger.LogWarning( "Self-or-admin authorization denied: no management context on the exchange (route={RouteId})", exchange.RouteId); Reject(exchange); return Task.CompletedTask; } var hasAdmin = scopes.Any(s => string.Equals(s, _adminScope, StringComparison.Ordinal)) || HasSurfaceAdmin(exchange, scopes); if (hasAdmin) return Task.CompletedTask; // admin may target any user var hasAccount = scopes.Any(s => string.Equals(s, _accountScope, StringComparison.Ordinal)); if (!hasAccount) { // Should not happen — ManagementBearerAuthProcessor admitted the token but it // carries neither scope. Defensive: deny. Reject(exchange); return Task.CompletedTask; } // Self-service path: body userId must match the token's internal user-id. // The public sub claim is now a GUID; ManagementBearerAuthProcessor mirrors // the bigint _users._id into `identity:management-user-id` from the // `redb:user_id` access-token claim. client_credentials tokens won't have // it — that's fine, this branch is only reached when the admin scope is // absent, and self-service requires an end-user grant. var bodyUserId = ExtractUserId(exchange.In.Body); var callerUserId = TryGetCallerUserId(exchange); if (bodyUserId is null || callerUserId is null || bodyUserId.Value != callerUserId.Value) { _logger.LogWarning( "Self-or-admin authorization denied: callerUserId={CallerUserId}, bodyUserId={BodyUserId}", callerUserId, bodyUserId); Reject(exchange); return Task.CompletedTask; } return Task.CompletedTask; } private static long? TryGetCallerUserId(IExchange exchange) { if (!exchange.Properties.TryGetValue("identity:management-user-id", out var raw)) return null; return raw switch { long l when l > 0 => l, int i when i > 0 => i, string s when long.TryParse(s, out var id) && id > 0 => id, _ => null }; } private static long? ExtractUserId(object? body) { if (body is not IDictionary dict) return null; if (!dict.TryGetValue("userId", out var v) || v is null) return null; return v switch { long l => l, int i => i, double d => (long)d, decimal m => (long)m, JsonElement je when je.TryGetInt64(out var jid) => jid, string s when long.TryParse(s, out var parsed) => parsed, _ => null }; } // B8: one generic message for every denial reason (no «existed/not existed» leakage); // the shape itself lives in ManagementProblem so every gate on the surface answers alike. private static void Reject(IExchange exchange) => ManagementProblem.Forbidden(exchange, "The access token does not authorize the requested operation."); } Path: redb-identity/src/redb.Identity.Core/Routes/Processors/RevokedSidsCleanupProcessor.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/Routes/Processors/RevokedSidsCleanupProcessor.cs ---- using Microsoft.Extensions.Options; using redb.Core; using redb.Core.Services; using redb.Identity.Contracts.Routes; using redb.Identity.Core.Configuration; using redb.Identity.Core.Models; using redb.Identity.Core.Services; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.RedbCore.Extensions; using redb.Identity.Contracts.Common; namespace redb.Identity.Core.Routes.Processors; /// /// W6-0: Periodic cleanup of expired entries in the backchannel revoked-sids list. /// Runs leader-only (.Cluster(true)) on the timer registered in /// . Soft-deletes via /// when an is registered (cluster-safe claim /// pattern); otherwise falls back to direct hard delete \u2014 mirrors /// . /// internal sealed class RevokedSidsCleanupProcessor : IProcessor { private const int BatchSize = 500; private readonly IRouteContext _context; private readonly string? _redbName; private readonly RedbIdentityOptions _options; private readonly IBackgroundDeletionService? _backgroundDeletion; private readonly TimeProvider _timeProvider; public RevokedSidsCleanupProcessor( IRouteContext context, IOptions options, string? redbName = null, IBackgroundDeletionService? backgroundDeletion = null, TimeProvider? timeProvider = null) { _context = context; _redbName = redbName; _options = options.Value; _backgroundDeletion = backgroundDeletion; _timeProvider = timeProvider ?? TimeProvider.System; } public async Task Process(IExchange exchange, CancellationToken ct = default) { var redb = _context.GetRedbService(_redbName, exchange); var now = _timeProvider.GetUtcNow(); // Entries past their ExpiresAt are no longer needed by any RP cache and can be // soft-deleted. Note: we don't add a safety margin \u2014 RPs reading the entry on // their next poll will already see ExpiresAt in the past and evict it locally. var expiredIds = await redb.Query() .WhereRedb(o => o.DateCreate <= now) .Where(p => p.ExpiresAt < now) .Take(BatchSize) .Select(o => o.Id) .ToListAsync() .ConfigureAwait(false); if (expiredIds.Count > 0) { await IdentityDeletionHelper.DeleteAsync(redb, _backgroundDeletion, expiredIds) .ConfigureAwait(false); } exchange.Out ??= new Message(); exchange.Out.Body = new RevokedSidsPruneResult { PrunedRevokedSids = expiredIds.Count }; exchange.Properties["identity-event-type"] = IdentityAuditEventIds.RevokedSidsPruned; exchange.Properties["identity-event-data"] = new { Count = expiredIds.Count, Threshold = now }; } } Path: redb-identity/src/redb.Identity.Core/Routes/Processors/RevokedSidsManagementProcessor.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/Routes/Processors/RevokedSidsManagementProcessor.cs ---- using Microsoft.Extensions.Options; using redb.Core; using redb.Core.Models.Entities; using redb.Identity.Contracts.Routes; using redb.Identity.Contracts.Sessions; using redb.Identity.Core.Configuration; using redb.Identity.Core.Models; using redb.Route.Abstractions; using redb.Route.RedbCore.Extensions; namespace redb.Identity.Core.Routes.Processors; /// /// W6-0: Management processor for the backchannel revoked-sids list. Dispatches on the /// "operation" header: /// /// add \u2014 publishes a new revocation entry (body: ); /// server clamps ExpiresAt to now + . /// since \u2014 incremental poll. Cursor passed via the cursor header /// (ISO-8601 string) or omitted on the first call. Returns entries with /// DateCreate > cursor, ordered ascending; capped at /// entries per response. The nextCursor field of /// the response equals the DateCreate of the last returned entry, or the /// supplied cursor when there were no new entries. /// /// internal sealed class RevokedSidsManagementProcessor : IProcessor { /// Hard cap on entries returned per since call. Polls usually run every /// 60s on RPs, so 1000 entries / poll is enough for any realistic revocation burst. public const int MaxBatchSize = 1000; private readonly IRouteContext _context; private readonly RedbIdentityOptions _options; private readonly TimeProvider _timeProvider; private readonly string? _redbName; public RevokedSidsManagementProcessor( IRouteContext context, IOptions options, string? redbName = null, TimeProvider? timeProvider = null) { _context = context; _options = options.Value; _redbName = redbName; _timeProvider = timeProvider ?? TimeProvider.System; } public async Task Process(IExchange exchange, CancellationToken ct = default) { var redb = _context.GetRedbService(_redbName!, exchange); var operation = exchange.In.GetHeader("operation") ?? throw new InvalidOperationException("Missing 'operation' header"); switch (operation) { case "add": await Add(redb, exchange, ct); break; case "since": await Since(redb, exchange, ct); break; default: IdentityProcessorHelpers.SetError(exchange, "invalid_operation", $"Unknown operation: {operation}"); break; } } private async Task Add(IRedbService redb, IExchange exchange, CancellationToken ct) { if (exchange.In.Body is not Dictionary dict) { IdentityProcessorHelpers.SetError(exchange, "invalid_request", "Body is required"); return; } var sid = TryString(dict, "sid"); var sub = TryString(dict, "sub"); var clientId = TryString(dict, "clientId"); if (string.IsNullOrEmpty(sid) && string.IsNullOrEmpty(sub)) { IdentityProcessorHelpers.SetError(exchange, "invalid_request", "Either 'sid' or 'sub' must be provided"); return; } var now = _timeProvider.GetUtcNow(); var maxExpires = now.Add(_options.RevokedSidsMaxRetention); var requested = TryDateTimeOffset(dict, "expiresAt"); // Clamp client-supplied ExpiresAt to [now, now + RevokedSidsMaxRetention]. var expiresAt = requested.HasValue && requested.Value < maxExpires && requested.Value > now ? requested.Value : maxExpires; var entry = new RedbObject { Props = new RevokedSidProps { Sid = string.IsNullOrEmpty(sid) ? null : sid, Sub = string.IsNullOrEmpty(sub) ? null : sub, ClientId = string.IsNullOrEmpty(clientId) ? null : clientId, RevokedAt = now, ExpiresAt = expiresAt } }; entry.id = await redb.SaveAsync(entry).ConfigureAwait(false); exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new RevokedSidEntry { Sid = entry.Props.Sid, Sub = entry.Props.Sub, ClientId = entry.Props.ClientId, RevokedAt = entry.Props.RevokedAt, ExpiresAt = entry.Props.ExpiresAt }; exchange.Properties["identity-event-type"] = IdentityAuditEventIds.SidRevoked; exchange.Properties["identity-event-data"] = new { Sid = entry.Props.Sid, Sub = entry.Props.Sub, ClientId = entry.Props.ClientId, ExpiresAt = entry.Props.ExpiresAt }; } private async Task Since(IRedbService redb, IExchange exchange, CancellationToken ct) { var dict = exchange.In.Body as Dictionary; var cursorRaw = dict is not null ? TryString(dict, "cursor") : null; var now = _timeProvider.GetUtcNow(); // Bootstrap window when no cursor supplied: full retention period. var defaultCursor = now.Subtract(_options.RevokedSidsMaxRetention); var cursor = ParseCursor(cursorRaw) ?? defaultCursor; var rows = await redb.Query() .WhereRedb(o => o.DateCreate > cursor) .OrderByRedb(o => o.DateCreate) .Take(MaxBatchSize) .ToListAsync() .ConfigureAwait(false); var entries = new List(rows.Count); var maxDateCreate = cursor; foreach (var row in rows) { entries.Add(new RevokedSidEntry { Sid = row.Props.Sid, Sub = row.Props.Sub, ClientId = row.Props.ClientId, RevokedAt = row.Props.RevokedAt, ExpiresAt = row.Props.ExpiresAt }); if (row.DateCreate > maxDateCreate) maxDateCreate = row.DateCreate; } exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new RevokedSidsSinceResponse { Entries = entries, NextCursor = maxDateCreate, ServerTime = now }; } // ── helpers ─────────────────────────────────────────────────────────── private static string? TryString(Dictionary dict, string key) => dict.TryGetValue(key, out var v) && v is not null ? v.ToString() : null; private static DateTimeOffset? TryDateTimeOffset(Dictionary dict, string key) { if (!dict.TryGetValue(key, out var v) || v is null) return null; return v switch { DateTimeOffset dto => dto, DateTime dt => new DateTimeOffset(DateTime.SpecifyKind(dt, DateTimeKind.Utc), TimeSpan.Zero), string s when DateTimeOffset.TryParse(s, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AssumeUniversal | System.Globalization.DateTimeStyles.AdjustToUniversal, out var parsed) => parsed, _ => null }; } private static DateTimeOffset? ParseCursor(string? raw) { if (string.IsNullOrWhiteSpace(raw)) return null; return DateTimeOffset.TryParse(raw, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AssumeUniversal | System.Globalization.DateTimeStyles.AdjustToUniversal, out var parsed) ? parsed : null; } } Path: redb-identity/src/redb.Identity.Core/Routes/Processors/RoleManagementProcessor.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/Routes/Processors/RoleManagementProcessor.cs ---- using Microsoft.Extensions.Logging; using redb.Core; using redb.Identity.Contracts.Common; using redb.Identity.Contracts.Roles; using redb.Identity.Contracts.Routes; using redb.Identity.Core.Models; using redb.Identity.Core.Services; using redb.Route.Abstractions; using redb.Route.RedbCore.Extensions; namespace redb.Identity.Core.Routes.Processors; /// /// B.3 — admin CRUD + assignment surface for the Roles registry. /// /// Operations: /// search / get / create / update / delete — role CRUD /// list-assignees / assign-user / unassign-user /// / assign-group / unassign-group — assignments /// user-roles (effective set) — read-only /// internal sealed class RoleManagementProcessor : IProcessor { private readonly IRouteContext _context; private readonly string? _redbName; private readonly ILogger _logger; public RoleManagementProcessor(IRouteContext context, string? redbName, ILogger logger) { _context = context; _redbName = redbName; _logger = logger; } public async Task Process(IExchange exchange, CancellationToken ct = default) { var operation = exchange.In.GetHeader("operation") ?? ""; var redb = _context.GetRedbService(_redbName, exchange); var svc = new RoleService(redb); switch (operation) { case "search": await Search(redb, svc, exchange, ct); break; case "get": await Get(redb, svc, exchange, ct); break; case "create": await Create(redb, svc, exchange, ct); break; case "update": await Update(svc, exchange, ct); break; case "delete": await Delete(svc, exchange, ct); break; case "list-assignees": await ListAssignees(redb, svc, exchange, ct); break; case "assign-user": await AssignUser(svc, exchange, ct); break; case "unassign-user": await UnassignUser(svc, exchange, ct); break; case "assign-group": await AssignGroup(svc, exchange, ct); break; case "unassign-group": await UnassignGroup(svc, exchange, ct); break; case "list-scopes": await ListScopes(redb, svc, exchange, ct); break; case "attach-scope": await AttachScope(svc, exchange, ct); break; case "detach-scope": await DetachScope(svc, exchange, ct); break; default: SetError(exchange, "invalid_operation", $"Unknown operation: {operation}"); break; } } // ── Role CRUD ────────────────────────────────────────────── private async Task Search(IRedbService redb, RoleService svc, IExchange exchange, CancellationToken ct) { var dict = exchange.In.Body as Dictionary ?? new(); string? query = dict.TryGetValue("query", out var q) ? q?.ToString() : null; string? audience = dict.TryGetValue("audience", out var a) ? a?.ToString() : null; long? applicationId = null; if (dict.TryGetValue("applicationId", out var app) && long.TryParse(app?.ToString(), out var pa)) applicationId = pa; var offset = 0; var count = 25; if (dict.TryGetValue("offset", out var oVal) && int.TryParse(oVal?.ToString(), out var po)) offset = Math.Max(0, po); if (dict.TryGetValue("count", out var cVal) && int.TryParse(cVal?.ToString(), out var pc)) count = Math.Clamp(pc, 1, 200); var (items, total) = await svc.SearchRolesAsync( string.IsNullOrWhiteSpace(query) ? null : query, string.IsNullOrWhiteSpace(audience) ? null : audience, applicationId, offset, count, ct).ConfigureAwait(false); var counts = await svc.CountAssignmentsByRoleAsync(items.Select(r => r.Id), ct).ConfigureAwait(false); // Bulk-resolve application display names for audience='application' rows. var appIds = items .Where(r => r.Props.ApplicationId.HasValue) .Select(r => r.Props.ApplicationId!.Value) .Distinct() .ToList(); var appNames = await ResolveApplicationNamesAsync(redb, appIds).ConfigureAwait(false); var responses = items.Select(r => MapToResponse(r, appNames, counts.GetValueOrDefault(r.Id, 0))).ToList(); exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new PagedResult { Items = responses, Total = total, Offset = offset, Count = count }; } private async Task Get(IRedbService redb, RoleService svc, IExchange exchange, CancellationToken ct) { var id = ExtractLongFromBody(exchange, "id"); if (id is null) { SetError(exchange, "validation_error", "id is required"); return; } var role = await svc.GetRoleAsync(id.Value, ct).ConfigureAwait(false); if (role is null) { SetError(exchange, "not_found", $"Role {id} not found"); return; } var appNames = role.Props.ApplicationId.HasValue ? await ResolveApplicationNamesAsync(redb, new[] { role.Props.ApplicationId.Value }).ConfigureAwait(false) : new Dictionary(); exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = MapToResponse(role, appNames, null); } private async Task Create(IRedbService redb, RoleService svc, IExchange exchange, CancellationToken ct) { if (exchange.In.Body is not CreateRoleRequest request) { SetError(exchange, "validation_error", "Body must be a CreateRoleRequest"); return; } var name = request.Name.Trim(); if (string.IsNullOrEmpty(name)) { SetError(exchange, "validation_error", "name is required"); return; } if (request.Audience is not ("organization" or "application")) { SetError(exchange, "validation_error", "audience must be 'organization' or 'application'"); return; } if (request.Audience == "application" && (request.ApplicationId is null or 0)) { SetError(exchange, "validation_error", "audience='application' requires applicationId"); return; } if (request.Audience == "organization" && request.ApplicationId is not null) { SetError(exchange, "validation_error", "audience='organization' requires applicationId to be null"); return; } try { var created = await svc.CreateRoleAsync( name, request.Audience, request.ApplicationId, request.DisplayName, request.Description, isSystem: false, ct).ConfigureAwait(false); var appNames = request.ApplicationId.HasValue ? await ResolveApplicationNamesAsync(redb, new[] { request.ApplicationId.Value }).ConfigureAwait(false) : new Dictionary(); exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = MapToResponse(created, appNames, 0); exchange.Properties["identity-event-type"] = IdentityAuditEventIds.RoleCreated; exchange.Properties["identity-event-data"] = new { RoleId = created.Id, Name = name }; } catch (InvalidOperationException ex) { SetError(exchange, "conflict", ex.Message); } } private async Task Update(RoleService svc, IExchange exchange, CancellationToken ct) { var id = ExtractLongFromBody(exchange, "id"); if (id is null) { SetError(exchange, "validation_error", "id is required"); return; } var dict = exchange.In.Body as Dictionary; string? displayName = dict?.TryGetValue("displayName", out var dn) == true ? dn?.ToString() : null; string? description = dict?.TryGetValue("description", out var dd) == true ? dd?.ToString() : null; // A role that does not exist is "not found"; the service would throw for it and the route // would answer a server error. if (await svc.GetRoleAsync(id.Value, ct).ConfigureAwait(false) is null) { SetError(exchange, "not_found", $"Role {id.Value} not found."); return; } await svc.UpdateRoleAsync(id.Value, displayName, description, ct).ConfigureAwait(false); exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new SuccessResponse(); exchange.Properties["identity-event-type"] = IdentityAuditEventIds.RoleUpdated; exchange.Properties["identity-event-data"] = new { RoleId = id.Value }; } private async Task Delete(RoleService svc, IExchange exchange, CancellationToken ct) { var id = ExtractLongFromBody(exchange, "id"); if (id is null) { SetError(exchange, "validation_error", "id is required"); return; } // A role that does not exist is "not found", not a conflict: the service reports both with // one exception type, so the question is asked here before the delete. if (await svc.GetRoleAsync(id.Value, ct).ConfigureAwait(false) is null) { SetError(exchange, "not_found", $"Role {id.Value} not found."); return; } try { await svc.DeleteRoleAsync(id.Value, ct).ConfigureAwait(false); exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new SuccessResponse(); exchange.Properties["identity-event-type"] = IdentityAuditEventIds.RoleDeleted; exchange.Properties["identity-event-data"] = new { RoleId = id.Value }; } catch (InvalidOperationException ex) { SetError(exchange, "conflict", ex.Message); } } // ── Assignments ──────────────────────────────────────────── private async Task ListAssignees(IRedbService redb, RoleService svc, IExchange exchange, CancellationToken ct) { var roleId = ExtractLongFromBody(exchange, "roleId") ?? ExtractLongFromBody(exchange, "id"); if (roleId is null) { SetError(exchange, "validation_error", "roleId is required"); return; } var (userIds, groupIds) = await svc.ListAssigneesAsync(roleId.Value, ct).ConfigureAwait(false); // Best-effort lookup user logins + group names for labels. // Earlier impl used GetUsersAsync(new UserSearchCriteria { Limit = N }) // which returned the first N users (unsorted by id, no filter) and // then .Where(userIds.Contains)-filtered them — i.e. on any install // with more than N users the assignee's actual record would not be // in the response and the UI showed only the raw id. Per-id lookup // through the dedicated provider entry-point is correct at any // user count; bounded by the assignee list (usually <100). var userLabels = new Dictionary(); if (userIds.Count > 0) { try { var lookups = userIds.Select(async id => { try { return (id, user: await redb.UserProvider.GetUserByIdAsync(id).ConfigureAwait(false)); } catch { return (id, user: (redb.Core.Models.Contracts.IRedbUser?)null); } }); foreach (var (id, user) in await Task.WhenAll(lookups)) { if (user is not null) userLabels[id] = user.Login; } } catch { /* swallow */ } } var groupLabels = new Dictionary(); if (groupIds.Count > 0) { try { var groups = await redb.Query() .WhereInRedb(o => o.Id, groupIds.Cast()) .ToListAsync() .ConfigureAwait(false); foreach (var g in groups) groupLabels[g.Id] = g.Name ?? $"group:{g.Id}"; } catch { /* swallow */ } } var role = await svc.GetRoleAsync(roleId.Value, ct).ConfigureAwait(false); var roleName = role?.Props.Name ?? ""; var audience = role?.Props.Audience ?? "organization"; var appId = role?.Props.ApplicationId; var rows = new List(); foreach (var uid in userIds) { rows.Add(new RoleAssignmentResponse { RoleId = roleId.Value, RoleName = roleName, Audience = audience, ApplicationId = appId, SubjectKind = "user", SubjectId = uid, SubjectLabel = userLabels.GetValueOrDefault(uid), AssignedAt = DateTimeOffset.UtcNow, }); } foreach (var gid in groupIds) { rows.Add(new RoleAssignmentResponse { RoleId = roleId.Value, RoleName = roleName, Audience = audience, ApplicationId = appId, SubjectKind = "group", SubjectId = gid, SubjectLabel = groupLabels.GetValueOrDefault(gid), AssignedAt = DateTimeOffset.UtcNow, }); } exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = rows; } private async Task AssignUser(RoleService svc, IExchange exchange, CancellationToken ct) { var roleId = ExtractLongFromBody(exchange, "roleId"); var userId = ExtractLongFromBody(exchange, "userId"); if (roleId is null || userId is null) { SetError(exchange, "validation_error", "roleId + userId required"); return; } await svc.AssignUserAsync(roleId.Value, userId.Value, null, ct).ConfigureAwait(false); exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new SuccessResponse(); exchange.Properties["identity-event-type"] = IdentityAuditEventIds.RoleAssignedUser; exchange.Properties["identity-event-data"] = new { RoleId = roleId.Value, UserId = userId.Value }; } private async Task UnassignUser(RoleService svc, IExchange exchange, CancellationToken ct) { var roleId = ExtractLongFromBody(exchange, "roleId"); var userId = ExtractLongFromBody(exchange, "userId"); if (roleId is null || userId is null) { SetError(exchange, "validation_error", "roleId + userId required"); return; } await svc.UnassignUserAsync(roleId.Value, userId.Value, ct).ConfigureAwait(false); exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new SuccessResponse(); } private async Task AssignGroup(RoleService svc, IExchange exchange, CancellationToken ct) { var roleId = ExtractLongFromBody(exchange, "roleId"); var groupId = ExtractLongFromBody(exchange, "groupId"); if (roleId is null || groupId is null) { SetError(exchange, "validation_error", "roleId + groupId required"); return; } await svc.AssignGroupAsync(roleId.Value, groupId.Value, null, ct).ConfigureAwait(false); exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new SuccessResponse(); } private async Task UnassignGroup(RoleService svc, IExchange exchange, CancellationToken ct) { var roleId = ExtractLongFromBody(exchange, "roleId"); var groupId = ExtractLongFromBody(exchange, "groupId"); if (roleId is null || groupId is null) { SetError(exchange, "validation_error", "roleId + groupId required"); return; } await svc.UnassignGroupAsync(roleId.Value, groupId.Value, ct).ConfigureAwait(false); exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new SuccessResponse(); } // ── Scope attachments ────────────────────────────────────── private async Task ListScopes(IRedbService redb, RoleService svc, IExchange exchange, CancellationToken ct) { var roleId = ExtractLongFromBody(exchange, "roleId") ?? ExtractLongFromBody(exchange, "id"); if (roleId is null) { SetError(exchange, "validation_error", "roleId required"); return; } var scopeIds = await svc.ListScopeIdsForRoleAsync(roleId.Value, ct).ConfigureAwait(false); if (scopeIds.Count == 0) { exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new List(); return; } var scopes = await redb.Query() .WhereInRedb(o => o.Id, scopeIds.Cast()) .ToListAsync() .ConfigureAwait(false); // V4-UNIQUE: ScopeName is a stored [RedbUnique] prop. value_string covers rows written before // that and not yet repaired by the boot backfill; the object name is the last resort. var rows = scopes.Select(s => new redb.Identity.Contracts.Roles.RoleScopeResponse { RoleId = roleId.Value, ScopeId = s.Id, ScopeName = s.Props.ScopeName ?? s.value_string ?? s.name, Description = s.Props.Description, AttachedAt = s.date_create }).ToList(); exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = rows; } private async Task AttachScope(RoleService svc, IExchange exchange, CancellationToken ct) { var roleId = ExtractLongFromBody(exchange, "roleId"); var scopeId = ExtractLongFromBody(exchange, "scopeId"); if (roleId is null || scopeId is null) { SetError(exchange, "validation_error", "roleId + scopeId required"); return; } await svc.AttachScopeAsync(roleId.Value, scopeId.Value, null, ct).ConfigureAwait(false); exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new SuccessResponse(); exchange.Properties["identity-event-type"] = IdentityAuditEventIds.RoleScopeAttached; exchange.Properties["identity-event-data"] = new { RoleId = roleId.Value, ScopeId = scopeId.Value }; } private async Task DetachScope(RoleService svc, IExchange exchange, CancellationToken ct) { var roleId = ExtractLongFromBody(exchange, "roleId"); var scopeId = ExtractLongFromBody(exchange, "scopeId"); if (roleId is null || scopeId is null) { SetError(exchange, "validation_error", "roleId + scopeId required"); return; } await svc.DetachScopeAsync(roleId.Value, scopeId.Value, ct).ConfigureAwait(false); exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new SuccessResponse(); } // ── Helpers ───────────────────────────────────────────────── private static long? ExtractLongFromBody(IExchange exchange, string field) { if (exchange.In.Body is not Dictionary dict) return null; if (!dict.TryGetValue(field, out var v) || v is null) return null; return long.TryParse(v.ToString(), out var parsed) ? parsed : null; } private static async Task> ResolveApplicationNamesAsync(IRedbService redb, IEnumerable ids) { var idList = ids.Distinct().ToList(); if (idList.Count == 0) return new(); try { var apps = await redb.Query() .WhereInRedb(o => o.Id, idList.Cast()) .ToListAsync() .ConfigureAwait(false); return apps.ToDictionary(a => a.Id, a => a.Props.ClientId ?? $"app:{a.Id}"); } catch { return new(); } } private static RoleResponse MapToResponse(redb.Core.Models.Entities.RedbObject r, IReadOnlyDictionary appNames, int? assignmentCount) => new() { Id = r.Id, Name = r.Props.Name, DisplayName = r.Props.DisplayName, Description = r.Props.Description, Audience = r.Props.Audience, ApplicationId = r.Props.ApplicationId, ApplicationName = r.Props.ApplicationId is { } aid ? appNames.GetValueOrDefault(aid) : null, IsSystem = r.Props.IsSystem, CreatedAt = r.date_create, ModifiedAt = r.date_modify, AssignmentCount = assignmentCount, }; private static void SetError(IExchange exchange, string code, string description) { exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new ErrorResponse { Error = code, ErrorDescription = description }; } } Path: redb-identity/src/redb.Identity.Core/Routes/Processors/ScimBulkProcessor.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/Routes/Processors/ScimBulkProcessor.cs ---- using System.Text.Json; using redb.Identity.Contracts.Scim; using redb.Route.Abstractions; using redb.Route.Core; using redb.Identity.Contracts.Routes; namespace redb.Identity.Core.Routes.Processors; /// /// SCIM 2.0 Bulk endpoint processor (RFC 7644 §3.7). /// /// Accepts a with up to maxOperations operations, /// dispatches each operation to the corresponding internal direct-vm endpoint /// (identity-scim-users / identity-scim-groups) and aggregates the /// per-operation results into a . /// /// /// Per RFC §3.7.3 partial success is allowed; each inner op runs in its own redb /// transaction (the inner SCIM routes are WithIdempotentTx). The /// failOnErrors attribute caps the error stream — once exceeded the bulk /// loop terminates and the partial response is returned. /// /// /// Forward bulkId references (RFC §3.7.2) are resolved client-side by scanning /// each operation's data JSON for "bulkId:<key>" string values /// and substituting the location of a previously-created resource. References /// to a not-yet-created bulkId fail the operation with status 409. /// /// internal sealed class ScimBulkProcessor : IProcessor { private readonly IRouteContext _context; private readonly int _maxOperations; private readonly int _maxPayloadSize; public ScimBulkProcessor(IRouteContext context, int maxOperations, int maxPayloadSize) { _context = context; _maxOperations = maxOperations <= 0 ? 1000 : maxOperations; _maxPayloadSize = maxPayloadSize <= 0 ? 1_048_576 : maxPayloadSize; } public async Task Process(IExchange exchange, CancellationToken ct = default) { var request = exchange.In.Body as ScimBulkRequest; if (request is null) { SetScimError(exchange, 400, null, "Invalid SCIM bulk request body"); return; } if (request.Operations.Count == 0) { SetScimError(exchange, 400, null, "Bulk request must contain at least one operation"); return; } if (request.Operations.Count > _maxOperations) { SetScimError(exchange, 413, "tooLarge", $"Bulk request exceeds maxOperations limit of {_maxOperations}"); return; } var baseUrl = exchange.In.GetHeader("scim.BaseUrl") ?? string.Empty; var ifMatch = exchange.In.GetHeader("scim.IfMatch"); // Map of bulkId → server-assigned location for forward-reference resolution (§3.7.2). var bulkIdLocations = new Dictionary(StringComparer.Ordinal); var response = new ScimBulkResponse(); var errorCount = 0; var failOnErrors = request.FailOnErrors > 0 ? request.FailOnErrors : int.MaxValue; var processedCount = 0; var successCount = 0; foreach (var op in request.Operations) { if (errorCount >= failOnErrors) break; var opResponse = new ScimBulkOperationResponse { Method = op.Method, BulkId = op.BulkId }; try { var routed = await DispatchOperationAsync(exchange, op, baseUrl, ifMatch, bulkIdLocations, ct); opResponse.Status = routed.Status; opResponse.Location = routed.Location; opResponse.Response = routed.Response; if (!string.IsNullOrEmpty(op.BulkId) && !string.IsNullOrEmpty(routed.Location)) bulkIdLocations[op.BulkId!] = routed.Location!; if (IsSuccessStatus(routed.Status)) successCount++; else errorCount++; } catch (Exception ex) { errorCount++; opResponse.Status = "500"; opResponse.Response = SerializeError(new ScimError { Status = "500", Detail = ex.Message }); } response.Operations.Add(opResponse); processedCount++; } SetResult(exchange, response); exchange.Out!.Headers["scim.ResponseCode"] = 200; // Audit: emit a single rolled-up event for the whole bulk request. exchange.Properties["identity-event-type"] = IdentityAuditEventIds.ScimBulkProcessed; exchange.Properties["identity-event-data"] = new { Operations = processedCount, Succeeded = successCount, Failed = errorCount, request.FailOnErrors }; } private async Task DispatchOperationAsync( IExchange parent, ScimBulkOperation op, string baseUrl, string? ifMatch, IReadOnlyDictionary bulkIdLocations, CancellationToken ct) { if (string.IsNullOrEmpty(op.Method) || string.IsNullOrEmpty(op.Path)) return DispatchResult.Error(400, "invalidValue", "Bulk operation requires 'method' and 'path'"); if (!TryParsePath(op.Path, out var resourceType, out var resourceId)) return DispatchResult.Error(400, "invalidPath", $"Unsupported bulk path '{op.Path}'. Only /Users[/{{id}}] and /Groups[/{{id}}] are supported."); var endpointUri = resourceType == "Users" ? IdentityEndpoints.ScimUsers : IdentityEndpoints.ScimGroups; // Resolve forward bulkId references inside the data JSON before deserialization. var resolvedData = op.Data; if (op.Data is { } d) { var (resolved, missingRef) = ResolveBulkIds(d, bulkIdLocations); if (missingRef is not null) return DispatchResult.Error(409, "invalidValue", $"Bulk operation references unresolved bulkId '{missingRef}'"); resolvedData = resolved; } // Build the body shape expected by the inner direct-vm processor. var method = op.Method.ToUpperInvariant(); object? body; string operationName; switch (method) { case "POST": if (!string.IsNullOrEmpty(resourceId)) return DispatchResult.Error(400, "invalidPath", "POST requires a collection path"); if (resolvedData is not { } pd) return DispatchResult.Error(400, "invalidValue", "POST requires a 'data' payload"); body = resourceType == "Users" ? (object?)pd.Deserialize() : pd.Deserialize(); if (body is null) return DispatchResult.Error(400, "invalidValue", "Invalid 'data' payload"); operationName = "create"; break; case "PUT": if (string.IsNullOrEmpty(resourceId)) return DispatchResult.Error(400, "invalidPath", "PUT requires a resource path"); if (resolvedData is not { } putData) return DispatchResult.Error(400, "invalidValue", "PUT requires a 'data' payload"); if (resourceType == "Users") { var u = putData.Deserialize(); if (u is null) return DispatchResult.Error(400, "invalidValue", "Invalid 'data' payload"); u.Id = resourceId; body = u; } else { var g = putData.Deserialize(); if (g is null) return DispatchResult.Error(400, "invalidValue", "Invalid 'data' payload"); g.Id = resourceId; body = g; } operationName = "replace"; break; case "PATCH": if (string.IsNullOrEmpty(resourceId)) return DispatchResult.Error(400, "invalidPath", "PATCH requires a resource path"); if (resolvedData is not { } patchData) return DispatchResult.Error(400, "invalidValue", "PATCH requires a 'data' payload"); var patch = patchData.Deserialize(); if (patch is null) return DispatchResult.Error(400, "invalidValue", "Invalid PatchOp payload"); body = new Dictionary { ["id"] = resourceId, ["patch"] = patch }; operationName = "patch"; break; case "DELETE": if (string.IsNullOrEmpty(resourceId)) return DispatchResult.Error(400, "invalidPath", "DELETE requires a resource path"); body = new Dictionary { ["id"] = resourceId }; operationName = "delete"; break; default: return DispatchResult.Error(400, "invalidValue", $"Unsupported HTTP method '{op.Method}'"); } var endpoint = _context.GetEndpoint(endpointUri); var msg = new Message(); msg.Headers["operation"] = operationName; msg.Body = body; if (!string.IsNullOrEmpty(baseUrl)) msg.Headers["scim.BaseUrl"] = baseUrl; if (!string.IsNullOrEmpty(ifMatch)) msg.Headers["scim.IfMatch"] = ifMatch!; // CreateChild gives the inner exchange its own fresh DI scope (per-op IRedbService), // so concurrent bulk inner ops don't share a connection. Without this the inner // Exchange has a null ServiceProvider and the SCIM processors fall back to the // captive root-provider IRedbService — single connection for all inner ops. var inner = parent.CreateChild(msg); inner.Pattern = ExchangePattern.InOut; var producer = endpoint.CreateProducer(); try { await producer.Process(inner).ConfigureAwait(false); var status = ExtractStatus(inner, operationName); var location = ExtractLocation(inner, baseUrl); var responseBody = ExtractResponseBody(inner, status); return new DispatchResult(status, location, responseBody); } finally { // CRITICAL: dispose the per-op inner exchange so its DI scope (and the scoped // NpgsqlConnection) is released back to the pool. Without this each bulk op // leaks one connection — quickly exhausts MaxPoolSize for large bulk batches. await inner.DisposeAsync().ConfigureAwait(false); } } /// /// Walks a JSON tree and replaces any string of the form "bulkId:<key>" /// with the corresponding location from . /// Returns the missing bulkId when an unresolved reference is encountered. /// private static (JsonElement Resolved, string? MissingRef) ResolveBulkIds( JsonElement source, IReadOnlyDictionary bulkIdLocations) { if (!ContainsBulkIdRef(source)) return (source, null); using var doc = JsonDocument.Parse(source.GetRawText()); var buffer = new System.IO.MemoryStream(); using (var writer = new Utf8JsonWriter(buffer)) { string? missing = null; WriteRewritten(doc.RootElement, writer, bulkIdLocations, ref missing); if (missing is not null) return (source, missing); } buffer.Position = 0; using var resolvedDoc = JsonDocument.Parse(buffer); return (resolvedDoc.RootElement.Clone(), null); } private static bool ContainsBulkIdRef(JsonElement el) { switch (el.ValueKind) { case JsonValueKind.String: var s = el.GetString(); return s is not null && s.StartsWith("bulkId:", StringComparison.Ordinal); case JsonValueKind.Object: foreach (var p in el.EnumerateObject()) if (ContainsBulkIdRef(p.Value)) return true; return false; case JsonValueKind.Array: foreach (var v in el.EnumerateArray()) if (ContainsBulkIdRef(v)) return true; return false; default: return false; } } private static void WriteRewritten( JsonElement el, Utf8JsonWriter writer, IReadOnlyDictionary bulkIdLocations, ref string? missing) { switch (el.ValueKind) { case JsonValueKind.Object: writer.WriteStartObject(); foreach (var p in el.EnumerateObject()) { writer.WritePropertyName(p.Name); WriteRewritten(p.Value, writer, bulkIdLocations, ref missing); if (missing is not null) return; } writer.WriteEndObject(); break; case JsonValueKind.Array: writer.WriteStartArray(); foreach (var v in el.EnumerateArray()) { WriteRewritten(v, writer, bulkIdLocations, ref missing); if (missing is not null) return; } writer.WriteEndArray(); break; case JsonValueKind.String: var s = el.GetString(); if (s is not null && s.StartsWith("bulkId:", StringComparison.Ordinal)) { var key = s.Substring("bulkId:".Length); if (!bulkIdLocations.TryGetValue(key, out var loc)) { missing = key; return; } writer.WriteStringValue(loc); } else { writer.WriteStringValue(s); } break; default: el.WriteTo(writer); break; } } private static bool TryParsePath(string path, out string resourceType, out string? resourceId) { resourceType = string.Empty; resourceId = null; if (string.IsNullOrEmpty(path) || path[0] != '/') return false; var parts = path.TrimStart('/').Split('/', StringSplitOptions.RemoveEmptyEntries); if (parts.Length == 0 || parts.Length > 2) return false; if (!string.Equals(parts[0], "Users", StringComparison.Ordinal) && !string.Equals(parts[0], "Groups", StringComparison.Ordinal)) return false; resourceType = parts[0]; if (parts.Length == 2) resourceId = parts[1]; return true; } private static int ExtractStatus(IExchange inner, string operationName) { // Camel canon: response = Out ?? In. The terminal pipeline step (e.g. WireTap) // may have caused the merge to clear Out and leave the business response on In. var src = inner.Out ?? inner.In; if (src?.Headers.TryGetValue("scim.ResponseCode", out var rc) == true && rc is int code) return code; // Defaults if the inner processor didn't set scim.ResponseCode. if (src?.Body is ScimError err && int.TryParse(err.Status, out var es)) return es; return operationName switch { "create" => 201, "delete" => 204, _ => 200 }; } private static string? ExtractLocation(IExchange inner, string baseUrl) { var src = inner.Out ?? inner.In; if (src?.Headers.TryGetValue("scim.Location", out var loc) == true) { var s = loc?.ToString(); if (string.IsNullOrEmpty(s)) return null; if (s.StartsWith("/", StringComparison.Ordinal) && !string.IsNullOrEmpty(baseUrl)) return baseUrl + s; return s; } return null; } private static JsonElement? ExtractResponseBody(IExchange inner, int status) { var body = (inner.Out ?? inner.In)?.Body; if (body is null) return null; // Per RFC 7644 §3.7.3, the per-op `response` field is REQUIRED for errors and // OPTIONAL for success. We include it for errors and omit on plain success // (clients can dereference Location for the created resource). if (status >= 400) return SerializeError(body as ScimError ?? new ScimError { Status = status.ToString() }); return null; } private static JsonElement SerializeError(object body) { var json = JsonSerializer.SerializeToUtf8Bytes(body); using var doc = JsonDocument.Parse(json); return doc.RootElement.Clone(); } private static bool IsSuccessStatus(string status) => int.TryParse(status, out var code) && code is >= 200 and < 300; private static void SetResult(IExchange exchange, object body) { exchange.Out ??= new Message(); exchange.Out.Body = body; } private static void SetScimError(IExchange exchange, int status, string? scimType, string detail) { exchange.Out ??= new Message(); exchange.Out.Body = new ScimError { Status = status.ToString(), ScimType = scimType, Detail = detail }; exchange.Out.Headers["scim.ResponseCode"] = status; } private readonly record struct DispatchResult(int StatusCode, string? Location, JsonElement? Response) { public string Status => StatusCode.ToString(); public static DispatchResult Error(int status, string? scimType, string detail) { var json = JsonSerializer.SerializeToUtf8Bytes(new ScimError { Status = status.ToString(), ScimType = scimType, Detail = detail }); using var doc = JsonDocument.Parse(json); return new DispatchResult(status, null, doc.RootElement.Clone()); } } } Path: redb-identity/src/redb.Identity.Core/Routes/Processors/ScimFilterParser.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/Routes/Processors/ScimFilterParser.cs ---- using System.Text.RegularExpressions; namespace redb.Identity.Core.Routes.Processors; /// /// Minimal SCIM filter parser (RFC 7644 §3.4.2.2). /// Supports single expressions: attrPath op "value" and attrPath pr. /// Attribute names are normalized to lowercase. /// internal static partial class ScimFilterParser { public sealed record ScimFilter(string Attribute, string Operator, string Value); /// /// Parses a SCIM filter expression like userName eq "john" or active pr. /// Returns null for unsupported or empty filters. /// public static ScimFilter? Parse(string? filter) { if (string.IsNullOrWhiteSpace(filter)) return null; var trimmed = filter.Trim(); // Try presence operator first: attrPath pr (no value) var prMatch = PresenceRegex().Match(trimmed); if (prMatch.Success) { return new ScimFilter( prMatch.Groups[1].Value.ToLowerInvariant(), "pr", string.Empty); } // Standard comparison: attrPath SP operator SP quotedValue var match = FilterRegex().Match(trimmed); if (!match.Success) return null; return new ScimFilter( match.Groups[1].Value.ToLowerInvariant(), match.Groups[2].Value.ToLowerInvariant(), match.Groups[3].Value); } // attrPath SP operator SP quotedValue [GeneratedRegex(@"^(\S+)\s+(eq|ne|co|sw|ew|gt|ge|lt|le)\s+""([^""]*)""$", RegexOptions.IgnoreCase)] private static partial Regex FilterRegex(); // attrPath SP pr (presence — no value) [GeneratedRegex(@"^(\S+)\s+pr$", RegexOptions.IgnoreCase)] private static partial Regex PresenceRegex(); } Path: redb-identity/src/redb.Identity.Core/Routes/Processors/ScimGroupProcessor.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/Routes/Processors/ScimGroupProcessor.cs ---- using System.Text.Json; using Microsoft.Extensions.Logging; using redb.Core; using redb.Core.Models.Entities; using redb.Core.Query; using redb.Core.Services; using redb.Identity.Contracts.Scim; using redb.Identity.Core.Models; using redb.Identity.Core.Services; using redb.Route.Abstractions; using redb.Route.RedbCore.Extensions; using redb.Identity.Contracts.Routes; namespace redb.Identity.Core.Routes.Processors; /// /// SCIM 2.0 Groups endpoint processor (RFC 7644 §3.2–3.5). /// Dispatches on "operation" header: list, read, create, replace, patch, delete. /// Maps SCIM Group resources to PROPS via . /// internal sealed class ScimGroupProcessor : IProcessor { private readonly IRouteContext _context; private readonly string? _redbName; private readonly ILogger? _logger; private readonly IBackgroundDeletionService? _backgroundDeletion; public ScimGroupProcessor(IRouteContext context, string? redbName = null, ILogger? logger = null, IBackgroundDeletionService? backgroundDeletion = null) { _context = context; _redbName = redbName; _logger = logger; _backgroundDeletion = backgroundDeletion; } public async Task Process(IExchange exchange, CancellationToken ct = default) { var redb = _context.GetRedbService(_redbName, exchange); var svc = new GroupService(redb, _backgroundDeletion); var operation = exchange.In.GetHeader("operation") ?? throw new InvalidOperationException("Missing 'operation' header"); switch (operation) { case "list": await List(svc, redb, exchange, ct); break; case "read": await Read(svc, redb, exchange, ct); break; // Group names are unique (by GroupNames.Key). The name is the first write of a create and // of a replace, so a taken name is answered here with nothing written yet. A patch checks // its new name before any write instead (see Patch). case "create": case "replace": try { if (operation == "create") await Create(svc, redb, exchange, ct); else await Replace(svc, redb, exchange, ct); } catch (global::redb.Core.Exceptions.RedbUniqueViolationException ex) when (ex.Kind == global::redb.Core.Exceptions.RedbUniqueViolationKind.ObjectKey) { IdentityProcessorHelpers.CountUniqueViolation(_context, exchange, ex); SetScimError(exchange, 409, "uniqueness", "displayName is already the name of another group"); } break; case "patch": await Patch(svc, redb, exchange, ct); break; case "delete": await Delete(svc, exchange, ct); break; default: SetScimError(exchange, 400, null, $"Unknown SCIM operation: {operation}"); break; } } // ── List (GET /Groups) ────────────────────────────────────── private static string GetBaseUrl(IExchange exchange) => exchange.In.GetHeader("scim.BaseUrl") ?? string.Empty; private static async Task List(IGroupService svc, IRedbService redb, IExchange exchange, CancellationToken ct) { var baseUrl = GetBaseUrl(exchange); var dict = exchange.In.Body as Dictionary ?? new(); var startIndex = GetInt(dict, "startIndex", 1); var count = Math.Min(GetInt(dict, "count", 25), 100); var filterStr = dict.GetValueOrDefault("filter")?.ToString(); var sortBy = dict.GetValueOrDefault("sortBy")?.ToString(); var sortOrder = dict.GetValueOrDefault("sortOrder")?.ToString(); var filter = ScimFilterParser.Parse(filterStr); // ── Filtered queries (displayName only) ── if (filter is not null) { if (filter.Attribute != "displayname") { SetScimError(exchange, 400, "invalidFilter", $"Unsupported filter attribute: {filter.Attribute}. Supported: displayName"); return; } // Build base query with filter IRedbQueryable q; switch (filter.Operator) { case "eq": var eqKey = global::redb.Identity.Core.Services.GroupNames.Key(filter.Value); q = redb.Query() // displayName is not case-exact (RFC 7643 4.2): compare by the name key. .WhereRedb(o => o.ParentId == null && o.ValueUnique == eqKey); break; case "ne": q = redb.Query() .WhereRedb(o => o.ParentId == null && o.Name != filter.Value); break; case "sw": q = redb.Query() .WhereRedb(o => o.ParentId == null && o.Name.StartsWith(filter.Value)); break; case "co": q = redb.Query() .WhereRedb(o => o.ParentId == null && o.Name.Contains(filter.Value)); break; case "pr": // displayName pr — all groups have a name, return all q = redb.Query() .WhereRedb(o => o.ParentId == null); break; default: SetScimError(exchange, 400, "invalidFilter", $"Unsupported operator: {filter.Operator}. Supported: eq, ne, sw, co, pr"); return; } // Total before pagination var filteredTotal = await q.CountAsync(); // Apply sort + pagination var filteredOffset = Math.Max(startIndex - 1, 0); var ordered = ApplyGroupSort(q, sortBy, sortOrder); var matched = await ordered.Skip(filteredOffset).Take(count).ToListAsync(); var filteredMembersByGroup = await svc.GetMembersByGroupIdsAsync( matched.Select(g => g.id), ct); var resources = new List(matched.Count); foreach (var g in matched) { filteredMembersByGroup.TryGetValue(g.id, out var members); resources.Add(await MapToScimGroup(g, members, redb, baseUrl)); } SetResult(exchange, new ScimListResponse { TotalResults = filteredTotal, StartIndex = startIndex, ItemsPerPage = resources.Count, Resources = resources }); return; } // ── No filter → server-side paginated query ── var baseQ = redb.Query() .WhereRedb(o => o.ParentId == null); var total = await baseQ.CountAsync(); var offset = Math.Max(startIndex - 1, 0); var orderedBase = ApplyGroupSort(baseQ, sortBy, sortOrder); var page = await orderedBase.Skip(offset).Take(count).ToListAsync(); var membersByGroup = await svc.GetMembersByGroupIdsAsync( page.Select(g => g.id), ct); var scimGroups = new List(page.Count); foreach (var g in page) { membersByGroup.TryGetValue(g.id, out var members); scimGroups.Add(await MapToScimGroup(g, members, redb, baseUrl)); } SetResult(exchange, new ScimListResponse { TotalResults = total, StartIndex = startIndex, ItemsPerPage = scimGroups.Count, Resources = scimGroups }); } // ── Read (GET /Groups/{id}) ───────────────────────────────── private static async Task Read(IGroupService svc, IRedbService redb, IExchange exchange, CancellationToken ct) { var id = ExtractResourceId(exchange); if (id is null) { SetScimError(exchange, 400, null, "Resource id is required"); return; } var group = await svc.GetGroupAsync(id.Value, ct); if (group is null) { SetScimError(exchange, 404, null, $"Group {id} not found"); return; } var members = await svc.GetMembersAsync(id.Value, ct); SetResult(exchange, await MapToScimGroup(group, members, redb, GetBaseUrl(exchange))); SetETagHeader(exchange, group.hash); } // ── Create (POST /Groups) ─────────────────────────────────── private static async Task Create(IGroupService svc, IRedbService redb, IExchange exchange, CancellationToken ct) { var scimGroup = exchange.In.Body as ScimGroup; if (scimGroup is null || string.IsNullOrEmpty(scimGroup.DisplayName)) { SetScimError(exchange, 400, null, "displayName is required"); return; } var group = await svc.CreateGroupAsync(scimGroup.DisplayName, "scim", null, ct); // I8: Store SCIM externalId as PROPS prop if (!string.IsNullOrEmpty(scimGroup.ExternalId)) { group.Props ??= new GroupProps(); group.Props.ExternalId = scimGroup.ExternalId; await redb.SaveAsync(group); } // Add initial members if provided (batch) if (scimGroup.Members is { Count: > 0 }) { var memberIds = scimGroup.Members .Select(m => long.TryParse(m.Value, out var uid) && uid > 0 ? uid : 0) .Where(uid => uid > 0).ToList(); if (memberIds.Count > 0) await svc.AddMembersAsync(group.id, memberIds, "member", ct); } var members = await svc.GetMembersAsync(group.id, ct); SetResult(exchange, await MapToScimGroup(group, members, redb, GetBaseUrl(exchange))); // I1: RFC 7644 §3.3 — return 201 Created with Location header exchange.Out!.Headers["scim.ResponseCode"] = 201; exchange.Out!.Headers["scim.Location"] = $"/scim/v2/Groups/{group.id}"; exchange.Properties["identity-event-type"] = IdentityAuditEventIds.ScimGroupCreated; exchange.Properties["identity-event-data"] = new { GroupId = group.id, Name = scimGroup.DisplayName }; } // ── Replace (PUT /Groups/{id}) ────────────────────────────── private static async Task Replace( IGroupService svc, IRedbService redb, IExchange exchange, CancellationToken ct) { var scimGroup = exchange.In.Body as ScimGroup; if (scimGroup is null || string.IsNullOrEmpty(scimGroup.Id)) { SetScimError(exchange, 400, null, "Resource id and body are required"); return; } if (!long.TryParse(scimGroup.Id, out var id) || id <= 0) { SetScimError(exchange, 400, null, "Invalid resource id"); return; } var existing = await svc.GetGroupAsync(id, ct); if (existing is null) { SetScimError(exchange, 404, null, $"Group {id} not found"); return; } // ETag precondition check if (!CheckIfMatch(exchange, existing.hash)) return; // Update group name await svc.UpdateGroupAsync(id, scimGroup.DisplayName, null, null, ct); // I8: Update SCIM externalId var reloaded = await svc.GetGroupAsync(id, ct); if (reloaded is not null) { reloaded.Props ??= new GroupProps(); reloaded.Props.ExternalId = scimGroup.ExternalId; // null clears it await redb.SaveAsync(reloaded); } // Replace members: batch remove + batch add await svc.RemoveAllMembersAsync(id, ct); if (scimGroup.Members is { Count: > 0 }) { var memberIds = scimGroup.Members .Select(m => long.TryParse(m.Value, out var uid) && uid > 0 ? uid : 0) .Where(uid => uid > 0).ToList(); if (memberIds.Count > 0) await svc.AddMembersAsync(id, memberIds, "member", ct); } var updatedGroup = await svc.GetGroupAsync(id, ct); var updatedMembers = await svc.GetMembersAsync(id, ct); SetResult(exchange, await MapToScimGroup(updatedGroup!, updatedMembers, redb, GetBaseUrl(exchange))); SetETagHeader(exchange, updatedGroup?.hash); exchange.Properties["identity-event-type"] = IdentityAuditEventIds.ScimGroupReplaced; exchange.Properties["identity-event-data"] = new { GroupId = id }; } // ── Patch (PATCH /Groups/{id}) ────────────────────────────── private static async Task Patch( IGroupService svc, IRedbService redb, IExchange exchange, CancellationToken ct) { if (exchange.In.Body is not Dictionary dict) { SetScimError(exchange, 400, null, "Invalid patch request"); return; } var idStr = dict.GetValueOrDefault("id")?.ToString(); if (!long.TryParse(idStr, out var id) || id <= 0) { SetScimError(exchange, 400, null, "Resource id is required"); return; } var patch = dict.GetValueOrDefault("patch") as ScimPatchRequest; if (patch is null || patch.Operations.Count == 0) { SetScimError(exchange, 400, null, "PatchOp request with Operations is required"); return; } var group = await svc.GetGroupAsync(id, ct); if (group is null) { SetScimError(exchange, 404, null, $"Group {id} not found"); return; } // ETag precondition check if (!CheckIfMatch(exchange, group.hash)) return; // A new displayName that another group already holds is refused before any operation of the // patch is applied, so a refused patch leaves the group as it was. foreach (var op in patch.Operations) { if (op.Path?.ToLowerInvariant() != "displayname" || op.Op?.ToLowerInvariant() is not ("add" or "replace")) continue; if (GetStringValue(op.Value) is { } wanted && await svc.FindGroupByNameAsync(wanted, ct) is { } holder && holder.Id != id) { SetScimError(exchange, 409, "uniqueness", "displayName is already the name of another group"); return; } } foreach (var op in patch.Operations) { var normalizedOp = op.Op?.ToLowerInvariant(); var path = op.Path?.ToLowerInvariant(); switch (path) { case "displayname": if (normalizedOp is "add" or "replace") { var newName = GetStringValue(op.Value); if (newName is not null) await svc.UpdateGroupAsync(id, newName, null, null, ct); } break; case "externalid": if (normalizedOp is "add" or "replace") { var extId = GetStringValue(op.Value); group.Props ??= new GroupProps(); group.Props.ExternalId = extId; await redb.SaveAsync(group); } else if (normalizedOp is "remove") { group.Props ??= new GroupProps(); group.Props.ExternalId = null; await redb.SaveAsync(group); } break; case "members": if (normalizedOp is "add") { // Batch-add members from value array await AddMembersFromValue(svc, id, op.Value, ct); } else if (normalizedOp is "replace") { // Batch replace: remove all + batch add await svc.RemoveAllMembersAsync(id, ct); await AddMembersFromValue(svc, id, op.Value, ct); } else if (normalizedOp is "remove") { // Batch remove all members await svc.RemoveAllMembersAsync(id, ct); } break; default: // Check for members[value eq "userId"] path (Azure Entra pattern) if (path is not null && path.StartsWith("members[")) { var memberId = ExtractMemberFilterId(path); if (memberId is not null) { if (normalizedOp is "remove") { try { await svc.RemoveMemberAsync(id, memberId.Value, ct); } catch (InvalidOperationException) { /* already removed */ } } } } break; } } var updatedGroup = await svc.GetGroupAsync(id, ct); var members = await svc.GetMembersAsync(id, ct); SetResult(exchange, await MapToScimGroup(updatedGroup!, members, redb, GetBaseUrl(exchange))); SetETagHeader(exchange, updatedGroup?.hash); exchange.Properties["identity-event-type"] = IdentityAuditEventIds.ScimGroupPatched; exchange.Properties["identity-event-data"] = new { GroupId = id }; } // ── Delete (DELETE /Groups/{id}) ──────────────────────────── private static async Task Delete(IGroupService svc, IExchange exchange, CancellationToken ct) { var id = ExtractResourceId(exchange); if (id is null) { SetScimError(exchange, 400, null, "Resource id is required"); return; } var group = await svc.GetGroupAsync(id.Value, ct); if (group is null) { SetScimError(exchange, 404, null, $"Group {id} not found"); return; } // ETag precondition check if (!CheckIfMatch(exchange, group.hash)) return; await svc.DeleteGroupAsync(id.Value, ct); exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = null; exchange.Properties["identity-event-type"] = IdentityAuditEventIds.ScimGroupDeleted; exchange.Properties["identity-event-data"] = new { GroupId = id.Value }; } // ── Mapping ───────────────────────────────────────────────── private static async Task MapToScimGroup( RedbObject group, List? members = null, IRedbService? redb = null, string? baseUrl = null) { var scimGroup = new ScimGroup { Id = group.id.ToString(), ExternalId = group.Props?.ExternalId, DisplayName = group.name, Meta = new ScimMeta { ResourceType = "Group", Created = group.date_create, LastModified = group.date_modify, Location = $"{baseUrl}/scim/v2/Groups/{group.id}", Version = group.hash.HasValue ? $"W/\"{group.hash.Value}\"" : null } }; if (members is { Count: > 0 }) { // I7+I4: Batch-load user display names in a single query Dictionary displayNames = new(); if (redb is not null) { var memberIds = members.Select(m => m.UserId); var users = await redb.UserProvider.GetUsersByIdsAsync(memberIds); foreach (var u in users) displayNames[u.Id] = u.Name; } scimGroup.Members = new List(members.Count); foreach (var m in members) { displayNames.TryGetValue(m.UserId, out var display); scimGroup.Members.Add(new ScimMemberRef { Value = m.UserId.ToString(), Display = display, Ref = $"{baseUrl}/scim/v2/Users/{m.UserId}" }); } } return scimGroup; } // ── PATCH helpers ─────────────────────────────────────────── private static async Task AddMembersFromValue( IGroupService svc, long groupId, JsonElement? value, CancellationToken ct) { if (value is null) return; var userIds = new List(); if (value.Value.ValueKind == JsonValueKind.Array) { foreach (var elem in value.Value.EnumerateArray()) { if (elem.TryGetProperty("value", out var v) && long.TryParse(v.GetString(), out var userId) && userId > 0) userIds.Add(userId); } } else if (value.Value.ValueKind == JsonValueKind.Object) { if (value.Value.TryGetProperty("value", out var v) && long.TryParse(v.GetString(), out var userId) && userId > 0) userIds.Add(userId); } if (userIds.Count > 0) await svc.AddMembersAsync(groupId, userIds, "member", ct); } /// /// Extracts userId from path like members[value eq "123"]. /// Azure Entra sends PATCH remove with this path pattern. /// private static long? ExtractMemberFilterId(string path) { // members[value eq "123"] var match = System.Text.RegularExpressions.Regex.Match( path, @"members\[value\s+eq\s+""(\d+)""\]", System.Text.RegularExpressions.RegexOptions.IgnoreCase); if (match.Success && long.TryParse(match.Groups[1].Value, out var id)) return id; return null; } // ── Helpers ───────────────────────────────────────────────── private static long? ExtractResourceId(IExchange exchange) { if (exchange.In.Body is Dictionary dict && dict.TryGetValue("id", out var idVal) && idVal is not null && long.TryParse(idVal.ToString(), out var id) && id > 0) return id; return null; } private static string? GetStringValue(JsonElement? value) { if (value is null) return null; return value.Value.ValueKind == JsonValueKind.String ? value.Value.GetString() : value.Value.GetRawText(); } private static void SetScimError(IExchange exchange, int status, string? scimType, string? detail) { exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new ScimError { Status = status.ToString(), ScimType = scimType, Detail = detail }; } private static void SetResult(IExchange exchange, object body) { exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = body; } private static int GetInt(Dictionary dict, string key, int defaultValue) { if (dict.TryGetValue(key, out var val) && val is not null && int.TryParse(val.ToString(), out var result)) return result; return defaultValue; } /// /// Applies SCIM sortBy/sortOrder to a group query. Defaults to Name ascending. /// private static IRedbQueryable ApplyGroupSort( IRedbQueryable query, string? sortBy, string? sortOrder) { bool desc = string.Equals(sortOrder, "descending", StringComparison.OrdinalIgnoreCase); return (sortBy?.ToLowerInvariant()) switch { "id" => desc ? query.OrderByDescendingRedb(x => x.Id) : query.OrderByRedb(x => x.Id), "meta.created" => desc ? query.OrderByDescendingRedb(x => x.DateCreate) : query.OrderByRedb(x => x.DateCreate), "meta.lastmodified" => desc ? query.OrderByDescendingRedb(x => x.DateModify) : query.OrderByRedb(x => x.DateModify), _ => desc ? query.OrderByDescendingRedb(x => x.Name) : query.OrderByRedb(x => x.Name), }; } private static bool CheckIfMatch(IExchange exchange, Guid? currentHash) { var ifMatch = exchange.In.GetHeader("scim.IfMatch"); if (string.IsNullOrEmpty(ifMatch)) return true; if (ifMatch == "*") return true; var expected = ifMatch.Replace("W/", "").Trim('"'); var actual = currentHash?.ToString(); if (!string.Equals(expected, actual, StringComparison.OrdinalIgnoreCase)) { SetScimError(exchange, 412, null, "ETag precondition failed — resource has been modified"); return false; } return true; } private static void SetETagHeader(IExchange exchange, Guid? hash) { if (hash.HasValue) exchange.Out!.Headers["scim.ETag"] = $"W/\"{hash.Value}\""; } } Path: redb-identity/src/redb.Identity.Core/Routes/Processors/ScimUserProcessor.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/Routes/Processors/ScimUserProcessor.cs ---- using System.Text.Json; using Microsoft.Extensions.DependencyInjection; using redb.Core; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Core.Query; using redb.Core.Services; using redb.Identity.Contracts.Scim; using redb.Identity.Core.Models; using redb.Identity.Core.Module; using redb.Identity.Core.Services; using redb.Route.Abstractions; using redb.Route.RedbCore.Extensions; using CoreCreateUserRequest = redb.Core.Models.Users.CreateUserRequest; using CoreUpdateUserRequest = redb.Core.Models.Users.UpdateUserRequest; using redb.Identity.Contracts.Routes; namespace redb.Identity.Core.Routes.Processors; /// /// SCIM 2.0 Users endpoint processor (RFC 7644 §3.2–3.5). /// Dispatches on "operation" header: list, read, create, replace, patch, delete. /// Maps SCIM User resources to core _users table + PROPS . /// internal sealed class ScimUserProcessor : IProcessor { private readonly IRouteContext _context; private readonly string? _redbName; public ScimUserProcessor(IRouteContext context, string? redbName = null) { _context = context; _redbName = redbName; } public async Task Process(IExchange exchange, CancellationToken ct = default) { var redb = _context.GetRedbService(_redbName, exchange); var operation = exchange.In.GetHeader("operation") ?? throw new InvalidOperationException("Missing 'operation' header"); switch (operation) { case "list": await List(redb, exchange, ct); break; case "read": await Read(redb, exchange, ct); break; case "create": await Create(redb, exchange, ct); break; case "replace": await Replace(redb, exchange, ct); break; case "patch": await Patch(redb, exchange, ct); break; case "delete": await Delete(redb, exchange, ct); break; default: SetScimError(exchange, 400, null, $"Unknown SCIM operation: {operation}"); break; } } private static string GetBaseUrl(IExchange exchange) => exchange.In.GetHeader("scim.BaseUrl") ?? string.Empty; // ── List (GET /Users) ─────────────────────────────────────── private async Task List(IRedbService redb, IExchange exchange, CancellationToken ct) { var baseUrl = GetBaseUrl(exchange); var dict = exchange.In.Body as Dictionary ?? new(); var startIndex = GetInt(dict, "startIndex", 1); var count = Math.Min(GetInt(dict, "count", 25), 100); var filterStr = dict.GetValueOrDefault("filter")?.ToString(); var sortBy = dict.GetValueOrDefault("sortBy")?.ToString(); var sortOrder = dict.GetValueOrDefault("sortOrder")?.ToString(); var filter = ScimFilterParser.Parse(filterStr); // ── Filtered queries ── if (filter is not null) { // userName eq → direct login lookup (fast path) if (filter is { Attribute: "username", Operator: "eq" }) { var user = await redb.UserProvider.GetUserByLoginAsync(filter.Value); if (user is null || !user.Enabled) { SetResult(exchange, EmptyList(startIndex)); return; } var oidc = await LoadOidcProps(redb, user.Id); SetResult(exchange, new ScimListResponse { TotalResults = 1, StartIndex = startIndex, ItemsPerPage = 1, Resources = [MapToScimUser(user, oidc, baseUrl: baseUrl, managerNames: await ResolveManagerNamesAsync(redb, [oidc?.Props]))] }); return; } // externalId eq → PROPS query on UserProps.ScimExternalId if (filter is { Attribute: "externalid", Operator: "eq" }) { var oidcObj = await redb.Query() .Where(p => p.ScimExternalId == filter.Value) .FirstOrDefaultAsync(); if (oidcObj?.key is null) { SetResult(exchange, EmptyList(startIndex)); return; } var user = await redb.UserProvider.GetUserByIdAsync(oidcObj.key.Value); if (user is null || !user.Enabled) { SetResult(exchange, EmptyList(startIndex)); return; } SetResult(exchange, new ScimListResponse { TotalResults = 1, StartIndex = startIndex, ItemsPerPage = 1, Resources = [MapToScimUser(user, oidcObj, baseUrl: baseUrl, managerNames: await ResolveManagerNamesAsync(redb, [oidcObj?.Props]))] }); return; } // Build UserSearchCriteria from SCIM filter for userName/displayName/emails.value var criteria = BuildUserCriteria(filter); if (criteria is not null) { criteria.ExcludeSystemUsers = true; criteria.Enabled = true; criteria.Limit = count; criteria.Offset = Math.Max(startIndex - 1, 0); ApplySortToCriteria(criteria, sortBy, sortOrder); // Count with same filters but no LIMIT/OFFSET var countCrit = BuildUserCriteria(filter)!; countCrit.ExcludeSystemUsers = true; countCrit.Enabled = true; var filteredTotal = await redb.UserProvider.CountUsersAsync(countCrit); var matched = await redb.UserProvider.GetUsersAsync(criteria); var resources = await BatchMapUsers(redb, matched, baseUrl); SetResult(exchange, new ScimListResponse { TotalResults = filteredTotal, StartIndex = startIndex, ItemsPerPage = resources.Count, Resources = resources }); return; } // Unsupported filter → error SetScimError(exchange, 400, "invalidFilter", $"Unsupported filter: {filter.Attribute} {filter.Operator}. " + "Supported attributes: userName, displayName, emails.value, externalId. " + "Supported operators: eq, sw, co, pr"); return; } // ── No filter → paginated list ── var offset = Math.Max(startIndex - 1, 0); // SCIM 1-based → 0-based var searchCriteria = new redb.Core.Models.Users.UserSearchCriteria { ExcludeSystemUsers = true, Enabled = true, Limit = count, Offset = offset }; ApplySortToCriteria(searchCriteria, sortBy, sortOrder); var pageUsers = await redb.UserProvider.GetUsersAsync(searchCriteria); // Count with same filters but no LIMIT/OFFSET — lightweight SELECT COUNT(*) var countCriteria = new redb.Core.Models.Users.UserSearchCriteria { ExcludeSystemUsers = true, Enabled = true }; var total = await redb.UserProvider.CountUsersAsync(countCriteria); // Batch-load PROPS props for the page in a single query var userIds = pageUsers.Select(u => (long?)u.Id).ToList(); var oidcObjects = userIds.Count > 0 ? await redb.Query() .WhereRedb(o => userIds.Contains(o.Key)) .ToListAsync() : new List>(); var oidcDict = oidcObjects .Where(o => o.key.HasValue) .ToDictionary(o => o.key!.Value); var scimUsers = new List(pageUsers.Count); // One resolve for the whole page — not one per row. var pageManagers = await ResolveManagerNamesAsync(redb, oidcDict.Values.Select(o => o?.Props)); foreach (var u in pageUsers) { oidcDict.TryGetValue(u.Id, out var oidc); scimUsers.Add(MapToScimUser(u, oidc, baseUrl: baseUrl, managerNames: pageManagers)); } SetResult(exchange, new ScimListResponse { TotalResults = total, StartIndex = startIndex, ItemsPerPage = scimUsers.Count, Resources = scimUsers }); } // ── Read (GET /Users/{id}) ────────────────────────────────── private async Task Read(IRedbService redb, IExchange exchange, CancellationToken ct) { var id = ExtractResourceId(exchange); if (id is null) { SetScimError(exchange, 400, null, "Resource id is required"); return; } var coreUser = await redb.UserProvider.GetUserByIdAsync(id.Value); if (coreUser is null || !coreUser.Enabled) { SetScimError(exchange, 404, null, $"User {id} not found"); return; } var oidc = await LoadOidcProps(redb, coreUser.Id); var groups = await LoadUserGroups(redb, coreUser.Id); SetResult(exchange, MapToScimUser(coreUser, oidc, groups, GetBaseUrl(exchange), managerNames: await ResolveManagerNamesAsync(redb, [oidc?.Props]))); SetETagHeader(exchange, coreUser.Hash); } // ── Create (POST /Users) ──────────────────────────────────── private async Task Create(IRedbService redb, IExchange exchange, CancellationToken ct) { var scimUser = exchange.In.Body as ScimUser; if (scimUser is null || string.IsNullOrEmpty(scimUser.UserName)) { SetScimError(exchange, 400, null, "userName is required"); return; } // C4: Validate userName var userName = scimUser.UserName.Trim(); if (userName.Length == 0) { SetScimError(exchange, 400, null, "userName cannot be empty"); return; } if (userName.Length < 3 || userName.Length > 200) { SetScimError(exchange, 400, null, "userName must be between 3 and 200 characters"); return; } scimUser.UserName = userName; // I5: Generate a strong password if not provided. // H10: when the SCIM client supplies a password, run it through the full policy // gate (length + composition + history + breach). Auto-generated 24-char secrets // skip validation — they are produced by GeneratePassword() which already meets // every reasonable rule and is never seen by a human. string password; if (scimUser.Password is { Length: > 0 }) { var pwErr = await IdentityProcessorHelpers.ValidatePasswordPolicyAsync( exchange, _context, scimUser.Password, userId: null, "password", ct); if (pwErr != null) { SetScimError(exchange, 400, "invalidValue", pwErr); return; } password = scimUser.Password; } else { password = GeneratePassword(24); } var primaryEmail = GetPrimaryEmail(scimUser); var primaryPhone = GetPrimaryPhone(scimUser); // C5: Create directly, rely on DB constraint for uniqueness IRedbUser coreUser; try { coreUser = await redb.UserProvider.CreateUserAsync(new CoreCreateUserRequest { Login = scimUser.UserName, Password = password, Name = scimUser.DisplayName ?? scimUser.UserName, Email = primaryEmail, Phone = primaryPhone, Enabled = scimUser.Active }); } catch (InvalidOperationException ex) when (ex.Message.Contains("already taken")) { SetScimError(exchange, 409, "uniqueness", $"userName '{scimUser.UserName}' already exists"); return; } catch (Exception ex) when (IdentityProcessorHelpers.IsUniqueViolation(ex)) { // The loser of a concurrent create is refused by the database, and each provider words // that in its own way (SQLite: "UNIQUE constraint failed", which a case-sensitive search // for "unique" missed). Left uncaught, the builder-level handler answered 409 with the // management error document, not the SCIM one a SCIM client parses (RFC 7644 3.12). // The detail names the attribute that collided: _users has two unique keys, and naming // userName when the e-mail was taken sends an operator after the wrong field. IdentityProcessorHelpers.CountUniqueViolation(_context, exchange, ex); SetScimError(exchange, 409, "uniqueness", IdentityProcessorHelpers.IsEmailUniqueViolation(ex) ? $"email '{primaryEmail}' already exists" : $"userName '{scimUser.UserName}' already exists"); return; } // PROPS OIDC extension. value_guid: stable, instance-unique public identity used // as the OIDC `sub` claim. var oidcObj = new RedbObject(new UserProps { UserId = coreUser.Id, // V4-UNIQUE GivenName = scimUser.Name?.GivenName, FamilyName = scimUser.Name?.FamilyName, Picture = scimUser.Photos?.FirstOrDefault()?.Value, ScimExternalId = scimUser.ExternalId, Address = MapScimAddress(scimUser.Addresses?.FirstOrDefault()) }); ApplyEnterprise(scimUser.Enterprise, oidcObj.Props); oidcObj.name = coreUser.Login; oidcObj.key = coreUser.Id; oidcObj.value_guid = Guid.NewGuid(); await redb.SaveAsync(oidcObj); // H10 — record initial password in history (covers both client-supplied and // auto-generated passwords; reuse blocked on subsequent admin rotation). await IdentityProcessorHelpers.RecordPasswordHistoryAsync( exchange, _context, redb, coreUser.Id, password, ct); // I1: RFC 7644 §3.3 — return 201 Created with Location + ETag headers. // RFC 7644 §3.14 requires the version (ETag) to be included on every resource // representation when versioning is advertised in ServiceProviderConfig; without // it the client cannot acquire the initial ETag for subsequent If-Match writes. SetResult(exchange, MapToScimUser(coreUser, oidcObj, baseUrl: GetBaseUrl(exchange), managerNames: await ResolveManagerNamesAsync(redb, [oidcObj.Props]))); exchange.Out!.Headers["scim.ResponseCode"] = 201; exchange.Out!.Headers["scim.Location"] = $"/scim/v2/Users/{coreUser.Id}"; SetETagHeader(exchange, coreUser.Hash); exchange.Properties["identity-event-type"] = IdentityAuditEventIds.ScimUserCreated; exchange.Properties["identity-event-data"] = new { UserId = coreUser.Id.ToString(), Login = scimUser.UserName }; } // ── Replace (PUT /Users/{id}) ─────────────────────────────── private async Task Replace(IRedbService redb, IExchange exchange, CancellationToken ct) { var scimUser = exchange.In.Body as ScimUser; if (scimUser is null || string.IsNullOrEmpty(scimUser.Id)) { SetScimError(exchange, 400, null, "Resource id and body are required"); return; } if (!long.TryParse(scimUser.Id, out var id) || id <= 0) { SetScimError(exchange, 400, null, "Invalid resource id"); return; } var coreUser = await redb.UserProvider.GetUserByIdAsync(id); if (coreUser is null || !coreUser.Enabled) { SetScimError(exchange, 404, null, $"User {id} not found"); return; } // ETag precondition check if (!CheckIfMatch(exchange, coreUser.Hash)) return; var primaryEmail = GetPrimaryEmail(scimUser); var primaryPhone = GetPrimaryPhone(scimUser); // userName (_login) is immutable — compare case-insensitively since logins are stored lowercase if (!string.IsNullOrEmpty(scimUser.UserName) && !string.Equals(scimUser.UserName, coreUser.Login, StringComparison.OrdinalIgnoreCase)) { SetScimError(exchange, 400, "mutability", "Attribute 'userName' is immutable and cannot be changed after creation"); return; } var updateReq = new CoreUpdateUserRequest { Name = scimUser.DisplayName ?? scimUser.UserName, Email = primaryEmail, Phone = primaryPhone, Enabled = scimUser.Active }; coreUser = await redb.UserProvider.UpdateUserAsync(coreUser, updateReq); // Full replace of PROPS extension var oidcObj = await LoadOidcProps(redb, id) ?? new RedbObject(new UserProps()) { value_guid = Guid.NewGuid() }; oidcObj.name = coreUser.Login; oidcObj.key = coreUser.Id; oidcObj.Props = new UserProps { UserId = coreUser.Id, // V4-UNIQUE GivenName = scimUser.Name?.GivenName, FamilyName = scimUser.Name?.FamilyName, Picture = scimUser.Photos?.FirstOrDefault()?.Value, ScimExternalId = scimUser.ExternalId, Address = MapScimAddress(scimUser.Addresses?.FirstOrDefault()) }; // PUT is a full replace (RFC 7644 §3.5.1): an absent extension means "the user has none", // so ApplyEnterprise writing nulls into a fresh UserProps is the correct outcome, not a bug. ApplyEnterprise(scimUser.Enterprise, oidcObj.Props); await redb.SaveAsync(oidcObj); SetResult(exchange, MapToScimUser(coreUser, oidcObj, baseUrl: GetBaseUrl(exchange), managerNames: await ResolveManagerNamesAsync(redb, [oidcObj.Props]))); SetETagHeader(exchange, coreUser.Hash); exchange.Properties["identity-event-type"] = IdentityAuditEventIds.ScimUserReplaced; exchange.Properties["identity-event-data"] = new { UserId = coreUser.Id.ToString(), Login = coreUser.Login }; } // ── Patch (PATCH /Users/{id}) ─────────────────────────────── private async Task Patch(IRedbService redb, IExchange exchange, CancellationToken ct) { if (exchange.In.Body is not Dictionary dict) { SetScimError(exchange, 400, null, "Invalid patch request"); return; } var idStr = dict.GetValueOrDefault("id")?.ToString(); if (!long.TryParse(idStr, out var id) || id <= 0) { SetScimError(exchange, 400, null, "Resource id is required"); return; } var patch = dict.GetValueOrDefault("patch") as ScimPatchRequest; if (patch is null || patch.Operations.Count == 0) { SetScimError(exchange, 400, null, "PatchOp request with Operations is required"); return; } var coreUser = await redb.UserProvider.GetUserByIdAsync(id); if (coreUser is null || !coreUser.Enabled) { SetScimError(exchange, 404, null, $"User {id} not found"); return; } // ETag precondition check if (!CheckIfMatch(exchange, coreUser.Hash)) return; var oidcObj = await LoadOidcProps(redb, id); var oidcCreated = false; if (oidcObj is null) { oidcObj = new RedbObject(new UserProps { UserId = coreUser.Id }); oidcObj.name = coreUser.Login; oidcObj.key = coreUser.Id; oidcObj.value_guid = Guid.NewGuid(); oidcCreated = true; } var coreUpdate = new CoreUpdateUserRequest(); bool coreChanged = false; bool oidcChanged = false; string? newPassword = null; foreach (var op in patch.Operations) { var normalizedOp = op.Op?.ToLowerInvariant(); var path = op.Path?.ToLowerInvariant(); // RFC 7644 §3.5.2 — an extension attribute is addressed by its fully-qualified URN, e.g. // "urn:ietf:params:scim:schemas:extension:enterprise:2.0:User:department" // Strip the namespace and fall through to the plain attribute name. We also accept the // bare name ("department"): it is what several provisioning clients send in practice, and // it is unambiguous here because no core User attribute carries any of these names. const string enterprisePrefix = ScimConstants.EnterpriseUserSchema + ":"; if (path is not null && path.StartsWith( enterprisePrefix, StringComparison.OrdinalIgnoreCase)) { path = path[enterprisePrefix.Length..]; } switch (path) { case "employeenumber": oidcObj.Props.EmployeeNumber = normalizedOp is "remove" ? null : GetStringValue(op.Value); oidcChanged = true; break; case "costcenter": oidcObj.Props.CostCenter = normalizedOp is "remove" ? null : GetStringValue(op.Value); oidcChanged = true; break; case "organization": oidcObj.Props.Organization = normalizedOp is "remove" ? null : GetStringValue(op.Value); oidcChanged = true; break; case "division": oidcObj.Props.Division = normalizedOp is "remove" ? null : GetStringValue(op.Value); oidcChanged = true; break; case "department": oidcObj.Props.Department = normalizedOp is "remove" ? null : GetStringValue(op.Value); oidcChanged = true; break; // `manager` is complex (§4.3): clients patch either the whole object or manager.value. // Both land on the same stored id — $ref and displayName are derived on read. case "manager": case "manager.value": oidcObj.Props.ManagerId = normalizedOp is "remove" ? null : GetManagerId(op.Value); oidcChanged = true; break; case "username": // userName (_login) is immutable at DB level (protect_system_users trigger) if (normalizedOp is "add" or "replace") { var newLogin = GetStringValue(op.Value); if (!string.Equals(newLogin, coreUser.Login, StringComparison.Ordinal)) { SetScimError(exchange, 400, "mutability", "Attribute 'userName' is immutable and cannot be changed after creation"); return; } } break; case "displayname": if (normalizedOp is "add" or "replace") { coreUpdate.Name = GetStringValue(op.Value); coreChanged = true; } break; case "active": if (normalizedOp is "add" or "replace") { coreUpdate.Enabled = GetBoolValue(op.Value) ?? true; coreChanged = true; } break; // I9: PATCH password support (write-only) case "password": if (normalizedOp is "add" or "replace") newPassword = GetStringValue(op.Value); break; case "name.givenname": if (normalizedOp is "add" or "replace") { oidcObj.Props.GivenName = GetStringValue(op.Value); oidcChanged = true; } else if (normalizedOp is "remove") { oidcObj.Props.GivenName = null; oidcChanged = true; } break; case "name.familyname": if (normalizedOp is "add" or "replace") { oidcObj.Props.FamilyName = GetStringValue(op.Value); oidcChanged = true; } else if (normalizedOp is "remove") { oidcObj.Props.FamilyName = null; oidcChanged = true; } break; case "externalid": if (normalizedOp is "add" or "replace") { oidcObj.Props.ScimExternalId = GetStringValue(op.Value); oidcChanged = true; } else if (normalizedOp is "remove") { oidcObj.Props.ScimExternalId = null; oidcChanged = true; } break; case "emails": if (normalizedOp is "add" or "replace") { var email = GetPrimaryMultiValue(op.Value); if (email is not null) { coreUpdate.Email = email; coreChanged = true; } } break; case "phonenumbers": if (normalizedOp is "add" or "replace") { var phone = GetPrimaryMultiValue(op.Value); if (phone is not null) { coreUpdate.Phone = phone; coreChanged = true; } } break; case null when normalizedOp is "add" or "replace": // No path → value is a partial resource (Azure Entra pattern) ApplyPartialResource(op.Value, coreUpdate, oidcObj.Props, ref coreChanged, ref oidcChanged); break; } } if (coreChanged) coreUser = await redb.UserProvider.UpdateUserAsync(coreUser, coreUpdate); // I9: Set password if patched (H10 — validate against policy first). var passwordChanged = !string.IsNullOrEmpty(newPassword); if (passwordChanged) { var pwErr = await IdentityProcessorHelpers.ValidatePasswordPolicyAsync( exchange, _context, redb, newPassword, coreUser.Id, "password", ct); if (pwErr != null) { SetScimError(exchange, 400, "invalidValue", pwErr); return; } await redb.UserProvider.SetPasswordAsync(coreUser, newPassword!); await IdentityProcessorHelpers.RecordPasswordHistoryAsync( exchange, _context, redb, coreUser.Id, newPassword!, ct); } if (oidcChanged || oidcCreated) await redb.SaveAsync(oidcObj); // C7: SCIM-driven password change must invalidate every existing session and // authorization for the user (same rule as the user-driven /change-password). // The user must re-authenticate with the new password. long sessionsRevoked = 0; if (passwordChanged) sessionsRevoked = await new SessionService(redb).LogoutAsync(coreUser.Id, ct); SetResult(exchange, MapToScimUser(coreUser, oidcObj, baseUrl: GetBaseUrl(exchange), managerNames: await ResolveManagerNamesAsync(redb, [oidcObj.Props]))); SetETagHeader(exchange, coreUser.Hash); exchange.Properties["identity-event-type"] = IdentityAuditEventIds.ScimUserPatched; exchange.Properties["identity-event-data"] = new { UserId = coreUser.Id.ToString(), Login = coreUser.Login, PasswordChanged = passwordChanged, SessionsRevoked = sessionsRevoked }; } // ── Delete (DELETE /Users/{id}) ───────────────────────────── private async Task Delete(IRedbService redb, IExchange exchange, CancellationToken ct) { var id = ExtractResourceId(exchange); if (id is null) { SetScimError(exchange, 400, null, "Resource id is required"); return; } var coreUser = await redb.UserProvider.GetUserByIdAsync(id.Value); if (coreUser is null) { SetScimError(exchange, 404, null, $"User {id} not found"); return; } // ETag precondition check if (!CheckIfMatch(exchange, coreUser.Hash)) return; // Delete PROPS extension first var oidcObj = await LoadOidcProps(redb, id.Value); if (oidcObj is not null) { var bg = _context.GetIdentityServiceOrDefault(exchange); await IdentityDeletionHelper.DeleteAsync(redb, bg, oidcObj.id); } // Soft-delete: disable user. UserProvider.DeleteUserAsync renames _login which is // blocked by the protect_system_users trigger ("Cannot change user login"). // Disabling achieves the same SCIM semantics: user is gone from active queries. await redb.UserProvider.UpdateUserAsync(coreUser, new CoreUpdateUserRequest { Enabled = false }); exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = null; exchange.Properties["identity-event-type"] = IdentityAuditEventIds.ScimUserDeleted; exchange.Properties["identity-event-data"] = new { Id = id.Value }; } // ── Data access helpers ───────────────────────────────────── private static long? ExtractResourceId(IExchange exchange) { if (exchange.In.Body is Dictionary dict && dict.TryGetValue("id", out var idVal) && idVal is not null && long.TryParse(idVal.ToString(), out var id) && id > 0) return id; return null; } private static async Task> BatchMapUsers( IRedbService redb, List users, string? baseUrl) { if (users.Count == 0) return new List(); var userIds = users.Select(u => (long?)u.Id).ToList(); var oidcObjects = await redb.Query() .WhereRedb(o => userIds.Contains(o.Key)) .ToListAsync(); var oidcDict = oidcObjects .Where(o => o.key.HasValue) .ToDictionary(o => o.key!.Value); var result = new List(users.Count); var bulkManagers = await ResolveManagerNamesAsync(redb, oidcDict.Values.Select(o => o?.Props)); foreach (var u in users) { oidcDict.TryGetValue(u.Id, out var oidc); result.Add(MapToScimUser(u, oidc, baseUrl: baseUrl, managerNames: bulkManagers)); } return result; } private static async Task?> LoadOidcProps(IRedbService redb, long userId) { return await redb.Query() .WhereRedb(o => o.Key == userId) .FirstOrDefaultAsync(); } private static async Task?> LoadUserGroups( IRedbService redb, long userId) { // Propagate errors instead of silently returning null \u2014 a SCIM client must NOT // receive a partial User resource missing its groups membership. Per RFC 7644 // a 500 from the server is the correct outcome when the backend is down. var svc = new GroupService(redb); return await svc.GetUserGroupsAsync(userId); } // ── SCIM ↔ Core mapping ───────────────────────────────────── /// /// Builds a from a parsed SCIM filter. /// Returns null when the filter attribute/operator combination is not supported. /// private static redb.Core.Models.Users.UserSearchCriteria? BuildUserCriteria( ScimFilterParser.ScimFilter filter) { var c = new redb.Core.Models.Users.UserSearchCriteria(); // pr (presence) — always present for these attributes on active users if (filter.Operator == "pr") { return filter.Attribute switch { "username" or "displayname" or "active" => c, // always present "emails.value" => c, // email may be null but presence means "has email" — we accept all _ => null }; } switch (filter.Attribute) { case "username": switch (filter.Operator) { case "eq": c.LoginExact = filter.Value; break; case "ne": c.LoginNotEqual = filter.Value; break; case "sw": c.LoginStartsWith = filter.Value; break; case "co": c.LoginPattern = filter.Value; break; default: return null; } break; case "displayname": switch (filter.Operator) { case "eq": c.NameExact = filter.Value; break; case "ne": c.NameNotEqual = filter.Value; break; case "sw": c.NameStartsWith = filter.Value; break; case "co": c.NamePattern = filter.Value; break; default: return null; } break; case "emails.value": switch (filter.Operator) { case "eq": c.EmailExact = filter.Value; break; case "ne": c.EmailNotEqual = filter.Value; break; case "sw": c.EmailStartsWith = filter.Value; break; case "co": c.EmailPattern = filter.Value; break; default: return null; } break; default: return null; } return c; } /// /// Maps SCIM sortBy/sortOrder query params to UserSearchCriteria fields. /// private static void ApplySortToCriteria( redb.Core.Models.Users.UserSearchCriteria criteria, string? sortBy, string? sortOrder) { if (!string.IsNullOrEmpty(sortBy)) { criteria.SortBy = sortBy.ToLowerInvariant() switch { "username" => redb.Core.Models.Users.UserSortField.Login, "displayname" => redb.Core.Models.Users.UserSortField.Name, "name.familyname" or "name.givenname" => redb.Core.Models.Users.UserSortField.Name, "emails.value" => redb.Core.Models.Users.UserSortField.Email, "meta.created" => redb.Core.Models.Users.UserSortField.DateRegister, "meta.lastmodified" => redb.Core.Models.Users.UserSortField.DateRegister, "id" => redb.Core.Models.Users.UserSortField.Id, _ => redb.Core.Models.Users.UserSortField.Name }; } if (string.Equals(sortOrder, "descending", StringComparison.OrdinalIgnoreCase)) criteria.SortDirection = redb.Core.Models.Users.UserSortDirection.Descending; } private static ScimUser MapToScimUser( IRedbUser user, RedbObject? oidc, List? groups = null, string? baseUrl = null, IReadOnlyDictionary? managerNames = null) { var scimUser = new ScimUser { Id = user.Id.ToString(), UserName = user.Login ?? string.Empty, DisplayName = user.Name, Active = user.Enabled, ExternalId = oidc?.Props.ScimExternalId, Meta = new ScimMeta { ResourceType = "User", Created = oidc?.DateCreate ?? user.DateRegister, LastModified = oidc?.DateModify ?? user.DateRegister, Location = $"{baseUrl}/scim/v2/Users/{user.Id}", Version = user.Hash.HasValue ? $"W/\"{user.Hash.Value}\"" : null } }; // Name if (oidc?.Props is { GivenName: not null } or { FamilyName: not null }) { scimUser.Name = new ScimName { GivenName = oidc!.Props.GivenName, FamilyName = oidc.Props.FamilyName, Formatted = FormatName(oidc.Props.GivenName, oidc.Props.FamilyName) }; } // Emails if (!string.IsNullOrEmpty(user.Email)) { scimUser.Emails = [ new ScimMultiValuedAttribute { Value = user.Email, Type = "work", Primary = true } ]; } // Phone numbers if (!string.IsNullOrEmpty(user.Phone)) { scimUser.PhoneNumbers = [ new ScimMultiValuedAttribute { Value = user.Phone, Type = "work", Primary = true } ]; } // Photos if (!string.IsNullOrEmpty(oidc?.Props.Picture)) { scimUser.Photos = [ new ScimMultiValuedAttribute { Value = oidc!.Props.Picture, Type = "photo", Primary = true } ]; } // Enterprise User extension (RFC 7643 §4.3). Emitted only when something is actually // populated — an empty extension object plus its URN in `schemas` would tell the client // "this user has enterprise data" when it has none. // // `manager.$ref` and `manager.displayName` are derived, never stored: §4.3 marks displayName // read-only (the provider resolves it) and $ref is just the manager's resource URI. Deriving // them means they cannot rot out of sync with the manager's own record. if (oidc?.Props is { } p) { var enterprise = new ScimEnterpriseUser { EmployeeNumber = p.EmployeeNumber, CostCenter = p.CostCenter, Organization = p.Organization, Division = p.Division, Department = p.Department, Manager = string.IsNullOrEmpty(p.ManagerId) ? null : new ScimManager { Value = p.ManagerId, Ref = $"{baseUrl}/scim/v2/Users/{p.ManagerId}", DisplayName = managerNames is not null && managerNames.TryGetValue(p.ManagerId, out var mn) ? mn : null } }; if (!enterprise.IsEmpty) { scimUser.Enterprise = enterprise; // §3 — the extension's URN must be listed in `schemas`; that is what distinguishes // "the extension is present on this resource" from "the server supports it". scimUser.Schemas = [ScimConstants.UserSchema, ScimConstants.EnterpriseUserSchema]; } } // Addresses if (oidc?.Props.Address is { } addr) { scimUser.Addresses = [ new ScimAddress { StreetAddress = addr.StreetAddress, Locality = addr.Locality, Region = addr.Region, PostalCode = addr.PostalCode, Country = addr.Country, Formatted = addr.Formatted, Primary = true } ]; } // Groups (read-only, populated on individual reads) if (groups is { Count: > 0 }) { scimUser.Groups = groups.Select(g => new ScimGroupRef { Value = g.GroupId.ToString(), Display = g.GroupName, Ref = $"/scim/v2/Groups/{g.GroupId}" }).ToList(); } return scimUser; } private static string? GetPrimaryEmail(ScimUser user) => user.Emails?.FirstOrDefault(e => e.Primary)?.Value ?? user.Emails?.FirstOrDefault()?.Value; private static string? GetPrimaryPhone(ScimUser user) => user.PhoneNumbers?.FirstOrDefault(e => e.Primary)?.Value ?? user.PhoneNumbers?.FirstOrDefault()?.Value; private static string? FormatName(string? given, string? family) => (given, family) switch { (not null, not null) => $"{given} {family}", (not null, _) => given, (_, not null) => family, _ => null }; private static AddressClaim? MapScimAddress(ScimAddress? addr) { if (addr is null) return null; return new AddressClaim { StreetAddress = addr.StreetAddress, Locality = addr.Locality, Region = addr.Region, PostalCode = addr.PostalCode, Country = addr.Country, Formatted = addr.Formatted }; } // ── PATCH value extraction ────────────────────────────────── private static string? GetStringValue(JsonElement? value) { if (value is null) return null; return value.Value.ValueKind == JsonValueKind.String ? value.Value.GetString() : value.Value.GetRawText(); } private static bool? GetBoolValue(JsonElement? value) { if (value is null) return null; if (value.Value.ValueKind == JsonValueKind.True) return true; if (value.Value.ValueKind == JsonValueKind.False) return false; if (value.Value.ValueKind == JsonValueKind.String) return bool.TryParse(value.Value.GetString(), out var b) ? b : null; return null; } /// Extracts the primary value from a multi-valued array (emails, phoneNumbers). private static string? GetPrimaryMultiValue(JsonElement? value) { if (value is null) return null; if (value.Value.ValueKind == JsonValueKind.Array) { foreach (var elem in value.Value.EnumerateArray()) { if (elem.TryGetProperty("primary", out var primary) && primary.GetBoolean() && elem.TryGetProperty("value", out var v)) return v.GetString(); } // No primary flag → take first element var first = value.Value.EnumerateArray().FirstOrDefault(); if (first.ValueKind == JsonValueKind.Object && first.TryGetProperty("value", out var fv)) return fv.GetString(); } if (value.Value.ValueKind == JsonValueKind.String) return value.Value.GetString(); return null; } /// /// Handles PATCH with no path — value is a partial ScimUser object. /// Azure Entra sends: { "op": "replace", "value": { "active": false } } /// private static void ApplyPartialResource( JsonElement? value, CoreUpdateUserRequest coreUpdate, UserProps oidcProps, ref bool coreChanged, ref bool oidcChanged) { if (value is null || value.Value.ValueKind != JsonValueKind.Object) return; var obj = value.Value; if (obj.TryGetProperty("displayName", out var dn)) { coreUpdate.Name = dn.GetString(); coreChanged = true; } if (obj.TryGetProperty("active", out var active)) { coreUpdate.Enabled = active.ValueKind == JsonValueKind.True; coreChanged = true; } if (obj.TryGetProperty("name", out var name)) { if (name.TryGetProperty("givenName", out var gn)) { oidcProps.GivenName = gn.GetString(); oidcChanged = true; } if (name.TryGetProperty("familyName", out var fn)) { oidcProps.FamilyName = fn.GetString(); oidcChanged = true; } } if (obj.TryGetProperty("externalId", out var eid)) { oidcProps.ScimExternalId = eid.GetString(); oidcChanged = true; } if (obj.TryGetProperty("emails", out var emails)) { var email = ExtractPrimaryFromElement(emails); if (email is not null) { coreUpdate.Email = email; coreChanged = true; } } if (obj.TryGetProperty("phoneNumbers", out var phones)) { var phone = ExtractPrimaryFromElement(phones); if (phone is not null) { coreUpdate.Phone = phone; coreChanged = true; } } // The Enterprise extension arrives as a member keyed by its URN (RFC 7643 §3), which is // exactly how Entra ID sends a no-path PATCH. if (obj.TryGetProperty(ScimConstants.EnterpriseUserSchema, out var ent) && ent.ValueKind == JsonValueKind.Object) { // A partial PATCH touches only what it names — unlike PUT, an absent attribute means // "leave it alone", not "clear it". Hence TryGetProperty per field, not a wholesale copy. if (ent.TryGetProperty("employeeNumber", out var v)) { oidcProps.EmployeeNumber = v.GetString(); oidcChanged = true; } if (ent.TryGetProperty("costCenter", out v)) { oidcProps.CostCenter = v.GetString(); oidcChanged = true; } if (ent.TryGetProperty("organization", out v)) { oidcProps.Organization = v.GetString(); oidcChanged = true; } if (ent.TryGetProperty("division", out v)) { oidcProps.Division = v.GetString(); oidcChanged = true; } if (ent.TryGetProperty("department", out v)) { oidcProps.Department = v.GetString(); oidcChanged = true; } if (ent.TryGetProperty("manager", out var mgr)) { oidcProps.ManagerId = mgr.ValueKind switch { JsonValueKind.Object when mgr.TryGetProperty("value", out var mv) => mv.GetString(), JsonValueKind.String => mgr.GetString(), _ => null }; oidcChanged = true; } } } /// /// Copies the Enterprise User extension (RFC 7643 §4.3) onto the stored props. Used by the write /// paths where the whole resource is supplied (POST, PUT), so a null extension legitimately /// clears the fields — that is what "replace the resource" means. /// private static void ApplyEnterprise(ScimEnterpriseUser? ent, UserProps props) { props.EmployeeNumber = ent?.EmployeeNumber; props.CostCenter = ent?.CostCenter; props.Organization = ent?.Organization; props.Division = ent?.Division; props.Department = ent?.Department; props.ManagerId = ent?.Manager?.Value; } /// /// Reads manager from a PATCH value, accepting both shapes seen in the wild: the spec's /// complex object ({"value":"42"}) and the bare id some clients send. /// private static string? GetManagerId(JsonElement? value) { if (value is null) return null; return value.Value.ValueKind switch { JsonValueKind.Object when value.Value.TryGetProperty("value", out var v) => v.GetString(), JsonValueKind.String => value.Value.GetString(), _ => null }; } /// /// Resolves manager.displayName for the managers referenced on a page of users. §4.3 marks /// displayName read-only — the provider is expected to resolve it — so we look it up rather than /// storing a copy that would drift when the manager renames. /// /// Bounded by the distinct manager ids actually present (usually a handful per page), so listing /// users does not fan out into a lookup per row. /// /// private static async Task?> ResolveManagerNamesAsync( IRedbService redb, IEnumerable props) { var ids = props .Select(p => p?.ManagerId) .Where(id => !string.IsNullOrEmpty(id)) .Distinct(StringComparer.Ordinal) .ToList(); if (ids.Count == 0) return null; var names = new Dictionary(StringComparer.Ordinal); foreach (var id in ids) { if (!long.TryParse(id, out var managerId)) continue; var manager = await redb.UserProvider.GetUserByIdAsync(managerId); // A dangling manager id (deleted user) yields no displayName rather than an error: the // reference itself is still the truth the provisioning client wrote. if (manager is not null) names[id!] = manager.Name ?? manager.Login ?? id!; } return names.Count > 0 ? names : null; } private static string? ExtractPrimaryFromElement(JsonElement value) { if (value.ValueKind != JsonValueKind.Array) return null; foreach (var elem in value.EnumerateArray()) { if (elem.TryGetProperty("primary", out var primary) && primary.GetBoolean() && elem.TryGetProperty("value", out var v)) return v.GetString(); } var first = value.EnumerateArray().FirstOrDefault(); if (first.ValueKind == JsonValueKind.Object && first.TryGetProperty("value", out var fv)) return fv.GetString(); return null; } // ── Error / result helpers ────────────────────────────────── private static void SetScimError(IExchange exchange, int status, string? scimType, string? detail) { exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new ScimError { Status = status.ToString(), ScimType = scimType, Detail = detail }; } private static void SetResult(IExchange exchange, object body) { exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = body; } private static ScimListResponse EmptyList(int startIndex) => new() { TotalResults = 0, StartIndex = startIndex, ItemsPerPage = 0 }; /// /// Checks the If-Match precondition header against the resource's current ETag. /// Returns false (and sets 412 error) if the precondition fails. /// private static bool CheckIfMatch(IExchange exchange, Guid? currentHash) { var ifMatch = exchange.In.GetHeader("scim.IfMatch"); if (string.IsNullOrEmpty(ifMatch)) return true; // no precondition if (ifMatch == "*") return true; // wildcard always matches // Strip W/ prefix and quotes: W/"abc" → abc var expected = ifMatch.Replace("W/", "").Trim('"'); var actual = currentHash?.ToString(); if (!string.Equals(expected, actual, StringComparison.OrdinalIgnoreCase)) { SetScimError(exchange, 412, null, "ETag precondition failed — resource has been modified"); return false; } return true; } /// /// Sets the response ETag header from the resource hash. Writes to three places so the /// header survives the route pipeline regardless of which branch the SCIM HTTP mapper /// takes downstream: /// /// exchange.In.Headers["scim.ETag"] — survives RedbHttpController rebinding /// and is what MapScimResponseToHttpStatus reads. /// exchange.Out.Headers["scim.ETag"] — canonical out-channel. /// exchange.Out.Headers["ETag"] — direct HTTP header so the http /// consumer projects it onto the wire even when the SCIM mapper does not run /// (some 2xx paths short-circuit). /// /// private static void SetETagHeader(IExchange exchange, Guid? hash) { if (!hash.HasValue) return; var value = $"W/\"{hash.Value}\""; exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Headers["scim.ETag"] = value; exchange.Out.Headers["ETag"] = value; exchange.In.Headers["scim.ETag"] = value; } private static int GetInt(Dictionary dict, string key, int defaultValue) { if (dict.TryGetValue(key, out var val) && val is not null && int.TryParse(val.ToString(), out var result)) return result; return defaultValue; } /// /// Generates a cryptographically strong random password that satisfies common complexity policies. /// Contains uppercase, lowercase, digits, and special characters. /// private static string GeneratePassword(int length) { const string upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; const string lower = "abcdefghijklmnopqrstuvwxyz"; const string digits = "0123456789"; const string special = "!@#$%^&*"; const string all = upper + lower + digits + special; Span bytes = stackalloc byte[length]; System.Security.Cryptography.RandomNumberGenerator.Fill(bytes); var chars = new char[length]; // Guarantee at least one of each category chars[0] = upper[bytes[0] % upper.Length]; chars[1] = lower[bytes[1] % lower.Length]; chars[2] = digits[bytes[2] % digits.Length]; chars[3] = special[bytes[3] % special.Length]; for (int i = 4; i < length; i++) chars[i] = all[bytes[i] % all.Length]; // Shuffle for (int i = length - 1; i > 0; i--) { int j = bytes[i] % (i + 1); (chars[i], chars[j]) = (chars[j], chars[i]); } return new string(chars); } } Path: redb-identity/src/redb.Identity.Core/Routes/Processors/ScopeManagementProcessor.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/Routes/Processors/ScopeManagementProcessor.cs ---- using Microsoft.Extensions.DependencyInjection; using redb.Core; using redb.Core.Models.Entities; using redb.Core.Services; using redb.Identity.Contracts.Common; using redb.Identity.Contracts.Scopes; using redb.Identity.Core.Models; using redb.Identity.Core.Module; using redb.Identity.Core.Services; using redb.Route.Abstractions; using redb.Route.RedbCore.Extensions; using redb.Identity.Contracts.Routes; namespace redb.Identity.Core.Routes.Processors; /// /// CRUD management processor for OAuth scopes. /// Dispatches on the "operation" header: create, read, update, delete, list. /// internal sealed class ScopeManagementProcessor : IProcessor { private readonly IRouteContext _context; private readonly string? _redbName; public ScopeManagementProcessor(IRouteContext context, string? redbName = null) { _context = context; _redbName = redbName; } public async Task Process(IExchange exchange, CancellationToken ct = default) { var redb = _context.GetRedbService(_redbName, exchange); var operation = exchange.In.GetHeader("operation") ?? throw new InvalidOperationException("Missing 'operation' header"); switch (operation) { case "create": await Create(redb, exchange, ct); break; case "read": await Read(redb, exchange, ct); break; case "update": await Update(redb, exchange, ct); break; case "delete": await Delete(redb, exchange, ct); break; case "list": await List(redb, exchange, ct); break; default: exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new ErrorResponse { Error = "invalid_operation", ErrorDescription = $"Unknown operation: {operation}" }; break; } } private async Task Create(IRedbService _redb, IExchange exchange, CancellationToken ct) { var request = exchange.In.Body as CreateScopeRequest; // Validate scope name var err = IdentityProcessorHelpers.ValidateIdentifier(request?.Name, "Name"); if (err != null) { SetError(exchange, "validation_error", err); return; } err = IdentityProcessorHelpers.ValidateDisplayName(request!.DisplayName, "DisplayName"); if (err != null) { SetError(exchange, "validation_error", err); return; } err = IdentityProcessorHelpers.ValidateDescription(request.Description, "Description"); if (err != null) { SetError(exchange, "validation_error", err); return; } // Check uniqueness (one probe of the [RedbUnique] index; the DB still guards the race) var existing = await _redb.GetByUniqueAsync(p => p.ScopeName, request.Name); if (existing != null) { SetError(exchange, "duplicate", $"Scope '{request.Name}' already exists"); return; } var obj = new RedbObject(new ScopeProps { ScopeName = request.Name, Description = request.Description, Resources = request.Resources }); obj.Name = request.DisplayName ?? request.Name; try { await _redb.SaveAsync(obj); } catch (redb.Core.Exceptions.RedbUniqueViolationException violation) { IdentityProcessorHelpers.CountUniqueViolation(_context, exchange, violation); // Concurrent writer won the race — the [RedbUnique] ScopeName index rejected // this insert (V4-UNIQUE). Same error as the app-level check above. SetError(exchange, "duplicate", $"Scope '{request.Name}' already exists"); return; } exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = MapToResponse(obj); exchange.Properties["identity-event-type"] = IdentityAuditEventIds.ScopeCreated; exchange.Properties["identity-event-data"] = new { Name = request.Name }; } private async Task Read(IRedbService _redb, IExchange exchange, CancellationToken ct) { RedbObject? scope = null; if (exchange.In.Body is Dictionary dict) { if (dict.TryGetValue("id", out var idVal) && idVal != null && long.TryParse(idVal.ToString(), out var id) && id > 0) scope = (await _redb.LoadAsync(id)); else if (dict.TryGetValue("name", out var nVal) && nVal is string name && !string.IsNullOrEmpty(name)) scope = await _redb.GetByUniqueAsync(p => p.ScopeName, name); else throw new InvalidOperationException("Either 'id' or 'name' required"); } else { throw new InvalidOperationException("Expected body with 'id' or 'name'"); } if (scope is null) { exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new ErrorResponse { Error = "not_found", ErrorDescription = "Scope not found" }; return; } exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = MapToResponse(scope); } private async Task Update(IRedbService _redb, IExchange exchange, CancellationToken ct) { var request = exchange.In.Body as UpdateScopeRequest; if (request is null || !long.TryParse(request.Id, out var objectId) || objectId <= 0) { SetError(exchange, "validation_error", "Id is required"); return; } var scope = (await _redb.LoadAsync(objectId)); if (scope is null) { exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new ErrorResponse { Error = "not_found", ErrorDescription = $"Scope {request.Id} not found" }; return; } if (request.DisplayName != null) { var err = IdentityProcessorHelpers.ValidateDisplayName(request.DisplayName, "DisplayName"); if (err != null) { SetError(exchange, "validation_error", err); return; } scope.Name = request.DisplayName; } if (request.Description != null) { var err = IdentityProcessorHelpers.ValidateDescription(request.Description, "Description"); if (err != null) { SetError(exchange, "validation_error", err); return; } scope.Props.Description = request.Description; } if (request.Resources != null) scope.Props.Resources = request.Resources; await _redb.SaveAsync(scope); exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = MapToResponse(scope); exchange.Properties["identity-event-type"] = IdentityAuditEventIds.ScopeUpdated; exchange.Properties["identity-event-data"] = new { scope.Props.ScopeName }; } private async Task Delete(IRedbService _redb, IExchange exchange, CancellationToken ct) { if (exchange.In.Body is not Dictionary dict || !dict.TryGetValue("id", out var idVal) || idVal == null || !long.TryParse(idVal.ToString(), out var id) || id <= 0) { SetError(exchange, "validation_error", "Id is required"); return; } var bg = _context.GetIdentityServiceOrDefault(exchange); // Delete only a record of this resource: the typed load answers null for an unknown id // and for the id of a record of another resource alike. if (await _redb.LoadAsync(id) is null) { SetError(exchange, "not_found", $"Scope {id} not found"); return; } await IdentityDeletionHelper.DeleteAsync(_redb, bg, id); exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new SuccessResponse(); exchange.Properties["identity-event-type"] = IdentityAuditEventIds.ScopeDeleted; exchange.Properties["identity-event-data"] = new { Id = id }; } private async Task List(IRedbService _redb, IExchange exchange, CancellationToken ct) { var request = exchange.In.Body as ListRequest ?? new ListRequest(); var query = _redb.Query() .OrderByRedb(o => o.Id); var total = await query.CountAsync(); var count = Math.Min(request.Count, 100); var items = await query .Skip(request.Offset) .Take(count) .ToListAsync(); exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new PagedResult { Items = items.Select(MapToResponse).ToList(), Total = total, Offset = request.Offset, Count = request.Count }; } private static void SetError(IExchange exchange, string error, string description) => IdentityProcessorHelpers.SetError(exchange, error, description); private static ScopeResponse MapToResponse(RedbObject scope) => new() { Id = scope.Id.ToString(), Name = scope.Props.ScopeName, DisplayName = scope.Name, Description = scope.Props.Description, Resources = scope.Props.Resources }; } Path: redb-identity/src/redb.Identity.Core/Routes/Processors/SessionCleanupProcessor.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/Routes/Processors/SessionCleanupProcessor.cs ---- using Microsoft.Extensions.Options; using redb.Core; using redb.Core.Services; using redb.Identity.Core.Configuration; using redb.Identity.Core.Models; using redb.Identity.Core.Services; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.RedbCore.Extensions; using redb.Identity.Contracts.Routes; using redb.Identity.Contracts.Sessions; namespace redb.Identity.Core.Routes.Processors; /// /// Periodic cleanup of revoked sessions older than retention period. /// Mirrors pattern: when an /// is registered, uses cluster-safe /// claim-pattern soft delete; otherwise falls back to direct hard delete. /// internal sealed class SessionCleanupProcessor : IProcessor { private readonly IRouteContext _context; private readonly string? _redbName; private readonly RedbIdentityOptions _options; private readonly IBackgroundDeletionService? _backgroundDeletion; private readonly TimeProvider _timeProvider; public SessionCleanupProcessor( IRouteContext context, IOptions options, string? redbName = null, IBackgroundDeletionService? backgroundDeletion = null, TimeProvider? timeProvider = null) { _context = context; _redbName = redbName; _options = options.Value; _backgroundDeletion = backgroundDeletion; _timeProvider = timeProvider ?? TimeProvider.System; } public async Task Process(IExchange exchange, CancellationToken ct = default) { var redb = _context.GetRedbService(_redbName, exchange); var now = _timeProvider.GetUtcNow(); var threshold = now.AddDays(-_options.SessionRetentionDays); const int batchSize = 500; // S-track: PASS 1 — expire active sessions that crossed either timeout. // Mark them as "revoked" so they fall through to the deletion pass on // the next run after SessionRetentionDays. We load + filter + save // server-side; the IsExpired predicate uses the same idle/absolute // timeouts SessionService.ListAsync applies lazily. var activeSessions = await redb.Query() .Where(s => s.Status == "active") .Take(batchSize) .ToListAsync(); var idleCutoff = now - _options.SessionIdleTimeout; var absoluteCutoff = now - _options.SessionAbsoluteTimeout; var expiredActive = 0; var freshlyRevokedIds = new HashSet(); foreach (var s in activeSessions) { var createdAt = s.date_create; var isAbsoluteExpired = createdAt is { } c && c < absoluteCutoff; var isIdleExpired = s.Props.LastAccessedAt is { } la ? la < idleCutoff : createdAt is { } c2 && c2 < idleCutoff; if (isAbsoluteExpired || isIdleExpired) { s.Props.Status = "revoked"; await redb.SaveAsync(s); expiredActive++; freshlyRevokedIds.Add(s.Id); } } // Revoked sessions older than retention → soft delete via background service if available. // Per design (PASS 1's commentary): sessions freshly revoked in this run // are NOT pruned in the same call — they fall through to the deletion // pass on the next run after SessionRetentionDays. Exclude them by id. var revokedIds = (await redb.Query() .WhereRedb(o => o.DateCreate < threshold) .Where(s => s.Status == "revoked") .Take(batchSize) .Select(o => o.Id) .ToListAsync()) .Where(id => !freshlyRevokedIds.Contains(id)) .ToList(); if (revokedIds.Count > 0) { await SoftDeleteAsync(redb, revokedIds); } exchange.Out ??= new Message(); exchange.Out.Body = new SessionPruneResult { PrunedSessions = revokedIds.Count, ExpiredActiveSessions = expiredActive }; exchange.Properties["identity-event-type"] = IdentityAuditEventIds.SessionsPruned; exchange.Properties["identity-event-data"] = new { SessionCount = revokedIds.Count, ExpiredActive = expiredActive, Threshold = threshold }; } private Task SoftDeleteAsync(IRedbService redb, List ids) => IdentityDeletionHelper.DeleteAsync(redb, _backgroundDeletion, ids); } Path: redb-identity/src/redb.Identity.Core/Routes/Processors/SessionManagementProcessor.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/Routes/Processors/SessionManagementProcessor.cs ---- using redb.Core; using redb.Identity.Contracts.Sessions; using redb.Identity.Core.Services; using redb.Route.Abstractions; using redb.Route.RedbCore.Extensions; using redb.Identity.Contracts.Routes; using redb.Identity.Contracts.Common; namespace redb.Identity.Core.Routes.Processors; /// /// Management processor for user sessions. /// Dispatches on the "operation" header: list, revoke, revoke-all, logout. /// internal sealed class SessionManagementProcessor : IProcessor { private readonly IRouteContext _context; private readonly string? _redbName; public SessionManagementProcessor(IRouteContext context, string? redbName = null) { _context = context; _redbName = redbName; } public async Task Process(IExchange exchange, CancellationToken ct = default) { var redb = _context.GetRedbService(_redbName!, exchange); var session = new SessionService(redb); var operation = exchange.In.GetHeader("operation") ?? throw new InvalidOperationException("Missing 'operation' header"); switch (operation) { case "list": await List(session, redb, exchange, ct); break; case "list-all": await ListAll(session, redb, exchange, ct); break; case "revoke": await Revoke(session, exchange, ct); break; case "revoke-all": await RevokeAll(session, exchange, ct); break; case "logout": await Logout(session, exchange, ct); break; default: exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new ErrorResponse { Error = "invalid_operation", ErrorDescription = $"Unknown operation: {operation}" }; break; } } private static async Task List(SessionService session, IRedbService redb, IExchange exchange, CancellationToken ct) { var userId = IdentityProcessorHelpers.ExtractRequiredLong(exchange, "userId"); var sessions = await session.ListAsync(userId, ct); var loginLookup = await ResolveLoginsAsync(redb, sessions.Select(s => s.UserId), ct); exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = sessions.Select(s => Map(s, loginLookup)).ToList(); } /// /// Admin-wide browse of active sessions across all users. Paginated; /// powers the /admin/sessions default view so the operator sees what's /// alive without first having to pick a target user. /// private static async Task ListAll(SessionService session, IRedbService redb, IExchange exchange, CancellationToken ct) { var dict = exchange.In.Body as Dictionary; var offset = (int)(IdentityProcessorHelpers.ExtractLong(dict ?? new(), "offset") ?? 0); var count = (int)(IdentityProcessorHelpers.ExtractLong(dict ?? new(), "count") ?? 25); var (items, total) = await session.ListAllActiveAsync(offset, count, ct); var loginLookup = await ResolveLoginsAsync(redb, items.Select(s => s.UserId), ct); exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new SessionPage { Items = items.Select(s => Map(s, loginLookup)).ToList(), Total = total, Offset = offset, Count = count }; } private static SessionResponse Map(SessionService.SessionInfo s, Dictionary loginLookup) => new() { SessionId = s.SessionId, UserId = s.UserId, UserLogin = loginLookup.GetValueOrDefault(s.UserId), ApplicationId = s.ApplicationObjectId, ClientId = s.ClientId, ApplicationName = s.ApplicationName, Status = s.Status, CreatedAt = s.CreatedAt, IpAddress = s.IpAddress, UserAgent = s.UserAgent, DeviceLabel = s.DeviceLabel, LastAccessedAt = s.LastAccessedAt, LastAccessedBy = s.LastAccessedBy }; /// /// Bulk-resolve user logins for a session set. Same pattern as /// RoleManagementProcessor.ListAssignees — per-id GetUserByIdAsync via /// the dedicated UserProvider entry point, in parallel, bounded by the /// page size. Correct at any user-count. /// private static async Task> ResolveLoginsAsync( IRedbService redb, IEnumerable userIds, CancellationToken ct) { var distinct = userIds.Where(id => id > 0).Distinct().ToArray(); if (distinct.Length == 0) return new Dictionary(); var lookups = distinct.Select(async id => { try { return (id, login: (await redb.UserProvider.GetUserByIdAsync(id).ConfigureAwait(false))?.Login); } catch { return (id, login: (string?)null); } }); var pairs = await Task.WhenAll(lookups).ConfigureAwait(false); var map = new Dictionary(pairs.Length); foreach (var (id, login) in pairs) map[id] = login; return map; } private static async Task Revoke(SessionService session, IExchange exchange, CancellationToken ct) { var dict = exchange.In.Body as Dictionary ?? throw new InvalidOperationException("Body is required"); var sessionId = IdentityProcessorHelpers.ExtractLong(dict, "sessionId") ?? throw new InvalidOperationException("sessionId is required"); var revoked = await session.RevokeAsync(sessionId, ct); exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new SuccessResponse { Revoked = revoked }; exchange.Properties["identity-event-type"] = IdentityAuditEventIds.SessionRevoked; exchange.Properties["identity-event-data"] = new { SessionId = sessionId }; } private static async Task RevokeAll(SessionService session, IExchange exchange, CancellationToken ct) { var userId = IdentityProcessorHelpers.ExtractRequiredLong(exchange, "userId"); var dryRun = ExtractDryRun(exchange); if (dryRun) { var preview = await session.PreviewRevokeAllAsync(userId, ct); exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new SessionRevokePreview { WouldRevoke = preview.Count, SampleSessionIds = preview.SampleSessionIds }; exchange.Properties["identity-event-type"] = IdentityAuditEventIds.AllSessionsRevocationPreviewed; exchange.Properties["identity-event-data"] = new { UserId = userId, WouldRevoke = preview.Count }; return; } var revoked = await session.RevokeAllAsync(userId, ct); exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new SuccessResponse { Revoked = revoked }; exchange.Properties["identity-event-type"] = IdentityAuditEventIds.AllSessionsRevoked; exchange.Properties["identity-event-data"] = new { UserId = userId }; } /// /// Pulls the optional dryRun flag from the request body. Accepts bool or string /// equivalents (case-insensitive "true"/"false"). Missing key → false. /// private static bool ExtractDryRun(IExchange exchange) { if (exchange.In.Body is not Dictionary dict) return false; if (!dict.TryGetValue("dryRun", out var raw) || raw is null) return false; return raw switch { bool b => b, string s => bool.TryParse(s, out var parsed) && parsed, _ => false }; } private static async Task Logout(SessionService session, IExchange exchange, CancellationToken ct) { var userId = IdentityProcessorHelpers.ExtractRequiredLong(exchange, "userId"); var revoked = await session.LogoutAsync(userId, ct); exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new SuccessResponse { SessionsRevoked = revoked }; exchange.Properties["identity-event-type"] = IdentityAuditEventIds.UserLoggedOut; exchange.Properties["identity-event-data"] = new { UserId = userId }; } } Path: redb-identity/src/redb.Identity.Core/Routes/Processors/SigningKeysManagementProcessor.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/Routes/Processors/SigningKeysManagementProcessor.cs ---- using redb.Identity.Contracts.Routes; using redb.Identity.Contracts.SigningKeys; using redb.Identity.Core.Keys; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Identity.Core.Routes.Processors; /// /// Admin /signing-keys lifecycle endpoint backing — list, rotate, retire. /// /// operation="list" → returns the full audit trail (active + retired). /// operation="rotate" → mints a fresh active key of the given kind, demotes /// any currently-active keys of the same kind. New tokens are signed under the new key /// after the OpenIddict options cache refreshes (process restart, or future /// IOptionsMonitor wiring). /// operation="retire" → sets NotAfter to "now" for the supplied kid; the /// key disappears from JWKS on the next request and tokens signed under it stop /// validating. /// /// Wired into identity-manage-signing-keys in the route builder; gated by /// identity:applications.manage (master identity:manage also passes) via the /// granular scope guard in the HTTP facade. /// internal sealed class SigningKeysManagementProcessor : IProcessor { private readonly ISigningKeyStore _store; public SigningKeysManagementProcessor(ISigningKeyStore store) { _store = store ?? throw new ArgumentNullException(nameof(store)); } public async Task Process(IExchange exchange, CancellationToken ct = default) { var op = exchange.In.GetHeader("operation") ?? "list"; switch (op) { case "list": await List(exchange, ct).ConfigureAwait(false); return; case "rotate": await Rotate(exchange, ct).ConfigureAwait(false); return; case "retire": await Retire(exchange, ct).ConfigureAwait(false); return; default: SetError(exchange, "validation_error", $"Unknown operation '{op}'. Expected one of: list, rotate, retire."); return; } } private async Task List(IExchange exchange, CancellationToken ct) { var keys = await _store.ListAllIncludingRetiredAsync(ct).ConfigureAwait(false); var now = DateTimeOffset.UtcNow; var response = new SigningKeyListResponse { Keys = keys.Select(k => new SigningKeyResponse { Kid = k.Kid, Kind = k.KeyKind, Algorithm = k.Algorithm, NotBefore = k.NotBefore, NotAfter = k.NotAfter, IsActive = k.IsActive, InJwks = k.NotAfter > now, }).ToList(), }; exchange.Out ??= new Message(); exchange.Out.Body = response; } private async Task Rotate(IExchange exchange, CancellationToken ct) { var kind = ResolveKind(exchange); var material = await _store.RotateAsync(kind, ct).ConfigureAwait(false); var response = new SigningKeyResponse { Kid = material.Kid, Kind = material.KeyKind, Algorithm = material.Algorithm, NotBefore = material.NotBefore, NotAfter = material.NotAfter, IsActive = material.IsActive, InJwks = true, }; exchange.Out ??= new Message(); exchange.Out.Body = response; exchange.Properties["identity-event-type"] = IdentityAuditEventIds.SigningKeyRotated; exchange.Properties["identity-event-data"] = new { Kid = material.Kid, Kind = material.KeyKind }; } private async Task Retire(IExchange exchange, CancellationToken ct) { var kid = exchange.In.GetHeader("kid") ?? (exchange.In.Body is Dictionary dict && dict.TryGetValue("kid", out var k) ? k?.ToString() : null); if (string.IsNullOrEmpty(kid)) { SetError(exchange, "validation_error", "kid is required for retire"); return; } var ok = await _store.RetireAsync(kid, ct).ConfigureAwait(false); if (!ok) { SetError(exchange, "not_found", $"No signing key with kid '{kid}'."); return; } exchange.Out ??= new Message(); exchange.Out.Body = new SigningKeyRetiredResponse { Kid = kid }; exchange.Properties["identity-event-type"] = IdentityAuditEventIds.SigningKeyRetired; exchange.Properties["identity-event-data"] = new { Kid = kid }; } private static string ResolveKind(IExchange exchange) { // Body may be either RotateSigningKeyRequest or a raw dictionary; accept either. if (exchange.In.Body is RotateSigningKeyRequest rot && !string.IsNullOrEmpty(rot.Kind)) return rot.Kind!; if (exchange.In.Body is Dictionary dict && dict.TryGetValue("kind", out var v) && v is string s && !string.IsNullOrEmpty(s)) return s; return "signing"; } private static void SetError(IExchange exchange, string error, string description) => IdentityProcessorHelpers.SetError(exchange, error, description); } Path: redb-identity/src/redb.Identity.Core/Routes/Processors/TokenCleanupProcessor.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/Routes/Processors/TokenCleanupProcessor.cs ---- using Microsoft.Extensions.Options; using redb.Core; using redb.Core.Services; using redb.Identity.Core.Configuration; using redb.Identity.Core.Models; using redb.Identity.Core.Services; using redb.Route.Abstractions; using redb.Route.RedbCore.Extensions; using static OpenIddict.Abstractions.OpenIddictConstants; using redb.Identity.Contracts.Routes; using redb.Identity.Contracts.Tokens; namespace redb.Identity.Core.Routes.Processors; /// /// Purges expired/revoked tokens and orphaned authorizations older than the retention period. /// Uses for cluster-safe soft-delete + background purge. /// Invoked manually via "prune" operation on ManageTokens route, or by the timer route. /// internal sealed class TokenCleanupProcessor : IProcessor { private readonly IRouteContext _context; private readonly string? _redbName; private readonly RedbIdentityOptions _options; private readonly IBackgroundDeletionService? _backgroundDeletion; private readonly TimeProvider _timeProvider; public TokenCleanupProcessor( IRouteContext context, IOptions options, string? redbName = null, IBackgroundDeletionService? backgroundDeletion = null, TimeProvider? timeProvider = null) { _context = context; _redbName = redbName; _options = options.Value; _backgroundDeletion = backgroundDeletion; _timeProvider = timeProvider ?? TimeProvider.System; } public async Task Process(IExchange exchange, CancellationToken ct = default) { var redb = _context.GetRedbService(_redbName, exchange); var now = _timeProvider.GetUtcNow(); var threshold = now.AddDays(-_options.TokenRetentionDays); var batchSize = _options.TokenCleanupBatchSize; var dryRun = ExtractDryRun(exchange); int prunedTokens = 0; // Step 1: Collect non-valid tokens older than retention (IDs only via projection) var nonValidIds = await redb.Query() .WhereRedb(o => o.DateCreate < threshold) .Where(t => t.Status != Statuses.Valid) .Take(batchSize) .Select(o => o.Id) .ToListAsync(); // Step 2: Collect expired-but-valid tokens older than retention var expiredValidIds = await redb.Query() .WhereRedb(o => o.DateComplete < now) .WhereRedb(o => o.DateCreate < threshold) .Where(t => t.Status == Statuses.Valid) .Take(batchSize) .Select(o => o.Id) .ToListAsync(); var allTokenIds = nonValidIds.Concat(expiredValidIds).Distinct().ToList(); if (dryRun) { var orphanPreview = await CountOrphanedAuthorizations(redb, threshold); exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new TokenPrunePreview { WouldPruneTokens = allTokenIds.Count, WouldPruneAuthorizations = orphanPreview, Threshold = threshold }; exchange.Properties["identity-event-type"] = IdentityAuditEventIds.TokensPrunePreviewed; exchange.Properties["identity-event-data"] = new { TokenCount = allTokenIds.Count, AuthorizationCount = orphanPreview, Threshold = threshold }; return; } if (allTokenIds.Count > 0) { prunedTokens = allTokenIds.Count; await SoftDeleteAsync(redb, allTokenIds); } // Step 3: Prune orphaned authorizations var prunedAuths = await PruneOrphanedAuthorizations(redb, threshold); exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new TokenPruneResult { PrunedTokens = prunedTokens, PrunedAuthorizations = prunedAuths }; exchange.Properties["identity-event-type"] = IdentityAuditEventIds.TokensPruned; exchange.Properties["identity-event-data"] = new { TokenCount = prunedTokens, AuthorizationCount = prunedAuths, Threshold = threshold }; } /// /// N7-4 dry-run helper: same selection logic as /// but returns the count of authorizations that would be deleted, without mutating. /// private static async Task CountOrphanedAuthorizations(IRedbService redb, DateTimeOffset threshold) { const int batchSize = 500; var candidateIds = await redb.Query() .WhereRedb(o => o.DateCreate < threshold) .Where(a => a.Status != Statuses.Valid) .Take(batchSize) .Select(o => o.Id) .ToListAsync(); if (candidateIds.Count == 0) return 0; var referencedAuthIds = await redb.Query() .Where(t => candidateIds.Contains(t.AuthorizationObjectId)) .Select(o => o.Props.AuthorizationObjectId) .Distinct() .ToListAsync(); var referenced = referencedAuthIds.ToHashSet(); return candidateIds.Count(id => !referenced.Contains(id)); } private static bool ExtractDryRun(IExchange exchange) { if (exchange.In.Body is not Dictionary dict) return false; if (!dict.TryGetValue("dryRun", out var raw) || raw is null) return false; return raw switch { bool b => b, string s => bool.TryParse(s, out var parsed) && parsed, _ => false }; } private Task SoftDeleteAsync(IRedbService redb, List ids) => IdentityDeletionHelper.DeleteAsync(redb, _backgroundDeletion, ids); private async Task PruneOrphanedAuthorizations(IRedbService redb, DateTimeOffset threshold) { const int batchSize = 500; var candidateIds = await redb.Query() .WhereRedb(o => o.DateCreate < threshold) .Where(a => a.Status != Statuses.Valid) .Take(batchSize) .Select(o => o.Id) .ToListAsync(); if (candidateIds.Count == 0) return 0; // Find which authorizations still have associated tokens (IDs only) var referencedAuthIds = await redb.Query() .Where(t => candidateIds.Contains(t.AuthorizationObjectId)) .Select(o => o.Props.AuthorizationObjectId) .Distinct() .ToListAsync(); var referencedIds = referencedAuthIds.ToHashSet(); var toDelete = candidateIds.Where(id => !referencedIds.Contains(id)).ToList(); if (toDelete.Count == 0) return 0; await SoftDeleteAsync(redb, toDelete); return toDelete.Count; } } Path: redb-identity/src/redb.Identity.Core/Routes/Processors/TokenManagementProcessor.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/Routes/Processors/TokenManagementProcessor.cs ---- using redb.Core; using redb.Core.Models.Entities; using redb.Core.Query; using redb.Identity.Contracts.Common; using redb.Identity.Contracts.Tokens; using redb.Identity.Core.Models; using redb.Route.Abstractions; using redb.Route.RedbCore.Extensions; using static OpenIddict.Abstractions.OpenIddictConstants; using redb.Identity.Contracts.Routes; namespace redb.Identity.Core.Routes.Processors; /// /// Administrative token management processor. /// Dispatches on: list, revoke, revoke-by-user, prune. /// internal sealed class TokenManagementProcessor : IProcessor { private readonly IRouteContext _context; private readonly string? _redbName; private readonly TokenCleanupProcessor? _cleanupProcessor; public TokenManagementProcessor(IRouteContext context, string? redbName = null, TokenCleanupProcessor? cleanupProcessor = null) { _context = context; _redbName = redbName; _cleanupProcessor = cleanupProcessor; } public async Task Process(IExchange exchange, CancellationToken ct = default) { var redb = _context.GetRedbService(_redbName, exchange); var operation = exchange.In.GetHeader("operation") ?? throw new InvalidOperationException("Missing 'operation' header"); switch (operation) { case "list": await List(redb, exchange, ct); break; case "revoke": await Revoke(redb, exchange, ct); break; case "revoke-by-user": await RevokeByUser(redb, exchange, ct); break; case "prune": if (_cleanupProcessor is null) { exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new ErrorResponse { Error = "not_configured", ErrorDescription = "Token cleanup not configured" }; } else { await _cleanupProcessor.Process(exchange, ct); } break; default: exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new ErrorResponse { Error = "invalid_operation", ErrorDescription = $"Unknown operation: {operation}" }; break; } } private async Task List(IRedbService _redb, IExchange exchange, CancellationToken ct) { var query = _redb.Query(); // Apply filters from body if (exchange.In.Body is Dictionary filters) { // Subject is now a GUID (the public sub claim). Accept either a Guid value // or a string parseable as Guid. if (filters.TryGetValue("subject", out var subVal) && subVal is not null) { Guid? subjectGuid = subVal switch { Guid g => g, string s when Guid.TryParse(s, out var parsed) => parsed, _ => null }; if (subjectGuid is not null && subjectGuid.Value != Guid.Empty) query = query.WhereRedb(o => o.ValueGuid == subjectGuid.Value); } if (filters.TryGetValue("applicationObjectId", out var appVal) && appVal is long appId && appId > 0) query = query.Where(t => t.ApplicationObjectId == appId); if (filters.TryGetValue("status", out var statusVal) && statusVal is string status && !string.IsNullOrEmpty(status)) query = query.Where(t => t.Status == status); if (filters.TryGetValue("type", out var typeVal) && typeVal is string type && !string.IsNullOrEmpty(type)) { // Rows written before OpenIddict 7 hold the short type ("refresh_token"), newer rows // the URI ("urn:ietf:params:oauth:token-type:refresh_token"). Either spelling of the // filter matches both. var (shortType, uriType) = TokenTypeForms(type); query = query.Where(t => t.Type == shortType || t.Type == uriType); } } var offset = 0; var count = 20; if (exchange.In.Body is Dictionary paging) { if (paging.TryGetValue("offset", out var offVal) && offVal != null && int.TryParse(offVal.ToString(), out var off)) offset = off; if (paging.TryGetValue("count", out var cntVal) && cntVal != null && int.TryParse(cntVal.ToString(), out var cnt)) count = Math.Min(cnt, 100); } var total = await query.CountAsync(); var items = await query .OrderByDescendingRedb(o => o.DateCreate) .Skip(offset) .Take(count) .ToListAsync(); // Enrich each row with the human-readable bits the table renders: // subject GUID → user_id → login, application_id → client_id + display name. // Bulk-lookup so the page doesn't pay N+1. var subjectGuids = items .Select(t => t.value_guid) .Where(g => g.HasValue && g.Value != Guid.Empty) .Select(g => g!.Value) .Distinct() .ToArray(); var subjectMap = new Dictionary(); if (subjectGuids.Length > 0) { // WhereInRedb on a Guid? column produces a less obvious query shape // than per-guid equality; just fan out — the page size is bounded // (default 25, max 100) and the per-row lookup is cheap. foreach (var g in subjectGuids) { try { var u = await _redb.Query() .WhereRedb(o => o.ValueGuid == g) .FirstOrDefaultAsync() .ConfigureAwait(false); if (u?.key is null) continue; var core = await _redb.UserProvider.GetUserByIdAsync(u.key.Value).ConfigureAwait(false); if (core is null) continue; subjectMap[g] = (core.Id, core.Login); } catch { /* skip — best-effort label resolution */ } } } var appIds = items.Select(t => t.Props.ApplicationObjectId).Where(a => a > 0).Distinct().ToArray(); var appsById = new Dictionary>(); if (appIds.Length > 0) { try { var apps = await _redb.Query() .WhereInRedb(o => o.Id, appIds) .ToListAsync() .ConfigureAwait(false); if (apps is not null) { foreach (var app in apps) { if (app is null) continue; appsById[app.id] = app; } } } catch { // Best-effort label enrichment — if the application store is // unavailable / mocked-out the response just omits ClientId // and ApplicationName instead of failing the whole list call. } } exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new PagedResult { Items = items.Select(t => MapToResponse(t, subjectMap, appsById)).ToList(), Total = total, Offset = offset, Count = count }; } private async Task Revoke(IRedbService _redb, IExchange exchange, CancellationToken ct) { if (exchange.In.Body is not Dictionary dict || !dict.TryGetValue("tokenId", out var idVal) || idVal == null || !long.TryParse(idVal.ToString(), out var tokenId) || tokenId <= 0) { exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new ErrorResponse { Error = "validation_error", ErrorDescription = "tokenId is required" }; return; } var token = await _redb.LoadAsync(tokenId); if (token is null) { exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new ErrorResponse { Error = "not_found", ErrorDescription = $"Token {tokenId} not found" }; return; } Stores.TokenStatus.Set(token, Statuses.Revoked); await _redb.SaveAsync(token); exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new SuccessResponse(); // The token's owner, so the event names the user: the subject column (value_guid) is the // public sub, the user's internal id is the key of their UserProps. A client token has no // subject and the event carries no user. long? userId = null; if (token.value_guid is { } subject && subject != Guid.Empty) { var user = await _redb.Query() .WhereRedb(o => o.ValueGuid == subject) .FirstOrDefaultAsync(); userId = user?.key; } exchange.Properties["identity-event-type"] = IdentityAuditEventIds.TokenRevoked; exchange.Properties["identity-event-data"] = new { TokenId = tokenId, UserId = userId }; } private async Task RevokeByUser(IRedbService _redb, IExchange exchange, CancellationToken ct) { if (exchange.In.Body is not Dictionary dict || !dict.TryGetValue("userId", out var idVal) || idVal == null || !long.TryParse(idVal.ToString(), out var userId) || userId <= 0) { exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new ErrorResponse { Error = "validation_error", ErrorDescription = "userId is required" }; return; } // Subject column on TokenProps is now value_guid (the public sub). Resolve the // user's GUID from their UserProps record so the admin "revoke all tokens for // user X" call still works against the new index. var userObj = await _redb.Query() .WhereRedb(o => o.Key == userId) .FirstOrDefaultAsync(); var subjectGuid = userObj?.value_guid ?? Guid.Empty; if (subjectGuid == Guid.Empty) { exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new RevokedCountResponse { RevokedCount = 0 }; return; } var tokens = await _redb.Query() .WhereRedb(o => o.ValueGuid == subjectGuid) .Where(t => t.Status == Statuses.Valid) .ToListAsync(); foreach (var token in tokens) { Stores.TokenStatus.Set(token, Statuses.Revoked); await _redb.SaveAsync(token); } exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new RevokedCountResponse { RevokedCount = tokens.Count }; exchange.Properties["identity-event-type"] = IdentityAuditEventIds.TokensRevokedByUser; exchange.Properties["identity-event-data"] = new { UserId = userId, Count = tokens.Count }; } /// /// The short (OpenIddict 6) and URI (OpenIddict 7) spelling of a stored token type. A value with /// no counterpart is returned as both. /// private static (string Short, string Uri) TokenTypeForms(string type) { (string, string)[] forms = [ ("access_token", TokenTypeIdentifiers.AccessToken), ("authorization_code", TokenTypeIdentifiers.Private.AuthorizationCode), ("device_code", TokenTypeIdentifiers.Private.DeviceCode), ("id_token", TokenTypeIdentifiers.IdentityToken), ("refresh_token", TokenTypeIdentifiers.RefreshToken), ("user_code", TokenTypeIdentifiers.Private.UserCode), ]; foreach (var (shortForm, uriForm) in forms) { if (string.Equals(type, shortForm, StringComparison.Ordinal) || string.Equals(type, uriForm, StringComparison.Ordinal)) return (shortForm, uriForm); } return (type, type); } private static TokenInfoResponse MapToResponse(RedbObject token) => MapToResponse(token, new Dictionary(), new Dictionary>()); private static TokenInfoResponse MapToResponse( RedbObject token, Dictionary subjectMap, Dictionary> appsById) { var resp = new TokenInfoResponse { Id = token.Id, ApplicationObjectId = token.Props.ApplicationObjectId, Subject = token.value_guid?.ToString("D"), Status = token.Props.Status, Type = token.Props.Type, CreatedAt = token.DateCreate, ExpiresAt = token.date_complete }; if (token.value_guid is Guid g && subjectMap.TryGetValue(g, out var subj)) { resp.SubjectUserId = subj.UserId; resp.SubjectLogin = subj.Login; } if (token.Props.ApplicationObjectId > 0 && appsById.TryGetValue(token.Props.ApplicationObjectId, out var app)) { resp.ClientId = app.Props.ClientId ?? app.value_string; resp.ApplicationName = app.name; } return resp; } } Path: redb-identity/src/redb.Identity.Core/Routes/Processors/TrustedProxyResolverProcessor.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/Routes/Processors/TrustedProxyResolverProcessor.cs ---- using System.Net; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using redb.Identity.Core.Configuration; using redb.Route.Abstractions; using redb.Route.Http; namespace redb.Identity.Core.Routes.Processors; /// /// C2 — Sanitizes the redbHttp.RemoteAddress exchange header before per-IP /// throttling (C1) and other client-IP-aware logic observe it. /// /// /// /// Behavior is controlled by : /// /// If TrustForwardedFor=false (default) — does nothing, /// RemoteAddress remains the immediate socket peer. /// If TrustForwardedFor=true AND the socket peer is whitelisted /// in KnownProxies / KnownNetworks — walks X-Forwarded-For /// right-to-left, skipping further whitelisted hops, and overwrites /// RemoteAddress with the first untrusted IP. /// If TrustForwardedFor=true but the socket peer is NOT /// whitelisted — does nothing (an attacker cannot forge X-Forwarded-For from an /// untrusted hop). /// /// /// /// The walk itself is from the shared HTTP host: one /// implementation of the trust model for the whole ecosystem, including its rule that an entry /// which does not parse ends the walk rather than being skipped. The primary place for this /// resolution is the host (HttpHostingOptions.TrustedProxies), which rewrites the address /// and the scheme before any consumer runs. This processor remains for a context whose host did /// not resolve, and it is idempotent after the host did: the address it then sees is the client's, /// which is not a trusted proxy, so it leaves it alone. /// /// internal sealed class TrustedProxyResolverProcessor : IProcessor { private readonly ReverseProxyOptions _options; private readonly TrustedProxyOptions _trust; private readonly ILogger _logger; public TrustedProxyResolverProcessor(ReverseProxyOptions options, ILogger? logger = null) { _options = options; _logger = logger ?? NullLogger.Instance; _trust = new TrustedProxyOptions(); foreach (var ip in options.KnownProxies) _trust.KnownProxies.Add(TrustedProxyOptions.Normalize(ip)); foreach (var net in options.KnownNetworks) _trust.KnownNetworks.Add(net); } public Task Process(IExchange exchange, CancellationToken ct = default) { if (!_options.TrustForwardedFor) return Task.CompletedTask; if (!exchange.In.Headers.TryGetValue("redbHttp.RemoteAddress", out var rawSocket) || rawSocket is not string socketIpStr || !IPAddress.TryParse(socketIpStr, out var socketIp)) return Task.CompletedTask; if (!_trust.IsTrusted(socketIp)) { _logger.LogDebug( "TrustedProxyResolver: socket peer {SocketIp} is not whitelisted; X-Forwarded-For ignored", socketIpStr); return Task.CompletedTask; } var forwardedFor = exchange.In.Headers.TryGetValue(ForwardedHeaderResolver.ForwardedFor, out var raw) ? raw?.ToString() : null; var resolved = ForwardedHeaderResolver.Resolve(socketIp, forwardedFor, forwardedProto: null, _trust); if (!resolved.AddressApplied || resolved.ClientAddress is null) return Task.CompletedTask; exchange.In.Headers["redbHttp.RemoteAddress"] = resolved.ClientAddress.ToString(); _logger.LogDebug( "TrustedProxyResolver: socket peer {SocketIp} is trusted; resolved client IP from X-Forwarded-For: {ClientIp}", socketIpStr, resolved.ClientAddress); return Task.CompletedTask; } } Path: redb-identity/src/redb.Identity.Core/Routes/Processors/UserManagementProcessor.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/Routes/Processors/UserManagementProcessor.cs ---- using Microsoft.Extensions.DependencyInjection; using redb.Core; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Core.Query; using redb.Core.Services; using redb.Identity.Contracts.Common; using redb.Identity.Contracts.Users; using redb.Identity.Core.Models; using redb.Identity.Core.Module; using redb.Identity.Core.Services; using redb.Route.Abstractions; using redb.Route.RedbCore.Extensions; using CoreCreateUserRequest = redb.Core.Models.Users.CreateUserRequest; using CoreUpdateUserRequest = redb.Core.Models.Users.UpdateUserRequest; using redb.Identity.Contracts.Routes; namespace redb.Identity.Core.Routes.Processors; /// /// CRUD management processor for identity users. /// Users live in the relational _users table (via ). /// OIDC profile extensions live in PROPS () linked via RedbObject.Key = _users._id. /// Dispatches on the "operation" header: create, read, update, delete, list, search, change-password. /// internal sealed class UserManagementProcessor : IProcessor { private readonly IRouteContext _context; private readonly string? _redbName; public UserManagementProcessor(IRouteContext context, string? redbName = null) { _context = context; _redbName = redbName; } public async Task Process(IExchange exchange, CancellationToken ct = default) { var redb = _context.GetRedbService(_redbName, exchange); var operation = exchange.In.GetHeader("operation") ?? throw new InvalidOperationException("Missing 'operation' header"); switch (operation) { case "create": await Create(redb, exchange, ct); break; case "read": await Read(redb, exchange, ct); break; case "update": await Update(redb, exchange, ct); break; case "delete": await Delete(redb, exchange, ct); break; case "list": await List(redb, exchange, ct); break; case "search": await Search(redb, exchange, ct); break; case "change-password": await ChangePassword(redb, exchange, ct); break; case "admin-reset-password": await AdminResetPassword(redb, exchange, ct); break; default: exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new ErrorResponse { Error = "invalid_operation", ErrorDescription = $"Unknown operation: {operation}" }; break; } } private async Task Create(IRedbService redb, IExchange exchange, CancellationToken ct) { var request = exchange.In.Body as CreateUserRequest; // Validate Login var err = IdentityProcessorHelpers.ValidateIdentifier(request?.Login, "Login"); if (err != null) { SetError(exchange, "validation_error", err); return; } // Validate Password (H10 — full policy: length + composition + history + breach) err = await IdentityProcessorHelpers.ValidatePasswordPolicyAsync( exchange, _context, request!.Password, userId: null, "Password", ct); if (err != null) { SetError(exchange, "validation_error", err); return; } // Validate optional fields err = IdentityProcessorHelpers.ValidateDisplayName(request.DisplayName, "DisplayName"); if (err != null) { SetError(exchange, "validation_error", err); return; } err = IdentityProcessorHelpers.ValidateEmail(request.Email); if (err != null) { SetError(exchange, "validation_error", err); return; } err = IdentityProcessorHelpers.ValidatePhoneNumber(request.PhoneNumber); if (err != null) { SetError(exchange, "validation_error", err); return; } // Create user in _users table via Core IRedbUser coreUser; try { coreUser = await redb.UserProvider.CreateUserAsync(new CoreCreateUserRequest { Login = request.Login, Password = request.Password, Name = request.DisplayName ?? request.Login, Email = request.Email, Phone = request.PhoneNumber, Enabled = true }); } catch (InvalidOperationException ex) when (ex.Message.Contains("already taken")) { SetError(exchange, "duplicate", $"Login '{request.Login}' already exists"); return; } // S2.3 — enforce global claim schema on create. Operator may supply // CustomClaims in the request to satisfy required definitions; the // helper fills in DefaultValues for required claims without one set // and rejects when a required claim has neither value nor default. var (defaultClaims, schemaErr) = await Services.ClaimSchemaValidator.EnforceGlobalAsync(redb, request.CustomClaims, ct); if (schemaErr is not null) { SetError(exchange, "validation_error", schemaErr); return; } // Save OIDC profile extension linked via key = _users._id. // value_guid: stable, instance-unique public identity used as the OIDC `sub` claim // (avoids cross-Identity-instance bigint collisions on _users._id sequences). var oidcObj = new RedbObject(new UserProps { UserId = coreUser.Id, // V4-UNIQUE GivenName = request.GivenName, FamilyName = request.FamilyName, Picture = request.Picture, CustomClaims = defaultClaims is { Count: > 0 } ? defaultClaims : null, }); oidcObj.name = coreUser.Login; oidcObj.key = coreUser.Id; oidcObj.value_guid = Guid.NewGuid(); await redb.SaveAsync(oidcObj); // H10 — record initial password in history so the user cannot immediately // "change" back to the bootstrap password. PERF: pass the in-tx redb so the // write reuses the same connection (avoids a 30 s deadlock against the open tx). await IdentityProcessorHelpers.RecordPasswordHistoryAsync( exchange, _context, redb, coreUser.Id, request.Password, ct); exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = MapToResponse(coreUser, oidcObj.Props, oidcObj.DateCreate, oidcObj.DateModify, oidcObj.value_guid); exchange.Properties["identity-event-type"] = IdentityAuditEventIds.UserCreated; exchange.Properties["identity-event-data"] = new { UserId = coreUser.Id.ToString(), Login = request.Login }; } private async Task Read(IRedbService redb, IExchange exchange, CancellationToken ct) { IRedbUser? coreUser = null; if (exchange.In.Body is Dictionary dict) { if (dict.TryGetValue("id", out var idVal) && idVal != null && long.TryParse(idVal.ToString(), out var id) && id > 0) coreUser = await redb.UserProvider.GetUserByIdAsync(id); else if (dict.TryGetValue("login", out var loginVal) && loginVal is string login && !string.IsNullOrEmpty(login)) coreUser = await redb.UserProvider.GetUserByLoginAsync(login); else throw new InvalidOperationException("Either 'id' or 'login' required"); } else { throw new InvalidOperationException("Expected body with 'id' or 'login'"); } if (coreUser is null) { exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new ErrorResponse { Error = "not_found", ErrorDescription = "User not found" }; return; } var oidcObj = await LoadOidcProps(redb, coreUser.Id); exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = MapToResponse(coreUser, oidcObj?.Props, oidcObj?.DateCreate, oidcObj?.DateModify, oidcObj?.value_guid); } private async Task Update(IRedbService redb, IExchange exchange, CancellationToken ct) { var request = exchange.In.Body as UpdateUserRequest; if (request is null || request.Id <= 0) { SetError(exchange, "validation_error", "Id is required"); return; } var coreUser = await redb.UserProvider.GetUserByIdAsync(request.Id); if (coreUser is null) { exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new ErrorResponse { Error = "not_found", ErrorDescription = $"User {request.Id} not found" }; return; } // Update _users fields via Core var coreUpdate = new CoreUpdateUserRequest(); bool coreChanged = false; if (request.DisplayName != null) { var err = IdentityProcessorHelpers.ValidateDisplayName(request.DisplayName, "DisplayName"); if (err != null) { SetError(exchange, "validation_error", err); return; } coreUpdate.Name = request.DisplayName; coreChanged = true; } if (request.Status != null) { if (request.Status is not ("active" or "blocked" or "pending")) { SetError(exchange, "validation_error", "Status must be 'active', 'blocked', or 'pending'"); return; } coreUpdate.Enabled = request.Status == "active"; coreChanged = true; } if (request.Email != null) { var err = IdentityProcessorHelpers.ValidateEmail(request.Email); if (err != null) { SetError(exchange, "validation_error", err); return; } coreUpdate.Email = request.Email; coreChanged = true; } if (request.PhoneNumber != null) { var err = IdentityProcessorHelpers.ValidatePhoneNumber(request.PhoneNumber); if (err != null) { SetError(exchange, "validation_error", err); return; } coreUpdate.Phone = request.PhoneNumber; coreChanged = true; } if (coreChanged) coreUser = await redb.UserProvider.UpdateUserAsync(coreUser, coreUpdate); // Update OIDC extension props var oidcObj = await LoadOidcProps(redb, coreUser.Id); bool oidcChanged = false; if (oidcObj is null && (request.EmailVerified.HasValue || request.PhoneNumberVerified.HasValue || request.GivenName != null || request.FamilyName != null || request.Picture != null || request.Address != null || request.CustomClaims is { Count: > 0 })) { // Create OIDC props on first OIDC field update oidcObj = new RedbObject(new UserProps { UserId = coreUser.Id }); oidcObj.name = coreUser.Login; oidcObj.key = coreUser.Id; oidcObj.value_guid = Guid.NewGuid(); } if (oidcObj is not null) { if (request.EmailVerified.HasValue) { oidcObj.Props.EmailVerified = request.EmailVerified.Value; oidcChanged = true; } if (request.PhoneNumberVerified.HasValue) { oidcObj.Props.PhoneNumberVerified = request.PhoneNumberVerified.Value; oidcChanged = true; } if (request.GivenName != null) { oidcObj.Props.GivenName = request.GivenName; oidcChanged = true; } if (request.FamilyName != null) { oidcObj.Props.FamilyName = request.FamilyName; oidcChanged = true; } if (request.Picture != null) { oidcObj.Props.Picture = request.Picture; oidcChanged = true; } if (request.Address != null) { oidcObj.Props.Address = new AddressClaim { StreetAddress = request.Address.StreetAddress, Locality = request.Address.Locality, Region = request.Address.Region, PostalCode = request.Address.PostalCode, Country = request.Address.Country, Formatted = request.Address.Formatted }; oidcChanged = true; } // S2.3 — claim-schema enforcement. We validate the EFFECTIVE // post-update CustomClaims dict (existing ∪ incoming) against // every global ClaimDefinition. Required-but-missing without a // DefaultValue → 400 validation_error; required-but-missing // WITH a DefaultValue → fill it in; present values → type + // regex check. if (request.CustomClaims is not null || oidcObj.Props.CustomClaims is { Count: > 0 }) { var effective = new Dictionary(oidcObj.Props.CustomClaims ?? new(), StringComparer.Ordinal); if (request.CustomClaims is not null) { foreach (var (k, v) in request.CustomClaims) effective[k] = v; } var (normalized, claimErr) = await Services.ClaimSchemaValidator.EnforceGlobalAsync(redb, effective, ct); if (claimErr is not null) { SetError(exchange, "validation_error", claimErr); return; } // Replace the stored dict with the normalized result (defaults // applied + types verified). Empty dict clears CustomClaims. if (normalized is null || normalized.Count == 0) { if (oidcObj.Props.CustomClaims is { Count: > 0 }) { oidcObj.Props.CustomClaims = null; oidcChanged = true; } } else { oidcObj.Props.CustomClaims = normalized; oidcChanged = true; } } if (oidcChanged) await redb.SaveAsync(oidcObj); } exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = MapToResponse(coreUser, oidcObj?.Props, oidcObj?.DateCreate, oidcObj?.DateModify, oidcObj?.value_guid); exchange.Properties["identity-event-type"] = IdentityAuditEventIds.UserUpdated; exchange.Properties["identity-event-data"] = new { UserId = coreUser.Id.ToString(), Login = coreUser.Login }; } private async Task Delete(IRedbService redb, IExchange exchange, CancellationToken ct) { if (exchange.In.Body is not Dictionary dict || !dict.TryGetValue("id", out var idVal) || idVal == null || !long.TryParse(idVal.ToString(), out var id) || id <= 0) { SetError(exchange, "validation_error", "Id is required"); return; } var coreUser = await redb.UserProvider.GetUserByIdAsync(id); if (coreUser is null) { // A user that does not exist is not found (RFC 9110 lets a repeated DELETE answer 404, // RFC 7644 requires it for SCIM); the old 200 with alreadyAbsent hid a mistyped id. SetError(exchange, "not_found", $"User {id} not found"); return; } // Cascade revoke BEFORE soft-deleting the user row. SessionService.LogoutAsync // kills every session for this user AND every OpenIddict authorization linked // to those sessions — that in turn invalidates all access/refresh tokens. // Same shape as the post-password-change revocation flow (UserManagementProcessor // .ChangePassword), so the cascade story stays uniform. var sessionsRevoked = await new SessionService(redb).LogoutAsync(coreUser.Id, ct); // Soft-delete the user row — _enabled=false + _date_dismiss now, _name suffixed // for tombstoning. Login STAYS as-is (immutable per protect_system_users trigger). await redb.UserProvider.DeleteUserAsync(coreUser); // Delete OIDC extension if it exists — re-parents under the trash scheme so it // vanishes from regular queries; background-deletion service handles the // physical purge of dependent _values rows on its own connection. var oidcObj = await LoadOidcProps(redb, id); if (oidcObj is not null) { var bg = _context.GetIdentityServiceOrDefault(exchange); await IdentityDeletionHelper.DeleteAsync(redb, bg, oidcObj.id); } exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new SuccessResponse { SessionsRevoked = sessionsRevoked }; exchange.Properties["identity-event-type"] = IdentityAuditEventIds.UserDeleted; exchange.Properties["identity-event-data"] = new { UserId = id.ToString(), Id = id, SessionsRevoked = sessionsRevoked }; } private async Task List(IRedbService redb, IExchange exchange, CancellationToken ct) { var request = exchange.In.Body as ListRequest ?? new ListRequest(); var count = Math.Min(request.Count, 100); var criteria = new redb.Core.Models.Users.UserSearchCriteria { ExcludeSystemUsers = true, Limit = count, Offset = request.Offset }; var users = await redb.UserProvider.GetUsersAsync(criteria); var total = await redb.UserProvider.GetUserCountAsync(); // Batch-load OIDC extensions for all users (one query, not N). var oidcByUserId = await LoadOidcPropsBatchAsync(redb, users.Select(u => u.Id).ToList()).ConfigureAwait(false); var responses = new List(users.Count); foreach (var u in users) { oidcByUserId.TryGetValue(u.Id, out var oidcObj); responses.Add(MapToResponse(u, oidcObj?.Props, oidcObj?.DateCreate, oidcObj?.DateModify, oidcObj?.value_guid)); } exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new PagedResult { Items = responses, Total = total, Offset = request.Offset, Count = request.Count }; } private async Task Search(IRedbService redb, IExchange exchange, CancellationToken ct) { if (exchange.In.Body is not Dictionary dict || !dict.TryGetValue("query", out var qVal) || qVal is not string searchQuery || string.IsNullOrEmpty(searchQuery)) { SetError(exchange, "validation_error", "Search 'query' is required"); return; } // Paginated search — replaces the legacy hard-cap @ 50. Operator can // walk past page 1 when a noisy tenant has lots of admin_probe_* // residue ahead of the real target. var offset = 0; if (dict.TryGetValue("offset", out var oVal) && oVal is not null && int.TryParse(oVal.ToString(), out var parsedOffset)) offset = Math.Max(0, parsedOffset); var count = 25; if (dict.TryGetValue("count", out var cVal) && cVal is not null && int.TryParse(cVal.ToString(), out var parsedCount)) count = Math.Clamp(parsedCount, 1, 200); var criteria = new redb.Core.Models.Users.UserSearchCriteria { LoginPattern = searchQuery, ExcludeSystemUsers = true, Limit = count, Offset = offset }; var users = await redb.UserProvider.GetUsersAsync(criteria); var total = await redb.UserProvider.CountUsersAsync(new redb.Core.Models.Users.UserSearchCriteria { LoginPattern = searchQuery, ExcludeSystemUsers = true, }); var oidcByUserId = await LoadOidcPropsBatchAsync(redb, users.Select(u => u.Id).ToList()).ConfigureAwait(false); var responses = new List(users.Count); foreach (var u in users) { oidcByUserId.TryGetValue(u.Id, out var oidcObj); responses.Add(MapToResponse(u, oidcObj?.Props, oidcObj?.DateCreate, oidcObj?.DateModify, oidcObj?.value_guid)); } exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new PagedResult { Items = responses, Total = total, Offset = offset, Count = count }; } private async Task ChangePassword(IRedbService redb, IExchange exchange, CancellationToken ct) { var request = exchange.In.Body as ChangePasswordRequest; if (request is null || request.Id <= 0) { SetError(exchange, "validation_error", "Id is required"); return; } if (string.IsNullOrEmpty(request.OldPassword)) { SetError(exchange, "validation_error", "OldPassword is required"); return; } var err = await IdentityProcessorHelpers.ValidatePasswordPolicyAsync( exchange, _context, redb, request.NewPassword, request.Id, "NewPassword", ct); if (err != null) { SetError(exchange, "validation_error", err); return; } if (request.OldPassword == request.NewPassword) { SetError(exchange, "validation_error", "NewPassword must differ from OldPassword"); return; } var coreUser = await redb.UserProvider.GetUserByIdAsync(request.Id); if (coreUser is null) { exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new ErrorResponse { Error = "not_found", ErrorDescription = $"User {request.Id} not found" }; return; } var changed = await redb.UserProvider.ChangePasswordAsync(coreUser, request.OldPassword, request.NewPassword); if (!changed) { SetError(exchange, "invalid_password", "Old password is incorrect"); return; } // H10 — record the new password in history (post-success), through this exchange's IRedbService: the // route is transacted, and a store opening a connection of its own would promote the transaction to a // distributed one, which PostgreSQL refuses unless max_prepared_transactions is set. await IdentityProcessorHelpers.RecordPasswordHistoryAsync( exchange, _context, redb, coreUser.Id, request.NewPassword, ct); // C7 (OWASP Session Management): when a user's password changes, every session // that was authenticated with the old password must be invalidated. This also // revokes all OpenIddict authorizations linked to those sessions, which in turn // invalidates any access/refresh tokens issued from them. The user must // re-authenticate with the new password. var sessionsRevoked = await new SessionService(redb).LogoutAsync(coreUser.Id, ct); exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new SuccessResponse(); exchange.Properties["identity-event-type"] = IdentityAuditEventIds.PasswordChanged; exchange.Properties["identity-event-data"] = new { UserId = coreUser.Id.ToString(), Login = coreUser.Login, SessionsRevoked = sessionsRevoked }; } /// /// Admin-side password reset. Bypasses the OldPassword challenge that the /// user-self change-password flow requires. Same post-success side effects /// as : password history, session revocation, /// audit event (with explicit AdminReset = true marker so the /// timeline distinguishes operator-initiated resets from user-initiated /// changes). /// private async Task AdminResetPassword(IRedbService redb, IExchange exchange, CancellationToken ct) { var request = exchange.In.Body as AdminResetPasswordRequest; if (request is null || request.Id <= 0) { SetError(exchange, "validation_error", "Id is required"); return; } if (string.IsNullOrEmpty(request.NewPassword)) { SetError(exchange, "validation_error", "NewPassword is required"); return; } var err = await IdentityProcessorHelpers.ValidatePasswordPolicyAsync( exchange, _context, redb, request.NewPassword, request.Id, "NewPassword", ct); if (err != null) { SetError(exchange, "validation_error", err); return; } var coreUser = await redb.UserProvider.GetUserByIdAsync(request.Id); if (coreUser is null) { exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new ErrorResponse { Error = "not_found", ErrorDescription = $"User {request.Id} not found" }; return; } var ok = await redb.UserProvider.SetPasswordAsync(coreUser, request.NewPassword); if (!ok) { SetError(exchange, "internal_error", "Failed to set password"); return; } // H10 — record the new password in history (post-success), through this exchange's IRedbService, as in // ChangePassword. await IdentityProcessorHelpers.RecordPasswordHistoryAsync( exchange, _context, redb, coreUser.Id, request.NewPassword, ct); // Same session-revocation semantics as user-initiated change-password // (C7 / OWASP Session Management) — every existing session must die so // the user can't keep an active workspace tied to the previous secret. var sessionsRevoked = await new SessionService(redb).LogoutAsync(coreUser.Id, ct); exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new SuccessResponse { SessionsRevoked = sessionsRevoked }; exchange.Properties["identity-event-type"] = IdentityAuditEventIds.PasswordChanged; exchange.Properties["identity-event-data"] = new { UserId = coreUser.Id.ToString(), Login = coreUser.Login, SessionsRevoked = sessionsRevoked, AdminReset = true, }; } // --- Helpers --- private static async Task?> LoadOidcProps(IRedbService redb, long userId) { return await redb.Query() .WhereRedb(o => o.Key == userId) .FirstOrDefaultAsync(); } /// /// Batch-load the OIDC props row for every supplied in a /// single round-trip. Returns a dictionary keyed by RedbObject.key (which equals /// _users._id); missing keys mean the user has no OIDC props row yet (legacy /// users — caller handles as null). The list endpoints used to fire one /// per user (a silent N+1) which /// scaled as O(users) × DB round-trip; this collapses it to one query. /// private static async Task>> LoadOidcPropsBatchAsync( IRedbService redb, IReadOnlyList userIds) { if (userIds.Count == 0) return new Dictionary>(0); var keys = userIds.Select(id => (long?)id).ToList(); var props = await redb.Query() .WhereRedb(o => keys.Contains(o.Key)) .ToListAsync() .ConfigureAwait(false); var map = new Dictionary>(props.Count); foreach (var p in props) { if (p.key is { } k) map[k] = p; } return map; } private static void SetError(IExchange exchange, string error, string description) => IdentityProcessorHelpers.SetError(exchange, error, description); private static UserResponse MapToResponse( IRedbUser user, UserProps? oidc, DateTimeOffset? createdAt, DateTimeOffset? modifiedAt, Guid? subjectGuid = null) => new() { Id = user.Id, SubjectGuid = subjectGuid is { } g && g != Guid.Empty ? g : null, Login = user.Login, DisplayName = user.Name, Status = user.Enabled ? "active" : "blocked", Email = user.Email, EmailVerified = oidc?.EmailVerified ?? false, PhoneNumber = user.Phone, PhoneNumberVerified = oidc?.PhoneNumberVerified ?? false, GivenName = oidc?.GivenName, FamilyName = oidc?.FamilyName, Picture = oidc?.Picture, Address = oidc?.Address is { } addr ? new Contracts.Users.AddressDto { StreetAddress = addr.StreetAddress, Locality = addr.Locality, Region = addr.Region, PostalCode = addr.PostalCode, Country = addr.Country, Formatted = addr.Formatted } : null, CustomClaims = oidc?.CustomClaims, ExternalIdentities = oidc?.ExternalIdentities is { Count: > 0 } extIds ? extIds.ToDictionary( kvp => kvp.Key, kvp => new Contracts.Users.ExternalIdentityDto { Sub = kvp.Value.Sub, LinkedAt = kvp.Value.LinkedAt }) : null, CreatedAt = createdAt ?? user.DateRegister, ModifiedAt = modifiedAt ?? user.DateRegister }; } Path: redb-identity/src/redb.Identity.Core/Routes/Processors/WebAuthnAssertProcessor.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/Routes/Processors/WebAuthnAssertProcessor.cs ---- using System.Text.Json; using Fido2NetLib; using Microsoft.Extensions.DependencyInjection; using redb.Core; using redb.Identity.Core.Models; using redb.Identity.Core.Services; using redb.Route.Abstractions; using redb.Route.Core; using redb.Identity.Contracts.Routes; namespace redb.Identity.Core.Routes.Processors; /// /// MFA-3: login-flow WebAuthn processor. Two operations: /// /// begin \u2014 caller supplies the previously-issued mfa_state /// (from /login); we issue a fresh WebAuthn challenge and a NEW mfa_state /// containing the assertion options. The original state remains valid until its TTL so the /// user can fall back to TOTP/SMS/email if WebAuthn fails. /// complete \u2014 caller supplies the WebAuthn-flow mfa_state /// + assertion blob. We verify under SELECT \u2026 FOR UPDATE, then create a /// session exactly like . /// /// internal sealed class WebAuthnAssertProcessor : IProcessor { private readonly IServiceProvider _sp; private static readonly JsonSerializerOptions s_json = new() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase, DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull, }; public WebAuthnAssertProcessor(IServiceProvider sp) => _sp = sp; public async Task Process(IExchange exchange, CancellationToken ct = default) { var body = exchange.In.Body as IDictionary; var operation = exchange.In.GetHeader("operation") ?? "begin"; exchange.Out = new Message(); using var scope = _sp.CreateScope(); var mfa = scope.ServiceProvider.GetRequiredService(); var mfaStateToken = GetString(body, "mfa_state"); if (string.IsNullOrEmpty(mfaStateToken)) { exchange.Out.Body = Error("invalid_request", "Missing mfa_state"); return; } var state = mfa.UnprotectState(mfaStateToken!); if (state is null) { exchange.Out.Body = Error("invalid_grant", "MFA session expired or invalid"); return; } if (operation == "begin") { var result = await mfa.BeginWebAuthnAssertionAsync( state.UserId, state.Username, state.ReturnUrl, ct); if (result is null) { exchange.Out.Body = Error("no_credentials", "No WebAuthn credentials registered"); return; } var (options, newToken) = result.Value; exchange.Out.Body = new Dictionary { ["success"] = true, ["options"] = JsonSerializer.SerializeToElement(options, s_json), ["mfa_state"] = newToken, }; return; } if (operation == "complete") { var assertionRaw = body is not null && body.TryGetValue("assertion", out var v) ? v : null; if (assertionRaw is null) { exchange.Out.Body = Error("invalid_request", "Missing assertion"); return; } AuthenticatorAssertionRawResponse? assertion; try { var json = JsonSerializer.Serialize(assertionRaw, s_json); assertion = JsonSerializer.Deserialize(json, s_json); } catch (JsonException ex) { exchange.Out.Body = Error("invalid_request", $"Malformed assertion: {ex.Message}"); return; } if (assertion is null) { exchange.Out.Body = Error("invalid_request", "assertion could not be parsed"); return; } var redb = scope.ServiceProvider.GetRequiredService(); var timeProvider = scope.ServiceProvider.GetService() ?? TimeProvider.System; var mfaObjId = await mfa.GetMfaObjectIdAsync(state.UserId, ct); (bool ok, string? error) result; await using (var tx = await redb.Context.BeginTransactionAsync()) { if (mfaObjId != 0) await redb.LockForUpdateAsync(mfaObjId); result = await mfa.CompleteWebAuthnAssertionAsync(state.UserId, assertion, state, ct); await tx.CommitAsync(); } if (!result.ok) { exchange.Properties["identity-event-type"] = result.error == "sign_counter_rollback" ? IdentityAuditEventIds.MfaWebAuthnSignCounterAnomaly : IdentityAuditEventIds.MfaVerifyFailed; exchange.Properties["identity-event-data"] = new { UserId = state.UserId, Username = state.Username, Reason = result.error, }; exchange.Out.Body = new Dictionary { ["success"] = false, ["error"] = result.error ?? "verification_failed", ["mfa_state"] = mfaStateToken, }; return; } // MFA passed \u2014 create session (parity with MfaVerifyProcessor). var sessionService = new SessionService(redb, timeProvider); var uaParser = scope.ServiceProvider.GetService(); var device = DeviceMetadataExtractor.Extract(exchange, uaParser); var session = await sessionService.CreateAsync( state.UserId, applicationObjectId: 0, mfaVerified: true, mfaMethod: "webauthn", ipAddress: device.IpAddress, userAgent: device.UserAgent, deviceLabel: device.DeviceLabel, ct: ct); exchange.Out.Body = new Dictionary { ["success"] = true, ["userId"] = state.UserId, ["username"] = state.Username, ["sessionId"] = session.id, ["returnUrl"] = state.ReturnUrl, }; exchange.Properties["identity-event-type"] = IdentityAuditEventIds.MfaWebAuthnAsserted; exchange.Properties["identity-event-data"] = new { UserId = state.UserId, Username = state.Username, Timestamp = timeProvider.GetUtcNow(), }; return; } exchange.Out.Body = Error("invalid_operation", $"Unknown operation: {operation}"); } private static string? GetString(IDictionary? body, string key) => body is not null && body.TryGetValue(key, out var v) ? v?.ToString() : null; private static Dictionary Error(string error, string description) => new() { ["error"] = error, ["error_description"] = description, }; } Path: redb-identity/src/redb.Identity.Core/Routes/Processors/WebAuthnConsumedChallengeCleanupProcessor.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/Routes/Processors/WebAuthnConsumedChallengeCleanupProcessor.cs ---- using redb.Core; using redb.Core.Services; using redb.Identity.Core.Models; using redb.Identity.Core.Services; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.RedbCore.Extensions; using redb.Identity.Contracts.Routes; using redb.Identity.Contracts.Common; namespace redb.Identity.Core.Routes.Processors; /// /// MFA-3: periodic cleanup of rows whose /// is in the past. /// /// Mirrors exactly \u2014 hash-marker rows are pure /// storage hygiene, so deleting expired ones is purely a size concern: replay protection is /// already enforced by the unique index at consume time. Uses /// claim-pattern soft delete when available, falls back to direct delete otherwise. /// /// internal sealed class WebAuthnConsumedChallengeCleanupProcessor : IProcessor { private readonly IRouteContext _context; private readonly string? _redbName; private readonly IBackgroundDeletionService? _backgroundDeletion; private readonly TimeProvider _timeProvider; public WebAuthnConsumedChallengeCleanupProcessor( IRouteContext context, string? redbName = null, IBackgroundDeletionService? backgroundDeletion = null, TimeProvider? timeProvider = null) { _context = context; _redbName = redbName; _backgroundDeletion = backgroundDeletion; _timeProvider = timeProvider ?? TimeProvider.System; } public async Task Process(IExchange exchange, CancellationToken ct = default) { var redb = _context.GetRedbService(_redbName, exchange); var now = _timeProvider.GetUtcNow(); const int batchSize = 500; var expiredIds = await redb.Query() .Where(o => o.ExpiresAt < now) .Take(batchSize) .Select(o => o.Id) .ToListAsync(); if (expiredIds.Count > 0) { await IdentityDeletionHelper.DeleteAsync(redb, _backgroundDeletion, expiredIds); } exchange.Out ??= new Message(); exchange.Out.Body = new WebAuthnChallengePruneResult { PrunedWebAuthnChallenges = expiredIds.Count }; exchange.Properties["identity-event-type"] = IdentityAuditEventIds.MfaOtpPruned; exchange.Properties["identity-event-data"] = new { RowCount = expiredIds.Count, Threshold = now, Source = "webauthn_consumed_challenge" }; } } Path: redb-identity/src/redb.Identity.Core/Routes/Processors/WebhookDeliveryWorker.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/Routes/Processors/WebhookDeliveryWorker.cs ---- using System.Security.Cryptography; using System.Text; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Core; using redb.Core.Query; using redb.Identity.Core.Configuration; using redb.Identity.Core.Events; using redb.Identity.Core.Metrics; using redb.Identity.Core.Models; using redb.Identity.Core.Services; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Identity.Core.Routes.Processors; /// /// Sends the due deliveries of the outbox: webhooks to their subscriptions and events to the external /// audit targets (Identity:Audit:Targets). Runs on a timer route marked .Cluster(true), so /// under a Tsak cluster only the leader sends; every row is also claimed with a lease by one conditional /// UPDATE that uses the database clock, so a leader change or a host with several nodes and no cluster /// policy never sends one row from two nodes at once. /// /// Fairness: one pass takes at most rows of one /// subscription and at most in all, counting what is still in /// flight from earlier passes; a subscriber that hangs holds its own slots and no more, and a pass /// starts its deliveries without waiting for them. /// /// /// The payload is the event; the signature is computed here from the subscription's current secret, so /// no secret is stored in the outbox. A subscription deleted or disabled before its delivery is not sent /// to: the row ends as cancelled, not failed. /// /// internal sealed class WebhookDeliveryWorker : IProcessor { private readonly IServiceProvider _sp; private readonly IRouteContext _context; private readonly DeliveryOptions _options; private readonly TimeProvider _time; private readonly ILogger _logger; private readonly string _node; private readonly object _gate = new(); private readonly Dictionary _inFlightByDestination = new(StringComparer.Ordinal); private int _inFlight; private readonly HashSet _running = new(); private IProducerTemplate? _producer; private readonly IReadOnlyDictionary _auditTargets; public WebhookDeliveryWorker( IServiceProvider sp, IRouteContext context, DeliveryOptions options, TimeProvider time, ILogger logger, string? node = null, IReadOnlyList? auditTargets = null) { _auditTargets = (auditTargets ?? []).ToDictionary(t => t.Name, StringComparer.Ordinal); _sp = sp; _context = context; _options = options; _time = time; _logger = logger; _node = node ?? $"{Environment.MachineName}:{Environment.ProcessId}:{Guid.NewGuid().ToString("N")[..8]}"; } public Task Process(IExchange exchange, CancellationToken ct = default) => RunOnceAsync(ct); /// /// One pass: read due rows, pick fairly within what is still in flight, and start their deliveries. /// It does not wait for them: a subscriber that hangs until its timeout must not hold back the next /// pass, or every other subscriber would wait with it. Returns the number of deliveries started. /// internal async Task RunOnceAsync(CancellationToken ct = default) { List due; await using (var scope = _sp.CreateAsyncScope()) { due = await Store(scope.ServiceProvider).DueAsync(Math.Max(1, _options.BatchSize), ct).ConfigureAwait(false); } if (due.Count == 0) return 0; var picked = Pick(due.Where(r => r.Kind is WebhookEnqueueProcessor.Kind or AuditTargetEnqueueProcessor.Kind).ToList()); foreach (var row in picked) { var task = RunTrackedAsync(row); lock (_gate) _running.Add(task); } return picked.Count; } /// Waits for every delivery this worker has started; for tests and orderly shutdown. internal async Task DrainAsync() { Task[] running; lock (_gate) running = _running.ToArray(); await Task.WhenAll(running).ConfigureAwait(false); } private async Task RunTrackedAsync(OutboxRow row) { try { await DeliverOneAsync(row, CancellationToken.None).ConfigureAwait(false); } finally { lock (_gate) { _inFlight--; var key = Key(row); if (--_inFlightByDestination[key] == 0) _inFlightByDestination.Remove(key); _running.RemoveWhere(t => t.IsCompleted); } } } /// Round-robin over destinations, within the per-destination and the total limits. private List Pick(List due) { var picked = new List(); var queues = due.GroupBy(Key).Select(g => new Queue(g)).ToList(); lock (_gate) { var progress = true; while (progress && _inFlight < Math.Max(1, _options.MaxParallel)) { progress = false; foreach (var q in queues) { if (q.Count == 0 || _inFlight >= Math.Max(1, _options.MaxParallel)) continue; var destination = Key(q.Peek()); _inFlightByDestination.TryGetValue(destination, out var busy); if (busy >= Math.Max(1, _options.MaxParallelPerDestination)) continue; picked.Add(q.Dequeue()); _inFlightByDestination[destination] = busy + 1; _inFlight++; progress = true; } } } return picked; } private async Task DeliverOneAsync(OutboxRow row, CancellationToken ct) { await using var scope = _sp.CreateAsyncScope(); var store = Store(scope.ServiceProvider); var redb = scope.ServiceProvider.GetRequiredService(); var metrics = scope.ServiceProvider.GetService(); try { var target = await ResolveAsync(redb, row, ct).ConfigureAwait(false); var lease = (int)Math.Ceiling(Math.Max(_options.Lease.TotalSeconds, ((target.Send?.TimeoutMs ?? 0) / 1000.0) + 10)); if (!await store.TryClaimAsync(row.Id, row.Attempts, lease, _node, ct).ConfigureAwait(false)) return; // another node holds it, it is no longer due, or another pass made an attempt since it was read if (target.Send is not { } send) { await store.MarkCancelledAsync(row.Id, _node, target.CancelReason!, ct).ConfigureAwait(false); Count(metrics, row.Kind, "cancelled"); return; } var attempt = row.Attempts + 1; try { using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct); timeout.CancelAfter(TimeSpan.FromMilliseconds(send.TimeoutMs)); var exchange = new Exchange(send.Message(attempt)); try { await GetProducer().SendAsync(send.Uri, exchange, timeout.Token).ConfigureAwait(false); } finally { await exchange.DisposeAsync().ConfigureAwait(false); } await store.MarkDeliveredAsync(row.Id, _node, CancellationToken.None).ConfigureAwait(false); Count(metrics, row.Kind, "delivered"); } catch (Exception ex) when (!ct.IsCancellationRequested) { var error = $"{ex.GetType().Name}: {ex.Message}"; if (attempt >= send.MaxAttempts) { await store.MarkFailedAsync(row.Id, _node, error, CancellationToken.None).ConfigureAwait(false); Count(metrics, row.Kind, "failed"); _logger.LogError(ex, "Delivery {Delivery} ({Kind} {Destination}) failed for good after {Attempts} attempt(s).", row.DeliveryIdText, row.Kind, row.Destination, attempt); } else { var delay = (int)Math.Min(send.RetryBackoffMs * Math.Pow(2, attempt - 1), send.MaxBackoffMs); await store.ScheduleRetryAsync(row.Id, _node, delay, error, CancellationToken.None).ConfigureAwait(false); Count(metrics, row.Kind, "retry"); _logger.LogWarning("Delivery {Delivery} ({Kind} {Destination}): attempt {Attempt} of {Max} failed ({Error}); next in {Delay} ms.", row.DeliveryIdText, row.Kind, row.Destination, attempt, send.MaxAttempts, error, delay); } } } catch (Exception ex) { // The row stays leased until the lease runs out and is then taken again: never lost. _logger.LogError(ex, "Delivery {Delivery} ({Kind}): could not process the outbox row; it is retried when its lease ends.", row.DeliveryIdText, row.Kind); } } /// Where and how one row goes, or why it does not go at all. private sealed record Target(SendPlan? Send, string? CancelReason); private sealed record SendPlan(string Uri, int TimeoutMs, int MaxAttempts, int RetryBackoffMs, int MaxBackoffMs, Func Message); private async Task ResolveAsync(IRedbService redb, OutboxRow row, CancellationToken ct) { if (row.Kind == AuditTargetEnqueueProcessor.Kind) { // The configuration of this process decides: a target removed or disabled since the event is // the operator's own act, like a deleted subscription. if (!_auditTargets.TryGetValue(row.Destination, out var t)) return new Target(null, "audit target no longer configured or disabled"); return new Target(new SendPlan(t.Uri, t.TimeoutMs, t.MaxAttempts, t.RetryBackoffMs, 60_000, _ => AuditTargetMessage.Build(row.Payload)), null); } var subscription = long.TryParse(row.Destination, out var subscriptionId) ? await new WebhookSubscriptionService(redb).GetAsync(subscriptionId, ct).ConfigureAwait(false) : null; if (subscription is null) return new Target(null, "subscription deleted"); if (!subscription.Props.Enabled) return new Target(null, "subscription disabled"); var sub = subscription.Props; return new Target(new SendPlan(sub.Url, sub.TimeoutMs, sub.MaxAttempts, sub.RetryBackoffMs, 30_000, attempt => BuildMessage(sub, row, attempt)), null); } private IdentityEventStore Store(IServiceProvider sp) => new(sp.GetRequiredService(), sp.GetRequiredService()); // A webhook subscription id and an audit target name share one column; the kind keeps them apart. private static string Key(OutboxRow row) => row.Kind + ":" + row.Destination; private static void Count(IdentityMetrics? metrics, string kind, string result) => metrics?.DeliveryAttempts.Add(1, new KeyValuePair("kind", kind), new KeyValuePair("result", result)); private IProducerTemplate GetProducer() { if (_producer is not null) return _producer; lock (_gate) { if (_producer is null) { var t = new ProducerTemplate(_context); t.Start(); _producer = t; } } return _producer; } /// The request: the event as stored, signed now with the subscription's current secret. private IMessage BuildMessage(WebhookSubscriptionProps sub, OutboxRow row, int attempt) { var body = Encoding.UTF8.GetBytes(row.Payload); var message = new Message(body) { ContentType = "application/json" }; message.Headers["redbHttp.Method"] = "POST"; message.Headers["X-RedbIdentity-Signature"] = $"sha256={Sign(sub.HmacSecret, body)}"; message.Headers["X-RedbIdentity-Timestamp"] = _time.GetUtcNow().ToString("O"); message.Headers["X-RedbIdentity-Delivery"] = row.DeliveryIdText; message.Headers["X-RedbIdentity-EventType"] = row.EventType; message.Headers["X-RedbIdentity-Attempt"] = attempt.ToString(); if (sub.ExtraHeaders is { Count: > 0 } operatorHeaders) { foreach (var (k, v) in operatorHeaders) { if (k.StartsWith("X-RedbIdentity-", StringComparison.OrdinalIgnoreCase)) continue; message.Headers[k] = v; } } return message; } private static string Sign(string secret, byte[] body) { using var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(secret)); return Convert.ToHexString(hmac.ComputeHash(body)).ToLowerInvariant(); } } Path: redb-identity/src/redb.Identity.Core/Routes/Processors/WebhookEnqueueProcessor.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/Routes/Processors/WebhookEnqueueProcessor.cs ---- using System.Text.Json; using Microsoft.Extensions.Logging; using redb.Core.Query; using redb.Identity.Contracts.Events; using redb.Identity.Contracts.Routes; using redb.Identity.Core.Events; using redb.Identity.Core.Metrics; using redb.Identity.Core.Module; using redb.Identity.Core.Services; using redb.Route.Abstractions; using redb.Route.RedbCore.Extensions; namespace redb.Identity.Core.Routes.Processors; /// /// Puts an event into the delivery outbox for every enabled webhook subscription that wants it. Runs /// in the events route after the audit row is written, and sends nothing itself: the delivery worker /// does, with its own bounded parallelism, leases and retries. /// /// An event nobody subscribed to costs no statement here: the subscriptions come from /// , and with no match there is no insert. A failure to write the /// outbox rows is logged and counted; the audit row is already written and the event goes on. /// /// internal sealed class WebhookEnqueueProcessor : IProcessor { internal const string Kind = "webhook"; private readonly IRouteContext _context; private readonly string? _redbName; private readonly WebhookSubscriptionCache _cache; private readonly ILogger _logger; public WebhookEnqueueProcessor(IRouteContext context, string? redbName, WebhookSubscriptionCache cache, ILogger logger) { _context = context; _redbName = redbName; _cache = cache; _logger = logger; } public async Task Process(IExchange exchange, CancellationToken ct = default) { if (exchange.In.Body is not IdentityEvent evt) return; var redb = _context.GetRedbService(_redbName, exchange); IReadOnlyList> subscriptions; try { subscriptions = await _cache.GetEnabledAsync(redb, ct).ConfigureAwait(false); } catch (Exception ex) { _logger.LogWarning(ex, "Webhook delivery: could not read the subscriptions for event {EventType}; nothing enqueued.", evt.EventType); Count(exchange, evt.EventType); return; } if (subscriptions.Count == 0) return; var category = IdentityAuditEventIds.CategoryOf(evt.EventType); var matching = subscriptions.Where(s => WebhookSubscriptionService.Matches(s.Props, evt.EventType, category)).ToList(); if (matching.Count == 0) return; var payload = JsonSerializer.Serialize(evt); var eventId = Guid.TryParse(evt.EventId, out var parsed) ? parsed : Guid.NewGuid(); var entries = matching .Select(s => new OutboxEntry(Guid.NewGuid(), eventId, Kind, s.Id.ToString(), evt.EventType, payload)) .ToList(); try { var dialect = _context.GetIdentityService(exchange); await new IdentityEventStore(redb, dialect).InsertOutboxAsync(entries, ct).ConfigureAwait(false); } catch (Exception ex) { _logger.LogError(ex, "Webhook delivery: could not enqueue event {EventType} for {Count} subscription(s); the audit row is written, these deliveries are lost.", evt.EventType, entries.Count); Count(exchange, evt.EventType); } } private void Count(IExchange exchange, string eventType) => _context.GetIdentityServiceOrDefault(exchange)?.DeliveryEnqueueFailures.Add( 1, new KeyValuePair("event_type", eventType)); } Path: redb-identity/src/redb.Identity.Core/Routes/Processors/WebhookManagementProcessor.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/Routes/Processors/WebhookManagementProcessor.cs ---- using Microsoft.Extensions.Logging; using redb.Core; using redb.Identity.Contracts.Common; using redb.Identity.Contracts.Routes; using redb.Identity.Contracts.Webhooks; using redb.Identity.Core.Models; using redb.Identity.Core.Services; using redb.Identity.Core.Module; using redb.Route.Abstractions; using redb.Route.RedbCore.Extensions; namespace redb.Identity.Core.Routes.Processors; /// /// W1 — admin CRUD for outbound webhook subscriptions. Operations: /// list / get / create / update / delete / rotate-secret. /// /// HMAC secret is included ONLY on the create + rotate-secret responses. /// All other responses omit it; the existence flag HasHmacSecret /// surfaces presence without leaking the value. /// internal sealed class WebhookManagementProcessor : IProcessor { private readonly IRouteContext _context; private readonly string? _redbName; private readonly ILogger _logger; private readonly redb.Identity.Core.Events.WebhookSubscriptionCache? _cache; public WebhookManagementProcessor(IRouteContext context, string? redbName, ILogger logger, redb.Identity.Core.Events.WebhookSubscriptionCache? cache = null) { _context = context; _redbName = redbName; _cache = cache; _logger = logger; } public async Task Process(IExchange exchange, CancellationToken ct = default) { var operation = exchange.In.GetHeader("operation") ?? ""; var redb = _context.GetRedbService(_redbName, exchange); var svc = new WebhookSubscriptionService(redb); switch (operation) { case "list": await List(svc, exchange, ct); break; case "get": await Get(svc, exchange, ct); break; case "create": await Create(svc, exchange, ct); break; case "update": await Update(svc, exchange, ct); break; case "delete": await Delete(svc, exchange, ct); break; case "rotate-secret": await RotateSecret(svc, exchange, ct); break; case "list-deliveries": await ListDeliveries(redb, exchange, ct); break; case "redeliver": await Redeliver(redb, exchange, ct); break; default: SetError(exchange, "invalid_operation", $"Unknown operation: {operation}"); break; } // Events read the enabled subscriptions from a cache; a change made here must reach them at // once on this node (other nodes within Delivery.SubscriptionCache). if (operation is "create" or "update" or "delete" or "rotate-secret") _cache?.Invalidate(); } private async Task List(WebhookSubscriptionService svc, IExchange exchange, CancellationToken ct) { var request = exchange.In.Body as ListRequest ?? new ListRequest(); var offset = Math.Max(0, request.Offset); var count = Math.Clamp(request.Count, 1, 200); var items = await svc.ListAsync(offset, count, ct).ConfigureAwait(false); var total = await svc.CountAsync(ct).ConfigureAwait(false); exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new PagedResult { Items = items.Select(o => MapToResponse(o, includeSecret: false)).ToList(), Total = total, Offset = offset, Count = count }; } private async Task Get(WebhookSubscriptionService svc, IExchange exchange, CancellationToken ct) { var id = ExtractLongFromBody(exchange, "id"); if (id is null) { SetError(exchange, "validation_error", "id is required"); return; } var obj = await svc.GetAsync(id.Value, ct).ConfigureAwait(false); if (obj is null) { SetError(exchange, "not_found", $"Webhook {id} not found"); return; } exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = MapToResponse(obj, includeSecret: false); } private async Task Create(WebhookSubscriptionService svc, IExchange exchange, CancellationToken ct) { if (exchange.In.Body is not CreateWebhookSubscriptionRequest request) { SetError(exchange, "validation_error", "Body must be a CreateWebhookSubscriptionRequest"); return; } try { var created = await svc.CreateAsync( url: request.Url, displayName: request.DisplayName, description: request.Description, eventTypeFilter: request.EventTypeFilter, enabled: request.Enabled ?? true, timeoutMs: request.TimeoutMs ?? 5000, maxAttempts: request.MaxAttempts ?? 3, retryBackoffMs: request.RetryBackoffMs ?? 500, extraHeaders: request.ExtraHeaders, hmacSecret: request.HmacSecret, ct: ct).ConfigureAwait(false); exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = MapToResponse(created, includeSecret: true); exchange.Properties["identity-event-type"] = IdentityAuditEventIds.WebhookSubscriptionCreated; exchange.Properties["identity-event-data"] = new { WebhookId = created.Id, Url = created.Props.Url }; } catch (ArgumentException ex) { SetError(exchange, "validation_error", ex.Message); } } private async Task Update(WebhookSubscriptionService svc, IExchange exchange, CancellationToken ct) { var id = ExtractLongFromBody(exchange, "id"); if (id is null) { SetError(exchange, "validation_error", "id is required"); return; } // The management controller forwards the update as a dictionary (the id from the path next to // the fields of the body); the fields are read from it. Requiring a typed request here refused // every update that came over HTTP. if (exchange.In.Body is not Dictionary fields) { SetError(exchange, "validation_error", "Body is required"); return; } var request = new UpdateWebhookSubscriptionRequest { DisplayName = fields.GetValueOrDefault("displayName") as string, Description = fields.GetValueOrDefault("description") as string, Url = fields.GetValueOrDefault("url") as string, EventTypeFilter = fields.GetValueOrDefault("eventTypeFilter") as string, Enabled = fields.GetValueOrDefault("enabled") as bool?, TimeoutMs = fields.GetValueOrDefault("timeoutMs") as int?, MaxAttempts = fields.GetValueOrDefault("maxAttempts") as int?, RetryBackoffMs = fields.GetValueOrDefault("retryBackoffMs") as int?, ExtraHeaders = fields.GetValueOrDefault("extraHeaders") as Dictionary, }; try { await svc.UpdateAsync( id.Value, request.DisplayName, request.Description, request.Url, request.EventTypeFilter, request.Enabled, request.TimeoutMs, request.MaxAttempts, request.RetryBackoffMs, request.ExtraHeaders, ct).ConfigureAwait(false); exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new SuccessResponse(); exchange.Properties["identity-event-type"] = IdentityAuditEventIds.WebhookSubscriptionUpdated; exchange.Properties["identity-event-data"] = new { WebhookId = id.Value }; } catch (ArgumentException ex) { SetError(exchange, "validation_error", ex.Message); } catch (InvalidOperationException ex) { SetError(exchange, "not_found", ex.Message); } } private async Task Delete(WebhookSubscriptionService svc, IExchange exchange, CancellationToken ct) { var id = ExtractLongFromBody(exchange, "id"); if (id is null) { SetError(exchange, "validation_error", "id is required"); return; } await svc.DeleteAsync(id.Value, ct).ConfigureAwait(false); exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new SuccessResponse(); exchange.Properties["identity-event-type"] = IdentityAuditEventIds.WebhookSubscriptionDeleted; exchange.Properties["identity-event-data"] = new { WebhookId = id.Value }; } private async Task RotateSecret(WebhookSubscriptionService svc, IExchange exchange, CancellationToken ct) { var id = ExtractLongFromBody(exchange, "id"); if (id is null) { SetError(exchange, "validation_error", "id is required"); return; } try { var newSecret = await svc.RotateSecretAsync(id.Value, ct).ConfigureAwait(false); var obj = await svc.GetAsync(id.Value, ct).ConfigureAwait(false); exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = obj is null ? new WebhookSecretRotatedResponse { HmacSecret = newSecret } : MapToResponse(obj, includeSecret: true); exchange.Properties["identity-event-type"] = IdentityAuditEventIds.WebhookSubscriptionSecretRotated; exchange.Properties["identity-event-data"] = new { WebhookId = id.Value }; } catch (InvalidOperationException ex) { SetError(exchange, "not_found", ex.Message); } } /// /// The rows of the delivery outbox (webhooks and audit targets), newest first, without their payload. /// Filters: status, kind, destination (a subscription id or an audit target name). /// private async Task ListDeliveries(IRedbService redb, IExchange exchange, CancellationToken ct) { var body = exchange.In.Body as Dictionary ?? new Dictionary(); var offset = Math.Max(0, ExtractInt(body, "offset") ?? 0); var count = Math.Clamp(ExtractInt(body, "count") ?? 25, 1, 200); var status = body.GetValueOrDefault("status")?.ToString() ?? ""; var kind = body.GetValueOrDefault("kind")?.ToString() ?? ""; var destination = body.GetValueOrDefault("destination")?.ToString() ?? ""; var items = await Store(redb, exchange).ListAsync(status, kind, destination, count, offset, ct).ConfigureAwait(false); exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new WebhookDeliveryPage { Items = items.Select(d => new WebhookDeliveryItem { Id = d.Id, DeliveryId = Text(d.DeliveryId), EventId = Text(d.EventId), Kind = d.Kind, Destination = d.Destination, EventType = d.EventType, Status = d.Status, Attempts = d.Attempts, LastError = d.LastError, CreatedAt = d.CreatedAt, NextAttemptAt = d.NextAttemptAt, FinishedAt = d.FinishedAt, }).ToList(), Offset = offset, Count = count, }; } /// /// A failed or cancelled delivery is sent again from its first attempt: 404 for an unknown id, 409 for a /// row that is pending or delivered. A webhook to a subscription that is gone, or an audit target no /// longer configured, ends cancelled again. A redelivery raises /// ; a refused one raises nothing. /// private async Task Redeliver(IRedbService redb, IExchange exchange, CancellationToken ct) { var id = ExtractLongFromBody(exchange, "id"); if (id is null) { SetError(exchange, "validation_error", "id is required"); return; } var store = Store(redb, exchange); if (await store.RedeliverAsync(id.Value, ct).ConfigureAwait(false)) { exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new SuccessResponse(); exchange.Properties["identity-event-type"] = IdentityAuditEventIds.WebhookDeliveryRedelivered; exchange.Properties["identity-event-data"] = new { OutboxId = id.Value }; return; } var status = await store.StatusOfAsync(id.Value, ct).ConfigureAwait(false); if (status is null) SetError(exchange, "not_found", $"Delivery {id} not found"); else SetError(exchange, "conflict", $"Delivery {id} is {status}; only a failed or cancelled delivery is sent again"); } private redb.Identity.Core.Events.IdentityEventStore Store(IRedbService redb, IExchange exchange) => new(redb, _context.GetIdentityService(exchange)); private static string? Text(object? id) => id switch { null => null, Guid g => g.ToString("D"), _ => id.ToString(), }; private static int? ExtractInt(Dictionary dict, string field) => dict.TryGetValue(field, out var v) && v is not null && int.TryParse(v.ToString(), out var parsed) ? parsed : null; private static long? ExtractLongFromBody(IExchange exchange, string field) { if (exchange.In.Body is not Dictionary dict) return null; if (!dict.TryGetValue(field, out var v) || v is null) return null; return long.TryParse(v.ToString(), out var parsed) ? parsed : null; } private static WebhookSubscriptionResponse MapToResponse( redb.Core.Models.Entities.RedbObject obj, bool includeSecret) => new() { Id = obj.Id, DisplayName = obj.Props.DisplayName, Description = obj.Props.Description, Url = obj.Props.Url, EventTypeFilter = obj.Props.EventTypeFilter, Enabled = obj.Props.Enabled, TimeoutMs = obj.Props.TimeoutMs, MaxAttempts = obj.Props.MaxAttempts, RetryBackoffMs = obj.Props.RetryBackoffMs, ExtraHeaders = obj.Props.ExtraHeaders, HmacSecret = includeSecret ? obj.Props.HmacSecret : null, HasHmacSecret = !string.IsNullOrEmpty(obj.Props.HmacSecret), CreatedAt = obj.date_create, ModifiedAt = obj.date_modify }; private static void SetError(IExchange exchange, string code, string description) { exchange.Out ??= new redb.Route.Core.Message(); exchange.Out.Body = new ErrorResponse { Error = code, ErrorDescription = description }; } } Path: redb-identity/src/redb.Identity.Core/Security/Argon2idPasswordHasher.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/Security/Argon2idPasswordHasher.cs ---- using System; using System.Globalization; using System.Security.Cryptography; using System.Text; using Konscious.Security.Cryptography; using Microsoft.Extensions.Logging; using redb.Core.Security; namespace redb.Identity.Core.Security; /// /// C12: Argon2id password hasher — OWASP 2023+ recommended primary algorithm. /// /// Encoded hash format (PHC string, compatible with libargon2 / other implementations): /// $argon2id$v=19$m={memoryKb},t={iterations},p={parallelism}$<base64-salt>$<base64-hash>. /// Base64 is unpadded (RFC 7693 §3.5) to match the de-facto PHC format. /// /// /// Defaults: memory=65536 KiB (64 MiB), iterations=3, parallelism=4, salt=16 bytes, hash=32 bytes. /// At these parameters a single verify takes ~50–150 ms on a modern desktop CPU. /// /// public sealed class Argon2idPasswordHasher : IPasswordHasher { /// PHC algorithm prefix for Argon2id hashes. public const string Prefix = "$argon2id$"; private readonly int _memoryKib; private readonly int _iterations; private readonly int _parallelism; private readonly int _saltBytes; private readonly int _hashBytes; private readonly ILogger? _logger; /// Memory cost in KiB used for new hashes. public int MemoryKib => _memoryKib; /// Iterations (time cost) used for new hashes. public int Iterations => _iterations; /// Degree of parallelism (lanes) used for new hashes. public int Parallelism => _parallelism; /// /// Creates an Argon2id hasher with OWASP 2023 parameters by default. /// public Argon2idPasswordHasher( int memoryKib = 65536, int iterations = 3, int parallelism = 4, int saltBytes = 16, int hashBytes = 32, ILogger? logger = null) { if (memoryKib < 8) throw new ArgumentOutOfRangeException(nameof(memoryKib), "Argon2id memory must be ≥ 8 KiB."); if (iterations < 1) throw new ArgumentOutOfRangeException(nameof(iterations)); if (parallelism < 1) throw new ArgumentOutOfRangeException(nameof(parallelism)); if (saltBytes < 8) throw new ArgumentOutOfRangeException(nameof(saltBytes), "Salt must be ≥ 8 bytes."); if (hashBytes < 16) throw new ArgumentOutOfRangeException(nameof(hashBytes), "Hash must be ≥ 16 bytes."); _memoryKib = memoryKib; _iterations = iterations; _parallelism = parallelism; _saltBytes = saltBytes; _hashBytes = hashBytes; _logger = logger; } /// public string HashPassword(string password) { if (string.IsNullOrEmpty(password)) throw new ArgumentException("Password cannot be empty", nameof(password)); var salt = RandomNumberGenerator.GetBytes(_saltBytes); var hash = Compute(Encoding.UTF8.GetBytes(password), salt, _memoryKib, _iterations, _parallelism, _hashBytes); var sb = new StringBuilder(96); sb.Append(Prefix); sb.Append("v=19$m=").Append(_memoryKib.ToString(CultureInfo.InvariantCulture)); sb.Append(",t=").Append(_iterations.ToString(CultureInfo.InvariantCulture)); sb.Append(",p=").Append(_parallelism.ToString(CultureInfo.InvariantCulture)); sb.Append('$').Append(ToB64NoPad(salt)); sb.Append('$').Append(ToB64NoPad(hash)); return sb.ToString(); } /// public bool VerifyPassword(string password, string hashedPassword) { if (string.IsNullOrEmpty(password) || string.IsNullOrEmpty(hashedPassword)) return false; if (!TryParse(hashedPassword, out var p)) return false; try { var computed = Compute(Encoding.UTF8.GetBytes(password), p.Salt, p.MemoryKib, p.Iterations, p.Parallelism, p.Hash.Length); return CryptographicOperations.FixedTimeEquals(computed, p.Hash); } catch (Exception ex) { // Compute() can throw on native-library errors, OOM under aggressive m=, or // wildly out-of-range parameters that slipped past TryParse. Treat as auth // failure (don't leak details to the user) but make sure operators see it \u2014 // a sustained run is an availability/operational signal, not just "wrong password". _logger?.LogWarning(ex, "Argon2idPasswordHasher: VerifyPassword failed during Compute (m={Memory}, t={Iter}, p={Par}).", p.MemoryKib, p.Iterations, p.Parallelism); return false; } } /// /// Returns true when the stored hash's parameters are weaker than the hasher's current settings /// (i.e. upgrade is desirable). Non-Argon2id hashes always return true. /// public bool NeedsRehash(string hashedPassword) { if (string.IsNullOrEmpty(hashedPassword)) return true; if (!hashedPassword.StartsWith(Prefix, StringComparison.Ordinal)) return true; if (!TryParse(hashedPassword, out var p)) return true; return p.MemoryKib < _memoryKib || p.Iterations < _iterations || p.Parallelism < _parallelism; } private static byte[] Compute(byte[] password, byte[] salt, int memoryKib, int iterations, int parallelism, int hashBytes) { using var argon2 = new Argon2id(password) { Salt = salt, DegreeOfParallelism = parallelism, Iterations = iterations, MemorySize = memoryKib, }; return argon2.GetBytes(hashBytes); } private readonly record struct Parsed(int MemoryKib, int Iterations, int Parallelism, byte[] Salt, byte[] Hash); private static bool TryParse(string encoded, out Parsed parsed) { parsed = default; // $argon2id$v=19$m=65536,t=3,p=4$$ if (!encoded.StartsWith(Prefix, StringComparison.Ordinal)) return false; var parts = encoded.Split('$'); // ["", "argon2id", "v=19", "m=...,t=...,p=...", "salt", "hash"] if (parts.Length != 6) return false; if (parts[1] != "argon2id") return false; if (!parts[2].StartsWith("v=", StringComparison.Ordinal)) return false; int m = 0, t = 0, p = 0; foreach (var kv in parts[3].Split(',')) { var eq = kv.IndexOf('='); if (eq <= 0) return false; var k = kv.AsSpan(0, eq); var v = kv.AsSpan(eq + 1); if (!int.TryParse(v, NumberStyles.Integer, CultureInfo.InvariantCulture, out var n)) return false; if (k.SequenceEqual("m".AsSpan())) m = n; else if (k.SequenceEqual("t".AsSpan())) t = n; else if (k.SequenceEqual("p".AsSpan())) p = n; } if (m < 8 || t < 1 || p < 1) return false; byte[] salt, hash; try { salt = FromB64NoPad(parts[4]); hash = FromB64NoPad(parts[5]); } catch { return false; } parsed = new Parsed(m, t, p, salt, hash); return true; } private static string ToB64NoPad(byte[] bytes) => Convert.ToBase64String(bytes).TrimEnd('='); private static byte[] FromB64NoPad(string s) { var pad = (4 - s.Length % 4) % 4; return Convert.FromBase64String(pad == 0 ? s : s + new string('=', pad)); } } Path: redb-identity/src/redb.Identity.Core/Security/DefaultPasswordPolicyValidator.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/Security/DefaultPasswordPolicyValidator.cs ---- using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using redb.Core; using redb.Identity.Core.Configuration; namespace redb.Identity.Core.Security; /// /// H10 — default implementation backed by /// . Phase 1: length + ASCII composition rules. /// Phase 2 (history) and Phase 5 (breach) hooks are wired through optional dependencies /// so the same instance keeps working as the stack grows. /// public sealed class DefaultPasswordPolicyValidator : IPasswordPolicyValidator { private readonly PasswordPolicyOptions _options; // Phase 2 hook — null = history check disabled. private readonly IPasswordHistoryStore? _history; // Phase 5 hook — null = breach check disabled even if BreachCheckEnabled=true. private readonly IBreachedPasswordChecker? _breachChecker; public DefaultPasswordPolicyValidator( PasswordPolicyOptions options, IPasswordHistoryStore? history = null, IBreachedPasswordChecker? breachChecker = null) { _options = options ?? throw new System.ArgumentNullException(nameof(options)); _history = history; _breachChecker = breachChecker; } /// public ValueTask ValidateAsync( string? password, long? userId = null, CancellationToken ct = default) => ValidateCoreAsync(password, userId, redb: null, ct); /// public ValueTask ValidateAsync( string? password, long? userId, IRedbService redb, CancellationToken ct = default) => ValidateCoreAsync(password, userId, redb ?? throw new System.ArgumentNullException(nameof(redb)), ct); private async ValueTask ValidateCoreAsync( string? password, long? userId, IRedbService? redb, CancellationToken ct) { var errors = new List(); if (string.IsNullOrEmpty(password)) { errors.Add("Password is required"); return PasswordValidationResult.Fail(errors); } // ── Length ── if (password.Length < _options.MinLength) errors.Add($"Password must be at least {_options.MinLength} characters"); if (password.Length > _options.MaxLength) errors.Add($"Password must not exceed {_options.MaxLength} characters"); // ── Composition (ASCII; non-ASCII letters/digits are NOT counted to keep // classification deterministic across cultures) ── bool hasDigit = false, hasUpper = false, hasLower = false, hasSpecial = false; var specials = _options.SpecialChars ?? string.Empty; for (int i = 0; i < password.Length; i++) { var c = password[i]; if (c >= '0' && c <= '9') hasDigit = true; else if (c >= 'A' && c <= 'Z') hasUpper = true; else if (c >= 'a' && c <= 'z') hasLower = true; else if (specials.IndexOf(c) >= 0) hasSpecial = true; } if (_options.RequireDigit && !hasDigit) errors.Add("Password must contain at least one digit"); if (_options.RequireUppercase && !hasUpper) errors.Add("Password must contain at least one uppercase letter"); if (_options.RequireLowercase && !hasLower) errors.Add("Password must contain at least one lowercase letter"); if (_options.RequireSpecial && !hasSpecial) errors.Add("Password must contain at least one special character"); // Stop short-circuit before more expensive checks if basic rules failed — // user gets the cheap rule violations first, history/breach only when shape is OK. if (errors.Count > 0) return PasswordValidationResult.Fail(errors); // ── Phase 2: history reuse ── if (_history is not null && _options.HistoryCount > 0 && userId.HasValue) { var reused = redb is null ? await _history.IsRecentlyUsedAsync(userId.Value, password, _options.HistoryCount, ct).ConfigureAwait(false) : await _history.IsRecentlyUsedAsync(redb, userId.Value, password, _options.HistoryCount, ct).ConfigureAwait(false); if (reused) errors.Add($"Password matches one of the last {_options.HistoryCount} passwords"); } // ── Phase 5: breach check (HIBP or other registered checker) ── if (_options.BreachCheckEnabled && _breachChecker is not null) { var breached = await _breachChecker.IsBreachedAsync(password, ct).ConfigureAwait(false); if (breached) errors.Add("Password has appeared in a known data breach and cannot be used"); } return errors.Count == 0 ? PasswordValidationResult.Ok() : PasswordValidationResult.Fail(errors); } } /// /// Phase 2 — pluggable per-user password-history store. Implemented in a follow-up /// phase; declared here so can take an /// optional dependency without a circular reference. /// public interface IPasswordHistoryStore { /// Returns true if matches any of the /// last hashes recorded for . Task IsRecentlyUsedAsync(long userId, string password, int count, CancellationToken ct); /// /// The same check through the caller's : what a processor on a transacted route /// calls, so the lookup runs on the route's connection and does not open a second one inside its /// transaction (a second connection promotes it to a distributed transaction, which PostgreSQL refuses /// unless max_prepared_transactions is set). A store without its own implementation keeps the check above. /// Task IsRecentlyUsedAsync(IRedbService redb, long userId, string password, int count, CancellationToken ct) => IsRecentlyUsedAsync(userId, password, count, ct); /// Records a new password hash for the user and trims older entries beyond /// . Task RecordAsync(long userId, string password, int keep, CancellationToken ct); } /// /// Phase 5 — pluggable breached-password checker (e.g. HIBP k-anonymity, local /// dictionary). Default deployment registers no implementation; the policy validator /// then skips the check entirely regardless of /// . /// public interface IBreachedPasswordChecker { Task IsBreachedAsync(string password, CancellationToken ct); } Path: redb-identity/src/redb.Identity.Core/Security/IPasswordPolicyValidator.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/Security/IPasswordPolicyValidator.cs ---- using System.Threading; using System.Threading.Tasks; using redb.Core; namespace redb.Identity.Core.Security; /// /// H10 — central server-side gate for every password mutation (admin Create/Change, /// self-service /me/password, SCIM Create/PATCH). Validates length + composition rules /// from , history reuse (Phase 2) and /// breach checking (Phase 5). Always invoked BEFORE /// IUserProvider.SetPasswordAsync/ChangePasswordAsync. /// public interface IPasswordPolicyValidator { /// /// Validates the candidate password against all configured rules. /// /// Candidate password (plaintext). /// User the password is being set for (used for history lookup); null for new accounts. /// Cancellation token. ValueTask ValidateAsync( string? password, long? userId = null, CancellationToken ct = default); /// /// The same validation with the database reads (the history lookup) through : what a /// processor on a transacted route calls with the exchange's , so no second /// connection opens inside the route's transaction. A validator without its own implementation validates /// as above. /// ValueTask ValidateAsync( string? password, long? userId, IRedbService redb, CancellationToken ct = default) => ValidateAsync(password, userId, ct); } /// /// Aggregated outcome of a password policy check. is true /// iff is empty. /// public sealed class PasswordValidationResult { public bool IsValid { get; init; } public System.Collections.Generic.IReadOnlyList Errors { get; init; } = System.Array.Empty(); public static PasswordValidationResult Ok() => new() { IsValid = true }; public static PasswordValidationResult Fail(params string[] errors) => new() { IsValid = false, Errors = errors }; public static PasswordValidationResult Fail(System.Collections.Generic.IReadOnlyList errors) => new() { IsValid = errors.Count == 0, Errors = errors }; /// /// Joins all errors with "; " for legacy single-line error_description fields. /// public string ToErrorMessage() => string.Join("; ", Errors); } Path: redb-identity/src/redb.Identity.Core/Security/IdentitySecurityLog.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/Security/IdentitySecurityLog.cs ---- using Microsoft.Extensions.Logging; namespace redb.Identity.Core.Security; /// /// E5 — security-event logging channel. All audit/security-sensitive events /// (login denial, MFA lockout, rate-limit breach, RBAC rejection) should be /// routed to the RedbIdentity.Security logger category so operators /// can surface them to a dedicated sink (SIEM / audit pipeline) without /// interleaving with routine operational logs. /// public static class IdentitySecurityLog { /// /// Logger category used for all security-sensitive events in redb.Identity. /// Keep stable: downstream log-routing rules key off this string. /// public const string CategoryName = "RedbIdentity.Security"; /// /// Creates a security-channel logger from the given factory. Callers that /// already hold an should call this helper /// rather than hand-formatting the category string. /// public static ILogger CreateLogger(ILoggerFactory factory) { ArgumentNullException.ThrowIfNull(factory); return factory.CreateLogger(CategoryName); } } Path: redb-identity/src/redb.Identity.Core/Security/MultiFormatPasswordHasher.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/Security/MultiFormatPasswordHasher.cs ---- using System; using redb.Core.Security; namespace redb.Identity.Core.Security; /// /// C12: dispatching password hasher that produces new hashes with the configured primary /// algorithm (Argon2id by default) while remaining able to verify and transparently migrate /// legacy hashes (BCrypt, legacy SHA256+salt, and — via any fallback /// supplied as — PBKDF2 or other formats). /// /// On successful verification of a legacy hash, callers should check /// and, if true, re-hash the plaintext with and persist the new hash. /// This is the standard OWASP "upgrade-on-login" pattern. /// /// public sealed class MultiFormatPasswordHasher : IPasswordHasher { private readonly Argon2idPasswordHasher _primary; private readonly BcryptPasswordHasher _bcrypt; private readonly IPasswordHasher? _legacyVerifier; /// /// Creates a multi-format hasher. /// /// Primary hasher used for new hashes (typically Argon2id). /// /// BCrypt hasher used to verify pre-existing $2a$/$2b$/$2y$ hashes (also falls back to /// the legacy SHA256+salt format emitted by when the stored /// hash contains a ':' separator). Required because BCrypt covers the install-base of existing /// deployments prior to C12. /// /// /// Optional additional verifier for other legacy formats (e.g. PBKDF2 if migrating from an /// ASP.NET Identity V3 store). Consulted only when the stored hash does not match any of the /// native formats (Argon2id, BCrypt, legacy SHA256+salt). /// public MultiFormatPasswordHasher( Argon2idPasswordHasher primary, BcryptPasswordHasher bcrypt, IPasswordHasher? legacyVerifier = null) { _primary = primary ?? throw new ArgumentNullException(nameof(primary)); _bcrypt = bcrypt ?? throw new ArgumentNullException(nameof(bcrypt)); _legacyVerifier = legacyVerifier; } /// public string HashPassword(string password) => _primary.HashPassword(password); /// public bool VerifyPassword(string password, string hashedPassword) { if (string.IsNullOrEmpty(password) || string.IsNullOrEmpty(hashedPassword)) return false; // Argon2id native format — primary path. if (hashedPassword.StartsWith(Argon2idPasswordHasher.Prefix, StringComparison.Ordinal)) return _primary.VerifyPassword(password, hashedPassword); // BCrypt modular crypt format — $2a$ / $2b$ / $2y$. if (hashedPassword.StartsWith("$2", StringComparison.Ordinal)) return _bcrypt.VerifyPassword(password, hashedPassword); // Legacy SHA256+salt (':' separator) — BcryptPasswordHasher handles this legacy path. if (hashedPassword.Contains(':')) return _bcrypt.VerifyPassword(password, hashedPassword); // External legacy (e.g. PBKDF2). return _legacyVerifier?.VerifyPassword(password, hashedPassword) ?? false; } /// /// Returns true when the stored hash is not produced by the primary algorithm at the /// current parameters (i.e. the password should be re-hashed after a successful verify). /// public bool NeedsRehash(string hashedPassword) { if (string.IsNullOrEmpty(hashedPassword)) return true; return _primary.NeedsRehash(hashedPassword); } } Path: redb-identity/src/redb.Identity.Core/Security/PropsPasswordHistoryStore.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/Security/PropsPasswordHistoryStore.cs ---- using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Core; using redb.Core.Models.Entities; using redb.Core.Query; using redb.Core.Security; using redb.Identity.Core.Models; namespace redb.Identity.Core.Security; /// /// H10 Phase 2 — PROPS-backed that mirrors the /// PropsWebAuthnChallengeStore pattern: registered as a singleton, opens a fresh /// DI scope per call so the captured is never captive across /// requests. Verifier-hashes are produced via the registered /// (Argon2id by default; same hasher used for live /// credentials so a future algorithm bump is automatically picked up). /// public sealed class PropsPasswordHistoryStore : IPasswordHistoryStore { private readonly IServiceScopeFactory _scopeFactory; private readonly TimeProvider _timeProvider; private readonly ILogger? _logger; public PropsPasswordHistoryStore( IServiceScopeFactory scopeFactory, TimeProvider? timeProvider = null, ILogger? logger = null) { _scopeFactory = scopeFactory ?? throw new System.ArgumentNullException(nameof(scopeFactory)); _timeProvider = timeProvider ?? TimeProvider.System; _logger = logger; } /// public async Task IsRecentlyUsedAsync(long userId, string password, int count, CancellationToken ct) { if (userId <= 0 || count <= 0 || string.IsNullOrEmpty(password)) return false; await using var scope = _scopeFactory.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); var hasher = scope.ServiceProvider.GetRequiredService(); return await IsRecentlyUsedCoreAsync(redb, hasher, userId, password, count).ConfigureAwait(false); } /// public async Task IsRecentlyUsedAsync(IRedbService redb, long userId, string password, int count, CancellationToken ct) { System.ArgumentNullException.ThrowIfNull(redb); if (userId <= 0 || count <= 0 || string.IsNullOrEmpty(password)) return false; // The scope only lends the hasher (a singleton): no IRedbService is resolved from it, so no // connection opens besides the caller's. await using var scope = _scopeFactory.CreateAsyncScope(); var hasher = scope.ServiceProvider.GetRequiredService(); return await IsRecentlyUsedCoreAsync(redb, hasher, userId, password, count).ConfigureAwait(false); } private static async Task IsRecentlyUsedCoreAsync( IRedbService redb, IPasswordHasher hasher, long userId, string password, int count) { // Pull the most recent N history rows for the user; ordering by CreatedAt desc. // Argon2id verify is O(~100ms each), so we cap the work by `count` upstream. var rows = await redb.Query() .Where(o => o.UserId == userId) .OrderByDescending(o => o.CreatedAt) .Take(count) .ToListAsync() .ConfigureAwait(false); foreach (var row in rows) { var stored = row.Props.HashedPassword; if (!string.IsNullOrEmpty(stored) && hasher.VerifyPassword(password, stored)) { return true; } } return false; } /// public async Task RecordAsync(long userId, string password, int keep, CancellationToken ct) { if (userId <= 0 || string.IsNullOrEmpty(password) || keep <= 0) return; await using var scope = _scopeFactory.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); var hasher = scope.ServiceProvider.GetRequiredService(); var now = _timeProvider.GetUtcNow(); var entry = new RedbObject(new PasswordHistoryProps { UserId = userId, HashedPassword = hasher.HashPassword(password), CreatedAt = now, }) { name = $"pwhist:{userId}:{now.ToUnixTimeMilliseconds()}", }; await redb.SaveAsync(entry).ConfigureAwait(false); // Trim: soft-delete everything older than the keep-newest-N window. Cleaning up // here keeps the table O(N*users) without a separate cleanup processor. try { var staleIds = await redb.Query() .Where(o => o.UserId == userId) .OrderByDescending(o => o.CreatedAt) .Skip(keep) .Select(o => o.id) .ToListAsync() .ConfigureAwait(false); if (staleIds.Count > 0) { await redb.SoftDeleteAsync(staleIds).ConfigureAwait(false); } } catch (System.Exception ex) { // Trim failures must not block password change — at worst the table grows // a bit until the next successful trim. _logger?.LogWarning(ex, "Password-history trim failed for userId={UserId}; keep window not enforced this round.", userId); } } } Path: redb-identity/src/redb.Identity.Core/Security/RegisteredClientOriginRegistry.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/Security/RegisteredClientOriginRegistry.cs ---- using System.Collections.Immutable; using Microsoft.Extensions.DependencyInjection; using OpenIddict.Abstractions; using redb.Identity.Contracts.Cors; namespace redb.Identity.Core.Security; /// /// Default implementation backed by /// . Rebuilds its snapshot lazily on demand /// after ; concurrent rebuilds are /// de-duplicated via a so a burst of CORS preflights does not /// trigger N parallel store scans. /// public sealed class RegisteredClientOriginRegistry : IRegisteredClientOriginRegistry { private readonly IServiceScopeFactory _scopeFactory; private readonly Func? _additionalOriginsCsv; private readonly SemaphoreSlim _refreshLock = new(1, 1); private volatile ImmutableHashSet? _snapshot; private int _generation; // bumped by Invalidate; observed by readers to skip stale snapshots /// Creates a new registry. /// DI scope factory used to resolve a fresh /// (a Scoped service) on every snapshot rebuild. /// Critical: holding a captured as a field /// here is a captive-singleton bug because the manager transitively closes over the /// Scoped IRedbService and therefore over a single NpgsqlConnection — every /// CORS preflight would then share that one connection with any in-flight request, which /// surfaces as NpgsqlOperationInProgressException: A command is already in progress. /// /// Optional callback returning a comma-separated list of /// origins always considered allowed (e.g. dev/staging fallbacks supplied via configuration). /// Evaluated on every refresh so config hot-reload is picked up. May return null. public RegisteredClientOriginRegistry( IServiceScopeFactory scopeFactory, Func? additionalOriginsCsv = null) { _scopeFactory = scopeFactory ?? throw new ArgumentNullException(nameof(scopeFactory)); _additionalOriginsCsv = additionalOriginsCsv is null ? null : () => additionalOriginsCsv() ?? string.Empty; } /// public async ValueTask IsAllowedAsync(string? origin, CancellationToken ct = default) { if (string.IsNullOrEmpty(origin)) return false; var snapshot = await GetAllowedOriginsAsync(ct).ConfigureAwait(false); return snapshot.Contains(origin); } /// public async ValueTask> GetAllowedOriginsAsync(CancellationToken ct = default) { var current = _snapshot; if (current is not null) return current; await _refreshLock.WaitAsync(ct).ConfigureAwait(false); try { // Re-check after acquiring the lock: another thread may have rebuilt while we waited. current = _snapshot; if (current is not null) return current; var rebuilt = await BuildAsync(ct).ConfigureAwait(false); _snapshot = rebuilt; return rebuilt; } finally { _refreshLock.Release(); } } /// public void Invalidate() { _snapshot = null; Interlocked.Increment(ref _generation); } private async Task> BuildAsync(CancellationToken ct) { var builder = ImmutableHashSet.CreateBuilder(StringComparer.OrdinalIgnoreCase); // Resolve the application manager from a fresh DI scope so its transitive // dependencies (notably the Scoped IRedbService -> NpgsqlConnection chain) live and // die with this single rebuild. See ctor doc for why a captured manager would be a // captive-singleton bug. await using var scope = _scopeFactory.CreateAsyncScope(); var applications = scope.ServiceProvider.GetRequiredService(); await foreach (var app in applications.ListAsync(count: null, offset: null, ct).ConfigureAwait(false)) { if (app is null) continue; var redirectUris = await applications.GetRedirectUrisAsync(app, ct).ConfigureAwait(false); foreach (var uri in redirectUris) AddOrigin(builder, uri); var postLogoutUris = await applications.GetPostLogoutRedirectUrisAsync(app, ct).ConfigureAwait(false); foreach (var uri in postLogoutUris) AddOrigin(builder, uri); } // Additional configured origins (dev/staging fallbacks). Evaluated on every refresh so // operators can toggle them without restarting the process. var additional = _additionalOriginsCsv?.Invoke(); if (!string.IsNullOrEmpty(additional)) { foreach (var raw in additional.Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries)) AddOrigin(builder, raw); } return builder.ToImmutable(); } private static void AddOrigin(ImmutableHashSet.Builder builder, string raw) { if (string.IsNullOrWhiteSpace(raw)) return; // Accept either a bare origin ("https://app.example.com") or a full redirect URI // ("https://app.example.com/callback?x=1") -- in both cases we want the authority only. if (!Uri.TryCreate(raw, UriKind.Absolute, out var parsed)) return; if (string.IsNullOrEmpty(parsed.Scheme) || string.IsNullOrEmpty(parsed.Host)) return; // Use Uri.GetLeftPart(Authority) which already strips userinfo, path, and query, and // collapses the default port for http/https. Lower-case to match browser-emitted Origin. var origin = parsed.GetLeftPart(UriPartial.Authority).ToLowerInvariant(); builder.Add(origin); } } Path: redb-identity/src/redb.Identity.Core/Serialization/IdentityCodecProfiles.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/Serialization/IdentityCodecProfiles.cs ---- using System.Text.Json; using System.Text.Json.Serialization; using redb.Identity.Contracts.Serialization; using redb.Route.Abstractions; using redb.Route.Serialization; namespace redb.Identity.Core.Serialization; /// /// Route-framework-bound view over the locked Identity wire profiles defined in /// (Contracts). Wraps each profile in an /// singleton and exposes /// for the route data-format registry. /// /// Transport facades that don't link Core (HTTP, gRPC, …) consume the raw /// from directly. /// Core processors and the route registry consume the serializer instances below. /// /// public static class IdentityCodecProfiles { // ── Re-exports of locked Contracts media types (kept for back-compat call sites) ── /// SCIM 2.0 protocol media type — RFC 7644 §3. Re-export of . public const string ScimMediaType = IdentityWireProfiles.ScimMediaType; /// Problem Details media type — RFC 9457 §3. Re-export of . public const string ProblemMediaType = IdentityWireProfiles.ProblemMediaType; /// OAuth / OIDC JSON media type — RFC 6749 §5.1. Re-export of . public const string OAuthMediaType = IdentityWireProfiles.OAuthMediaType; // ── Re-exports of locked Contracts options (kept for in-Core call sites) ── /// SCIM response options. Re-export of . public static JsonSerializerOptions ScimOptions => IdentityWireProfiles.ScimOptions; /// Problem Details response options. Re-export of . public static JsonSerializerOptions ProblemOptions => IdentityWireProfiles.ProblemOptions; /// OAuth / OIDC / DCR response options. Re-export of . public static JsonSerializerOptions OAuthOptions => IdentityWireProfiles.OAuthOptions; // ── IMessageSerializer-typed profile singletons ────────────────────────── /// Serializer instance for SCIM responses (). Thread-safe singleton. public static readonly IMessageSerializer Scim = new JsonMessageSerializer(IdentityWireProfiles.ScimOptions, ScimMediaType, new[] { ScimMediaType }); /// Serializer instance for Problem Details responses (). Thread-safe singleton. public static readonly IMessageSerializer Problem = new JsonMessageSerializer(IdentityWireProfiles.ProblemOptions, ProblemMediaType, new[] { ProblemMediaType }); /// /// Serializer instance for OAuth / OIDC / DCR responses. /// /// Not registered into by /// — OAuth/OIDC/DCR processors invoke /// this directly so an application-level reconfiguration of the generic /// application/json codec cannot reshape the OAuth wire format. /// /// public static readonly IMessageSerializer OAuthJson = new JsonMessageSerializer(IdentityWireProfiles.OAuthOptions, OAuthMediaType, new[] { OAuthMediaType }); /// /// Registers the media-type-addressable Identity profiles into the supplied /// route-context registry. Call site: IdentityCodecProfilesConfigurator.Configure. /// public static void RegisterInto(IDataFormatRegistry registry) { ArgumentNullException.ThrowIfNull(registry); registry.Register(ScimMediaType, Scim); registry.RegisterProfile("scim", Scim); registry.Register(ProblemMediaType, Problem); registry.RegisterProfile("problem", Problem); } } Path: redb-identity/src/redb.Identity.Core/Serialization/IdentityCodecProfilesConfigurator.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/Serialization/IdentityCodecProfilesConfigurator.cs ---- using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Extensions; namespace redb.Identity.Core.Serialization; /// /// Registers into the route context's /// at engine-start time. /// /// Runs through the pattern so the profile /// registration happens after has materialised its /// internal service map (registry is context-local, not DI-resolved). Adding via /// services.AddSingleton<IRouteContextConfigurator>(...) in /// AddRedbIdentityServer is sufficient; no additional wiring required. /// /// /// Only media-type-addressable profiles (application/scim+json, /// application/problem+json) are registered. The OAuth profile /// () is invoked by callers directly to /// insulate OAuth/OIDC wire format from app-level registry reconfiguration /// (ConfigureJsonCodec must never affect RFC 6749 responses). /// /// internal sealed class IdentityCodecProfilesConfigurator : IRouteContextConfigurator { public void Configure(RouteContext context) { ArgumentNullException.ThrowIfNull(context); var registry = context.GetService() ?? throw new InvalidOperationException( "IDataFormatRegistry is not available on the route context. " + "Ensure redb.Route is registered before redb.Identity."); IdentityCodecProfiles.RegisterInto(registry); } } Path: redb-identity/src/redb.Identity.Core/Services/BackchannelLogoutDispatcher.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/Services/BackchannelLogoutDispatcher.cs ---- using System.Net.Http.Headers; using Microsoft.Extensions.Logging; using redb.Core; using redb.Identity.Core.Models; namespace redb.Identity.Core.Services; /// /// Sends OIDC Back-Channel Logout 1.0 notifications to relying parties after a successful /// logout. For each application that the user had active authorizations with AND that has /// a configured, POSTs a signed /// logout_token to that URL. /// /// /// Delivery is best-effort: failures are logged + emitted as an audit event, but do not /// fail the logout operation. Persistent retry / DLQ should be handled by Multicast'ing /// the audit event to a durable transport (RabbitMQ / Kafka) — see /// IdentityAuditOptions.Targets. /// /// public sealed class BackchannelLogoutDispatcher { private const string HttpClientName = "redb-identity-backchannel-logout"; private readonly IHttpClientFactory _httpClientFactory; private readonly LogoutTokenBuilder _tokenBuilder; private readonly ILogger? _logger; private readonly redb.Identity.Core.Configuration.BackchannelLogoutOptions _options; public BackchannelLogoutDispatcher( IHttpClientFactory httpClientFactory, LogoutTokenBuilder tokenBuilder, Microsoft.Extensions.Options.IOptions options, ILogger? logger = null) { ArgumentNullException.ThrowIfNull(httpClientFactory); ArgumentNullException.ThrowIfNull(tokenBuilder); ArgumentNullException.ThrowIfNull(options); _options = options.Value.BackchannelLogout; _httpClientFactory = httpClientFactory; _tokenBuilder = tokenBuilder; _logger = logger; } /// /// Sends logout_token POSTs for every distinct RP affected by a logout. /// /// redb service for loading application records. /// /// The End-User's public subject — the sub of every token this server issued for them /// (), which is what a relying party matches the logout token /// against. Not the internal user id. /// /// /// When > 0 and the application opted into BackchannelLogoutSessionRequired, /// this becomes the sid claim. /// /// /// Distinct application object ids that obtained tokens through the session being ended (or, for a /// logout of every session, hold tokens for the user). Caller must collect them BEFORE revoking. /// /// The number of POSTs successfully delivered (HTTP 2xx). public async Task DispatchAsync( IRedbService redb, Guid subject, long sessionId, IReadOnlyCollection applicationObjectIds, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(redb); ArgumentNullException.ThrowIfNull(applicationObjectIds); if (applicationObjectIds.Count == 0) return 0; if (subject == Guid.Empty) throw new ArgumentException("The subject must be the user's public subject GUID.", nameof(subject)); if (!_tokenBuilder.CanIssue) { _logger?.LogDebug("LogoutTokenBuilder.CanIssue=false — skipping backchannel dispatch."); return 0; } var sub = subject.ToString("D"); var sid = sessionId > 0 ? sessionId.ToString(System.Globalization.CultureInfo.InvariantCulture) : null; var http = _httpClientFactory.CreateClient(HttpClientName); if (http.Timeout == Timeout.InfiniteTimeSpan) http.Timeout = TimeSpan.FromSeconds(10); // Batch-load every distinct ApplicationProps in ONE query rather than per-id LoadAsync. // A user with many active client sessions otherwise turned this fan-out into an O(N) // round-trip storm before the HTTP fan-out even started. var distinctIds = applicationObjectIds.Where(i => i > 0).Distinct().ToArray(); if (distinctIds.Length == 0) return 0; var apps = await redb.Query() .WhereInRedb(o => o.Id, distinctIds) .ToListAsync() .ConfigureAwait(false); var delivered = 0; foreach (var loaded in apps) { var app = loaded; var props = app.Props; if (string.IsNullOrEmpty(props.BackchannelLogoutUri) || string.IsNullOrEmpty(props.ClientId)) continue; var includeSid = props.BackchannelLogoutSessionRequired && sid is not null; var token = _tokenBuilder.Build(props.ClientId, sub, includeSid ? sid : null); if (token is null) continue; // The address is checked before every POST, not only when it was registered: it may resolve // differently now, and records from earlier versions were never checked. A refusal skips this // relying party only; the logout itself goes on. var rejection = await OutboundUrlGuard.ValidateAsync( props.BackchannelLogoutUri, _options.RequireHttps, _options.AllowPrivateNetworkTargets, ct).ConfigureAwait(false); if (rejection != OutboundUrlGuard.Rejection.None) { _logger?.LogWarning("Backchannel logout to {ClientId} refused: {Reason}.", props.ClientId, OutboundUrlGuard.Describe(rejection)); continue; } try { using var content = new FormUrlEncodedContent(new[] { new KeyValuePair("logout_token", token) }); content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded"); using var response = await http.PostAsync(props.BackchannelLogoutUri, content, ct).ConfigureAwait(false); if (response.IsSuccessStatusCode) { delivered++; _logger?.LogDebug("Backchannel logout delivered to {ClientId} ({Status}).", props.ClientId, (int)response.StatusCode); } else { _logger?.LogWarning("Backchannel logout to {ClientId} returned {Status}.", props.ClientId, (int)response.StatusCode); } } catch (Exception ex) when (ex is not OperationCanceledException || !ct.IsCancellationRequested) { // Best-effort delivery: never let an RP outage break the logout flow. _logger?.LogWarning("Backchannel logout to {ClientId} failed: {Failure}.", props.ClientId, ex.GetType().Name); } } return delivered; } } Path: redb-identity/src/redb.Identity.Core/Services/ClaimMappersResolver.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/Services/ClaimMappersResolver.cs ---- using System.Collections.Concurrent; using System.Reflection; using System.Security.Claims; using System.Text.Json; using Microsoft.Extensions.Logging; using OpenIddict.Abstractions; using redb.Core; using redb.Core.Models.Entities; using redb.Core.Query; using redb.Identity.Core.Models; using static OpenIddict.Abstractions.OpenIddictConstants; namespace redb.Identity.Core.Services; /// /// H5 (v1.0 DoD §5): Resolves declarative rules and applies /// them to a at token-issuance time. /// /// Resolution scope (in apply order, last write wins per ClaimType): /// /// Global rules: parent_id IS NULL. /// Assigned Client Scope rules: parent_id IN (assigned scope ids). /// Per-application overlay rules: parent_id = applicationId. /// /// Within the same precedence band, ascending breaks /// ties (last in Order wins). /// /// /// Mirror of Keycloak's "default scope mappers + assigned client scopes + client mappers" /// composition, applied at the OpenIddict ProcessSignInContext stage. /// /// public sealed class ClaimMappersResolver { private readonly IRedbService _redb; private readonly ILogger? _logger; /// Reflected getter cache for dotted paths. private static readonly ConcurrentDictionary?> _propPathCache = new(); public ClaimMappersResolver(IRedbService redb, ILogger? logger = null) { _redb = redb ?? throw new ArgumentNullException(nameof(redb)); _logger = logger; } /// /// Loads applicable mappers, resolves their values and adds claims to /// 's identity. Existing claims with the same /// are removed before the mapper-emitted /// claim is added (mappers ALWAYS override values from /// and other earlier sources for their claim type). /// /// Principal to enrich. null identity = no-op. /// Subject id for resolving UserProps sources. /// /// Object id of the OAuth application receiving the token, or null for grants /// without a client (e.g. some service-to-service flows). When null, only global /// mappers run; per-app overlay and assigned scopes are skipped. /// /// Scopes requested for this issuance. /// Cancellation token. /// /// Thrown when a mapper marked resolves to a /// null / empty value. Caller (OpenIddict handler) should translate to /// error=invalid_request. /// public async Task EnrichPrincipalAsync( ClaimsPrincipal principal, long userId, long? applicationId, IEnumerable requestedScopes, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(principal); if (principal.Identity is not ClaimsIdentity identity) return; var scopeSet = new HashSet( requestedScopes ?? Array.Empty(), StringComparer.Ordinal); // ── 1. Load all applicable mapper rules in two queries ── // Sequential by design: IRedbService is not thread-safe across concurrent // operations on the same instance (same constraint as EF DbContext). // Reduce round-trips by collapsing global + per-app-overlay into ONE // query (parent_id IS NULL OR parent_id == appId), and pushing the // `Enabled` and scope-id filters down to the database — the resolver // never needs disabled rules in memory. // NOTE: defensive `?? []` on every ToListAsync() result. IRedbService is a // public interface; substitute/mock implementations may return Task> // with a null Result. Production (EF) never does, but this resolver runs from // an OpenIddict server handler that we cannot easily disable per-test, so // tolerating null-list returns prevents NREs in unit tests that never set up // ClaimMapper queries. Empty list = "no mappers" = correct behavior. List> globalMappers; List> appOverlayMappers = []; List> scopeMappers = []; if (applicationId is long appId && appId > 0) { // One query covers both global (parent_id IS NULL) and per-app overlay // (parent_id == appId). Split locally by parent_id. var globalAndOverlay = (await _redb.Query() .WhereRedb(o => o.ParentId == null || o.ParentId == appId) .Where(m => m.Enabled) .ToListAsync().ConfigureAwait(false)) ?? []; globalMappers = globalAndOverlay.Where(m => m.ParentId is null).ToList(); appOverlayMappers = globalAndOverlay.Where(m => m.ParentId == appId).ToList(); // Resolve assigned Client Scopes for the application var assignments = (await _redb.Query() .WhereRedb(o => o.Key == appId) .ToListAsync().ConfigureAwait(false)) ?? []; var assignedScopeIds = assignments .Select(a => a.Props.ScopeId) .Where(id => id > 0) .Distinct() .ToList(); if (assignedScopeIds.Count > 0) { // Server-side filter + projection: only enabled scopes, return ids only. // Avoids materialising full ClaimScopeProps rows just to read the id. var enabledScopeIds = (await _redb.Query() .WhereInRedb(o => o.Id, assignedScopeIds) .Where(s => s.Enabled) .Select(o => o.id) .ToListAsync().ConfigureAwait(false)) ?? []; if (enabledScopeIds.Count > 0) { var enabledScopeIdsAsParent = enabledScopeIds.Cast().ToList(); scopeMappers = (await _redb.Query() .WhereInRedb(o => o.ParentId, enabledScopeIdsAsParent) .Where(m => m.Enabled) .ToListAsync().ConfigureAwait(false)) ?? []; } } } else { // No application context — only global mappers apply. globalMappers = (await _redb.Query() .WhereRedb(o => o.ParentId == null) .Where(m => m.Enabled) .ToListAsync().ConfigureAwait(false)) ?? []; } var allMappers = globalMappers .Concat(scopeMappers) .Concat(appOverlayMappers) .ToList(); // Filter: scope-gated (Enabled already enforced at the DB layer above). var applicable = allMappers .Where(m => MatchesRequiredScopes(m.Props.RequiredScopes, scopeSet)) .OrderBy(m => GetPrecedence(m, applicationId)) // global=0, scope=1, app=2 .ThenBy(m => m.Props.Order) .ToList(); if (applicable.Count == 0) return; // ── 2. Lazy-load UserProps ONCE if any mapper needs it ── UserProps? userProps = null; if (applicable.Any(m => NeedsUserProps(m.Props.SourceKind))) { var oidcObj = await _redb.Query() .WhereRedb(o => o.Key == userId) .FirstOrDefaultAsync().ConfigureAwait(false); userProps = oidcObj?.Props; } // ── 3. Resolve + apply with last-write-wins by ClaimType ── var emitted = new Dictionary(StringComparer.Ordinal); foreach (var mapper in applicable) { var props = mapper.Props; var claimType = props.ClaimType?.Trim(); if (string.IsNullOrEmpty(claimType)) { _logger?.LogWarning("ClaimMapper {Id} has empty ClaimType; skipped", mapper.Id); continue; } string? value; try { value = ResolveValue(props, userProps); } catch (Exception ex) { _logger?.LogError(ex, "ClaimMapper {Id} ({ClaimType}) value resolution failed", mapper.Id, claimType); if (props.Required) throw new InvalidOperationException( $"Required claim mapper '{claimType}' (id {mapper.Id}) failed to resolve: {ex.Message}", ex); continue; } if (string.IsNullOrEmpty(value)) { if (props.Required) throw new InvalidOperationException( $"Required claim mapper '{claimType}' (id {mapper.Id}) resolved to empty value"); continue; } var destinations = NormalizeDestinations(props.Destinations); emitted[claimType] = (value, destinations); } // Apply: remove pre-existing claims for these types, then add foreach (var (claimType, payload) in emitted) { foreach (var existing in identity.FindAll(claimType).ToList()) identity.RemoveClaim(existing); var claim = new Claim(claimType, payload.Value); claim.SetDestinations(payload.Destinations); identity.AddClaim(claim); } } // ── value resolution helpers ── private static bool NeedsUserProps(string? sourceKind) => sourceKind is "UserProps" or "CustomClaim"; private static string? ResolveValue(ClaimMapperProps props, UserProps? userProps) { return props.SourceKind switch { "Constant" => props.ConstantValue, "CustomClaim" => ResolveCustomClaim(props.SourcePath, userProps), "UserProps" => ResolveUserPropsPath(props.SourcePath, userProps), _ => throw new InvalidOperationException( $"Unknown SourceKind '{props.SourceKind}' (expected: Constant | CustomClaim | UserProps)") }; } private static string? ResolveCustomClaim(string? key, UserProps? userProps) { if (string.IsNullOrEmpty(key) || userProps?.CustomClaims is null) return null; return userProps.CustomClaims.TryGetValue(key, out var v) ? v : null; } private static string? ResolveUserPropsPath(string? path, UserProps? userProps) { if (userProps is null || string.IsNullOrEmpty(path)) return null; var getter = _propPathCache.GetOrAdd(path, BuildPropPathGetter); if (getter is null) return null; var raw = getter(userProps); return raw switch { null => null, string s => s, bool b => b ? "true" : "false", DateTime dt => dt.ToString("O"), DateTimeOffset dto => dto.ToString("O"), IFormattable f => f.ToString(null, System.Globalization.CultureInfo.InvariantCulture), _ => JsonSerializer.Serialize(raw) }; } private static Func? BuildPropPathGetter(string path) { // Compiled path traversal: segment.segment.segment via reflection. // First segment must be a public instance property of UserProps; subsequent segments // resolve against the running value's runtime type. Returns null for any missing segment. var segments = path.Split('.', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); if (segments.Length == 0) return null; return (UserProps p) => { object? current = p; foreach (var segment in segments) { if (current is null) return null; var prop = current.GetType().GetProperty(segment, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase); if (prop is null) return null; current = prop.GetValue(current); } return current; }; } private static bool MatchesRequiredScopes(string[]? required, HashSet requestedScopes) { if (required is null || required.Length == 0) return true; foreach (var scope in required) { if (!requestedScopes.Contains(scope)) return false; } return true; } private static string[] NormalizeDestinations(string[]? destinations) { if (destinations is null || destinations.Length == 0) return new[] { Destinations.AccessToken, Destinations.IdentityToken }; var result = new List(destinations.Length); foreach (var d in destinations) { switch (d?.Trim().ToLowerInvariant()) { case "access_token": result.Add(Destinations.AccessToken); break; case "id_token": case "identity_token": result.Add(Destinations.IdentityToken); break; // Unknown destinations silently dropped — admin error in DB shouldn't break issuance. } } return result.Count == 0 ? new[] { Destinations.AccessToken, Destinations.IdentityToken } : result.ToArray(); } private static int GetPrecedence(RedbObject mapper, long? applicationId) { if (mapper.ParentId is null) return 0; if (applicationId is long appId && mapper.ParentId == appId) return 2; return 1; // scope } } Path: redb-identity/src/redb.Identity.Core/Services/ClaimSchemaValidator.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/Services/ClaimSchemaValidator.cs ---- using redb.Core; using redb.Core.Query; using redb.Identity.Core.Models; namespace redb.Identity.Core.Services; /// /// S2 — shared validator for global . /// Used by both the admin user-management path /// (UserManagementProcessor.Create/Update) and the public /// self-service registration path (AccountRegisterProcessor) so the /// schema is enforced uniformly regardless of how the user enters the /// system. /// /// /// Per-application definitions are NOT enforced here — those gate token /// issuance time (a user may exist without ever signing into the app whose /// schema requires them). /// /// public static class ClaimSchemaValidator { /// /// Validate (may be null on create) against /// every global . Returns a tuple: /// /// normalized — the validated dict with defaults applied; /// null on validation failure. /// errorMessage — null on success, error string on failure. /// /// public static async Task<(Dictionary? normalized, string? errorMessage)> EnforceGlobalAsync(IRedbService redb, Dictionary? incoming, CancellationToken ct = default) { var definitions = await redb.Query() .Where(p => p.Scope == "global") .ToListAsync() .ConfigureAwait(false); var result = new Dictionary(incoming ?? new(), StringComparer.Ordinal); // Null-guard for the Query result — production providers always return // a (possibly empty) list, but unit-test substitutes may not configure // the schema-defs query and return null. No-op when empty / null. if (definitions is null) return (result, null); foreach (var def in definitions) { var name = def.Props.ClaimName; var has = result.TryGetValue(name, out var value); if (!has || string.IsNullOrEmpty(value)) { if (def.Props.Required) { if (!string.IsNullOrEmpty(def.Props.DefaultValue)) { result[name] = def.Props.DefaultValue; continue; } return (null, $"Claim '{name}' is required"); } // Optional + missing — leave unset. continue; } switch ((def.Props.Type ?? "string").ToLowerInvariant()) { case "int": if (!int.TryParse(value, out _)) return (null, $"Claim '{name}' must be an int"); break; case "long": if (!long.TryParse(value, out _)) return (null, $"Claim '{name}' must be a long"); break; case "bool": if (!bool.TryParse(value, out _)) return (null, $"Claim '{name}' must be 'true' or 'false'"); break; case "datetime": if (!DateTimeOffset.TryParse(value, out _)) return (null, $"Claim '{name}' must be an ISO-8601 datetime"); break; case "url": if (!Uri.TryCreate(value, UriKind.Absolute, out _)) return (null, $"Claim '{name}' must be an absolute URL"); break; case "email": if (!value.Contains('@') || value.Length < 3) return (null, $"Claim '{name}' must be a valid email"); break; case "string": default: if (!string.IsNullOrEmpty(def.Props.ValidationPattern)) { try { if (!System.Text.RegularExpressions.Regex.IsMatch(value, def.Props.ValidationPattern)) return (null, $"Claim '{name}' does not match the required pattern"); } catch (Exception) { // Malformed pattern — treat as no constraint to avoid blocking // operator mutations behind a definition row they can't fix. } } break; } } return (result, null); } } Path: redb-identity/src/redb.Identity.Core/Services/ClientChosenAddressHandler.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/Services/ClientChosenAddressHandler.cs ---- using System.Net; using System.Net.Sockets; namespace redb.Identity.Core.Services; /// /// The primary handler of the HTTP clients that contact an address a client chose (its jwks_uri, a JAR /// request_uri, its back-channel logout URI). checks the name /// before a request as an early refusal; this handler makes the connection itself safe: /// /// the host is resolved once, here, and the connection goes only to an address from that answer, so the name /// cannot resolve to one address for the check and to another for the connection; /// unless private targets are allowed, one non-public address in the answer refuses the name /// (, IPv4-mapped forms included); /// the approved addresses are tried in order until one connects, within the caller's cancellation and the /// client's timeout; /// redirects are not followed. /// /// TLS stays the handler's, validated against the request's host name. With a proxy configured the handler connects /// to the proxy, not the target: the proxy endpoint is not checked by the address rule (a proxy usually sits on a /// private address), the name pre-check is Identity's only check, and the proxy's policy decides where the request /// ends. /// internal static class ClientChosenAddressHandler { /// Resolves a host name to its addresses; replaceable in tests. internal delegate Task Resolver(string host, CancellationToken ct); internal static SocketsHttpHandler Create(bool allowPrivateNetworkTargets, Resolver? resolve = null) { resolve ??= static (host, ct) => Dns.GetHostAddressesAsync(host, ct); var handler = new SocketsHttpHandler { AllowAutoRedirect = false }; handler.ConnectCallback = (context, ct) => ConnectAsync(handler, context, allowPrivateNetworkTargets, resolve, ct); return handler; } private static async ValueTask ConnectAsync( SocketsHttpHandler handler, SocketsHttpConnectionContext context, bool allowPrivate, Resolver resolve, CancellationToken ct) { var endpoint = context.DnsEndPoint; // Everything is the target and checked, except the one endpoint this handler's proxy configuration names for // this request: a wrong guess then refuses a connection, it never leaves one unchecked. var isTarget = !IsProxyEndpoint(handler, context.InitialRequestMessage.RequestUri, endpoint); var addresses = IPAddress.TryParse(Unbracket(endpoint.Host), out var literal) ? [literal] : await resolve(endpoint.Host, ct).ConfigureAwait(false); if (addresses.Length == 0) throw new HttpRequestException("The host does not resolve."); if (isTarget && !allowPrivate && addresses.Any(a => !OutboundUrlGuard.IsPublic(a))) throw new HttpRequestException("The host resolves to a non-public address."); Exception? last = null; foreach (var address in addresses) { var socket = new Socket(address.AddressFamily, SocketType.Stream, ProtocolType.Tcp) { NoDelay = true }; try { await socket.ConnectAsync(new IPEndPoint(address, endpoint.Port), ct).ConfigureAwait(false); return new NetworkStream(socket, ownsSocket: true); } catch (SocketException e) { socket.Dispose(); last = e; } catch { socket.Dispose(); throw; } } throw new HttpRequestException("No address of the host accepted the connection.", last); } /// /// True when is the proxy the handler uses for : the /// handler's , or when none is set, /// with the request not bypassed, compared by host and port. A proxy answer that names the request's own host is /// not a proxy. /// private static bool IsProxyEndpoint(SocketsHttpHandler handler, Uri? requestUri, DnsEndPoint endpoint) { if (requestUri is null || !handler.UseProxy) return false; var proxy = handler.Proxy ?? HttpClient.DefaultProxy; if (proxy is null || proxy.IsBypassed(requestUri)) return false; var proxyUri = proxy.GetProxy(requestUri); if (proxyUri is null) return false; if (SameEndpoint(proxyUri, requestUri.IdnHost, requestUri.Port)) return false; return SameEndpoint(proxyUri, endpoint.Host, endpoint.Port); } private static bool SameEndpoint(Uri uri, string host, int port) => uri.Port == port && string.Equals(Unbracket(uri.IdnHost), Unbracket(host), StringComparison.OrdinalIgnoreCase); private static string Unbracket(string host) => host.Length > 1 && host[0] == '[' && host[^1] == ']' ? host[1..^1] : host; } Path: redb-identity/src/redb.Identity.Core/Services/ClientKeyResolver.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/Services/ClientKeyResolver.cs ---- using System.Collections.Concurrent; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Microsoft.IdentityModel.Tokens; using redb.Core.Models.Entities; using redb.Identity.Core.Configuration; using redb.Identity.Core.Models; namespace redb.Identity.Core.Services; /// /// Default : the inline JWKS when the client has one, otherwise a cached fetch of /// the client's jwks_uri. /// /// The fetch can be set off by an unauthenticated caller (a client assertion or a request object naming any client), /// so it is bounded per address: /// /// a fetched set is reused for ; /// at most one fetch is started per , whatever asks /// for it (an expired cache, a forced refresh after an unknown kid, a retry after a failure), so a failed /// fetch is not retried per request; /// concurrent callers share the one fetch in flight; /// a fetch ends after and reads at most /// ; /// checks the address before every fetch, since it may resolve differently /// from one fetch to the next. /// /// A failed fetch keeps the last good set until a later fetch succeeds; with none, the client has no keys and the /// caller refuses the request. The log names the client and the failure class, never the document. /// /// internal sealed class ClientKeyResolver : IClientKeyResolver { private readonly IHttpClientFactory _httpClientFactory; private readonly ClientKeysOptions _options; private readonly ILogger _logger; private readonly TimeProvider _time; /// One entry per jwks_uri; they hold the cached set, so they live as long as this singleton. private readonly ConcurrentDictionary _entries = new(StringComparer.Ordinal); public ClientKeyResolver( IHttpClientFactory httpClientFactory, IOptions identityOptions, ILogger logger, TimeProvider? timeProvider = null) { _httpClientFactory = httpClientFactory ?? throw new ArgumentNullException(nameof(httpClientFactory)); _options = identityOptions?.Value?.ClientKeys ?? throw new ArgumentNullException(nameof(identityOptions)); _logger = logger ?? throw new ArgumentNullException(nameof(logger)); _time = timeProvider ?? TimeProvider.System; } public async ValueTask> GetSigningKeysAsync( RedbObject application, bool forceRefresh = false, CancellationToken cancellationToken = default) { var set = await GetJsonWebKeySetAsync(application, forceRefresh, cancellationToken).ConfigureAwait(false); // Copy: a cached set may be handed out again. return set?.GetSigningKeys().ToArray() ?? []; } public async ValueTask GetJsonWebKeySetAsync( RedbObject application, bool forceRefresh = false, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(application); // Inline wins and is the only source when present: operator-controlled, no network call. A CONFIGURED inline // set is final even when it yields nothing — falling back to jwks_uri would hide a typo behind a working login. var json = application.Props.JsonWebKeySet; if (!string.IsNullOrWhiteSpace(json)) { try { return JsonWebKeySet.Create(json); } catch (Exception e) { _logger.LogWarning(e, "Client {ClientId} has an unparseable inline JWKS; treating it as having no keys.", application.Props.ClientId); return null; } } var jwksUri = application.Props.JwksUri; if (string.IsNullOrWhiteSpace(jwksUri)) return null; var added = false; var entry = _entries.GetOrAdd(jwksUri, _ => { added = true; return new Entry(); }); if (added && _entries.Count > _options.MaxCachedKeySets) Trim(jwksUri); Task fetch; lock (entry) { var now = _time.GetUtcNow(); entry.LastUsed = now; var fresh = entry.Keys is not null && now - entry.FetchedAt < _options.CacheLifetime; if (fresh && !forceRefresh) return entry.Keys; if (entry.InFlight is null) { // One fetch per interval, whatever asked for it; a failure is not retried per request. if (now - entry.LastAttempt < _options.MinimumRefreshInterval) return entry.Keys; entry.LastAttempt = now; entry.InFlight = FetchAsync(jwksUri, application.Props.ClientId, entry); } fetch = entry.InFlight; } // The shared fetch has its own timeout; a caller that gives up does not cancel it for the others. var result = await fetch.WaitAsync(cancellationToken).ConfigureAwait(false); if (result is not null) return result; lock (entry) return entry.Keys; // a failed fetch keeps the last good set } private async Task FetchAsync(string jwksUri, string? clientId, Entry entry) { await Task.Yield(); JsonWebKeySet? fetched = null; try { var rejection = await OutboundUrlGuard.ValidateAsync( jwksUri, _options.RequireHttps, _options.AllowPrivateNetworkTargets, CancellationToken.None) .ConfigureAwait(false); if (rejection != OutboundUrlGuard.Rejection.None) { // Refused before any socket is opened: the URL came from the client record. _logger.LogWarning("Refusing to fetch jwks_uri for client {ClientId}: {Reason}.", clientId, OutboundUrlGuard.Describe(rejection)); return null; } var http = _httpClientFactory.CreateClient(HttpClientName); http.Timeout = _options.FetchTimeout; // Caps the buffered body so a hostile endpoint cannot stream an unbounded response at us. http.MaxResponseContentBufferSize = _options.MaxDocumentBytes; // HttpClient.Timeout cancels the request; WaitAsync bounds the wait even if a handler ignores that. var document = await http.GetStringAsync(jwksUri).WaitAsync(_options.FetchTimeout).ConfigureAwait(false); var set = JsonWebKeySet.Create(document); // A set that verifies nothing is no better than none: keep the last good set. if (set.GetSigningKeys().Count == 0) { _logger.LogWarning("Failed to fetch JWKS for client {ClientId}: {Failure}.", clientId, "no usable signing keys"); return null; } fetched = set; return fetched; } catch (Exception e) { // Unreachable, slow, refused or malformed: no new keys. Only the class of the failure is logged. _logger.LogWarning("Failed to fetch JWKS for client {ClientId}: {Failure}.", clientId, FailureClass(e)); return null; } finally { lock (entry) { if (fetched is not null) { entry.Keys = fetched; entry.FetchedAt = _time.GetUtcNow(); } entry.InFlight = null; } } } /// /// Brings the cache back to : entries whose cache lifetime has /// passed (or that never got a set) go first, then the least recently used. An entry with a fetch in flight, and /// the one just added, stay. /// private void Trim(string keep) { var now = _time.GetUtcNow(); var candidates = new List<(string Uri, bool Expired, DateTimeOffset LastUsed)>(); foreach (var (uri, e) in _entries) { if (uri == keep) continue; lock (e) { if (e.InFlight is not null) continue; candidates.Add((uri, e.Keys is null || now - e.FetchedAt >= _options.CacheLifetime, e.LastUsed)); } } foreach (var c in candidates.OrderByDescending(c => c.Expired).ThenBy(c => c.LastUsed)) { if (_entries.Count <= _options.MaxCachedKeySets) break; if (!_entries.TryGetValue(c.Uri, out var e)) continue; lock (e) { if (e.InFlight is not null) continue; _entries.TryRemove(new KeyValuePair(c.Uri, e)); } } } private static string FailureClass(Exception e) => e switch { TaskCanceledException or TimeoutException => "timeout", HttpRequestException { StatusCode: { } status } => $"HTTP {(int)status}", HttpRequestException => "connection failed", ArgumentException or System.Text.Json.JsonException => "not a JSON Web Key Set", _ => e.GetType().Name, }; /// Number of addresses currently cached (for tests and diagnostics). internal int CachedKeySetCount => _entries.Count; /// Named used for client JWKS fetches. internal const string HttpClientName = "redb-identity-client-keys"; private sealed class Entry { public JsonWebKeySet? Keys; public DateTimeOffset FetchedAt; public DateTimeOffset LastAttempt = DateTimeOffset.MinValue; public DateTimeOffset LastUsed; public Task? InFlight; } } Path: redb-identity/src/redb.Identity.Core/Services/ConsentService.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/Services/ConsentService.cs ---- using redb.Core; using redb.Core.Models.Entities; using redb.Identity.Core.Models; using OpenIddict.Abstractions; namespace redb.Identity.Core.Services; /// /// Manages explicit user consent grants. Consent is stored as an OpenIddict Authorization /// with Type = "permanent" and Status = "valid". /// This is a thin wrapper over that queries /// directly for performance. /// public sealed class ConsentService { private readonly IRedbService _redb; public ConsentService(IRedbService redb) => _redb = redb; /// /// Checks whether the user has an existing valid permanent consent for the given application /// that covers all the requested scopes. /// /// The matching consent authorization, or null if none found. public async Task?> CheckAsync( long userId, long applicationId, IReadOnlyCollection requestedScopes, CancellationToken ct = default) { var candidates = await _redb.Query() .WhereRedb(o => o.Key == userId) .Where(a => a.ApplicationObjectId == applicationId) .Where(a => a.Status == OpenIddictConstants.Statuses.Valid) .Where(a => a.Type == OpenIddictConstants.AuthorizationTypes.Permanent) .ToListAsync() .ConfigureAwait(false); foreach (var candidate in candidates) { var grantedScopes = candidate.Props.Scopes ?? []; if (requestedScopes.All(s => grantedScopes.Contains(s))) return candidate; } return null; } /// /// Creates or extends a permanent consent grant. /// If an existing valid permanent authorization exists for the same user+app, /// its scopes are merged (union) with the new scopes. /// /// The created or updated consent authorization. public async Task> GrantAsync( long userId, long applicationId, IReadOnlyCollection scopes, CancellationToken ct = default) { // Check for existing consent to merge scopes var existing = await _redb.Query() .WhereRedb(o => o.Key == userId) .Where(a => a.ApplicationObjectId == applicationId) .Where(a => a.Status == OpenIddictConstants.Statuses.Valid) .Where(a => a.Type == OpenIddictConstants.AuthorizationTypes.Permanent) .FirstOrDefaultAsync() .ConfigureAwait(false); if (existing is not null) { var merged = (existing.Props.Scopes ?? []).Union(scopes).Distinct().ToArray(); existing.Props.Scopes = merged; await _redb.SaveAsync(existing).ConfigureAwait(false); return existing; } var auth = new RedbObject { key = userId, Props = new AuthorizationProps { ApplicationObjectId = applicationId, Status = OpenIddictConstants.Statuses.Valid, Type = OpenIddictConstants.AuthorizationTypes.Permanent, Scopes = scopes.ToArray() } }; auth.id = await _redb.SaveAsync(auth).ConfigureAwait(false); return auth; } /// /// Revokes all permanent consent grants for a user+application pair. /// /// Number of consents revoked. public async Task RevokeAsync( long userId, long applicationId, CancellationToken ct = default) { var targets = await _redb.Query() .WhereRedb(o => o.Key == userId) .Where(a => a.ApplicationObjectId == applicationId) .Where(a => a.Type == OpenIddictConstants.AuthorizationTypes.Permanent) .Where(a => a.Status == OpenIddictConstants.Statuses.Valid) .ToListAsync() .ConfigureAwait(false); foreach (var target in targets) { target.Props.Status = OpenIddictConstants.Statuses.Revoked; await _redb.SaveAsync(target).ConfigureAwait(false); } return targets.Count; } /// /// Revokes ALL permanent consent grants for a user (across all applications). /// public async Task RevokeAllAsync(long userId, CancellationToken ct = default) { var targets = await _redb.Query() .WhereRedb(o => o.Key == userId) .Where(a => a.Type == OpenIddictConstants.AuthorizationTypes.Permanent) .Where(a => a.Status == OpenIddictConstants.Statuses.Valid) .ToListAsync() .ConfigureAwait(false); foreach (var target in targets) { target.Props.Status = OpenIddictConstants.Statuses.Revoked; await _redb.SaveAsync(target).ConfigureAwait(false); } return targets.Count; } /// /// Lists all valid permanent consent grants for a user. /// Includes application info (ClientId, DisplayName) by loading the referenced apps. /// /// Application metadata is fetched in a single batched WhereInRedb(o => o.Id, ids) /// query rather than per-row — a power user (or a /// service-principal that accumulated many permanent grants over time) would /// otherwise turn this admin endpoint into an O(N) round-trip storm. Production /// repro: a single user with ~1300 permanent grants caused this method to take ~10 s /// because each ApplicationProps load was a separate DB round-trip. /// /// public async Task> ListAsync(long userId, CancellationToken ct = default) { var consents = await _redb.Query() .WhereRedb(o => o.Key == userId) .Where(a => a.Type == OpenIddictConstants.AuthorizationTypes.Permanent) .Where(a => a.Status == OpenIddictConstants.Statuses.Valid) .ToListAsync() .ConfigureAwait(false); // Batch-fetch every distinct ApplicationProps in ONE query instead of per-row // LoadAsync. The Dictionary lookup below replaces the N+1 round-trip pattern. var appIds = consents .Where(c => c.Props.ApplicationObjectId > 0) .Select(c => c.Props.ApplicationObjectId) .Distinct() .ToArray(); var appsById = new Dictionary>(appIds.Length); if (appIds.Length > 0) { var apps = await _redb.Query() .WhereInRedb(o => o.Id, appIds) .ToListAsync() .ConfigureAwait(false); foreach (var app in apps) appsById[app.id] = app; } var result = new List(consents.Count); foreach (var consent in consents) { string? clientId = null; string? appName = null; if (consent.Props.ApplicationObjectId > 0 && appsById.TryGetValue(consent.Props.ApplicationObjectId, out var app)) { clientId = app.Props.ClientId; appName = app.Name; } result.Add(new ConsentInfo { Id = consent.id, UserId = consent.key ?? 0, ApplicationId = consent.Props.ApplicationObjectId, ClientId = clientId, ApplicationName = appName, Scopes = consent.Props.Scopes ?? [], CreatedAt = consent.date_create }); } return result; } /// /// Finds the application object ID by client_id. /// public async Task FindApplicationIdAsync(string clientId, CancellationToken ct = default) { var app = await _redb.GetByUniqueAsync(p => p.ClientId, clientId) .ConfigureAwait(false); return app?.id; } public sealed class ConsentInfo { public long Id { get; set; } public long UserId { get; set; } public long ApplicationId { get; set; } public string? ClientId { get; set; } public string? ApplicationName { get; set; } public string[] Scopes { get; set; } = []; public DateTimeOffset CreatedAt { get; set; } } } Path: redb-identity/src/redb.Identity.Core/Services/DeviceMetadataExtractor.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/Services/DeviceMetadataExtractor.cs ---- using MyCSharp.HttpUserAgentParser; using MyCSharp.HttpUserAgentParser.Providers; using redb.Route.Abstractions; namespace redb.Identity.Core.Services; /// /// Device-identification fields captured from an authentication exchange: sanitized /// client IP, raw User-Agent string, and a human-friendly parsed device label /// (browser + OS family). All fields are optional — non-HTTP transports (CLI, test /// harnesses) produce all-nulls without failing authentication. /// internal readonly record struct DeviceMetadata(string? IpAddress, string? UserAgent, string? DeviceLabel) { public static readonly DeviceMetadata Empty = new(null, null, null); } /// /// Reads client-IP and User-Agent from the inbound exchange headers (as populated /// by HttpConsumer and sanitized by TrustedProxyResolverProcessor) and /// derives a display-friendly device label via . /// /// /// The IP source is redbHttp.RemoteAddress — which already reflects the /// real client after trusted-proxy resolution (see TrustedProxyResolverProcessor). /// X-Forwarded-For is intentionally not read here to avoid a second, uncoordinated /// trust decision. /// The UA string is truncated to 512 characters before persistence to bound the PROPS /// row payload against hostile or buggy clients sending megabyte-sized UA strings. /// When no parser is registered (lean test host), still /// populates IpAddress/UserAgent and returns DeviceLabel = null. /// internal static class DeviceMetadataExtractor { private const int UserAgentMaxLength = 512; public static DeviceMetadata Extract(IExchange? exchange, IHttpUserAgentParserProvider? parser) { if (exchange?.In is null) return DeviceMetadata.Empty; var headers = exchange.In.Headers; // redbHttp.RemoteAddress is populated by HttpConsumer from HttpContext.Connection // and — when ReverseProxyOptions.TrustForwardedFor=true and the socket peer is // whitelisted — replaced with the first untrusted hop of X-Forwarded-For by // TrustedProxyResolverProcessor. We consume it as-is here. string? ip = null; if (headers.TryGetValue("redbHttp.RemoteAddress", out var ipHdr) && ipHdr is not null) ip = ipHdr.ToString(); string? ua = null; if (headers.TryGetValue("User-Agent", out var uaHdr) && uaHdr is not null) { ua = uaHdr.ToString(); if (ua is { Length: > UserAgentMaxLength }) ua = ua.Substring(0, UserAgentMaxLength); } return new DeviceMetadata(ip, ua, ParseLabel(ua, parser)); } internal static string? ParseLabel(string? userAgent, IHttpUserAgentParserProvider? parser) { if (string.IsNullOrWhiteSpace(userAgent) || parser is null) return null; HttpUserAgentInformation info; try { info = parser.Parse(userAgent); } catch { // Parser is best-effort — a malformed UA must never fail the authentication // flow. Fall back to a safe truncated snippet so operators still see *something* // in the sessions UI. return Truncate(userAgent, 64); } var browser = string.IsNullOrEmpty(info.Name) ? null : info.Name!; var version = MajorVersion(info.Version); var platform = info.Platform?.Name; if (browser is null && platform is null) return Truncate(userAgent, 64); var left = browser is null ? "Unknown browser" : (version is null ? browser : $"{browser} {version}"); var right = string.IsNullOrEmpty(platform) ? "unknown OS" : platform!; return $"{left} on {right}"; } private static string? MajorVersion(string? fullVersion) { if (string.IsNullOrEmpty(fullVersion)) return null; var dot = fullVersion.IndexOf('.'); return dot > 0 ? fullVersion.Substring(0, dot) : fullVersion; } private static string Truncate(string value, int maxLength) => value.Length <= maxLength ? value : value.Substring(0, maxLength); } Path: redb-identity/src/redb.Identity.Core/Services/DisabledUserRejectionHandler.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/Services/DisabledUserRejectionHandler.cs ---- using System.Security.Claims; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using OpenIddict.Abstractions; using OpenIddict.Validation; using redb.Core; using static OpenIddict.Abstractions.OpenIddictConstants; using static OpenIddict.Validation.OpenIddictValidationEvents; namespace redb.Identity.Core.Services; /// /// Rejects bearer tokens whose subject points to a disabled / soft-deleted user. /// /// Standard JWT bearer validation only checks signature + expiry — once a token is /// issued, deleting or disabling the underlying user account doesn't instantly /// invalidate the token (the JWT is self-contained, OpenIddict has no per-request /// hook into the user store). This handler closes that gap: after the built-in /// principal-extraction handlers have set context.Principal, we load the /// subject's user row from the redb user store and reject the request if the user /// is missing or _enabled=false (soft-deleted via ). /// /// /// Client-credentials tokens (no sub resolvable to a redb user) skip this /// check — they're scoped to client identity, not a deletable user. /// /// internal sealed class DisabledUserRejectionHandler : IOpenIddictValidationHandler { public static OpenIddictValidationHandlerDescriptor Descriptor { get; } = OpenIddictValidationHandlerDescriptor .CreateBuilder() // Run AFTER principal-extraction handlers populate context.Principal but // before downstream handlers that depend on the principal. .UseSingletonHandler() .SetOrder(int.MaxValue - 1000) .Build(); private readonly IServiceProvider _sp; private readonly ILogger _logger; public DisabledUserRejectionHandler( IServiceProvider sp, ILogger logger) { _sp = sp; _logger = logger; } public async ValueTask HandleAsync(ProcessAuthenticationContext context) { if (context.IsRejected) return; // For OpenIddict.Validation, the access-token principal lives on // `AccessTokenPrincipal` (set by the built-in extraction handlers). The // unified `Principal` is set later in the pipeline. var principal = context.AccessTokenPrincipal; if (principal is null) return; try { var (userId, state) = await GetUserStateAsync(_sp, principal).ConfigureAwait(false); if (state is TokenUserState.Missing or TokenUserState.Disabled) { _logger.LogInformation( "Bearer rejected: user {UserId} is {State}", userId, state is TokenUserState.Missing ? "missing" : "disabled"); context.Reject( error: Errors.InvalidToken, description: "The user account associated with this token has been disabled or deleted."); } } catch (Exception ex) { // Don't fail-open on unexpected errors — surface as invalid_token so the // caller gets a clear 401 rather than masquerading as a successful auth. _logger.LogWarning(ex, "Bearer validation failed for user {UserId} — store unavailable", principal.GetClaim(UserIdClaim)); context.Reject( error: Errors.ServerError, description: "Token validation failed due to an internal error."); } } private const string UserIdClaim = "redb:user_id"; /// /// Resolves the redb user behind a token principal. Also used by the token exchange grant, whose /// subject and actor tokens are validated by the OpenIddict server stack, where this handler /// does not run. Store errors propagate to the caller. /// internal static async Task<(long UserId, TokenUserState State)> GetUserStateAsync( IServiceProvider sp, ClaimsPrincipal principal) { // Look for the internal numeric user id — IdentityPrincipalBuilder emits it // as `redb:user_id` for end-user grants. CC tokens carry only Claims.Subject // (the client id), no redb:user_id → skip them. var rawUserId = principal.GetClaim(UserIdClaim); if (string.IsNullOrEmpty(rawUserId)) return (0, TokenUserState.NotAUser); if (!long.TryParse(rawUserId, out var userId) || userId <= 0) return (0, TokenUserState.NotAUser); using var scope = sp.CreateScope(); var redb = scope.ServiceProvider.GetService(); if (redb is null) return (userId, TokenUserState.Unknown); // misconfigured DI — fail open rather than block all var user = await redb.UserProvider.GetUserByIdAsync(userId).ConfigureAwait(false); return (userId, user is null ? TokenUserState.Missing : user.Enabled ? TokenUserState.Enabled : TokenUserState.Disabled); } } /// State of the redb user a token principal points to. internal enum TokenUserState { /// No redb user id on the principal (client_credentials token). NotAUser, /// The user store could not be resolved; callers fail open. Unknown, Enabled, Disabled, Missing } Path: redb-identity/src/redb.Identity.Core/Services/DpopProofValidator.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/Services/DpopProofValidator.cs ---- using System.Security.Cryptography; using System.Text; using System.Text.Json; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Microsoft.IdentityModel.JsonWebTokens; using Microsoft.IdentityModel.Tokens; using redb.Identity.Core.Configuration; namespace redb.Identity.Core.Services; /// /// Z4 (RFC 9449): validates a DPoP proof JWT and reserves its jti /// against the configured . /// public sealed class DpopProofValidator { private static readonly JsonWebTokenHandler _handler = new(); private readonly IDpopReplayStore _replayStore; private readonly DpopOptions _options; private readonly TimeProvider _timeProvider; private readonly ILogger _logger; public DpopProofValidator( IDpopReplayStore replayStore, IOptions identityOptions, ILogger logger, TimeProvider? timeProvider = null) { _replayStore = replayStore ?? throw new ArgumentNullException(nameof(replayStore)); _options = (identityOptions ?? throw new ArgumentNullException(nameof(identityOptions))).Value.Dpop; _logger = logger ?? throw new ArgumentNullException(nameof(logger)); _timeProvider = timeProvider ?? TimeProvider.System; } /// /// Validates a DPoP proof JWT bound to the given HTTP method + URL. /// /// The raw DPoP header value (a JWS compact-serialization JWT). /// HTTP method of the protected request (e.g. POST). /// Absolute URL of the protected request, with query stripped per RFC 9449 §4.2. /// Optional expected ath claim (SHA-256 of access-token, base64url) — required at resource servers, not at /token. /// Cancellation token. public async Task ValidateAsync( string proof, string httpMethod, string httpUri, string? expectedAth = null, CancellationToken ct = default) { if (string.IsNullOrEmpty(proof)) return DpopValidationResult.Fail("invalid_dpop_proof", "DPoP header missing."); if (!_handler.CanReadToken(proof)) return DpopValidationResult.Fail("invalid_dpop_proof", "DPoP proof is not a well-formed JWT."); JsonWebToken parsed; try { parsed = _handler.ReadJsonWebToken(proof); } catch (Exception ex) { _logger.LogDebug(ex, "DPoP proof parse failed"); return DpopValidationResult.Fail("invalid_dpop_proof", "DPoP proof is malformed."); } // Header checks (RFC 9449 §4.2) if (!parsed.TryGetHeaderValue("typ", out var typ) || !string.Equals(typ, "dpop+jwt", StringComparison.Ordinal)) { return DpopValidationResult.Fail("invalid_dpop_proof", "DPoP proof typ must be 'dpop+jwt'."); } if (!parsed.TryGetHeaderValue("alg", out var alg) || string.IsNullOrEmpty(alg) || string.Equals(alg, "none", StringComparison.OrdinalIgnoreCase) || !_options.AllowedSigningAlgorithms.Contains(alg, StringComparer.Ordinal)) { return DpopValidationResult.Fail("invalid_dpop_proof", $"DPoP proof alg '{alg}' is not in the allowed list."); } // The embedded JWK in the header is the proof's verification key. if (!parsed.TryGetHeaderValue("jwk", out var jwkElement)) { return DpopValidationResult.Fail("invalid_dpop_proof", "DPoP proof jwk header is missing."); } JsonWebKey jwk; try { jwk = new JsonWebKey(jwkElement.GetRawText()); } catch (Exception ex) { _logger.LogDebug(ex, "DPoP jwk parse failed"); return DpopValidationResult.Fail("invalid_dpop_proof", "DPoP proof jwk is malformed."); } // Reject any private-key components — the proof MUST carry only the public key. if (!string.IsNullOrEmpty(jwk.D)) return DpopValidationResult.Fail("invalid_dpop_proof", "DPoP proof jwk MUST NOT contain a private key."); // Verify signature var validationParameters = new TokenValidationParameters { ValidateIssuer = false, ValidateAudience = false, ValidateLifetime = false, ValidateIssuerSigningKey = true, IssuerSigningKey = jwk, ValidAlgorithms = _options.AllowedSigningAlgorithms, }; var validation = await _handler.ValidateTokenAsync(proof, validationParameters).ConfigureAwait(false); if (!validation.IsValid) { _logger.LogDebug(validation.Exception, "DPoP signature validation failed"); return DpopValidationResult.Fail("invalid_dpop_proof", "DPoP proof signature is invalid."); } // Claim checks if (!parsed.TryGetPayloadValue("htm", out var htm) || !string.Equals(htm, httpMethod, StringComparison.OrdinalIgnoreCase)) { return DpopValidationResult.Fail("invalid_dpop_proof", $"DPoP proof htm '{htm}' does not match request method '{httpMethod}'."); } if (!parsed.TryGetPayloadValue("htu", out var htu)) return DpopValidationResult.Fail("invalid_dpop_proof", "DPoP proof htu claim is missing."); if (!HtuMatches(htu, httpUri)) { return DpopValidationResult.Fail("invalid_dpop_proof", $"DPoP proof htu '{htu}' does not match request URI '{httpUri}'."); } if (!parsed.TryGetPayloadValue("iat", out var iat)) return DpopValidationResult.Fail("invalid_dpop_proof", "DPoP proof iat claim is missing."); var nowSeconds = _timeProvider.GetUtcNow().ToUnixTimeSeconds(); var skew = Math.Abs(nowSeconds - iat); if (skew > _options.IatToleranceSeconds) { return DpopValidationResult.Fail("invalid_dpop_proof", $"DPoP proof iat is outside the {_options.IatToleranceSeconds}s tolerance window."); } if (!parsed.TryGetPayloadValue("jti", out var jti) || string.IsNullOrEmpty(jti)) return DpopValidationResult.Fail("invalid_dpop_proof", "DPoP proof jti claim is missing."); if (expectedAth is not null) { if (!parsed.TryGetPayloadValue("ath", out var ath) || !CryptographicOperations.FixedTimeEquals( Encoding.ASCII.GetBytes(ath ?? ""), Encoding.ASCII.GetBytes(expectedAth))) { return DpopValidationResult.Fail("invalid_dpop_proof", "DPoP proof ath claim does not match the access token hash."); } } // Extract optional nonce claim — nonce policy is enforced by the calling handler // against an IDpopNonceProvider (RFC 9449 §8). The validator only surfaces the value. parsed.TryGetPayloadValue("nonce", out var nonce); // Compute jkt (RFC 7638 SHA-256 thumbprint) var jkt = ComputeJwkThumbprint(jwk); // Replay check — reserve (jkt, jti) for the iat tolerance window (×2 for safety). var ttl = TimeSpan.FromSeconds(_options.IatToleranceSeconds * 2); var reserved = await _replayStore.TryReserveAsync(jkt, jti, ttl, ct).ConfigureAwait(false); if (!reserved) { return DpopValidationResult.Fail("invalid_dpop_proof", "DPoP proof has already been used (replay)."); } return DpopValidationResult.Success(jkt, jti, nonce); } /// /// Compares request URL to the proof's htu claim per RFC 9449 §4.3: /// query and fragment are stripped from both sides; case-insensitive scheme/host; /// path comparison is case-sensitive. /// private static bool HtuMatches(string htu, string requestUri) { return string.Equals(Normalise(htu), Normalise(requestUri), StringComparison.Ordinal); static string Normalise(string value) { if (!Uri.TryCreate(value, UriKind.Absolute, out var u)) return value; // Drop query + fragment; lowercase scheme + host. var builder = new UriBuilder(u) { Query = "", Fragment = "" }; builder.Scheme = builder.Scheme.ToLowerInvariant(); builder.Host = builder.Host.ToLowerInvariant(); // UriBuilder injects default port — strip when implied. if ((builder.Scheme == "http" && builder.Port == 80) || (builder.Scheme == "https" && builder.Port == 443)) { builder.Port = -1; } // Trim trailing slash for symmetric comparison. var s = builder.Uri.ToString(); return s.EndsWith('/') ? s.TrimEnd('/') : s; } } /// /// Computes the RFC 7638 JWK SHA-256 thumbprint, base64url-encoded. /// Microsoft.IdentityModel exposes /// returning raw bytes; we base64url-encode without padding per RFC 7515. /// public static string ComputeJwkThumbprint(JsonWebKey jwk) { var bytes = jwk.ComputeJwkThumbprint(); return Base64UrlEncoder.Encode(bytes); } } /// Result of a DPoP proof validation. public readonly record struct DpopValidationResult( bool IsValid, string? Jkt, string? Jti, string? Nonce, string? Error, string? ErrorDescription) { public static DpopValidationResult Success(string jkt, string jti, string? nonce = null) => new(true, jkt, jti, nonce, null, null); public static DpopValidationResult Fail(string error, string description) => new(false, null, null, null, error, description); } Path: redb-identity/src/redb.Identity.Core/Services/EmailMfaDeliveryChannel.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/Services/EmailMfaDeliveryChannel.cs ---- using redb.Identity.Core.Exceptions; namespace redb.Identity.Core.Services; /// /// Delivers the one-time code of e-mail MFA through the host's /// (the SMTP channel when Smtp.Enabled is on, or whatever channel the host registered), with the /// template. uses it for the "email" /// channel when the host registered no of its own for e-mail. /// internal sealed class EmailMfaDeliveryChannel : IMfaDeliveryChannel { private readonly IEmailNotificationChannel _mail; private readonly int _ttlMinutes; public EmailMfaDeliveryChannel(IEmailNotificationChannel mail, TimeSpan codeLifetime) { _mail = mail ?? throw new ArgumentNullException(nameof(mail)); _ttlMinutes = Math.Max(1, (int)Math.Ceiling(codeLifetime.TotalMinutes)); } public string ChannelId => "email"; public string DisplayName => "Email"; public async Task SendCodeAsync(string destination, string code, CancellationToken ct = default) { try { await _mail.SendTemplateAsync(destination, IdentityEmailTemplates.MfaCode, new Dictionary { ["code"] = code, ["ttlMinutes"] = _ttlMinutes.ToString(System.Globalization.CultureInfo.InvariantCulture), }, ct).ConfigureAwait(false); } catch (Exception ex) when (ex is not OperationCanceledException) { throw new MfaDeliveryException("email", null, "The e-mail with the verification code could not be sent.", ex); } } } Path: redb-identity/src/redb.Identity.Core/Services/EmailMfaMethod.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/Services/EmailMfaMethod.cs ---- using redb.Identity.Core.Mfa; using redb.Identity.Core.Models; namespace redb.Identity.Core.Services; /// /// Email OTP MFA method. /// Stores the user's email in . The OTP code itself /// is persisted server-side in (SHA-256 hashed, single-use /// under LockForUpdate) via — the encrypted /// only carries a jti reference (B3). /// internal sealed class EmailMfaMethod : IMfaMethod { private readonly IServerSideOtpStore? _otpStore; public EmailMfaMethod(IServerSideOtpStore? otpStore = null) { _otpStore = otpStore; } public string MethodId => "email"; public Task InitiateSetupAsync(string username, string? destination = null, CancellationToken ct = default) { if (string.IsNullOrWhiteSpace(destination)) { return Task.FromResult(new MfaSetupInitiation { MethodId = MethodId, ClientResult = new MfaSetupResult { MethodId = MethodId, Extra = new Dictionary { ["error"] = "Email address is required" } } }); } var email = NormalizeEmail(destination); if (email is null) { return Task.FromResult(new MfaSetupInitiation { MethodId = MethodId, ClientResult = new MfaSetupResult { MethodId = MethodId, Extra = new Dictionary { ["error"] = "Invalid email address" } } }); } return Task.FromResult(new MfaSetupInitiation { MethodId = MethodId, Destination = email, ClientResult = new MfaSetupResult { MethodId = MethodId, Extra = new Dictionary { ["masked_email"] = MaskEmail(email) } } }); } public async Task ConfirmAndApplyAsync(MfaProps props, MfaSetupInitiation initiation, string code, MfaState? state = null, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(props); ArgumentNullException.ThrowIfNull(initiation); if (string.IsNullOrEmpty(initiation.Destination)) return false; if (!await VerifyAgainstStateAsync(state, code, ct).ConfigureAwait(false)) return false; props.OtpEmail = initiation.Destination; props.EmailConfirmed = true; return true; } public Task VerifyAsync(MfaProps props, string code, MfaState? state = null, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(props); return VerifyAgainstStateAsync(state, code, ct); } private async Task VerifyAgainstStateAsync(MfaState? state, string code, CancellationToken ct) { if (state is null) return false; if (state.OtpMethod != MethodId) return false; if (string.IsNullOrEmpty(code)) return false; // B3: server-side OTP store is the authoritative source; jti must be present. if (_otpStore is null || !state.OtpJti.HasValue) return false; var res = await _otpStore.VerifyAndConsumeAsync(state.OtpJti.Value, state.UserId, code, ct).ConfigureAwait(false); return res.Success; } internal static string? NormalizeEmail(string input) { if (string.IsNullOrWhiteSpace(input)) return null; var trimmed = input.Trim().ToLowerInvariant(); var atIdx = trimmed.IndexOf('@'); if (atIdx <= 0 || atIdx == trimmed.Length - 1) return null; if (trimmed.Length < 5) return null; // Domain must contain at least one dot if (!trimmed[(atIdx + 1)..].Contains('.')) return null; return trimmed; } internal static string MaskEmail(string email) { var parts = email.Split('@'); if (parts.Length != 2) return "****"; var local = parts[0]; var domain = parts[1]; if (local.Length <= 1) return $"*@{domain}"; return $"{local[0]}***@{domain}"; } } Path: redb-identity/src/redb.Identity.Core/Services/FederationProviderSecretProtector.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/Services/FederationProviderSecretProtector.cs ---- using Microsoft.AspNetCore.DataProtection; using Microsoft.Extensions.Logging; namespace redb.Identity.Core.Services; /// /// H8 (DoD §4 gap (e)): encrypts/decrypts federation provider client secrets at rest /// using ASP.NET DataProtection. Mirrors in shape; /// distinct purpose string keeps key isolation between unrelated subsystems. /// public sealed class FederationProviderSecretProtector { private const string Purpose = "redb.identity.federation-provider-secret"; private readonly IDataProtector _protector; private readonly ILogger? _logger; public FederationProviderSecretProtector( IDataProtectionProvider provider, ILogger? logger = null) { ArgumentNullException.ThrowIfNull(provider); _protector = provider.CreateProtector(Purpose); _logger = logger; } /// Encrypts a plaintext secret. Returns null when input is null/empty. public string? Protect(string? plainSecret) { if (string.IsNullOrEmpty(plainSecret)) return null; var bytes = System.Text.Encoding.UTF8.GetBytes(plainSecret); var encrypted = _protector.Protect(bytes); return Convert.ToBase64String(encrypted); } /// Decrypts a protected secret. Returns null on failure (rotated/lost keys). public string? Unprotect(string? protectedSecret) { if (string.IsNullOrEmpty(protectedSecret)) return null; try { var encrypted = Convert.FromBase64String(protectedSecret); var bytes = _protector.Unprotect(encrypted); return System.Text.Encoding.UTF8.GetString(bytes); } catch (Exception ex) { _logger?.LogWarning(ex, "FederationProviderSecretProtector: failed to decrypt federation provider secret (length={Length}).", protectedSecret.Length); return null; } } } Path: redb-identity/src/redb.Identity.Core/Services/FederationStateProtector.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/Services/FederationStateProtector.cs ---- using System.Security.Cryptography; using System.Text; using System.Text.Json; using Microsoft.AspNetCore.DataProtection; using Microsoft.Extensions.Logging; using redb.Identity.Core.Configuration; using redb.Identity.Contracts.Common; namespace redb.Identity.Core.Services; /// /// Result of validating a federation state blob. Distinguishes the failure mode so /// callers / audit hooks can react appropriately (and so tests can assert precisely). /// public enum FederationStateValidationFailure { None = 0, /// Blob is null/empty/garbage or its DataProtection envelope was tampered with. Tampered, /// Blob decrypted but its IssuedAt + StateMaxAge has elapsed. Expired, /// Blob's jti was already consumed (one-time-use violation, replay). AlreadyUsed, /// Browser-binding cookie missing or its hash didn't match the value baked into the state. BindingMismatch, } /// /// Encrypts/decrypts federation state parameters using ASP.NET DataProtection. /// State carries the provider id, return URL, OIDC nonce, PKCE code verifier, /// issuance timestamp, a unique jti for one-time-use enforcement (C6), /// and an optional browser-binding hash (C6). /// public sealed class FederationStateProtector { private const string Purpose = "redb.identity.federation-state"; private static readonly TimeSpan FallbackMaxAge = TimeSpan.FromMinutes(5); private readonly IDataProtector _protector; private readonly TimeProvider _timeProvider; private readonly IFederationStateNonceStore? _nonceStore; private readonly FederationStateOptions _options; private readonly ILogger? _logger; public FederationStateProtector(IDataProtectionProvider provider) : this(provider, TimeProvider.System, nonceStore: null, options: null, logger: null) { } public FederationStateProtector( IDataProtectionProvider provider, TimeProvider? timeProvider, IFederationStateNonceStore? nonceStore, FederationStateOptions? options) : this(provider, timeProvider, nonceStore, options, logger: null) { } public FederationStateProtector( IDataProtectionProvider provider, TimeProvider? timeProvider, IFederationStateNonceStore? nonceStore, FederationStateOptions? options, ILogger? logger) { ArgumentNullException.ThrowIfNull(provider); _protector = provider.CreateProtector(Purpose); _timeProvider = timeProvider ?? TimeProvider.System; _nonceStore = nonceStore; _options = options ?? new FederationStateOptions(); _logger = logger; } /// /// Encrypts federation state into a base64-safe string. Sets IssuedAt to /// the current time when missing and assigns a fresh /// Jti when missing. /// public string Protect(FederationState state) { ArgumentNullException.ThrowIfNull(state); state.IssuedAt ??= _timeProvider.GetUtcNow(); if (string.IsNullOrEmpty(state.Jti)) state.Jti = Guid.NewGuid().ToString("N"); var json = JsonSerializer.SerializeToUtf8Bytes(state); var encrypted = _protector.Protect(json); return Convert.ToBase64String(encrypted); } /// /// Computes the browser-binding hash that should be stored inside the state blob /// for a given per-flow secret. Uses SHA-256 — the secret never traverses storage. /// public static string ComputeBindingHash(string secret) { ArgumentException.ThrowIfNullOrEmpty(secret); var bytes = SHA256.HashData(Encoding.UTF8.GetBytes(secret)); return Convert.ToBase64String(bytes); } /// /// Legacy synchronous overload. Decrypts and validates TTL only. Does NOT consult /// the nonce store and does NOT verify browser binding — kept for compatibility /// with callers that don't need C6 hardening (and for unit tests). /// public FederationState? Unprotect(string protectedState, TimeSpan? maxAge = null) { var (state, _) = TryDecrypt(protectedState, maxAge); return state; } /// /// Full C6 validation path: decrypt, TTL check, browser-binding (if present in state), /// one-time-use (if a nonce store is configured and RequireOneTimeUse). /// Returns the decrypted state and a precise failure reason. /// public async Task<(FederationState? State, FederationStateValidationFailure Failure)> UnprotectAsync( string protectedState, string? bindingSecret, CancellationToken ct = default) { var (state, failure) = TryDecrypt(protectedState, _options.StateMaxAge); if (state is null) return (null, failure); if (!string.IsNullOrEmpty(state.BindingHash)) { if (string.IsNullOrEmpty(bindingSecret)) return (null, FederationStateValidationFailure.BindingMismatch); var presented = ComputeBindingHash(bindingSecret); if (!CryptographicOperations.FixedTimeEquals( Encoding.ASCII.GetBytes(presented), Encoding.ASCII.GetBytes(state.BindingHash))) { return (null, FederationStateValidationFailure.BindingMismatch); } } if (_options.RequireOneTimeUse && _nonceStore is not null) { var jti = state.Jti; if (string.IsNullOrEmpty(jti)) return (null, FederationStateValidationFailure.Tampered); var consumed = await _nonceStore.TryConsumeAsync(jti, _options.StateMaxAge, ct).ConfigureAwait(false); if (!consumed) return (null, FederationStateValidationFailure.AlreadyUsed); } return (state, FederationStateValidationFailure.None); } private (FederationState? State, FederationStateValidationFailure Failure) TryDecrypt( string protectedState, TimeSpan? maxAge) { if (string.IsNullOrEmpty(protectedState)) return (null, FederationStateValidationFailure.Tampered); FederationState? state; try { var encrypted = Base64Canonical.Decode(protectedState); var json = _protector.Unprotect(encrypted); state = JsonSerializer.Deserialize(json); } catch (Exception ex) { // Tampered ciphertext OR DataProtection key rotation. Both must be visible to // operators — a sustained run of these is a security signal. _logger?.LogWarning(ex, "FederationStateProtector: failed to decrypt federation state (length={Length}).", protectedState.Length); return (null, FederationStateValidationFailure.Tampered); } if (state is null || string.IsNullOrEmpty(state.ProviderId)) { _logger?.LogWarning( "FederationStateProtector: decrypted state was null or had empty ProviderId."); return (null, FederationStateValidationFailure.Tampered); } var ttl = maxAge ?? FallbackMaxAge; var age = _timeProvider.GetUtcNow() - (state.IssuedAt ?? DateTimeOffset.MinValue); if (age > ttl) { _logger?.LogDebug( "FederationStateProtector: state expired (age={AgeSeconds}s, max={MaxSeconds}s, provider={ProviderId}).", age.TotalSeconds, ttl.TotalSeconds, state.ProviderId); return (null, FederationStateValidationFailure.Expired); } return (state, FederationStateValidationFailure.None); } } /// /// Data encrypted in the federation state parameter. /// public sealed class FederationState { public required string ProviderId { get; set; } public string? ReturnUrl { get; set; } public string? Nonce { get; set; } public string? CodeVerifier { get; set; } public DateTimeOffset? IssuedAt { get; set; } /// Unique id for one-time-use enforcement (C6). Assigned by Protect when missing. public string? Jti { get; set; } /// Optional SHA-256 hash of the per-flow browser-binding secret (C6, opt-in). public string? BindingHash { get; set; } /// /// H8 (DoD §4 gap (b)): when present, the callback is interpreted as an /// "add this federated identity to the existing user" operation rather than a regular /// login. The challenge processor sets this from the access-token subject of the /// authenticated caller; the callback processor must reject when the resolved value /// does not match the still-authenticated session. /// public long? LinkUserId { get; set; } } Path: redb-identity/src/redb.Identity.Core/Services/GitHubFederatedAuthProvider.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/Services/GitHubFederatedAuthProvider.cs ---- using System.Net.Http.Headers; using System.Net.Http.Json; using System.Security.Cryptography; using System.Text.Json; using Microsoft.IdentityModel.Tokens; using redb.Identity.Core.Configuration; using redb.Identity.Contracts.Configuration; namespace redb.Identity.Core.Services; /// /// H8 (DoD §4 gap (a) "GitHub-style"): GitHub OAuth2 federated auth provider. /// Unlike , GitHub is OAuth2 only — no /// id_token and no OIDC discovery, so we exchange the auth code for an /// access_token and then call /user + /user/emails to build /// the . /// /// PKCE is supported (GitHub added S256 PKCE in 2022 and ignores code_verifier /// silently for old apps), nonce is not — GitHub has no id_token to bind it to. /// /// /// Required scope to obtain a primary verified email when the profile email is /// private: user:email (we add it implicitly if the caller forgot). /// /// public sealed class GitHubFederatedAuthProvider : IFederatedAuthProvider { // Defaults — public github.com. Override via FederationProviderConfig.Endpoints to // support GitHub Enterprise, Gitea, or a self-hosted mock for testing. private const string DefaultAuthorizeEndpoint = "https://github.com/login/oauth/authorize"; private const string DefaultTokenEndpoint = "https://github.com/login/oauth/access_token"; private const string DefaultUserEndpoint = "https://api.github.com/user"; private const string DefaultEmailsEndpoint = "https://api.github.com/user/emails"; private readonly FederationProviderConfig _config; private readonly IHttpClientFactory _httpClientFactory; private string AuthorizeEndpoint => _config.Endpoints?.AuthorizeEndpoint ?? DefaultAuthorizeEndpoint; private string TokenEndpoint => _config.Endpoints?.TokenEndpoint ?? DefaultTokenEndpoint; private string UserEndpoint => _config.Endpoints?.UserEndpoint ?? DefaultUserEndpoint; private string EmailsEndpoint => _config.Endpoints?.EmailsEndpoint ?? DefaultEmailsEndpoint; public GitHubFederatedAuthProvider( FederationProviderConfig config, IHttpClientFactory httpClientFactory) { _config = config ?? throw new ArgumentNullException(nameof(config)); _httpClientFactory = httpClientFactory ?? throw new ArgumentNullException(nameof(httpClientFactory)); } public string ProviderId => _config.ProviderId; public string DisplayName => _config.DisplayName; public int Priority => _config.Priority; public Task CreateChallengeAsync( string callbackUrl, string returnUrl, CancellationToken ct = default) { var codeVerifier = GenerateCodeVerifier(); var codeChallenge = ComputeCodeChallenge(codeVerifier); var state = GenerateNonce(); // GitHub uses space-separated scopes per RFC 6749. Ensure user:email is present // so we can fetch a verified primary email even when the user's profile email // is set to private. var scopes = _config.Scopes.Length == 0 ? new[] { "read:user", "user:email" } : (Array.IndexOf(_config.Scopes, "user:email") >= 0 ? _config.Scopes : _config.Scopes.Concat(new[] { "user:email" }).ToArray()); var authUrl = AuthorizeEndpoint + "?response_type=code" + "&client_id=" + Uri.EscapeDataString(_config.ClientId) + "&redirect_uri=" + Uri.EscapeDataString(callbackUrl) + "&scope=" + Uri.EscapeDataString(string.Join(" ", scopes)) + "&state=" + Uri.EscapeDataString(state) + "&code_challenge=" + Uri.EscapeDataString(codeChallenge) + "&code_challenge_method=S256" + "&allow_signup=true"; return Task.FromResult(new FederationChallenge { RedirectUri = authUrl, State = state, // Nonce intentionally null — GitHub has no id_token to bind it to. Nonce = null, CodeVerifier = codeVerifier, }); } public async Task HandleCallbackAsync( string code, string callbackUrl, string? codeVerifier = null, string? nonce = null, CancellationToken ct = default) { var http = _httpClientFactory.CreateClient("redb-identity-federation"); // 1. Exchange code → access_token using var tokenReq = new HttpRequestMessage(HttpMethod.Post, TokenEndpoint); tokenReq.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var form = new Dictionary { ["grant_type"] = "authorization_code", ["code"] = code, ["redirect_uri"] = callbackUrl, ["client_id"] = _config.ClientId, ["client_secret"] = _config.ClientSecret, }; if (!string.IsNullOrEmpty(codeVerifier)) form["code_verifier"] = codeVerifier; tokenReq.Content = new FormUrlEncodedContent(form); using var tokenResp = await http.SendAsync(tokenReq, ct).ConfigureAwait(false); if (!tokenResp.IsSuccessStatusCode) return ExternalAuthResult.Failed($"GitHub token exchange failed: HTTP {(int)tokenResp.StatusCode}"); var token = await tokenResp.Content.ReadFromJsonAsync(cancellationToken: ct) .ConfigureAwait(false); if (token is null || string.IsNullOrEmpty(token.access_token)) { // GitHub returns 200 + {"error":"bad_verification_code"} on most failures, hence the explicit check. return ExternalAuthResult.Failed("GitHub token exchange returned no access_token."); } // 2. Fetch user profile var profile = await GetJsonAsync(http, UserEndpoint, token.access_token, ct).ConfigureAwait(false); if (profile is null || profile.id <= 0) return ExternalAuthResult.Failed("GitHub /user returned no usable profile."); // 3. Resolve verified primary email (profile.email may be null when private). string? email = profile.email; if (string.IsNullOrEmpty(email)) { var emails = await GetJsonAsync(http, EmailsEndpoint, token.access_token, ct) .ConfigureAwait(false); email = emails? .Where(e => e is { verified: true }) .OrderByDescending(e => e.primary) .Select(e => e.email) .FirstOrDefault(); } var displayName = !string.IsNullOrWhiteSpace(profile.name) ? profile.name : profile.login; return ExternalAuthResult.Success( externalId: profile.id.ToString(System.Globalization.CultureInfo.InvariantCulture), displayName: displayName, email: email, additionalClaims: new Dictionary { ["github:login"] = profile.login ?? string.Empty, ["github:id"] = profile.id.ToString(System.Globalization.CultureInfo.InvariantCulture), }); } private static async Task GetJsonAsync(HttpClient http, string url, string accessToken, CancellationToken ct) { using var req = new HttpRequestMessage(HttpMethod.Get, url); req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); req.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/vnd.github+json")); // GitHub requires a non-empty User-Agent on every API request. req.Headers.UserAgent.ParseAdd("redb.Identity/1.0"); using var resp = await http.SendAsync(req, ct).ConfigureAwait(false); if (!resp.IsSuccessStatusCode) return default; return await resp.Content.ReadFromJsonAsync(cancellationToken: ct).ConfigureAwait(false); } // ── PKCE / state helpers (mirror OidcFederatedAuthProvider) ── private static string GenerateCodeVerifier() { var bytes = new byte[32]; RandomNumberGenerator.Fill(bytes); return Base64UrlEncoder.Encode(bytes); } private static string ComputeCodeChallenge(string codeVerifier) { var bytes = SHA256.HashData(System.Text.Encoding.ASCII.GetBytes(codeVerifier)); return Base64UrlEncoder.Encode(bytes); } private static string GenerateNonce() { var bytes = new byte[16]; RandomNumberGenerator.Fill(bytes); return Base64UrlEncoder.Encode(bytes); } // ── DTOs ── private sealed class GitHubTokenResponse { public string? access_token { get; set; } public string? token_type { get; set; } public string? scope { get; set; } } private sealed class GitHubUser { public long id { get; set; } public string? login { get; set; } public string? name { get; set; } public string? email { get; set; } } private sealed class GitHubEmail { public string email { get; set; } = string.Empty; public bool primary { get; set; } public bool verified { get; set; } public string? visibility { get; set; } } } Path: redb-identity/src/redb.Identity.Core/Services/GroupClaimsResolver.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/Services/GroupClaimsResolver.cs ---- using System.Security.Claims; using Microsoft.Extensions.Logging; using OpenIddict.Abstractions; using redb.Core; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Identity.Core.Models; using static OpenIddict.Abstractions.OpenIddictConstants; namespace redb.Identity.Core.Services; /// /// Enriches a with group/role claims /// when the corresponding scopes ("groups", "roles") are requested. /// public sealed class GroupClaimsResolver { public const string GroupsScope = "groups"; public const string RolesScope = "roles"; public const string GroupsClaim = "groups"; public const string RolesClaim = "roles"; public const string OrgClaim = "org"; private readonly IGroupService _groupService; private readonly IRedbService? _redb; private readonly ILogger? _logger; public GroupClaimsResolver(IGroupService groupService, ILogger? logger = null) { _groupService = groupService; _redb = null; _logger = logger; } public GroupClaimsResolver(IRedbService redb, ILogger? logger = null) { _redb = redb; _groupService = new GroupService(redb); _logger = logger; } /// /// Adds group names and/or role names to the principal's identity /// based on requested scopes. /// /// /// Group claims include both direct memberships AND ancestor groups via tree-hierarchy /// (composite group inheritance — DoD §5 H2). For example, if user is in "developers" /// which is a child of "engineering" which is a child of "company", the principal /// receives groups: ["developers", "engineering", "company"]. Ancestor expansion /// uses a single server-side recursive CTE (via TreeQuery + ToTreeListAsync) — /// not an N+1 client-side walk — so it scales to deep / wide group hierarchies. /// The org claim also walks the tree to find the closest organization-type /// ancestor when no direct organization-type membership exists. Per-membership /// Role labels () are NOT inherited — they describe /// the user's role within a specific group, not a transitive concept. /// public async Task EnrichPrincipalAsync( ClaimsPrincipal principal, long userId, IEnumerable scopes, CancellationToken ct = default) { var scopeList = scopes as IReadOnlyList ?? scopes.ToList(); var needGroups = scopeList.Contains(GroupsScope); var needRoles = scopeList.Contains(RolesScope); if (!needGroups && !needRoles) return; var identity = principal.Identity as ClaimsIdentity; if (identity is null) return; var userGroups = await _groupService.GetUserGroupsAsync(userId, ct).ConfigureAwait(false); if (needGroups) { // Step 1: collect direct group names + walk tree ancestors for inherited groups. // Deduped by name (HashSet) — same group may be ancestor of multiple direct // memberships, and case-sensitive uniqueness is intentional (group names are // typically slug-like identifiers, not display labels). var allGroupNames = new HashSet(StringComparer.Ordinal); string? inheritedOrg = null; foreach (var ug in userGroups) { if (!string.IsNullOrEmpty(ug.GroupName)) allGroupNames.Add(ug.GroupName!); } // Step 2: server-side ancestor expansion via single recursive CTE round-trip. // TreeQuery + ToTreeListAsync internally calls GetIdsWithAncestorsAsync (one // recursive CTE) and LoadObjectsByIdsAsync (one batched load), avoiding the // N+1 pattern of per-membership GetPathToRootAsync calls. Falls back to // per-membership ancestor walk only when _redb is unavailable (legacy ctor). var directIds = userGroups .Where(g => g.GroupId > 0) .Select(g => g.GroupId) .Distinct() .ToList(); if (directIds.Count > 0) { if (_redb is not null) { List> directNodes; try { directNodes = await _redb .TreeQuery() .WhereInRedb(o => o.Id, directIds) .ToTreeListAsync() .ConfigureAwait(false); } catch (Exception ex) { // Ancestor expansion failure must not 500 the token endpoint — // the principal still gets direct-membership groups + roles, // which is enough for most authorisation flows. Logged so an // operator can see the regression even when degraded. _logger?.LogWarning(ex, "GroupClaimsResolver: TreeQuery ancestor expansion failed for groups [{Ids}] — falling back to direct-only group names", string.Join(",", directIds)); directNodes = new List>(); } foreach (var direct in directNodes) { // Walk parent chain — parents already materialized in-memory via // ToTreeListAsync's recursive CTE, no further round-trips needed. ITreeRedbObject? node = direct.Parent; while (node is not null) { if (!string.IsNullOrEmpty(node.Name)) allGroupNames.Add(node.Name); // Track first organization-type ancestor for fallback org claim. if (inheritedOrg is null && node is TreeRedbObject typed && string.Equals(typed.Props?.GroupType, "organization", StringComparison.OrdinalIgnoreCase) && !string.IsNullOrEmpty(typed.name)) { inheritedOrg = typed.name; } node = node.Parent; } } } else { // Legacy fallback: per-membership ancestor walk (used only when // resolver was constructed via IGroupService-only ctor). foreach (var ug in userGroups) { if (ug.GroupId <= 0) continue; List>? path = null; try { path = await _groupService.GetPathToRootAsync(ug.GroupId, ct).ConfigureAwait(false); } catch (InvalidOperationException) { continue; } foreach (var ancestor in path) { if (ancestor.id == ug.GroupId) continue; if (!string.IsNullOrEmpty(ancestor.name)) allGroupNames.Add(ancestor.name); if (inheritedOrg is null && string.Equals(ancestor.Props?.GroupType, "organization", StringComparison.OrdinalIgnoreCase) && !string.IsNullOrEmpty(ancestor.name)) { inheritedOrg = ancestor.name; } } } } } foreach (var name in allGroupNames) { var claim = new Claim(GroupsClaim, name); claim.SetDestinations(Destinations.AccessToken, Destinations.IdentityToken); identity.AddClaim(claim); } // RFC-compatible org claim: prefer direct organization-type membership; // fall back to closest organization-type ancestor in the tree. var directOrg = userGroups.FirstOrDefault(g => string.Equals(g.GroupType, "organization", StringComparison.OrdinalIgnoreCase)); var orgName = directOrg?.GroupName ?? inheritedOrg; if (!string.IsNullOrEmpty(orgName)) { var orgClaim = new Claim(OrgClaim, orgName); orgClaim.SetDestinations(Destinations.AccessToken, Destinations.IdentityToken); identity.AddClaim(orgClaim); } } if (needRoles) { // Per-membership role label — NOT inherited via tree (see method remarks). var roles = userGroups .Where(g => g.Role is not null) .Select(g => g.Role!) .Distinct() .ToList(); foreach (var role in roles) { var claim = new Claim(RolesClaim, role); claim.SetDestinations(Destinations.AccessToken, Destinations.IdentityToken); identity.AddClaim(claim); } } } } Path: redb-identity/src/redb.Identity.Core/Services/GroupNames.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/Services/GroupNames.cs ---- using System.Text; namespace redb.Identity.Core.Services; /// /// The unique key of a group name. A group name is unique across the whole group tree, compared /// without regard to surrounding whitespace, letter case or the Unicode form it was typed in: the /// groups claim, the scope gates (ScopeRequiredGroups) and the LDAP and SCIM mappings all /// identify a group by its name, so two groups that a person would read as the same name must not /// exist. The key is stored in the group object's ValueUnique; the name itself keeps the form /// it was given in. /// public static class GroupNames { /// Trim, Unicode NFC, then lower-invariant. public static string Key(string name) { ArgumentNullException.ThrowIfNull(name); return name.Trim().Normalize(NormalizationForm.FormC).ToLowerInvariant(); } } Path: redb-identity/src/redb.Identity.Core/Services/GroupService.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/Services/GroupService.cs ---- using redb.Core; using redb.Core.Extensions; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Core.Services; using redb.Identity.Core.Models; namespace redb.Identity.Core.Services; /// /// Manages hierarchical groups (tree via parent_id) and flat memberships (GroupMemberProps). /// public sealed class GroupService : IGroupService { private readonly IRedbService _redb; private readonly IBackgroundDeletionService? _backgroundDeletion; private readonly TimeProvider _timeProvider; public GroupService(IRedbService redb, IBackgroundDeletionService? backgroundDeletion = null) : this(redb, backgroundDeletion, TimeProvider.System) { } public GroupService(IRedbService redb, IBackgroundDeletionService? backgroundDeletion, TimeProvider? timeProvider) { _redb = redb; _backgroundDeletion = backgroundDeletion; _timeProvider = timeProvider ?? TimeProvider.System; } // ── Group CRUD ────────────────────────────────────────────── public async Task> CreateGroupAsync( string name, string? groupType = null, string? description = null, CancellationToken ct = default) { var obj = new RedbObject { name = name, ValueUnique = GroupNames.Key(name), Props = new GroupProps { GroupType = groupType, Description = description } }; obj.id = await _redb.SaveAsync(obj).ConfigureAwait(false); return obj; } public async Task> CreateChildGroupAsync( long parentGroupId, string name, string? groupType = null, string? description = null, CancellationToken ct = default) { var parent = await _redb.LoadAsync(parentGroupId).ConfigureAwait(false) ?? throw new InvalidOperationException($"Parent group {parentGroupId} not found."); var child = new TreeRedbObject { name = name, ValueUnique = GroupNames.Key(name), Props = new GroupProps { GroupType = groupType, Description = description } }; child.id = await _redb.CreateChildAsync(child, parent).ConfigureAwait(false); return child; } public async Task?> FindGroupByNameAsync(string name, CancellationToken ct = default) { var key = GroupNames.Key(name); return await _redb.Query() .WhereRedb(o => o.ValueUnique == key) .FirstOrDefaultAsync() .ConfigureAwait(false); } public async Task?> GetGroupAsync(long groupId, CancellationToken ct = default) { var group = await _redb.LoadAsync(groupId).ConfigureAwait(false); if (group is null || group.IsSoftDeleted()) return null; return group; } public async Task UpdateGroupAsync( long groupId, string? name = null, string? groupType = null, string? description = null, CancellationToken ct = default) { var group = await _redb.LoadAsync(groupId).ConfigureAwait(false) ?? throw new InvalidOperationException($"Group {groupId} not found."); if (name is not null) { group.name = name; group.ValueUnique = GroupNames.Key(name); } // A group stored with no properties loads with Props null (redb stores no props rows for it). group.Props ??= new GroupProps(); if (groupType is not null) group.Props.GroupType = groupType; if (description is not null) group.Props.Description = description; await _redb.SaveAsync(group).ConfigureAwait(false); } public async Task DeleteGroupAsync(long groupId, CancellationToken ct = default) { // SoftDelete: marks group + all descendants with scheme = @@__deleted (-10). // No LoadAsync needed — works by ID, no FK cascade, instant return. var mark = await _redb.SoftDeleteAsync(new[] { groupId }).ConfigureAwait(false); // Enqueue background purge (physical deletion in batches) if available. _backgroundDeletion?.EnqueuePurge(mark.TrashId, mark.MarkedCount, 0); } // ── Tree operations ───────────────────────────────────────── public async Task> LoadTreeAsync( long rootGroupId, int? maxDepth = null, CancellationToken ct = default) { return await _redb.LoadTreeAsync(rootGroupId, maxDepth).ConfigureAwait(false); } public async Task>> GetChildGroupsAsync( long parentGroupId, CancellationToken ct = default) { var parent = await _redb.LoadAsync(parentGroupId).ConfigureAwait(false) ?? throw new InvalidOperationException($"Group {parentGroupId} not found."); var children = await _redb.GetChildrenAsync(parent).ConfigureAwait(false); return children.Cast>().ToList(); } public async Task>> GetPathToRootAsync( long groupId, CancellationToken ct = default) { var group = await _redb.LoadAsync(groupId).ConfigureAwait(false) ?? throw new InvalidOperationException($"Group {groupId} not found."); var path = await _redb.GetPathToRootAsync(group).ConfigureAwait(false); return path.ToList(); } public async Task MoveGroupAsync(long groupId, long newParentGroupId, CancellationToken ct = default) { var group = await _redb.LoadAsync(groupId).ConfigureAwait(false) ?? throw new InvalidOperationException($"Group {groupId} not found."); var newParent = await _redb.LoadAsync(newParentGroupId).ConfigureAwait(false) ?? throw new InvalidOperationException($"Target parent group {newParentGroupId} not found."); await _redb.MoveObjectAsync(group, newParent).ConfigureAwait(false); } public async Task>> ListRootGroupsAsync(CancellationToken ct = default) { return await _redb.Query() .WhereRedb(o => o.ParentId == null) .ToListAsync() .ConfigureAwait(false); } /// /// B.2 — flat paginated search across ALL groups (root + nested), /// optionally filtered by name substring and groupType. Powers the /// `/admin/groups` list page where operators want to find a single /// group across a deeply nested tree without expanding nodes. /// public async Task<(List> Items, int Total)> SearchGroupsAsync( string? namePattern, string? groupType, int offset, int count, CancellationToken ct = default) { var query = _redb.Query(); if (!string.IsNullOrEmpty(namePattern)) { var pat = namePattern; query = query.WhereRedb(o => o.Name.Contains(pat)); } if (!string.IsNullOrEmpty(groupType)) { var gt = groupType; query = query.Where(p => p.GroupType == gt); } var total = (int)await query.CountAsync().ConfigureAwait(false); var items = await query .OrderByRedb(o => o.Name) .Skip(offset) .Take(count) .ToListAsync() .ConfigureAwait(false); return (items, total); } /// /// Bulk-count members per group — drives the per-row member-count badge /// on the groups list page without N round-trips. /// public async Task> CountMembersByGroupAsync( IEnumerable groupIds, CancellationToken ct = default) { var ids = groupIds.Distinct().ToList(); if (ids.Count == 0) return new(); var rows = await _redb.Query() .WhereInRedb(o => o.ParentId, ids.Cast()) .ToListAsync() .ConfigureAwait(false); return rows .Where(r => r.parent_id.HasValue) .GroupBy(r => r.parent_id!.Value) .ToDictionary(g => g.Key, g => g.Count()); } // ── Membership ────────────────────────────────────────────── public async Task> AddMemberAsync( long groupId, long userId, string? role = "member", DateTimeOffset? expiresAt = null, CancellationToken ct = default) { _ = await _redb.LoadAsync(groupId).ConfigureAwait(false) ?? throw new InvalidOperationException($"Group {groupId} not found."); var existing = await _redb.Query() .WhereRedb(o => o.Key == userId && o.ParentId == groupId) .FirstOrDefaultAsync() .ConfigureAwait(false); if (existing is not null) throw new InvalidOperationException($"User {userId} is already a member of group {groupId}."); var member = new RedbObject { key = userId, parent_id = groupId, Props = new GroupMemberProps { Role = role, JoinedAt = _timeProvider.GetUtcNow(), ExpiresAt = expiresAt } }; member.id = await _redb.SaveAsync(member).ConfigureAwait(false); return member; } public async Task AddMembersAsync( long groupId, IEnumerable userIds, string? role = "member", CancellationToken ct = default) { var idList = userIds.ToList(); if (idList.Count == 0) return; // Single query: find existing memberships to skip duplicates var nullableGroupId = (long?)groupId; var existingKeys = (await _redb.Query() .WhereRedb(o => o.ParentId == nullableGroupId) .ToListAsync().ConfigureAwait(false)) .Where(m => m.key.HasValue) .Select(m => m.key!.Value) .ToHashSet(); var now = _timeProvider.GetUtcNow(); var toAdd = idList .Where(uid => !existingKeys.Contains(uid)) .Select(uid => (IRedbObject)new RedbObject { key = uid, parent_id = groupId, Props = new GroupMemberProps { Role = role, JoinedAt = now } }) .ToList(); if (toAdd.Count > 0) await _redb.AddNewObjectsAsync(toAdd).ConfigureAwait(false); } public async Task RemoveMemberAsync(long groupId, long userId, CancellationToken ct = default) { var member = await _redb.Query() .WhereRedb(o => o.Key == userId && o.ParentId == groupId) .FirstOrDefaultAsync() .ConfigureAwait(false) ?? throw new InvalidOperationException($"User {userId} is not a member of group {groupId}."); await IdentityDeletionHelper.DeleteAsync(_redb, _backgroundDeletion, member).ConfigureAwait(false); } public async Task RemoveMembersAsync(long groupId, IEnumerable userIds, CancellationToken ct = default) { var idSet = userIds.ToHashSet(); if (idSet.Count == 0) return; var nullableGroupId = (long?)groupId; var members = await _redb.Query() .WhereRedb(o => o.ParentId == nullableGroupId) .ToListAsync().ConfigureAwait(false); var toRemove = members.Where(m => m.key.HasValue && idSet.Contains(m.key.Value)).ToList(); if (toRemove.Count > 0) await IdentityDeletionHelper.DeleteAsync(_redb, _backgroundDeletion, toRemove).ConfigureAwait(false); } public async Task RemoveAllMembersAsync(long groupId, CancellationToken ct = default) { var nullableGroupId = (long?)groupId; var members = await _redb.Query() .WhereRedb(o => o.ParentId == nullableGroupId) .ToListAsync().ConfigureAwait(false); if (members.Count > 0) await IdentityDeletionHelper.DeleteAsync(_redb, _backgroundDeletion, members).ConfigureAwait(false); } public async Task UpdateMemberRoleAsync( long groupId, long userId, string role, CancellationToken ct = default) { var member = await _redb.Query() .WhereRedb(o => o.Key == userId && o.ParentId == groupId) .FirstOrDefaultAsync() .ConfigureAwait(false) ?? throw new InvalidOperationException($"User {userId} is not a member of group {groupId}."); member.Props.Role = role; await _redb.SaveAsync(member).ConfigureAwait(false); } public async Task> GetMembersAsync( long groupId, CancellationToken ct = default) { var now = _timeProvider.GetUtcNow(); var members = await _redb.Query() .WhereRedb(o => o.ParentId == groupId) .Where(m => m.ExpiresAt == null || m.ExpiresAt >= now) .ToListAsync() .ConfigureAwait(false); return members .Select(m => new IGroupService.MemberInfo { MembershipId = m.id, UserId = m.key ?? 0, GroupId = groupId, Role = m.Props.Role, JoinedAt = m.Props.JoinedAt, ExpiresAt = m.Props.ExpiresAt }).ToList(); } public async Task>> GetMembersByGroupIdsAsync( IEnumerable groupIds, CancellationToken ct = default) { var idList = groupIds.ToList(); if (idList.Count == 0) return new Dictionary>(); var now = _timeProvider.GetUtcNow(); var nullableIds = idList.Select(id => (long?)id).ToList(); var allMembers = await _redb.Query() .WhereRedb(o => nullableIds.Contains(o.ParentId)) .ToListAsync() .ConfigureAwait(false); var result = idList.ToDictionary(id => id, _ => new List()); foreach (var m in allMembers) { if (m.Props.ExpiresAt.HasValue && m.Props.ExpiresAt.Value < now) continue; var gid = m.parent_id ?? 0; if (result.TryGetValue(gid, out var list)) { list.Add(new IGroupService.MemberInfo { MembershipId = m.id, UserId = m.key ?? 0, GroupId = gid, Role = m.Props.Role, JoinedAt = m.Props.JoinedAt, ExpiresAt = m.Props.ExpiresAt }); } } return result; } public async Task> GetUserGroupsAsync( long userId, CancellationToken ct = default) { var now = _timeProvider.GetUtcNow(); var memberships = await _redb.Query() .WhereRedb(o => o.Key == userId) .Where(m => m.ExpiresAt == null || m.ExpiresAt >= now) .ToListAsync() .ConfigureAwait(false); return await EnrichWithGroupInfo(memberships).ConfigureAwait(false); } public async Task HasMembershipRecordAsync(long groupId, long userId, CancellationToken ct = default) => await _redb.Query() .WhereRedb(o => o.Key == userId && o.ParentId == groupId) .FirstOrDefaultAsync() .ConfigureAwait(false) is not null; public async Task IsMemberAsync(long groupId, long userId, CancellationToken ct = default) { // Check direct membership first var member = await _redb.Query() .WhereRedb(o => o.Key == userId && o.ParentId == groupId) .FirstOrDefaultAsync() .ConfigureAwait(false); if (member is not null) { if (!member.Props.ExpiresAt.HasValue || member.Props.ExpiresAt.Value >= _timeProvider.GetUtcNow()) return true; } // Ancestor traversal: check if user is member of any ancestor group. // Server-side: one path-to-root load + ONE batched WhereInRedb across all // ancestor parent_ids (instead of N round-trips, one per ancestor). var group = await _redb.LoadAsync(groupId).ConfigureAwait(false); if (group is null) return false; var path = await _redb.GetPathToRootAsync(group).ConfigureAwait(false); var ancestorIds = path .Select(a => (long?)a.id) .Where(id => id != groupId) .ToList(); if (ancestorIds.Count == 0) return false; var now = _timeProvider.GetUtcNow(); var ancestorMemberships = await _redb.Query() .WhereRedb(o => o.Key == userId) .WhereInRedb(o => o.ParentId, ancestorIds) .Where(m => m.ExpiresAt == null || m.ExpiresAt >= now) .AnyAsync() .ConfigureAwait(false); return ancestorMemberships; } // ── Role resolution ───────────────────────────────────────── public async Task> ResolveUserRolesAsync( long userId, CancellationToken ct = default) { var now = _timeProvider.GetUtcNow(); var memberships = await _redb.Query() .WhereRedb(o => o.Key == userId) .Where(m => m.ExpiresAt == null || m.ExpiresAt >= now) .ToListAsync() .ConfigureAwait(false); return await EnrichWithGroupInfo(memberships).ConfigureAwait(false); } // ── Helpers ────────────────────────────────────────────────── private async Task> EnrichWithGroupInfo( List> memberships) { if (memberships.Count == 0) return []; // Batch-load all referenced groups in ONE query to avoid N+1 round-trips // — a user with many group memberships otherwise turned this admin enrichment // into an O(N) round-trip storm. var groupIds = memberships .Where(m => m.parent_id.HasValue) .Select(m => m.parent_id!.Value) .Distinct() .ToArray(); var groups = new Dictionary>(groupIds.Length); if (groupIds.Length > 0) { var loaded = await _redb.Query() .WhereInRedb(o => o.Id, groupIds) .ToListAsync() .ConfigureAwait(false); foreach (var g in loaded) groups[g.id] = g; } return memberships.Select(m => { groups.TryGetValue(m.parent_id ?? 0, out var g); return new IGroupService.UserGroupInfo { GroupId = m.parent_id ?? 0, GroupName = g?.name, GroupType = g?.Props?.GroupType, Role = m.Props.Role }; }).ToList(); } } Path: redb-identity/src/redb.Identity.Core/Services/IClientKeyResolver.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/Services/IClientKeyResolver.cs ---- using Microsoft.IdentityModel.Tokens; using redb.Core.Models.Entities; using redb.Identity.Core.Models; namespace redb.Identity.Core.Services; /// /// Resolves the public signing keys of a client application — the keys used to verify /// something the client signed (a JAR request object per RFC 9101, a private_key_jwt /// client assertion per RFC 7523). /// /// Two sources, in this order: /// /// inline — the JWKS pasted into the client record; /// — an absolute HTTPS URL fetched and cached. /// /// They are mutually exclusive by the admin UI's contract (see ), /// but if both are present the inline set wins: it is operator-controlled and needs no network call. /// /// /// Asymmetric only. HMAC (HS*) cannot be supported: /// stores a BCrypt hash, and verifying an HMAC signature needs the original secret, which is /// unrecoverable by design. FAPI 2.0 forbids HS* for request objects anyway and mandates /// PS256/ES256, so this is a correctness boundary rather than a gap. /// /// public interface IClientKeyResolver { /// /// Returns the client's public signing keys, or an empty collection when the client has /// published none (no inline JWKS and no reachable jwks_uri). /// /// The client application record. /// /// When , bypasses the cached copy of a jwks_uri document and /// re-fetches it. Used for a single retry after a kid miss, so that a client rotating /// its keys does not break sign-in until the cache expires. Never set it on the first attempt — /// an unauthenticated caller must not be able to trigger outbound fetches at will. /// /// Keys suitable for signature verification; never . ValueTask> GetSigningKeysAsync( RedbObject application, bool forceRefresh = false, CancellationToken cancellationToken = default); /// /// The same keys as , as the key set itself (inline, or the cached /// jwks_uri document), or when the client has none. Used where a /// is the expected shape, such as the application store for client assertions. /// ValueTask GetJsonWebKeySetAsync( RedbObject application, bool forceRefresh = false, CancellationToken cancellationToken = default); } Path: redb-identity/src/redb.Identity.Core/Services/IDpopNonceProvider.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/Services/IDpopNonceProvider.cs ---- using System.Security.Cryptography; using System.Text; using Microsoft.Extensions.Options; using Microsoft.IdentityModel.Tokens; using redb.Identity.Core.Configuration; namespace redb.Identity.Core.Services; /// /// Z4 P2 (RFC 9449 §8): provider of server-issued DPoP nonces. Implementations may be /// stateless (HMAC-signed timestamps) or stateful (Redis/redb). The default registered /// implementation is — stateless, lock-free, and /// safe to use in single-process deployments. For a clustered Identity tier set /// to a shared value so any server can /// validate nonces issued by any other. /// public interface IDpopNonceProvider { /// Issues a fresh nonce string suitable for the DPoP-Nonce header. string IssueNonce(); /// /// Returns true when the supplied nonce is well-formed, signature-valid /// and within of issuance. /// bool ValidateNonce(string nonce); } /// /// Stateless HMAC-SHA256 nonce provider. Each nonce encodes a Unix-second timestamp and /// 16 random bytes plus an HMAC; validation re-computes the HMAC and checks the timestamp /// against . /// /// Format: base64url(timestamp_be8 || rand16 || hmac_sha256(secret, timestamp_be8 || rand16)). /// /// public sealed class HmacDpopNonceProvider : IDpopNonceProvider { private readonly DpopOptions _options; private readonly TimeProvider _timeProvider; private readonly byte[] _secret; public HmacDpopNonceProvider(IOptions identityOptions, TimeProvider? timeProvider = null) { ArgumentNullException.ThrowIfNull(identityOptions); _options = identityOptions.Value.Dpop; _timeProvider = timeProvider ?? TimeProvider.System; if (!string.IsNullOrEmpty(_options.NonceSigningSecret)) _secret = Encoding.UTF8.GetBytes(_options.NonceSigningSecret); else _secret = RandomNumberGenerator.GetBytes(32); } public string IssueNonce() { Span payload = stackalloc byte[8 + 16]; var ts = _timeProvider.GetUtcNow().ToUnixTimeSeconds(); BitConverter.TryWriteBytes(payload[..8], !BitConverter.IsLittleEndian ? ts : System.Buffers.Binary.BinaryPrimitives.ReverseEndianness(ts)); RandomNumberGenerator.Fill(payload[8..]); Span mac = stackalloc byte[32]; HMACSHA256.HashData(_secret, payload, mac); Span token = stackalloc byte[payload.Length + mac.Length]; payload.CopyTo(token); mac.CopyTo(token[payload.Length..]); return Base64UrlEncoder.Encode(token.ToArray()); } public bool ValidateNonce(string nonce) { if (string.IsNullOrEmpty(nonce)) return false; byte[] decoded; try { decoded = Base64UrlEncoder.DecodeBytes(nonce); } catch { return false; } // 8 ts + 16 rand + 32 mac = 56 if (decoded.Length != 56) return false; var payload = decoded.AsSpan(0, 24); var providedMac = decoded.AsSpan(24, 32); Span expectedMac = stackalloc byte[32]; HMACSHA256.HashData(_secret, payload, expectedMac); if (!CryptographicOperations.FixedTimeEquals(providedMac, expectedMac)) return false; var tsBe = BitConverter.ToInt64(payload[..8]); var ts = !BitConverter.IsLittleEndian ? tsBe : System.Buffers.Binary.BinaryPrimitives.ReverseEndianness(tsBe); var now = _timeProvider.GetUtcNow().ToUnixTimeSeconds(); var ageSeconds = now - ts; if (ageSeconds < -5) return false; // future-dated beyond clock skew return ageSeconds <= (long)_options.NonceLifetime.TotalSeconds; } } Path: redb-identity/src/redb.Identity.Core/Services/IDpopReplayStore.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/Services/IDpopReplayStore.cs ---- namespace redb.Identity.Core.Services; /// /// Z4 (RFC 9449 §11.1): DPoP proof jti replay-prevention store. /// Implementations MUST atomically reserve a (jkt, jti) pair so that a /// concurrent replay attempt sees the prior reservation and is rejected. /// public interface IDpopReplayStore { /// /// Attempts to reserve the given bound to the proof's /// for the duration of . /// /// Base64url-encoded JWK SHA-256 thumbprint (RFC 7638) of the /// proof's public key. Scoping the reservation by jkt prevents cross-client jti /// collisions from being treated as replays. /// The jti claim from the DPoP proof. /// Reservation TTL — typically the iat-tolerance window. /// Cancellation token. /// /// true if the jti was newly reserved (proof is fresh); /// false if a prior reservation exists (proof is a replay). /// Task TryReserveAsync(string jkt, string jti, TimeSpan ttl, CancellationToken ct = default); } Path: redb-identity/src/redb.Identity.Core/Services/IEmailNotificationChannel.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/Services/IEmailNotificationChannel.cs ---- using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace redb.Identity.Core.Services; /// /// N-4 (Session C): SPI for delivering identity-system transactional e-mails /// (password reset, account-verification, change-of-email confirmation, etc.) via the /// host's mail infrastructure. /// /// Mirrors the role plays for SMS/Email OTP delivery: /// the Core defines only the contract; concrete implementations (SMTP, SendGrid, in-memory /// test capture) are registered by the host application or by satellite packages. /// /// /// Templates are referenced by a stable templateId string (e.g. "password-reset"); /// the implementation resolves the localized body and the variable substitution. Core /// passes the values as a flat dictionary keyed by template-variable names (e.g. /// userName, resetLink, ttlMinutes). /// /// public interface IEmailNotificationChannel { /// /// Renders with the supplied and /// dispatches the resulting message to . The call MUST be safe /// to invoke concurrently and MUST NOT throw on transient errors that the host has /// chosen to absorb (logging is acceptable); fatal misconfiguration MAY throw so the /// caller can degrade gracefully. /// /// Recipient e-mail address. /// Stable template identifier (e.g. "password-reset"). /// Variable substitutions for the template body. Task SendTemplateAsync( string to, string templateId, IReadOnlyDictionary vars, CancellationToken ct = default); } /// /// N-4 (Session C): stable template identifiers consumed by /// . Centralized so processors /// and template-implementation packages share a single source of truth. /// public static class IdentityEmailTemplates { /// Password-reset link e-mail. Vars: userName, resetLink, ttlMinutes. public const string PasswordReset = "password-reset"; /// N4-6: e-mail verification link. Vars: userName, verifyLink, ttlHours. public const string EmailVerification = "email-verification"; /// N4-7: change-of-e-mail confirmation link delivered to the NEW address. /// Vars: userName, oldEmail, newEmail, confirmLink, ttlHours. public const string ChangeEmail = "change-email"; /// The one-time code of e-mail MFA, at enrollment and at sign-in. Vars: code, ttlMinutes. public const string MfaCode = "mfa-code"; } Path: redb-identity/src/redb.Identity.Core/Services/IEmailTemplateRegistry.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/Services/IEmailTemplateRegistry.cs ---- using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace redb.Identity.Core.Services; /// /// N-4 (Session C): rendered e-mail payload returned by an /// lookup. Carries everything the /// needs to dispatch (subject line + HTML body /// + optional text alternative). The default registry produces both an HTML and a /// plain-text version so SMTP-side multipart/alternative messages render correctly in /// clients that disable HTML. /// public sealed class RenderedEmailTemplate { public required string Subject { get; init; } public required string HtmlBody { get; init; } public string? TextBody { get; init; } } /// /// N-4 (Session C): renders identity-system e-mail templates by /// id + locale + variable substitutions. /// Implementations MAY consult UserProps.Locale (when added) or fall back to a /// default locale; the default ships with /// English and Russian variants and falls back to English when the requested locale is /// missing. /// public interface IEmailTemplateRegistry { /// /// Resolves the template body. Throws when /// is unknown; missing locales degrade silently to the /// default (English). /// ValueTask RenderAsync( string templateId, string? locale, IReadOnlyDictionary vars, CancellationToken ct = default); } Path: redb-identity/src/redb.Identity.Core/Services/IExternalUserProvider.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/Services/IExternalUserProvider.cs ---- namespace redb.Identity.Core.Services; /// /// SPI for pluggable external authentication providers (LDAP, SAML, OIDC federation, etc.). /// Implementations are registered in DI and tried in order by /// before falling back to the local _users password check. /// public interface IExternalUserProvider { /// Provider identifier, e.g. "ldap", "oidc:google", "saml:corp". string ProviderName { get; } /// Lower value = tried first. Default providers should use 100+. int Priority { get; } /// /// Attempts to authenticate / /// against the external system. /// Returns null if this provider does not handle the given user (next provider is tried). /// Returns a result with = false for explicit auth failure /// (e.g. valid LDAP user but wrong password — do NOT fall through to local). /// Task AuthenticateAsync(string username, string password, CancellationToken ct = default); } /// /// Result of an external authentication attempt. /// public sealed class ExternalAuthResult { /// Whether the authentication succeeded. public bool Succeeded { get; private init; } /// Unique identifier in the external system (DN, sub, UPN, etc.). public string? ExternalId { get; private init; } /// Display name from the external directory. public string? DisplayName { get; private init; } /// Email from the external directory. public string? Email { get; private init; } /// Phone from the external directory. public string? Phone { get; private init; } /// Given name (first name). public string? GivenName { get; private init; } /// Family name (last name). public string? FamilyName { get; private init; } /// Additional claims from the external system (department, title, etc.). public Dictionary? AdditionalClaims { get; set; } /// Error message for failed authentication. public string? ErrorMessage { get; private init; } public static ExternalAuthResult Success( string externalId, string? displayName = null, string? email = null, string? phone = null, string? givenName = null, string? familyName = null, Dictionary? additionalClaims = null) => new() { Succeeded = true, ExternalId = externalId, DisplayName = displayName, Email = email, Phone = phone, GivenName = givenName, FamilyName = familyName, AdditionalClaims = additionalClaims }; public static ExternalAuthResult Failed(string message) => new() { Succeeded = false, ErrorMessage = message }; } Path: redb-identity/src/redb.Identity.Core/Services/IFederatedAuthProvider.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/Services/IFederatedAuthProvider.cs ---- namespace redb.Identity.Core.Services; /// /// SPI for redirect-based federated authentication (OIDC, SAML, etc.). /// Unlike (password-based, synchronous), /// federation uses a two-step redirect flow: challenge → callback. /// public interface IFederatedAuthProvider { /// Provider ID used as key in ExternalIdentities dict. E.g. "google", "azure-ad". string ProviderId { get; } /// Display name for login page button. string DisplayName { get; } /// Priority for ordering on the login page. Lower = shown first. int Priority { get; } /// Build authorization redirect URI with state, nonce, PKCE. Task CreateChallengeAsync(string callbackUrl, string returnUrl, CancellationToken ct = default); /// Handle callback: exchange code → validate tokens → return identity. Task HandleCallbackAsync( string code, string callbackUrl, string? codeVerifier = null, string? nonce = null, CancellationToken ct = default); } /// /// Result of : /// contains the redirect URI and state that must be round-tripped. /// public sealed class FederationChallenge { /// Full URI to external IdP authorization endpoint. public required string RedirectUri { get; init; } /// Opaque state for CSRF protection (round-tripped via query param). public required string State { get; init; } /// Nonce for id_token replay protection. public string? Nonce { get; init; } /// PKCE code_verifier (S256). Must be stored server-side for token exchange. public string? CodeVerifier { get; init; } } Path: redb-identity/src/redb.Identity.Core/Services/IFederationStateNonceStore.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/Services/IFederationStateNonceStore.cs ---- namespace redb.Identity.Core.Services; /// /// One-time-use nonce store for federation state blobs (C6). /// Each issued state carries a unique jti; the callback path consumes it /// exactly once. Implementations MUST be safe for concurrent calls and MUST /// auto-expire entries after their TTL to bound memory. /// public interface IFederationStateNonceStore { /// /// Records the as consumed and returns true iff /// it was previously unseen. Subsequent calls with the same /// (within ) MUST return false. /// Task TryConsumeAsync(string jti, TimeSpan ttl, CancellationToken ct = default); } Path: redb-identity/src/redb.Identity.Core/Services/IGroupService.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/Services/IGroupService.cs ---- using redb.Core.Models.Entities; using redb.Identity.Core.Models; namespace redb.Identity.Core.Services; /// /// Groups/RBAC service — manages hierarchical groups and flat memberships. /// public interface IGroupService { // ── Group CRUD ────────────────────────────────────────────── Task> CreateGroupAsync( string name, string? groupType = null, string? description = null, CancellationToken ct = default); Task> CreateChildGroupAsync( long parentGroupId, string name, string? groupType = null, string? description = null, CancellationToken ct = default); Task?> GetGroupAsync(long groupId, CancellationToken ct = default); /// /// The group with this name, compared by (case, surrounding /// whitespace and Unicode form ignored), or null. Names are unique across the tree. /// Task?> FindGroupByNameAsync(string name, CancellationToken ct = default); Task UpdateGroupAsync( long groupId, string? name = null, string? groupType = null, string? description = null, CancellationToken ct = default); Task DeleteGroupAsync(long groupId, CancellationToken ct = default); // ── Tree operations ───────────────────────────────────────── Task> LoadTreeAsync(long rootGroupId, int? maxDepth = null, CancellationToken ct = default); Task>> GetChildGroupsAsync(long parentGroupId, CancellationToken ct = default); Task>> GetPathToRootAsync(long groupId, CancellationToken ct = default); Task MoveGroupAsync(long groupId, long newParentGroupId, CancellationToken ct = default); Task>> ListRootGroupsAsync(CancellationToken ct = default); /// /// B.2 — flat paginated search across ALL groups. /// Task<(List> Items, int Total)> SearchGroupsAsync( string? namePattern, string? groupType, int offset, int count, CancellationToken ct = default); /// /// B.2 — bulk member-count for a set of groups, used to render the /// per-row badge on the groups list page without N round-trips. /// Task> CountMembersByGroupAsync( IEnumerable groupIds, CancellationToken ct = default); // ── Membership ────────────────────────────────────────────── Task> AddMemberAsync( long groupId, long userId, string? role = "member", DateTimeOffset? expiresAt = null, CancellationToken ct = default); /// /// Batch-add members to a group. /// Skips duplicates (existing memberships) without throwing. /// Uses AddNewObjectsAsync for bulk insert. /// Task AddMembersAsync(long groupId, IEnumerable userIds, string? role = "member", CancellationToken ct = default); Task RemoveMemberAsync(long groupId, long userId, CancellationToken ct = default); /// /// Batch-remove members by userId. Single query + bulk delete. /// Task RemoveMembersAsync(long groupId, IEnumerable userIds, CancellationToken ct = default); /// /// Remove all members of a group. Single query + bulk delete. /// Task RemoveAllMembersAsync(long groupId, CancellationToken ct = default); Task UpdateMemberRoleAsync(long groupId, long userId, string role, CancellationToken ct = default); Task> GetMembersAsync(long groupId, CancellationToken ct = default); /// /// Batch-load members for multiple groups in a single query. /// Returns a dictionary: groupId → list of active members. /// Task>> GetMembersByGroupIdsAsync( IEnumerable groupIds, CancellationToken ct = default); Task> GetUserGroupsAsync(long userId, CancellationToken ct = default); Task IsMemberAsync(long groupId, long userId, CancellationToken ct = default); /// /// Whether the user has a membership record in exactly this group, expired or not. This is the /// record and act on, and not /// the question answers: that one leaves an expired membership out and /// counts a membership inherited from an ancestor group in. /// Task HasMembershipRecordAsync(long groupId, long userId, CancellationToken ct = default); // ── Role resolution ───────────────────────────────────────── /// /// Returns all group names and roles for a user (active, non-expired memberships). /// Used by GroupClaimsResolver to populate token claims. /// Task> ResolveUserRolesAsync(long userId, CancellationToken ct = default); // ── DTOs ──────────────────────────────────────────────────── public sealed class MemberInfo { public long MembershipId { get; init; } public long UserId { get; init; } public long GroupId { get; init; } public string? Role { get; init; } public DateTimeOffset? JoinedAt { get; init; } public DateTimeOffset? ExpiresAt { get; init; } } public sealed class UserGroupInfo { public long GroupId { get; init; } public string? GroupName { get; init; } public string? GroupType { get; init; } public string? Role { get; init; } } } Path: redb-identity/src/redb.Identity.Core/Services/IMfaDeliveryChannel.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/Services/IMfaDeliveryChannel.cs ---- namespace redb.Identity.Core.Services; /// /// SPI for delivering MFA codes via external channels (SMS, Email). /// /// /// Implementations are provided by external packages (e.g. redb.Identity.Sms, redb.Identity.Email) /// or registered by the host application. Core defines only the contract. /// public interface IMfaDeliveryChannel { /// Channel identifier matching : "sms", "email". string ChannelId { get; } /// Human-readable display name (e.g. "SMS", "Email"). string DisplayName { get; } /// /// Sends the OTP code to the destination. /// /// Phone number (E.164) for SMS, email address for email. /// 6-digit OTP code. /// Cancellation token. /// Thrown when delivery fails. Task SendCodeAsync(string destination, string code, CancellationToken ct = default); } Path: redb-identity/src/redb.Identity.Core/Services/IMfaMethod.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/Services/IMfaMethod.cs ---- using redb.Identity.Core.Models; namespace redb.Identity.Core.Services; /// /// SPI for MFA verification methods (TOTP, SMS, WebAuthn, etc.). /// Implementations are stateless — they receive directly /// and never load/save data. Orchestration is done by . /// public interface IMfaMethod { /// Unique method identifier (e.g. "totp", "sms", "email"). string MethodId { get; } /// /// Pure setup: generates the candidate secret/destination and the client-facing payload /// (QR URI, masked destination, …) WITHOUT mutating . /// The orchestrator wraps the returned in an encrypted /// setup token (B5) which the client must present back during confirm. This eliminates the /// "two parallel setups overwrite the secret" race. /// /// Username for QR label (TOTP). May be ignored by other methods. /// Phone/email for SMS/Email methods. Ignored by TOTP/WebAuthn. Task InitiateSetupAsync(string username, string? destination = null, CancellationToken ct = default); /// /// Verifies the user-supplied code against the candidate setup data and, on success, /// writes the secret/destination into . Single atomic step — /// caller must persist only after this method returns true. /// /// /// Decrypted MFA challenge state for SMS/Email (carries /// referencing MfaOtpProps). Null for TOTP. /// Task ConfirmAndApplyAsync(MfaProps props, MfaSetupInitiation initiation, string code, MfaState? state = null, CancellationToken ct = default); /// Verify code during login. /// /// Decrypted MFA state for SMS/Email (carries referencing /// server-side OTP material). Null/ignored for TOTP. /// Task VerifyAsync(MfaProps props, string code, MfaState? state = null, CancellationToken ct = default); } Path: redb-identity/src/redb.Identity.Core/Services/IRateLimitStore.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/Services/IRateLimitStore.cs ---- namespace redb.Identity.Core.Services; /// /// C1 — Outcome of a rate-limit check / increment. /// /// true if the call may proceed; false if it should be rejected with HTTP 429. /// The bucket count AFTER the increment (or the current count when denied without incrementing). /// When is false, hint to the client for the Retry-After header. public readonly record struct RateLimitDecision(bool Allowed, int Count, TimeSpan RetryAfter); /// /// C1 — Sliding-window counter store used by the rate-limit processors. Implementations /// must be safe for concurrent use across many threads. Default impl: in-memory per-node; /// optional impl: Redis (cluster-global). Selected via /// . /// public interface IRateLimitStore { /// /// Records a hit on within a sliding window of /// length and returns whether the bucket is still under . /// /// /// MUST behave atomically: concurrent callers either all see the increment or none do. /// When is false, implementations MAY /// still record the hit (extends penalty) — caller treats both modes uniformly via 429. /// Task TryIncrementAsync(string key, int limit, TimeSpan window, CancellationToken ct = default); /// /// Forcibly resets the counter for . Used when an authentication /// attempt SUCCEEDS so a single legitimate sign-in clears the failure tally. /// Task ResetAsync(string key, CancellationToken ct = default); } Path: redb-identity/src/redb.Identity.Core/Services/IUserProfileService.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/Services/IUserProfileService.cs ---- using System.Security.Claims; using redb.Core.Models.Contracts; using redb.Identity.Core.Models; using redb.Identity.Core.OpenIddict; namespace redb.Identity.Core.Services; /// /// Unified user profile and claims service. /// Single entry point for loading user data (Core + OIDC + groups) /// and building a ClaimsPrincipal for any grant type or session. /// public interface IUserProfileService { /// /// Builds a for the given user with the specified scopes. /// Loads the Core user, OIDC profile extension, and group/role memberships, /// then delegates to + . /// /// The _users._id value. /// Requested OIDC scopes (profile, email, phone, address, groups, roles, etc.). /// Whether the current session passed MFA. Adds the appropriate amr claim. /// MFA method id used for verification ("totp", "sms", "email", "webauthn", "recovery"). /// /// Parsed claims request parameter (OIDC Core §5.5), when the RP sent one. Only the /// authorization endpoint can carry it; every other grant passes null. /// /// Cancellation token. /// Fully populated or null if user not found / disabled. Task BuildPrincipalAsync( long userId, IEnumerable scopes, bool mfaVerified = false, string? mfaMethod = null, OidcClaimsRequest? claimsRequest = null, CancellationToken ct = default); /// /// Fast-path overload for callers that already loaded the Core user + OIDC props + /// subject GUID (e.g. LoginService.AuthenticateAsync). Skips the redundant /// _users + UserProps round-trips and only loads what isn't supplied — /// group memberships when groups / roles scopes are requested. /// Behaves identically to the userId-only overload otherwise. /// Task BuildPrincipalAsync( IRedbUser user, UserProps? oidcProps, Guid subjectGuid, IEnumerable scopes, bool mfaVerified = false, string? mfaMethod = null, CancellationToken ct = default); } Path: redb-identity/src/redb.Identity.Core/Services/IWebAuthnMfaMethod.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/Services/IWebAuthnMfaMethod.cs ---- using System.Threading; using System.Threading.Tasks; using Fido2NetLib; using redb.Identity.Core.Models; namespace redb.Identity.Core.Services; /// /// MFA-3: typed SPI for the WebAuthn (FIDO2 / Passkey) flow. Standalone — does NOT /// inherit because the WebAuthn shape (typed ceremony objects, /// dual begin/complete, allow-credentials filtering) is fundamentally different from the /// OTP-style InitiateSetup / ConfirmAndApply / Verify(code) contract. Orchestration /// of WebAuthn lives on dedicated methods rather than the generic /// / pipeline. /// /// All cryptographic verification (attestation parsing, signature verification, sign-counter /// rollback) is delegated to Fido2NetLib (IFido2). This abstraction sits ONE level above /// it and adds: per-credential UV-downgrade ratchet (), /// AAGUID blocklist enforcement, anti-replay via , /// fail-fast options validation. owns the surrounding transactions /// and persists the resulting mutations. /// /// public interface IWebAuthnMfaMethod { /// /// Builds for the browser to invoke /// navigator.credentials.create. Generates 32 random challenge bytes; the caller /// is expected to encrypt them into the setup-token so the corresponding complete /// call can verify byte-equality. on any /// existing credential of the user is honoured by passing the matching /// UserVerification requirement so a downgrade attack at registration time is rejected. /// /// Numeric Identity user id; encoded into user.id. /// Login (e.g. e-mail). Shown in the OS authenticator UI. /// Friendly display name. Shown in the OS authenticator UI. /// Already-registered credentials for the user — added /// to excludeCredentials so a single device cannot register twice. /// If true, requires UV at registration. False → preferred. /// The Fido2 with 32-byte /// Challenge; caller persists those bytes in the setup-token. CredentialCreateOptions BeginRegistration( long userId, string username, string displayName, IReadOnlyDictionary? existingCredentials, bool enforceUv); /// /// Verifies an attestation response against the original options + challenge bytes. /// On success returns a fully-formed with UV/BE/BS flags /// (parsed from authenticatorData) and AAGUID. Throws /// with code aaguid_blocked when the /// attested AAGUID is in the configured blocklist. /// /// Raw browser response (deserialized). /// Options that produced the challenge. /// User who initiated the ceremony. /// Cancellation. Task CompleteRegistrationAsync( AuthenticatorAttestationRawResponse attestationResponse, CredentialCreateOptions originalOptions, long userId, CancellationToken ct = default); /// /// Builds for the browser to invoke /// navigator.credentials.get. Allow-credentials lists every credential registered /// to the user. UV requirement is set to required when ANY existing credential has /// =true (per-user UV ratchet — rejects a /// downgrade attack where the attacker chooses a less-protected credential). /// AssertionOptions BeginAssertion(IReadOnlyDictionary credentials); /// /// Verifies an assertion response. Returns the matched credential (mutated in-place /// with new , /// and ) on success. Returns null on signature /// failure. Throws with codes: /// /// uv_downgrade — credential was registered with UV but assertion has UV=0 /// sign_counter_rollback — new SignCount < stored SignCount (CTAP2 §6.1.4) /// credential_not_found — assertion's credentialId not in user's set /// /// Task CompleteAssertionAsync( AuthenticatorAssertionRawResponse assertionResponse, AssertionOptions originalOptions, IReadOnlyDictionary credentials, long userId, CancellationToken ct = default); } Path: redb-identity/src/redb.Identity.Core/Services/IdentityDeletionHelper.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/Services/IdentityDeletionHelper.cs ---- using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using redb.Core; using redb.Core.Models.Contracts; using redb.Core.Services; namespace redb.Identity.Core.Services; /// /// Identity-wide deletion pattern. /// /// Identity NEVER hard-deletes via redb.DeleteAsync directly. Hard-deletes /// cascade through the _values PROPS table (an unbounded fan-out for objects /// with many properties / descendants — User, Application, Authorization, etc.), /// running synchronously inside the request and able to time out the foreground /// connection. /// /// /// Strategy: mark here, purge there. /// /// Mark — /// on the caller's : the objects move under a trash /// container and vanish from regular Query results immediately. /// Purge — polls for trash /// containers and physically deletes them on its own connection. It finds the /// container written above by itself; nothing has to be handed to it. /// /// /// /// The mark deliberately does NOT go through . /// That method opens its own DI scope, i.e. a second connection, and marks there. /// Under a route-level transaction (WithRedbTx, active whenever /// RedbInstanceName is configured) that second connection fights the first: /// on SQLite it waits on the writer lock held by the route transaction and fails after /// the busy timeout (~34 s), and on PostgreSQL / MSSQL the mark either blocks on the /// row locks of an object the route already wrote, or commits on its own — so a route /// that fails afterwards rolls back everything except the deletion. Marking on the /// caller's service joins whatever transaction that service is in (SoftDeleteAsync /// runs through ExecuteAtomicAsync), so the deletion commits and rolls back with /// the rest of the operation. /// /// internal static class IdentityDeletionHelper { /// Bulk delete by ids using the Identity-wide pattern. public static async Task DeleteAsync( IRedbService redb, IBackgroundDeletionService? backgroundDeletion, IEnumerable objectIds, ILogger? logger = null) { var ids = objectIds as IList ?? objectIds.ToList(); if (ids.Count == 0) return; if (backgroundDeletion is null) { // The mark below still hides the objects from every query, but nothing will // physically purge them — operators must run a maintenance job. Worth a warning: // in production the service is registered by the provider's DI extension. logger?.LogWarning( "IBackgroundDeletionService is not registered. Objects will be marked deleted " + "but no physical purge will run. Count={Count}", ids.Count); } // Always on the caller's service — see the class remarks for why the background // service's own DeleteAsync (a second connection) must not do this. await redb.SoftDeleteAsync(ids, redb.SecurityContext.GetEffectiveUser()).ConfigureAwait(false); } /// Delete a single object by id using the Identity-wide pattern. public static Task DeleteAsync( IRedbService redb, IBackgroundDeletionService? backgroundDeletion, long objectId, ILogger? logger = null) => DeleteAsync(redb, backgroundDeletion, new[] { objectId }, logger); /// Delete by IRedbObject reference using the Identity-wide pattern. public static Task DeleteAsync( IRedbService redb, IBackgroundDeletionService? backgroundDeletion, IRedbObject obj, ILogger? logger = null) => DeleteAsync(redb, backgroundDeletion, new[] { obj.Id }, logger); /// Delete by IRedbObject collection using the Identity-wide pattern. public static Task DeleteAsync( IRedbService redb, IBackgroundDeletionService? backgroundDeletion, IEnumerable objects, ILogger? logger = null) => DeleteAsync(redb, backgroundDeletion, objects.Select(o => o.Id), logger); } Path: redb-identity/src/redb.Identity.Core/Services/IdentityPrincipalBuilder.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/Services/IdentityPrincipalBuilder.cs ---- using System.Security.Claims; using System.Text.Json; using OpenIddict.Abstractions; using redb.Core.Models.Contracts; using redb.Identity.Core.Models; using redb.Identity.Core.OpenIddict; using static OpenIddict.Abstractions.OpenIddictConstants; namespace redb.Identity.Core.Services; /// /// Builds a for an authenticated user. /// Single source of truth for claim construction — used by both /// session-based auth and ROPC grant. /// public static class IdentityPrincipalBuilder { private static readonly JsonSerializerOptions AddressJsonOptions = new() { PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower, DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull }; /// /// Internal claim carrying the bigint _users._id alongside the public GUID /// sub. Identity-internal processors (e.g. /me/*, scope/group resolvers) /// read this claim to query redb without needing a GUID→long round-trip. Emitted only /// to the access token, never to the id_token, since RPs should rely on the GUID /// sub for cross-Identity-instance correctness. /// public const string InternalUserIdClaim = "redb:user_id"; /// /// Internal marker listing the claim types the RP requested for /connect/userinfo via /// the claims parameter (OIDC Core §5.5), space-separated. /// /// UserInfo is served from the access token, so by the time the request reaches /// HandleUserInfoRequestContext the original authorization request is long gone — all /// that survives is the principal. Without this marker the userinfo handler cannot tell /// "the RP asked for `name` individually" from "`name` happens to sit in the principal", /// and would have to either leak scope-gated claims to everyone or ignore the parameter. /// /// /// Access-token destination only, so it never reaches the id_token, and the userinfo handler /// strips it from its own output — it is our bookkeeping, not a claim about the user. /// /// public const string RequestedUserInfoClaims = "redb:claims_userinfo"; /// /// Builds a ClaimsPrincipal from a Core user and optional OIDC profile extension. /// Credentials (login, email, phone) come from (_users table). /// OIDC profile claims (given_name, family_name, picture, *_verified) come from . /// The is emitted as the public sub claim; the /// bigint .Id is mirrored into the internal /// for redb queries. /// public static ClaimsPrincipal Build( IRedbUser user, Guid subjectGuid, UserProps? oidcProps, IEnumerable scopes, bool mfaVerified = false, string? mfaMethod = null, OidcClaimsRequest? claimsRequest = null) { ArgumentNullException.ThrowIfNull(user); if (subjectGuid == Guid.Empty) throw new ArgumentException("Subject GUID must not be empty.", nameof(subjectGuid)); var scopeList = scopes as IReadOnlyList ?? scopes.ToList(); var identity = new ClaimsIdentity( authenticationType: "OpenIddict.Server", nameType: Claims.Name, roleType: Claims.Role); identity.SetClaim(Claims.Subject, subjectGuid.ToString("D")); identity.SetClaim(InternalUserIdClaim, user.Id.ToString()); identity.SetClaim(Claims.Name, user.Login); identity.SetScopes(scopeList); // Profile scope claims — the full OIDC Core §5.1 set. The conformance suite // (oidcc-scope-profile / oidcc-scope-all) compares userinfo against this exact list and // warns for each claim the OP omits, so emit every one we hold. // // Two are derived rather than stored: `preferred_username` falls back to the login, and // `updated_at` to the registration date when the profile was never edited. `updated_at` is // a JSON NUMBER (seconds since the epoch) per the spec — not a string. if (scopeList.Contains(Scopes.Profile)) { if (!string.IsNullOrEmpty(oidcProps?.GivenName)) identity.SetClaim(Claims.GivenName, oidcProps.GivenName); if (!string.IsNullOrEmpty(oidcProps?.FamilyName)) identity.SetClaim(Claims.FamilyName, oidcProps.FamilyName); if (!string.IsNullOrEmpty(oidcProps?.MiddleName)) identity.SetClaim(Claims.MiddleName, oidcProps.MiddleName); if (!string.IsNullOrEmpty(oidcProps?.Nickname)) identity.SetClaim(Claims.Nickname, oidcProps.Nickname); if (!string.IsNullOrEmpty(oidcProps?.Profile)) identity.SetClaim(Claims.Profile, oidcProps.Profile); if (!string.IsNullOrEmpty(oidcProps?.Picture)) identity.SetClaim(Claims.Picture, oidcProps.Picture); if (!string.IsNullOrEmpty(oidcProps?.Website)) identity.SetClaim(Claims.Website, oidcProps.Website); if (!string.IsNullOrEmpty(oidcProps?.Gender)) identity.SetClaim(Claims.Gender, oidcProps.Gender); if (!string.IsNullOrEmpty(oidcProps?.Birthdate)) identity.SetClaim(Claims.Birthdate, oidcProps.Birthdate); if (!string.IsNullOrEmpty(oidcProps?.ZoneInfo)) identity.SetClaim(Claims.Zoneinfo, oidcProps.ZoneInfo); if (!string.IsNullOrEmpty(oidcProps?.Locale)) identity.SetClaim(Claims.Locale, oidcProps.Locale); identity.SetClaim(Claims.PreferredUsername, !string.IsNullOrEmpty(oidcProps?.PreferredUsername) ? oidcProps.PreferredUsername : user.Login); var updatedAt = oidcProps?.UpdatedAt ?? user.DateRegister; identity.SetClaim(Claims.UpdatedAt, updatedAt.ToUnixTimeSeconds()); } // Email scope claims (email from _users, verified flag from OIDC extension) if (scopeList.Contains(Scopes.Email)) { if (!string.IsNullOrEmpty(user.Email)) { identity.SetClaim(Claims.Email, user.Email); var verified = oidcProps?.EmailVerified ?? false; // OIDC Core §5.1 — email_verified MUST be a JSON boolean. OpenIddict's bool // SetClaim overload stamps ClaimValueTypes.Boolean so it serialises as true/false // (not the string "true"), which the conformance suite requires. identity.SetClaim(Claims.EmailVerified, verified); } } // Phone scope claims (phone from _users, verified flag from OIDC extension) if (scopeList.Contains(Scopes.Phone)) { if (!string.IsNullOrEmpty(user.Phone)) { identity.SetClaim(Claims.PhoneNumber, user.Phone); var verified = oidcProps?.PhoneNumberVerified ?? false; // OIDC Core §5.1 — phone_number_verified MUST be a JSON boolean (see email_verified above). identity.SetClaim(Claims.PhoneNumberVerified, verified); } } // Address scope claim (OIDC §5.1.1 — structured JSON object). Set as a JSON-typed claim: // OpenIddict 7 rejects a sign-in whose `address` is not a JSON object claim. if (scopeList.Contains(Scopes.Address) && oidcProps?.Address is not null) { identity.SetClaim(Claims.Address, JsonSerializer.SerializeToElement(oidcProps.Address, AddressJsonOptions)); } // Custom claims (arbitrary key-value pairs, always emitted if present) if (oidcProps?.CustomClaims is not null) { foreach (var (key, value) in oidcProps.CustomClaims) { if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(value)) identity.SetClaim(key, value); } } // OIDC Core §2 — `auth_time` (epoch seconds when the End-User auth occurred). // Must be a NumericDate (RFC 7519 §2). OpenIddict's ValidateSignInDemand parses // this claim as Int64; passing a plain string-valued Claim ("12345") trips // "auth_time claim is malformed or isn't of the expected type". So we add the // claim explicitly with ClaimValueTypes.Integer64 instead of SetClaim(). identity.AddClaim(new Claim( Claims.AuthenticationTime, DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString(System.Globalization.CultureInfo.InvariantCulture), ClaimValueTypes.Integer64)); // Authentication Method Reference (RFC 8176) identity.SetClaim("amr", "pwd"); if (mfaVerified && !string.IsNullOrEmpty(mfaMethod)) { // RFC 8176 mapping var mfaAmr = mfaMethod switch { "totp" => "otp", "sms" => "sms", "email" => "email", "webauthn" => "hwk", "recovery" => "rc", _ => "mfa" }; identity.AddClaim(new Claim("amr", mfaAmr)); // Standardised "mfa" marker (see RFC 8176 §2) so RPs can check a single claim instead of enumerating values. identity.AddClaim(new Claim("amr", "mfa")); } // OIDC Core §2 — Authentication Context Class Reference. Emit a single acr value // derived from the actual authentication strength: // "0" — no authentication (long-lived session, currently unreachable here), // "1" — single-factor / password-only (default for ROPC + cookie sessions), // "2" — multi-factor verified (mfaVerified=true in SessionProps). // RPs that ask for acr_values via /connect/authorize get this back unconditionally; // enforcement of "this RP REQUIRES acr=2" is the RP's job (compare the claim) — the // OP intentionally does NOT reject below the requested level here, since OIDC §5.5.1.1 // marks acr as a Voluntary Claim by default. The RP can opt into strict matching by // sending an `acr` claim in the `claims` parameter (out of scope; will reject if so). identity.SetClaim(Claims.AuthenticationContextReference, mfaVerified ? "2" : "1"); // OIDC Core §5.5 — the `claims` request parameter. Scopes are a coarse instrument: an RP // that needs one claim (say `name`) would otherwise have to ask for the whole `profile` // scope and receive twelve. The `claims` parameter lets it name exactly what it needs, and // say where it wants it delivered — in the id_token, or from UserInfo. // // So this runs AFTER the scope-derived claims above and only ever ADDS: a claim the RP // named individually is emitted even when its scope was not requested, and a claim that is // already present just gains the extra destination the RP asked for. It never removes a // claim the scopes granted — the two mechanisms are additive, per §5.5. var requestedDestinations = ApplyClaimsRequest(identity, user, oidcProps, claimsRequest); // Claim destinations. // // OIDC Core §5.4: in the authorization-code flow the scope-derived identity claims // (profile / email / phone / address) are delivered from the UserInfo endpoint — NOT in // the id_token. Emitting them in the id_token anyway is what the OIDF conformance suite // flags as "may result in user data being exposed in unintended ways": the id_token is // routinely forwarded to third parties and logged as proof of the authentication event, // so any PII inside it travels further than the RP intended. Access-token destination is // what makes a claim visible at /connect/userinfo, which is exactly where these belong. // // The id_token keeps only what identifies the authentication event itself: sub, auth_time, // acr (plus sid/nonce/at_hash, attached by their own handlers). foreach (var claim in identity.Claims) { var scopeDestinations = claim.Type switch { // Internal bigint user id (stringified). Emitted on BOTH tokens so external // projects can decode the id_token client-side and cross-reference their own user // table by this id. Namespaced with the "redb:" prefix per RFC 7519 §4.3 // private-claim convention; doesn't shadow the public OIDC `sub` GUID. InternalUserIdClaim => new[] { Destinations.AccessToken, Destinations.IdentityToken }, // Identifies the authentication event → belongs in the id_token. Claims.Subject => new[] { Destinations.AccessToken, Destinations.IdentityToken }, Claims.AuthenticationTime or Claims.AuthenticationContextReference => new[] { Destinations.AccessToken, Destinations.IdentityToken }, // Scope-derived user data → UserInfo only (access_token destination). Never the // id_token: the RP asked for "access to the user's email/profile", not for the PII // to be embedded in a token it forwards elsewhere. Claims.Name or Claims.GivenName or Claims.FamilyName or Claims.MiddleName or Claims.Nickname or Claims.PreferredUsername or Claims.Profile or Claims.Picture or Claims.Website or Claims.Gender or Claims.Birthdate or Claims.Zoneinfo or Claims.Locale or Claims.UpdatedAt => new[] { Destinations.AccessToken }, Claims.Email or Claims.EmailVerified => new[] { Destinations.AccessToken }, Claims.PhoneNumber or Claims.PhoneNumberVerified => new[] { Destinations.AccessToken }, Claims.Address => new[] { Destinations.AccessToken }, _ => new[] { Destinations.AccessToken, Destinations.IdentityToken } }; // §5.5 again: an RP that asked for `email` in the id_token gets the IdentityToken // destination added on top of the AccessToken one the `email` scope grants. Union, not // replace — otherwise naming a claim in `claims` would silently revoke the delivery // channel its scope already earned. if (requestedDestinations.TryGetValue(claim.Type, out var extra) && extra.Count > 0) { var union = new HashSet(scopeDestinations, StringComparer.Ordinal); union.UnionWith(extra); claim.SetDestinations(union.ToArray()); } else { claim.SetDestinations(scopeDestinations); } } return new ClaimsPrincipal(identity); } /// /// Emits the claims the RP named in the claims parameter (OIDC Core §5.5) and reports /// the extra destination each one earned. Returns claim-type → destinations to be unioned with /// the scope-derived destinations by the caller. /// /// /// Three rules, all from §5.5.1: /// /// A claim we do not hold a value for is omitted, Essential or not. "essential" /// tells us the RP needs it, not that we can invent it. /// A claim requested with value / values that our value does not /// match is omitted — the RP asked for a specific value; answering with a different one would be /// worse than answering with nothing. /// Requesting a claim never removes anything: we only add. /// /// sub is deliberately not handled here. A claims request that pins sub to a /// value is a statement about which End-User must be signed in, not a claim to emit, and /// §5.5.1 requires the request to fail when the session belongs to somebody else. That check /// belongs at the authorize endpoint, where we can still reject — see /// AttachSessionPrincipalHandler. /// private static Dictionary> ApplyClaimsRequest( ClaimsIdentity identity, IRedbUser user, UserProps? oidcProps, OidcClaimsRequest? claimsRequest) { var destinations = new Dictionary>(StringComparer.Ordinal); if (claimsRequest is null || claimsRequest.IsEmpty) return destinations; var userInfoRequested = new List(); Apply(claimsRequest.IdToken, Destinations.IdentityToken, null); Apply(claimsRequest.UserInfo, Destinations.AccessToken, userInfoRequested); // Tell the userinfo handler which claims were individually requested — see // RequestedUserInfoClaims for why the principal is the only channel available there. if (userInfoRequested.Count > 0) identity.SetClaim(RequestedUserInfoClaims, string.Join(' ', userInfoRequested)); return destinations; void Apply( IReadOnlyDictionary entries, string destination, List? emitted) { foreach (var (type, entry) in entries) { // `sub` is always emitted to both tokens anyway; its `value` constraint is enforced // at authorize, not here. if (type == Claims.Subject) continue; var existing = identity.FindFirst(type)?.Value; var value = existing ?? ResolveClaimValue(type, user, oidcProps); if (!entry.Accepts(value)) continue; if (existing is null) SetTypedClaim(identity, type, value!); if (!destinations.TryGetValue(type, out var set)) destinations[type] = set = new HashSet(StringComparer.Ordinal); set.Add(destination); emitted?.Add(type); } } } /// /// Resolves a claim the scopes did not emit, straight from the user record and the OIDC profile /// extension. Returns null for anything we do not hold — including claims we simply do not /// implement (address is resolved, an arbitrary vendor claim is not), which the caller /// turns into "omit the claim". /// private static string? ResolveClaimValue(string type, IRedbUser user, UserProps? oidcProps) { var value = type switch { Claims.Name => user.Login, Claims.GivenName => oidcProps?.GivenName, Claims.FamilyName => oidcProps?.FamilyName, Claims.MiddleName => oidcProps?.MiddleName, Claims.Nickname => oidcProps?.Nickname, Claims.Profile => oidcProps?.Profile, Claims.Picture => oidcProps?.Picture, Claims.Website => oidcProps?.Website, Claims.Gender => oidcProps?.Gender, Claims.Birthdate => oidcProps?.Birthdate, Claims.Zoneinfo => oidcProps?.ZoneInfo, Claims.Locale => oidcProps?.Locale, Claims.PreferredUsername => oidcProps?.PreferredUsername ?? user.Login, Claims.UpdatedAt => (oidcProps?.UpdatedAt ?? user.DateRegister).ToUnixTimeSeconds() .ToString(System.Globalization.CultureInfo.InvariantCulture), Claims.Email => user.Email, Claims.EmailVerified => (oidcProps?.EmailVerified ?? false) ? "true" : "false", Claims.PhoneNumber => user.Phone, Claims.PhoneNumberVerified => (oidcProps?.PhoneNumberVerified ?? false) ? "true" : "false", Claims.Address => oidcProps?.Address is { } address ? JsonSerializer.Serialize(address, AddressJsonOptions) : null, _ => oidcProps?.CustomClaims is { } custom && custom.TryGetValue(type, out var c) ? c : null }; // A *_verified flag on its own is meaningless — and misleading, since "false" would read as // "we checked and it isn't verified" when the truth is we hold no email/phone at all. if (type == Claims.EmailVerified && string.IsNullOrEmpty(user.Email)) return null; if (type == Claims.PhoneNumberVerified && string.IsNullOrEmpty(user.Phone)) return null; return string.IsNullOrEmpty(value) ? null : value; } /// /// Adds a claim with the JSON type OIDC Core §5.1 requires for it: updated_at is a /// number, the *_verified flags are booleans, everything else a string. Getting this /// wrong is not cosmetic — an RP deserialising "email_verified": "true" into a bool /// fails, and the conformance suite flags it. /// private static void SetTypedClaim(ClaimsIdentity identity, string type, string value) { switch (type) { case Claims.EmailVerified or Claims.PhoneNumberVerified when bool.TryParse(value, out var flag): identity.SetClaim(type, flag); break; case Claims.UpdatedAt when long.TryParse(value, out var epoch): identity.SetClaim(type, epoch); break; // OIDC §5.1.1: a JSON object, and OpenIddict 7 requires the JSON claim value type. case Claims.Address: identity.SetClaim(type, JsonSerializer.Deserialize(value)); break; default: identity.SetClaim(type, value); break; } } } Path: redb-identity/src/redb.Identity.Core/Services/InMemoryEmailNotificationChannel.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/Services/InMemoryEmailNotificationChannel.cs ---- using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace redb.Identity.Core.Services; /// /// N-4 (Session C): test / preview implementation of /// . Captures every dispatched message in an /// in-memory ring (default cap = 256 messages) instead of sending it out. Used in /// integration tests to assert that the right templated e-mail reached the right /// recipient with the right variables. /// /// /// Production hosts MUST replace this with a real SMTP / SendGrid / SES channel. /// Registering this singleton in production silently swallows every notification. /// public sealed class InMemoryEmailNotificationChannel : IEmailNotificationChannel { private readonly IEmailTemplateRegistry _registry; private readonly int _capacity; private readonly ConcurrentQueue _messages = new(); public InMemoryEmailNotificationChannel(IEmailTemplateRegistry registry, int capacity = 256) { _registry = registry ?? throw new ArgumentNullException(nameof(registry)); if (capacity <= 0) throw new ArgumentOutOfRangeException(nameof(capacity)); _capacity = capacity; } /// Snapshot of all messages captured so far, oldest first. public IReadOnlyList Messages => _messages.ToArray(); /// All messages directed at the given recipient (case-insensitive match). public IReadOnlyList ForRecipient(string to) => _messages.Where(m => string.Equals(m.To, to, StringComparison.OrdinalIgnoreCase)).ToArray(); /// Drops all captured messages. public void Clear() { while (_messages.TryDequeue(out _)) { } } public async Task SendTemplateAsync( string to, string templateId, IReadOnlyDictionary vars, CancellationToken ct = default) { if (string.IsNullOrWhiteSpace(to)) throw new ArgumentException("recipient required", nameof(to)); var rendered = await _registry.RenderAsync(templateId, locale: null, vars, ct).ConfigureAwait(false); _messages.Enqueue(new CapturedEmail { To = to, TemplateId = templateId, Subject = rendered.Subject, HtmlBody = rendered.HtmlBody, TextBody = rendered.TextBody, Vars = vars.ToDictionary(kv => kv.Key, kv => kv.Value, StringComparer.Ordinal), SentAt = DateTimeOffset.UtcNow, }); // Cap the ring so misconfigured tests don't leak memory across the whole suite. while (_messages.Count > _capacity && _messages.TryDequeue(out _)) { } } } /// Snapshot of a single e-mail captured by . public sealed class CapturedEmail { public required string To { get; init; } public required string TemplateId { get; init; } public required string Subject { get; init; } public required string HtmlBody { get; init; } public string? TextBody { get; init; } public required Dictionary Vars { get; init; } public DateTimeOffset SentAt { get; init; } }