vars)
{
// Simple {name} replacement — no recursion, no formatting. Sufficient for the
// transactional e-mails we currently produce.
if (vars.Count == 0 || template.IndexOf('{') < 0) return template;
var sb = new StringBuilder(template.Length + 64);
var i = 0;
while (i < template.Length)
{
var open = template.IndexOf('{', i);
if (open < 0) { sb.Append(template, i, template.Length - i); break; }
var close = template.IndexOf('}', open + 1);
if (close < 0) { sb.Append(template, i, template.Length - i); break; }
sb.Append(template, i, open - i);
var key = template.Substring(open + 1, close - open - 1);
if (vars.TryGetValue(key, out var value)) sb.Append(value);
else sb.Append(template, open, close - open + 1);
i = close + 1;
}
return sb.ToString();
}
private sealed record Template(string Subject, string HtmlBody, string? TextBody);
private static readonly Dictionary<(string templateId, string locale), Template> _templates =
new()
{
// ── password-reset / en ──
[(IdentityEmailTemplates.PasswordReset, "en")] = new(
Subject: "Reset your password",
HtmlBody:
""
+ "Hello {userName},
"
+ "We received a request to reset the password for your account. "
+ "Click the link below to set a new password — it expires in {ttlMinutes} minutes "
+ "and can be used only once.
"
+ "Reset password
"
+ "If the button does not work, copy this link into your browser:
"
+ "{resetLink}
"
+ "If you did not request a password reset you can safely ignore this e-mail — "
+ "your password will remain unchanged.
"
+ "redb.Identity
"
+ "",
TextBody:
"Hello {userName},\r\n\r\n"
+ "We received a request to reset the password for your account. "
+ "Open the following link to set a new password (expires in {ttlMinutes} minutes, single-use):\r\n\r\n"
+ "{resetLink}\r\n\r\n"
+ "If you did not request a password reset you can safely ignore this e-mail.\r\n\r\n"
+ "— redb.Identity"),
// ── email-verification / en ──
[(IdentityEmailTemplates.EmailVerification, "en")] = new(
Subject: "Verify your e-mail address",
HtmlBody:
""
+ "Hello {userName},
"
+ "Please confirm that this is your e-mail address by clicking the button below. "
+ "The link expires in {ttlHours} hours and can be used only once.
"
+ "Verify e-mail
"
+ "If the button does not work, copy this link into your browser:
"
+ "{verifyLink}
"
+ "If you did not register or change your e-mail you can safely ignore this message.
"
+ "redb.Identity
"
+ "",
TextBody:
"Hello {userName},\r\n\r\n"
+ "Please confirm your e-mail address by opening the following link "
+ "(expires in {ttlHours} hours, single-use):\r\n\r\n"
+ "{verifyLink}\r\n\r\n"
+ "If you did not register or change your e-mail you can safely ignore this message.\r\n\r\n"
+ "— redb.Identity"),
// ── change-email / en ── (N4-7: confirmation delivered to the NEW address)
[(IdentityEmailTemplates.ChangeEmail, "en")] = new(
Subject: "Confirm your new e-mail address",
HtmlBody:
""
+ "Hello {userName},
"
+ "We received a request to switch the e-mail address on your account from "
+ "{oldEmail} to {newEmail}. "
+ "Click the button below to confirm the change. The link expires in {ttlHours} hours and can be used only once.
"
+ "Confirm new e-mail
"
+ "If the button does not work, copy this link into your browser:
"
+ "{confirmLink}
"
+ "If you did not request this change you can safely ignore this message \u2014 your account e-mail will not be changed.
"
+ "redb.Identity
"
+ "",
TextBody:
"Hello {userName},\r\n\r\n"
+ "We received a request to switch the e-mail address on your account "
+ "from {oldEmail} to {newEmail}. Open the link below to confirm "
+ "(expires in {ttlHours} hours, single-use):\r\n\r\n"
+ "{confirmLink}\r\n\r\n"
+ "If you did not request this change you can safely ignore this message.\r\n\r\n"
+ "— redb.Identity"),
// ── mfa-code / en ── (the one-time code of e-mail MFA: enrollment and sign-in)
[(IdentityEmailTemplates.MfaCode, "en")] = new(
Subject: "Your verification code",
HtmlBody:
""
+ "Your verification code is:
"
+ "{code}
"
+ "It expires in {ttlMinutes} minutes and can be used only once.
"
+ "If you did not ask for a code you can ignore this message.
"
+ "redb.Identity
"
+ "",
TextBody:
"Your verification code is: {code}\r\n\r\n"
+ "It expires in {ttlMinutes} minutes and can be used only once.\r\n\r\n"
+ "If you did not ask for a code you can ignore this message.\r\n\r\n"
+ "— redb.Identity"),
};
}
Path: redb-identity/src/redb.Identity.Core/Services/LoginService.cs
Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.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/LoginService.cs
----
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using redb.Core;
using redb.Core.Exceptions;
using redb.Core.Models.Contracts;
using redb.Core.Models.Entities;
using redb.Core.Models.Users;
using redb.Core.Query;
using redb.Core.Security;
using redb.Identity.Core.Metrics;
using redb.Identity.Core.Models;
namespace redb.Identity.Core.Services;
///
/// Verifies user credentials via external providers (if any) then falls back
/// to the local _users table. Single orchestration point for all
/// authentication: Login page, ROPC grant, Device code verification.
///
public sealed class LoginService
{
private readonly IRedbService _redb;
private readonly ILogger _logger;
private readonly ILogger _securityLogger;
private readonly IExternalUserProvider[] _externalProviders;
private readonly MfaService? _mfaService;
private readonly TimeProvider _timeProvider;
private readonly IPasswordHasher? _passwordHasher;
private readonly IdentityMetrics? _metrics;
private readonly IServiceScopeFactory? _scopeFactory;
private readonly Configuration.PasswordPolicyOptions? _passwordPolicy;
public LoginService(
IRedbService redb,
ILogger logger,
IEnumerable? externalProviders = null,
MfaService? mfaService = null,
TimeProvider? timeProvider = null,
ILoggerFactory? loggerFactory = null,
IPasswordHasher? passwordHasher = null,
IdentityMetrics? metrics = null,
IServiceScopeFactory? scopeFactory = null,
Configuration.PasswordPolicyOptions? passwordPolicy = null)
{
_redb = redb;
_logger = logger;
_scopeFactory = scopeFactory;
_externalProviders = (externalProviders ?? [])
.OrderBy(p => p.Priority)
.ToArray();
_mfaService = mfaService;
_timeProvider = timeProvider ?? TimeProvider.System;
_passwordHasher = passwordHasher;
_metrics = metrics;
_passwordPolicy = passwordPolicy;
// E5: route audit-class signals (denied logins, per-provider deny) to the
// RedbIdentity.Security channel so SIEM/audit sinks can subscribe without
// also ingesting routine operational logs. Fall back to the regular logger
// when no factory is available (tests / non-DI construction).
_securityLogger = loggerFactory is not null
? Security.IdentitySecurityLog.CreateLogger(loggerFactory)
: logger;
}
///
/// Validates username/password and returns the user on success.
/// Tries external providers in priority order, then falls back to local.
///
public async Task AuthenticateAsync(
string username, string password, CancellationToken ct = default)
{
if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
return LoginResult.Failed("Username and password are required.");
// Phase 1: Try external providers in priority order
foreach (var provider in _externalProviders)
{
ExternalAuthResult? extResult;
try
{
extResult = await provider.AuthenticateAsync(username, password, ct).ConfigureAwait(false);
}
catch (Exception ex)
{
_logger.LogWarning(ex, "External provider '{Provider}' threw for user '{Username}', skipping",
provider.ProviderName, username);
continue;
}
if (extResult is null)
continue; // provider doesn't handle this user
if (!extResult.Succeeded)
{
// Provider recognized the user but auth failed — do NOT fall through
_securityLogger.LogWarning("Login denied by '{Provider}' for user '{Username}': {Error}",
provider.ProviderName, username, extResult.ErrorMessage);
return LoginResult.Failed(extResult.ErrorMessage ?? "Authentication failed.");
}
_logger.LogDebug("User '{Username}' authenticated via external provider '{Provider}'",
username, provider.ProviderName);
return await ResolveExternalUser(provider.ProviderName, extResult, username)
.ConfigureAwait(false);
}
// Phase 2: Fall back to local _users password check
return await AuthenticateLocal(username, password).ConfigureAwait(false);
}
private async Task AuthenticateLocal(string username, string password)
{
// C12 / F3: measure verify duration across both success and failure branches —
// ValidateUserAsync wraps the BCrypt/Argon2id verify plus SELECT latency. The
// histogram bucket discriminates `result` success/fail for OTEL tagging.
var sw = System.Diagnostics.Stopwatch.StartNew();
var coreUser = await _redb.UserProvider.ValidateUserAsync(username, password)
.ConfigureAwait(false);
sw.Stop();
_metrics?.PasswordVerifyDuration.Record(
sw.Elapsed.TotalMilliseconds,
new KeyValuePair("result", coreUser is null ? "fail" : "success"));
if (coreUser is null)
{
// C14 / SEC-A20: timing-equivalence. ValidateUserAsync returns null for
// (a) user not found, (b) user disabled, (c) wrong password — but only the
// last path actually invokes the BCrypt verify (~100 ms). The first two paths
// return early, leaking via timing whether a username exists. Run a fake
// BCrypt verify so the wall-clock cost of all three negative branches is
// approximately equivalent. The fake hash is precomputed and the result is
// intentionally discarded.
try { _ = BCrypt.Net.BCrypt.Verify(password ?? "", FakeBcryptHash); } catch { }
_securityLogger.LogWarning("Login denied: user '{Username}' — invalid credentials or not found", username);
return LoginResult.Failed("Invalid credentials.");
}
// C12: upgrade-on-login. If the stored hash is in a legacy format (BCrypt,
// SHA256+salt) or uses weaker Argon2id parameters than the current configuration,
// re-hash the plaintext and persist. Fire-and-forget — a rehash failure must not
// block login (the user is already authenticated).
if (_passwordHasher is not null && !string.IsNullOrEmpty(coreUser.Password)
&& NeedsRehash(_passwordHasher, coreUser.Password))
{
// AWAITED, deliberately — this used to be Task.Run and that was the bug. A detached
// rehash lands about a second after the login that scheduled it (the hash itself costs
// ~250 ms before anything reaches the database), and an admin password reset fits into
// that window comfortably. When the rehash landed last it put the pre-login password
// back over the freshly set one: the account silently reverted to exactly the credential
// the operator had just retired, while their reset had long answered success. Measured
// on a live worker: nine resets out of nine lost when a login preceded them. A guard
// that checks the stored hash before writing does not close this — the expensive hashing
// sits between the check and the write, and the reset lands inside it.
//
// Awaiting removes the detached writer altogether: the login answers only after the
// rehash is on disk, so anything that changes the password afterwards writes last and
// wins, by construction. The cost is one extra hash on the login path — capped to one
// attempt per user per process below, because until the upgrade actually converges
// (see the rehash method's remarks) every local login would pay it.
//
// Through the request-scoped service, not a fresh scope: the fresh scope existed only
// because fire-and-forget outlived the request. Awaited, a second scope means a second
// connection — and on SQLite that second writer promptly hits 'database is locked'
// against the login's own connection. Same connection: no second writer, and inside a
// transacted route the rehash simply joins the route's transaction.
if (RehashAttempted.TryAdd(coreUser.Id, 0))
{
await RehashPasswordIfUnchangedAsync(
_redb, coreUser.Id, password, coreUser.Password, _logger)
.ConfigureAwait(false);
}
}
// Note: ValidateUserAsync already returns null for disabled users — no separate
// branch is needed here, and adding one would re-introduce the enumeration leak
// (different error message for "disabled" vs "wrong password").
var oidcObj = await _redb.Query()
.WhereRedb(o => o.Key == coreUser.Id)
.FirstOrDefaultAsync()
.ConfigureAwait(false);
_logger.LogDebug("User '{Username}' (id={UserId}) authenticated locally",
username, coreUser.Id);
// Check MFA (after password validated, before session creation).
// B9 / BUG-4: single atomic read of MfaProps via LoadMfaStatusAsync (was two
// separate reads — IsMfaEnabledAsync + GetEnabledMethodsAsync — leaving a TOCTOU
// window where MFA could be enabled/disabled between the two calls).
if (_mfaService is not null)
{
var (mfaEnabled, methods) = await _mfaService.LoadMfaStatusAsync(coreUser.Id).ConfigureAwait(false);
if (mfaEnabled && methods.Length > 0)
{
_logger.LogDebug("MFA required for user '{Username}' (id={UserId}), methods={Methods}",
username, coreUser.Id, string.Join(",", methods));
return LoginResult.MfaChallenge(coreUser, methods);
}
}
// H10 — password expiration. Compare against the configured MaxAge if any. Null
// PasswordChangedAt is treated as "not tracked" (legacy users), to avoid forcing
// a password change on every account that pre-dates H10.
var maxAge = _passwordPolicy?.MaxAge ?? TimeSpan.Zero;
if (maxAge > TimeSpan.Zero
&& oidcObj?.Props.PasswordChangedAt is DateTimeOffset changedAt
&& _timeProvider.GetUtcNow() - changedAt > maxAge)
{
_logger.LogDebug(
"Password expired for user '{Username}' (id={UserId}); changedAt={ChangedAt}, maxAge={MaxAge}",
username, coreUser.Id, changedAt, maxAge);
return LoginResult.PasswordExpired(coreUser, oidcObj);
}
return LoginResult.Success(coreUser, oidcObj);
}
///
/// Pre-computed BCrypt hash of an arbitrary unguessable string used solely for
/// timing-equivalence (see C14 / SEC-A20). Cost factor 12 to mirror the production
/// hash work factor used by .
///
private static readonly string FakeBcryptHash =
BCrypt.Net.BCrypt.HashPassword(Guid.NewGuid().ToString("N"), workFactor: 12);
///
/// C12: ask the hasher whether the stored hash should be re-hashed after a successful
/// verify. itself has no NeedsRehash contract, so
/// we duck-type against the concrete hashers supplied by this module. Unknown
/// implementations report "no upgrade needed" (conservative — no spurious rehashes).
///
private static bool NeedsRehash(IPasswordHasher hasher, string storedHash) => hasher switch
{
Security.MultiFormatPasswordHasher mf => mf.NeedsRehash(storedHash),
Security.Argon2idPasswordHasher a => a.NeedsRehash(storedHash),
_ => false,
};
///
/// Users whose rehash was already attempted in this process. The upgrade does not currently
/// converge — the write goes through the core provider's own hasher, and when that is BCrypt the
/// "upgraded" hash is BCrypt again, so stays true forever. Without this
/// cap every local login would pay the extra awaited hash; with it, one per user per process.
/// The convergence itself (writing with this module's Argon2id) needs a way to hand the core a
/// ready-made hash, which is a redb.Core API question — reported, not worked around.
///
private static readonly System.Collections.Concurrent.ConcurrentDictionary RehashAttempted = new();
///
/// C12 upgrade-on-login, second half. Runs on the caller's own — it
/// is awaited from the login path (see the call site for why fire-and-forget was a security bug,
/// not a latency optimisation), so a separate DI scope would only add a second connection, and
/// on SQLite a second writer means 'database is locked' against the login's own.
/// Internal and awaitable so both halves are testable.
///
/// true when the hash was rewritten; false when skipped or failed.
internal static async Task RehashPasswordIfUnchangedAsync(
IRedbService rehashRedb, long userId, string password, string hashAtLogin, ILogger? logger)
{
try
{
var freshUser = await rehashRedb.UserProvider.GetUserByIdAsync(userId).ConfigureAwait(false);
if (freshUser is null) return false;
// Guard: rehash only while the stored hash is still the one this login verified.
// This task lands roughly a second after the login that scheduled it — Argon2id is slow
// by design, Task.Run adds scheduling, the fresh scope adds a connection — and an admin
// reset fits into that window comfortably. Writing without the check would put the
// pre-login password back over the freshly set one: the account silently reverts to
// exactly the credential the operator was trying to retire, while their reset call has
// long since answered success. Observed on a live worker, nine times out of nine.
//
// The check narrows the window to the read-to-write gap below; closing it fully needs a
// compare-and-set on the UPDATE itself (WHERE _password = @expected), which is a
// redb.Core API question, not this method's.
if (!string.Equals(freshUser.Password, hashAtLogin, StringComparison.Ordinal))
{
logger?.LogDebug(
"Password rehash skipped for user id={UserId}: the stored hash changed since login",
userId);
return false;
}
await rehashRedb.UserProvider.SetPasswordAsync(freshUser, password, currentUser: freshUser)
.ConfigureAwait(false);
logger?.LogDebug("Password hash upgraded to current algorithm for user id={UserId}", userId);
return true;
}
catch (Exception ex)
{
logger?.LogWarning(ex, "Password hash auto-rehash failed for user id={UserId}", userId);
return false;
}
}
///
/// Find-or-create local _users + UserProps for an externally authenticated user.
/// On subsequent logins, updates profile from external source.
///
private async Task ResolveExternalUser(
string providerName, ExternalAuthResult ext, string username)
{
return await ResolveExternalUserCore(providerName, ext, username).ConfigureAwait(false);
}
///
/// Resolves a federated user by reverse lookup on the [RedbUnique] LinkKey (one index probe).
/// Used by the federation callback flow where there is no username/password — only
/// an from the external IdP.
/// On first login: auto-provisions a local user (login = email ?? sub).
/// On subsequent logins: syncs profile from external source.
///
public async Task ResolveFederatedUserAsync(
string providerName, ExternalAuthResult ext, CancellationToken ct = default)
{
if (ext is null || !ext.Succeeded || string.IsNullOrEmpty(ext.ExternalId))
return LoginResult.Failed("Invalid external authentication result.");
// H8/V4-UNIQUE: per-link reverse lookup via the [RedbUnique] LinkKey — one probe of
// the unique index. O(1) — supports many federated identities per user.
var linkKey = FederatedIdentityProps.MakeLinkKey(providerName, ext.ExternalId);
var link = await FindLinkAsync(linkKey).ConfigureAwait(false);
long? linkedUserId = link?.key;
if (linkedUserId.HasValue)
{
var coreUser = await _redb.UserProvider.GetUserByIdAsync(linkedUserId.Value)
.ConfigureAwait(false);
if (coreUser is null)
{
_logger.LogWarning(
"Federated link references userId={UserId} but _users row not found (provider={Provider}, sub={Sub})",
linkedUserId.Value, providerName, ext.ExternalId);
return LoginResult.Failed("User account not found.");
}
if (!coreUser.Enabled)
{
_securityLogger.LogWarning("Login denied: federated user '{Username}' is disabled locally", coreUser.Login);
return LoginResult.Failed("User account is not active.");
}
// Authoritative profile sync
await SyncCoreProfile(coreUser, ext).ConfigureAwait(false);
var oidcObj = await _redb.Query()
.WhereRedb(o => o.Key == coreUser.Id)
.FirstOrDefaultAsync()
.ConfigureAwait(false);
if (oidcObj is not null)
{
await SyncOidcProps(oidcObj, providerName, ext, coreUser.Login ?? ext.Email ?? ext.ExternalId)
.ConfigureAwait(false);
}
// H8: upsert per-link record
await UpsertFederatedIdentityLinkAsync(coreUser.Id, providerName, ext, isNewLink: link is null)
.ConfigureAwait(false);
_logger.LogDebug(
"Federated user '{Username}' (id={UserId}) authenticated via '{Provider}'",
coreUser.Login, coreUser.Id, providerName);
return LoginResult.Success(coreUser, oidcObj);
}
// H8 (gap (c)): conflict-on-email — if a local user already exists with this email
// but no federated link, refuse to silently take over the account. Caller
// (FederationCallbackProcessor) translates this into a redirect to the configured
// conflict-resolution page so the user can either log in locally then link, or
// confirm a takeover with proper credentials.
//
// Was previously `GetUserByLoginAsync(ext.Email)` — that only triggered when the
// local user's login literally equalled the external email, but self-register
// forbids '@' in login so the probe was effectively dead code. `GetUserByEmailAsync`
// (added to redb.Core in this batch) does a proper case-insensitive lookup on
// `_users._email`, so the conflict path now fires for genuine email overlap.
if (!string.IsNullOrEmpty(ext.Email))
{
var existingByEmail = await _redb.UserProvider.GetUserByEmailAsync(ext.Email)
.ConfigureAwait(false);
if (existingByEmail is not null)
{
_securityLogger.LogWarning(
"Federated email conflict: provider={Provider} sub={Sub} email={Email} matches existing local user id={UserId}",
providerName, ext.ExternalId, ext.Email, existingByEmail.Id);
return LoginResult.EmailConflict(ext.Email, providerName, ext.ExternalId);
}
}
// New user — auto-provision
var username = ext.Email ?? ext.ExternalId;
return await ResolveExternalUserCore(providerName, ext, username).ConfigureAwait(false);
}
private async Task ResolveExternalUserCore(
string providerName, ExternalAuthResult ext, string username)
{
// Try to find existing user by login (unique in _users)
var coreUser = await _redb.UserProvider.GetUserByLoginAsync(username)
.ConfigureAwait(false);
if (coreUser is null)
{
// First login ever — create local user with random password (external-only)
coreUser = await _redb.UserProvider.CreateUserAsync(new CreateUserRequest
{
Login = username,
Password = Guid.NewGuid().ToString("N") + "Aa1!", // satisfies any complexity rules
Name = ext.DisplayName ?? username,
Email = ext.Email,
Phone = ext.Phone,
Enabled = true,
CodeString = providerName // quick marker on _users level
}).ConfigureAwait(false);
_logger.LogDebug("Created local user '{Username}' (id={UserId}) for external provider '{Provider}'",
username, coreUser.Id, providerName);
}
if (!coreUser.Enabled)
{
_securityLogger.LogWarning("Login denied: external user '{Username}' is disabled locally", username);
return LoginResult.Failed("User account is not active.");
}
// Authoritative sync: always push external profile → _users row
var needsUpdate = false;
var updateReq = new UpdateUserRequest();
if (ext.DisplayName is not null && ext.DisplayName != coreUser.Name)
{
updateReq.Name = ext.DisplayName;
needsUpdate = true;
}
if (ext.Email is not null && ext.Email != coreUser.Email)
{
updateReq.Email = ext.Email;
needsUpdate = true;
}
if (ext.Phone is not null && ext.Phone != coreUser.Phone)
{
updateReq.Phone = ext.Phone;
needsUpdate = true;
}
if (needsUpdate)
{
coreUser = await _redb.UserProvider.UpdateUserAsync(coreUser, updateReq)
.ConfigureAwait(false);
}
// Upsert UserProps with external linking + profile sync
var oidcObj = await _redb.Query()
.WhereRedb(o => o.Key == coreUser.Id)
.FirstOrDefaultAsync()
.ConfigureAwait(false);
if (oidcObj is null)
{
oidcObj = new RedbObject(new UserProps { UserId = coreUser.Id });
oidcObj.name = username;
oidcObj.key = coreUser.Id;
oidcObj.value_guid = Guid.NewGuid();
}
// Always sync external profile on login
oidcObj.Props.ExternalIdentities ??= new Dictionary();
oidcObj.Props.ExternalIdentities[providerName] = new ExternalIdentity
{
Sub = ext.ExternalId,
LinkedAt = _timeProvider.GetUtcNow()
};
// H8: do NOT touch oidcObj.value_string here — it would silently overwrite any
// earlier federated link's reverse-lookup key. Per-link reverse lookup is
// handled by FederatedIdentityProps (UpsertFederatedIdentityLinkAsync below).
if (ext.GivenName is not null) oidcObj.Props.GivenName = ext.GivenName;
if (ext.FamilyName is not null) oidcObj.Props.FamilyName = ext.FamilyName;
if (ext.Email is not null) oidcObj.Props.EmailVerified = true;
if (ext.Phone is not null) oidcObj.Props.PhoneNumberVerified = true;
// Merge additional claims from external provider
if (ext.AdditionalClaims is { Count: > 0 })
{
oidcObj.Props.CustomClaims ??= new Dictionary();
foreach (var (key, value) in ext.AdditionalClaims)
oidcObj.Props.CustomClaims[key] = value;
}
await _redb.SaveAsync(oidcObj).ConfigureAwait(false);
// H8: per-link PROPS record (enables multi-provider linking + reverse lookup)
await UpsertFederatedIdentityLinkAsync(coreUser.Id, providerName, ext, isNewLink: true)
.ConfigureAwait(false);
return LoginResult.Success(coreUser, oidcObj);
}
private async Task SyncCoreProfile(IRedbUser coreUser, ExternalAuthResult ext)
{
var needsUpdate = false;
var updateReq = new UpdateUserRequest();
if (ext.DisplayName is not null && ext.DisplayName != coreUser.Name)
{
updateReq.Name = ext.DisplayName;
needsUpdate = true;
}
if (ext.Email is not null && ext.Email != coreUser.Email)
{
updateReq.Email = ext.Email;
needsUpdate = true;
}
if (ext.Phone is not null && ext.Phone != coreUser.Phone)
{
updateReq.Phone = ext.Phone;
needsUpdate = true;
}
if (needsUpdate)
await _redb.UserProvider.UpdateUserAsync(coreUser, updateReq).ConfigureAwait(false);
}
private async Task SyncOidcProps(
RedbObject oidcObj, string providerName, ExternalAuthResult ext, string username)
{
oidcObj.Props.ExternalIdentities ??= new Dictionary();
oidcObj.Props.ExternalIdentities[providerName] = new ExternalIdentity
{
Sub = ext.ExternalId,
LinkedAt = _timeProvider.GetUtcNow()
};
// H8: do NOT touch oidcObj.value_string — see ResolveExternalUserCore for rationale.
if (ext.GivenName is not null) oidcObj.Props.GivenName = ext.GivenName;
if (ext.FamilyName is not null) oidcObj.Props.FamilyName = ext.FamilyName;
if (ext.Email is not null) oidcObj.Props.EmailVerified = true;
if (ext.Phone is not null) oidcObj.Props.PhoneNumberVerified = true;
if (ext.AdditionalClaims is { Count: > 0 })
{
oidcObj.Props.CustomClaims ??= new Dictionary();
foreach (var (key, value) in ext.AdditionalClaims)
oidcObj.Props.CustomClaims[key] = value;
}
await _redb.SaveAsync(oidcObj).ConfigureAwait(false);
}
// ─────────────────────────────────────────────────────────────────────────
// H8 (DoD §4): per-link FederatedIdentityProps maintenance + public
// self-service link/unlink/list API consumed by MeFederatedIdentitiesProcessor.
// ─────────────────────────────────────────────────────────────────────────
///
/// Upserts a single (user, provider) federated link in the per-link PROPS scheme.
/// Idempotent — safe to call on every successful federated login. The
/// [RedbUnique] makes concurrent
/// inserts of one external identity collide at the DB level on every provider
/// (V4-UNIQUE; before F2 no index actually existed and duplicates were possible);
/// the loser re-reads the winner and runs the same integrity check.
///
private async Task UpsertFederatedIdentityLinkAsync(
long userId, string providerName, ExternalAuthResult ext, bool isNewLink)
{
var linkKey = FederatedIdentityProps.MakeLinkKey(providerName, ext.ExternalId);
var existing = await FindLinkAsync(linkKey).ConfigureAwait(false);
var now = _timeProvider.GetUtcNow();
if (existing is null)
{
var fresh = new RedbObject(new FederatedIdentityProps
{
ProviderId = providerName,
ExternalSub = ext.ExternalId,
LinkKey = linkKey,
LinkedAt = now,
ExternalEmail = ext.Email,
ExternalDisplayName = ext.DisplayName,
LastLoginAt = now,
});
fresh.name = linkKey;
fresh.key = userId;
try
{
await _redb.SaveAsync(fresh).ConfigureAwait(false);
return;
}
catch (RedbUniqueViolationException)
{
// Lost the creation race on the [RedbUnique] LinkKey. Deliberately NOT
// SaveByUniqueAsync: its last-writer-wins would silently re-point a link
// owned by ANOTHER user. Re-read the winner and fall through to the same
// integrity check every non-race path runs.
existing = await FindLinkAsync(linkKey).ConfigureAwait(false);
if (existing is null)
throw; // key vanished between the violation and the re-read; surface it
}
}
if (existing.key != userId)
{
// Hard data integrity: same external sub linked to a different local user.
// Log and refuse rather than silently re-pointing the link.
_securityLogger.LogError(
"FederatedIdentityProps integrity violation: LinkKey={LinkKey} already links to userId={ExistingUserId}, refused re-link to userId={NewUserId}",
linkKey, existing.key, userId);
throw new InvalidOperationException(
$"External identity '{linkKey}' is already linked to a different user.");
}
existing.Props.ExternalEmail = ext.Email;
existing.Props.ExternalDisplayName = ext.DisplayName;
existing.Props.LastLoginAt = now;
await _redb.SaveAsync(existing).ConfigureAwait(false);
}
///
/// The one lookup for a federated link (V4-UNIQUE): a probe of the [RedbUnique]
/// LinkKey index, with a transition fallback to the pre-V4 value_string mirror.
/// The fallback matters: a legacy row the backfill has not repaired yet MUST still
/// resolve — a miss on the login path would auto-provision a SECOND local user for an
/// already-linked external identity. A row found through the fallback is repaired in
/// place. The fallback goes away at teardown.
///
private async Task?> FindLinkAsync(string linkKey)
{
var link = await _redb.GetByUniqueAsync(p => p.LinkKey, linkKey)
.ConfigureAwait(false);
if (link is not null)
return link;
link = await _redb.Query()
.WhereRedb(o => o.ValueString == linkKey)
.FirstOrDefaultAsync()
.ConfigureAwait(false);
if (link is not null && link.Props.LinkKey is null)
{
link.Props.LinkKey = linkKey;
try { await _redb.SaveAsync(link).ConfigureAwait(false); }
catch (RedbUniqueViolationException)
{
// A concurrent repair of the same legacy row won; harmless — re-read it.
return await _redb.GetByUniqueAsync(p => p.LinkKey, linkKey)
.ConfigureAwait(false);
}
}
return link;
}
///
/// H8 (gap (b)): self-service link of a federated identity to an already-authenticated
/// local user. Used by MeFederatedIdentitiesProcessor. Throws when the external
/// identity is already linked to a different user.
///
public async Task LinkFederatedIdentityAsync(
long userId, string providerName, ExternalAuthResult ext, CancellationToken ct = default)
{
await UpsertFederatedIdentityLinkAsync(userId, providerName, ext, isNewLink: true)
.ConfigureAwait(false);
// Mirror to denormalized cache on UserProps
var oidcObj = await _redb.Query()
.WhereRedb(o => o.Key == userId)
.FirstOrDefaultAsync()
.ConfigureAwait(false);
if (oidcObj is null)
{
oidcObj = new RedbObject(new UserProps { UserId = userId });
oidcObj.key = userId;
oidcObj.value_guid = Guid.NewGuid();
}
oidcObj.Props.ExternalIdentities ??= new Dictionary();
oidcObj.Props.ExternalIdentities[providerName] = new ExternalIdentity
{
Sub = ext.ExternalId,
LinkedAt = _timeProvider.GetUtcNow()
};
await _redb.SaveAsync(oidcObj).ConfigureAwait(false);
}
///
/// H8 (gap (b)/(d)): self-service unlink. Returns false when no such link exists.
/// Caller is responsible for the "last credential method" guard (it requires reading
/// ).
///
public async Task UnlinkFederatedIdentityAsync(
long userId, string providerName, CancellationToken ct = default)
{
var links = await _redb.Query()
.WhereRedb(o => o.Key == userId)
.ToListAsync()
.ConfigureAwait(false);
var match = links.FirstOrDefault(o => string.Equals(o.Props.ProviderId, providerName, StringComparison.OrdinalIgnoreCase));
if (match is null) return false;
await _redb.DeleteAsync(match).ConfigureAwait(false);
// Mirror to denormalized cache
var oidcObj = await _redb.Query()
.WhereRedb(o => o.Key == userId)
.FirstOrDefaultAsync()
.ConfigureAwait(false);
if (oidcObj?.Props.ExternalIdentities is { } map && map.Remove(providerName))
await _redb.SaveAsync(oidcObj).ConfigureAwait(false);
return true;
}
///
/// H8 (gap (b)): list all federated links for a user. Returned in stable order
/// (provider id ascending) for deterministic UI display.
///
public async Task> ListFederatedIdentitiesAsync(
long userId, CancellationToken ct = default)
{
var links = await _redb.Query()
.WhereRedb(o => o.Key == userId)
.ToListAsync()
.ConfigureAwait(false);
return links
.OrderBy(o => o.Props.ProviderId, StringComparer.OrdinalIgnoreCase)
.Select(o => new FederatedIdentityLink(
o.Props.ProviderId,
o.Props.ExternalSub,
o.Props.ExternalEmail,
o.Props.ExternalDisplayName,
o.Props.LinkedAt,
o.Props.LastLoginAt))
.ToList();
}
}
///
/// H8: read-model record for a single federated identity link, returned to callers of
/// .
///
public sealed record FederatedIdentityLink(
string ProviderId,
string ExternalSub,
string? ExternalEmail,
string? ExternalDisplayName,
DateTimeOffset LinkedAt,
DateTimeOffset? LastLoginAt);
///
/// Result of a login attempt.
///
public sealed class LoginResult
{
public bool Succeeded { get; private init; }
public long UserId { get; private init; }
public string? Username { get; private init; }
/// Core _users row.
public IRedbUser? User { get; private init; }
/// OIDC extension props (may be null if profile was never saved).
public UserProps? OidcProps { get; private init; }
///
/// Public-facing GUID identity used for the OIDC sub claim. Pulled from
/// RedbObject<UserProps>.value_guid at login time so the same user has
/// the same GUID across all sessions and tokens. when the
/// login attempt failed (no user resolved) or for legacy data without value_guid.
///
public Guid SubjectGuid { get; private init; }
public string? ErrorMessage { get; private init; }
/// True when password is valid but MFA verification is still required.
public bool MfaRequired { get; private init; }
/// Available MFA methods when is true.
public string[]? MfaMethods { get; private init; }
///
/// H10 — password verified, but
/// elapsed since
/// . Caller (interactive login or password
/// grant) must redirect the user to the password-change flow before issuing tokens.
///
public bool MustChangePassword { get; private init; }
///
/// H8 (gap (c)): set when the federated callback discovered an existing local user
/// with the same email but no explicit federated link. Caller must NOT mint tokens —
/// it should redirect the user to a "log in locally and link your social account" page.
///
public bool IsEmailConflict { get; private init; }
/// H8 (gap (c)): conflicting email reported by the external IdP.
public string? ConflictEmail { get; private init; }
/// H8 (gap (c)): provider id that initiated the conflicting callback.
public string? ConflictProviderId { get; private init; }
/// H8 (gap (c)): external subject from the IdP for the pending link.
public string? ConflictExternalSub { get; private init; }
public static LoginResult Success(IRedbUser user, RedbObject? oidcObj) => new()
{
Succeeded = true,
UserId = user.Id,
Username = user.Login,
User = user,
OidcProps = oidcObj?.Props,
SubjectGuid = oidcObj?.value_guid ?? Guid.Empty
};
public static LoginResult Failed(string message) => new()
{
Succeeded = false,
ErrorMessage = message
};
/// Password verified, but MFA is required before session creation.
public static LoginResult MfaChallenge(IRedbUser user, string[] methods) => new()
{
Succeeded = false,
MfaRequired = true,
UserId = user.Id,
Username = user.Login,
User = user,
MfaMethods = methods
};
///
/// H10 — password verified but expired. Caller must steer the user into the
/// password-change flow (interactive: redirect; ROPC: reject with
/// password_expired).
///
public static LoginResult PasswordExpired(IRedbUser user, RedbObject? oidcObj) => new()
{
Succeeded = false,
MustChangePassword = true,
UserId = user.Id,
Username = user.Login,
User = user,
OidcProps = oidcObj?.Props,
SubjectGuid = oidcObj?.value_guid ?? Guid.Empty,
ErrorMessage = "Password expired."
};
///
/// H8 (gap (c)): federated callback discovered an existing local user with this
/// email but no link from this provider yet. Caller redirects to the conflict
/// resolution page so the user can sign in locally and explicitly add the link.
///
public static LoginResult EmailConflict(string email, string providerId, string externalSub) => new()
{
Succeeded = false,
IsEmailConflict = true,
ConflictEmail = email,
ConflictProviderId = providerId,
ConflictExternalSub = externalSub,
ErrorMessage = "Federated email already registered locally."
};
}
Path: redb-identity/src/redb.Identity.Core/Services/LogoutConfirmationProtector.cs
Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.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/LogoutConfirmationProtector.cs
----
using System.Security.Cryptography;
using System.Text.Json;
using Microsoft.AspNetCore.DataProtection;
using redb.Identity.Contracts.Common;
namespace redb.Identity.Core.Services;
///
/// The proof that the End-User, not a page they happened to visit, asked to sign out.
///
/// /connect/logout is the OIDC end_session_endpoint and works on the browser's own session
/// cookie, which a cross-site top-level navigation carries (SameSite=Lax): a link on any page could
/// end the visitor's OP session. A relying party proves its intent with a valid id_token_hint whose
/// sub is the session's user; a request without one gets a confirmation page instead, and the page's
/// form carries a state issued here. The state is bound to the user and the session it was shown for and
/// lives five minutes; a foreign page cannot read it (same-origin policy) nor forge it (DataProtection), so
/// presenting it is the confirmation. Same shape as Duende's logout prompt and Keycloak's confirmation
/// without id_token_hint.
///
///
public sealed class LogoutConfirmationProtector
{
private const string Purpose = "redb.identity.logout-confirmation";
private static readonly TimeSpan MaxAge = TimeSpan.FromMinutes(5);
private readonly IDataProtector _protector;
private readonly TimeProvider _timeProvider;
public LogoutConfirmationProtector(IDataProtectionProvider provider, TimeProvider? timeProvider = null)
{
ArgumentNullException.ThrowIfNull(provider);
_protector = provider.CreateProtector(Purpose);
_timeProvider = timeProvider ?? TimeProvider.System;
}
/// Issues a state for the confirmation page shown to in session .
public string Issue(long userId, long sessionId)
{
var state = new State(userId, sessionId, _timeProvider.GetUtcNow());
return Convert.ToBase64String(_protector.Protect(JsonSerializer.SerializeToUtf8Bytes(state)));
}
///
/// True when is a state this server issued for exactly this user and
/// session, and it is not older than five minutes. Anything else — absent, altered, foreign, another
/// session's, expired — is not a confirmation, and the caller shows the page again.
///
public bool Accepts(string? protectedState, long userId, long sessionId)
{
if (string.IsNullOrEmpty(protectedState)) return false;
State? state;
try
{
var payload = _protector.Unprotect(Base64Canonical.Decode(protectedState));
state = JsonSerializer.Deserialize(payload);
}
catch (Exception ex) when (ex is CryptographicException or FormatException or JsonException)
{
// Not something this server issued: a tampered envelope, foreign bytes or a malformed value.
// That is the answer, not a fault.
return false;
}
return state is not null
&& state.UserId == userId
&& state.SessionId == sessionId
&& _timeProvider.GetUtcNow() - state.IssuedAt <= MaxAge;
}
private sealed record State(long UserId, long SessionId, DateTimeOffset IssuedAt);
}
Path: redb-identity/src/redb.Identity.Core/Services/LogoutTokenBuilder.cs
Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.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/LogoutTokenBuilder.cs
----
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using OpenIddict.Server;
namespace redb.Identity.Core.Services;
///
/// Builds OIDC Back-Channel Logout 1.0 logout_token JWTs (RFC: OIDC Back-Channel
/// Logout 1.0 §2.4). Uses the same signing keys as the issuer's id_token, so any RP that
/// already validates id_tokens from this issuer can validate the logout_token unchanged.
///
public sealed class LogoutTokenBuilder
{
/// Mandatory event identifier per OIDC Back-Channel Logout 1.0 §2.4.
public const string LogoutEventIdentifier = "http://schemas.openid.net/event/backchannel-logout";
private static readonly JwtSecurityTokenHandler _tokenHandler = new() { MapInboundClaims = false };
private readonly IOptionsMonitor _serverOptions;
private readonly TimeProvider _timeProvider;
private readonly ILogger? _logger;
public LogoutTokenBuilder(
IOptionsMonitor serverOptions,
TimeProvider? timeProvider = null,
ILogger? logger = null)
{
ArgumentNullException.ThrowIfNull(serverOptions);
_serverOptions = serverOptions;
_timeProvider = timeProvider ?? TimeProvider.System;
_logger = logger;
}
///
/// Returns true when at least one signing credential is configured. Without one
/// we cannot produce a logout_token and backchannel logout must be a no-op.
///
public bool CanIssue => _serverOptions.CurrentValue.SigningCredentials.Count > 0;
///
/// Builds a signed logout_token for a given RP.
///
/// RP's client_id (becomes the aud claim).
/// End-user identifier (becomes the sub claim).
///
/// Optional session id. When not null/empty, an sid claim is added so the RP can
/// terminate only the matching session instead of all sessions for the user.
///
/// A signed JWS string, or null when no signing key is configured.
public string? Build(string audience, string subject, string? sessionId = null)
{
ArgumentException.ThrowIfNullOrEmpty(audience);
ArgumentException.ThrowIfNullOrEmpty(subject);
var opts = _serverOptions.CurrentValue;
var signing = opts.SigningCredentials.FirstOrDefault();
if (signing is null)
{
_logger?.LogWarning("No signing credential configured — cannot issue logout_token for {Audience}.", audience);
return null;
}
var issuer = opts.Issuer?.ToString().TrimEnd('/') ?? string.Empty;
var now = _timeProvider.GetUtcNow().UtcDateTime;
// OIDC Back-Channel Logout 1.0 §2.4:
// - MUST contain: iss, aud, iat, jti, events
// - MUST contain at least one of: sub, sid
// - MUST NOT contain: nonce
var claims = new List
{
new(JwtRegisteredClaimNames.Sub, subject),
new(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString("N")),
// events is a JSON object; we serialize it as a literal so JwtPayload doesn't escape it.
new("events", $"{{\"{LogoutEventIdentifier}\":{{}}}}", JsonClaimValueTypes.Json),
};
if (!string.IsNullOrEmpty(sessionId))
claims.Add(new Claim("sid", sessionId));
var token = new JwtSecurityToken(
issuer: string.IsNullOrEmpty(issuer) ? null : issuer,
audience: audience,
claims: claims,
notBefore: null,
expires: null, // logout_token has no exp per spec; iat + clock skew is what RP checks
signingCredentials: signing);
// iat is set automatically by JwtSecurityToken when not in claims; force it to our TimeProvider.
token.Payload[JwtRegisteredClaimNames.Iat] = new DateTimeOffset(now).ToUnixTimeSeconds();
return _tokenHandler.WriteToken(token);
}
}
Path: redb-identity/src/redb.Identity.Core/Services/MemoryDpopReplayStore.cs
Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.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/MemoryDpopReplayStore.cs
----
using System.Collections.Concurrent;
namespace redb.Identity.Core.Services;
///
/// In-process implementation of . Backed by a
/// with TTL-based pruning.
/// Single-instance only — see .
///
public sealed class MemoryDpopReplayStore : IDpopReplayStore, IDisposable
{
private readonly TimeProvider _timeProvider;
private readonly ConcurrentDictionary _seen = new(StringComparer.Ordinal);
private readonly Timer? _sweeper;
public MemoryDpopReplayStore(TimeProvider? timeProvider = null, TimeSpan? sweepInterval = null)
{
_timeProvider = timeProvider ?? TimeProvider.System;
var interval = sweepInterval ?? TimeSpan.FromMinutes(5);
if (interval > TimeSpan.Zero && interval != Timeout.InfiniteTimeSpan)
{
_sweeper = new Timer(_ => Prune(), null, interval, interval);
}
}
///
public Task TryReserveAsync(string jkt, string jti, TimeSpan ttl, CancellationToken ct = default)
{
if (string.IsNullOrEmpty(jkt) || string.IsNullOrEmpty(jti))
return Task.FromResult(false);
var nowTicks = _timeProvider.GetUtcNow().UtcTicks;
var expiryTicks = nowTicks + Math.Max(ttl.Ticks, TimeSpan.TicksPerSecond);
var key = jkt + "|" + jti;
if (_seen.TryAdd(key, expiryTicks))
return Task.FromResult(true);
// Existing entry: only allow re-reservation when it has expired.
if (_seen.TryGetValue(key, out var existing) && existing <= nowTicks
&& _seen.TryUpdate(key, expiryTicks, existing))
{
return Task.FromResult(true);
}
return Task.FromResult(false);
}
private void Prune()
{
var nowTicks = _timeProvider.GetUtcNow().UtcTicks;
foreach (var kv in _seen)
{
if (kv.Value <= nowTicks)
_seen.TryRemove(kv.Key, out _);
}
}
public void Dispose() => _sweeper?.Dispose();
}
Path: redb-identity/src/redb.Identity.Core/Services/MfaSecretProtector.cs
Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.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/MfaSecretProtector.cs
----
using Microsoft.AspNetCore.DataProtection;
using Microsoft.Extensions.Logging;
namespace redb.Identity.Core.Services;
///
/// Encrypts/decrypts TOTP secrets at rest using ASP.NET DataProtection.
/// Unlike , no TTL — secrets live until user disables MFA.
///
public sealed class MfaSecretProtector
{
private const string Purpose = "redb.identity.mfa-secret";
private readonly IDataProtector _protector;
private readonly ILogger? _logger;
public MfaSecretProtector(IDataProtectionProvider provider, ILogger? logger = null)
{
ArgumentNullException.ThrowIfNull(provider);
_protector = provider.CreateProtector(Purpose);
_logger = logger;
}
/// Encrypts a plaintext secret (e.g. base32-encoded TOTP key).
public string Protect(string plainSecret)
{
ArgumentNullException.ThrowIfNull(plainSecret);
var bytes = System.Text.Encoding.UTF8.GetBytes(plainSecret);
var encrypted = _protector.Protect(bytes);
return Convert.ToBase64String(encrypted);
}
/// Decrypts a protected secret. Returns null if decryption fails (tampered/rotated 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)
{
// Log every decrypt failure: each one is either a security signal (tampered ciphertext)
// or an operational alert (DataProtection key rotation/loss). Returning null keeps the
// public contract intact for callers (treat as "secret unavailable").
_logger?.LogWarning(ex,
"MfaSecretProtector: failed to decrypt protected MFA secret (length={Length}).",
protectedSecret.Length);
return null;
}
}
}
Path: redb-identity/src/redb.Identity.Core/Services/MfaService.WebAuthn.cs
Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.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/MfaService.WebAuthn.cs
----
using System.Text.Json;
using Fido2NetLib;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using redb.Core;
using redb.Core.Models.Entities;
using redb.Identity.Core.Configuration;
using redb.Identity.Core.Exceptions;
using redb.Identity.Core.Mfa;
using redb.Identity.Core.Models;
namespace redb.Identity.Core.Services;
///
/// MFA-3: WebAuthn (FIDO2) orchestration on top of .
///
/// Unlike OTP-based methods, WebAuthn does not flow through 's
/// InitiateSetupAsync / ConfirmAndApplyAsync / VerifyAsync path
/// (the shapes are mismatched: WebAuthn has no shared secret, no destination, no 6-digit
/// code). Instead, this partial exposes four bespoke methods (Begin/Complete \u00d7 Register/Assert)
/// that the dedicated processors call. The orchestrator integrates the same lockout,
/// recovery-code, audit and challenge-replay primitives used by the OTP path.
///
///
public sealed partial class MfaService
{
private static readonly JsonSerializerOptions s_webAuthnJson = new()
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull,
};
///
/// MFA-3: starts a WebAuthn registration ceremony. Returns
/// (forwarded as JSON to the browser) bundled with
/// an opaque setupToken that round-trips the challenge + serialized options.
///
/// No DB write occurs until succeeds.
///
///
public async Task<(CredentialCreateOptions Options, string SetupToken)> BeginWebAuthnRegistrationAsync(
long userId,
string username,
string? displayName,
CancellationToken ct = default)
{
var webAuthn = ResolveWebAuthnMethod();
var existing = await LoadMfaPropsAsync(userId, ct).ConfigureAwait(false);
var creds = existing?.Props?.WebAuthnCredentials;
// Per-user UV ratchet: if the user already has a UV credential, force UV on the new
// credential too \u2014 we never let a user weaken their own posture by adding a
// non-UV authenticator after a UV one.
bool enforceUv = creds is { Count: > 0 } && creds.Values.Any(c => c.UserVerified);
var options = webAuthn.BeginRegistration(
userId,
username,
string.IsNullOrEmpty(displayName) ? username : displayName,
creds,
enforceUv);
var token = _setupTokenProtector.Protect(new MfaSetupTokenPayload
{
UserId = userId,
MethodId = "webauthn",
IssuedAt = _timeProvider.GetUtcNow(),
Jti = Guid.NewGuid(),
WebAuthnChallenge = options.Challenge,
WebAuthnOptionsJson = JsonSerializer.Serialize(options, s_webAuthnJson),
});
_logger.LogDebug("WebAuthn registration begin: userId={UserId}", userId);
return (options, token);
}
///
/// MFA-3: completes a WebAuthn registration ceremony. Verifies the attestation, runs the
/// AAGUID/UV gates inside , persists the credential, and
/// (if this is the user's first MFA method) issues fresh recovery codes returned to the
/// caller exactly once.
///
/// Caller must hold a transaction with a row-lock on the user's MFA props row when
/// calling this method \u2014 the processor wraps it in BeginTransactionAsync +
/// LockForUpdateAsync just like .
///
///
///
/// Tuple of (success, recoveryCodes-or-null, credentialKey). recoveryCodes is non-null
/// only on the very first MFA method enrolled by this user. credentialKey is the
/// dictionary key used to look up / rename / delete this credential later.
///
public async Task<(bool Success, string[]? RecoveryCodes, string? CredentialKey, string? ErrorCode)>
CompleteWebAuthnRegistrationAsync(
long userId,
AuthenticatorAttestationRawResponse attestationResponse,
string setupToken,
string? credentialDisplayName,
CancellationToken ct = default)
{
var payload = _setupTokenProtector.Unprotect(setupToken);
if (payload is null
|| payload.UserId != userId
|| !string.Equals(payload.MethodId, "webauthn", StringComparison.OrdinalIgnoreCase)
|| payload.WebAuthnChallenge is null
|| string.IsNullOrEmpty(payload.WebAuthnOptionsJson))
{
_logger.LogWarning("WebAuthn register confirm rejected: invalid setup token (userId={UserId})", userId);
return (false, null, null, "invalid_setup_token");
}
var originalOptions = JsonSerializer.Deserialize(
payload.WebAuthnOptionsJson, s_webAuthnJson);
if (originalOptions is null)
return (false, null, null, "invalid_setup_token");
// Single-use: reject second confirm with the same setup token.
var consumeResult = await ResolveChallengeStore().ConsumeAsync(
payload.WebAuthnChallenge, userId, "register",
TimeSpan.FromMinutes(10), ct).ConfigureAwait(false);
if (consumeResult == WebAuthnConsumeResult.Replay)
{
_securityLogger.LogWarning("WebAuthn register replay detected: userId={UserId}", userId);
return (false, null, null, "replay_detected");
}
WebAuthnCredential newCred;
try
{
newCred = await ResolveWebAuthnMethod().CompleteRegistrationAsync(
attestationResponse, originalOptions, userId, ct).ConfigureAwait(false);
}
catch (WebAuthnException ex)
{
_logger.LogWarning("WebAuthn register failed: userId={UserId}, code={Code}", userId, ex.ErrorCode);
return (false, null, null, ex.ErrorCode);
}
if (!string.IsNullOrWhiteSpace(credentialDisplayName))
newCred.DisplayName = credentialDisplayName!.Trim();
var key = EncodeCredentialKey(newCred.CredentialId);
var obj = await LoadOrCreateMfaPropsAsync(userId, ct).ConfigureAwait(false);
obj.Props.WebAuthnCredentials ??= new Dictionary(StringComparer.Ordinal);
// Defence-in-depth: same credential id MUST NOT be added twice. Fido2NetLib's
// ExcludeCredentials covers the well-behaved-browser case; this guards against a
// malicious/buggy client that strips ExcludeCredentials and submits a duplicate.
if (obj.Props.WebAuthnCredentials.ContainsKey(key))
{
return (false, null, null, "credential_already_registered");
}
obj.Props.WebAuthnCredentials[key] = newCred;
var wasAlreadyEnabled = obj.Props.Enabled;
obj.Props.Enabled = true;
if (string.IsNullOrEmpty(obj.Props.DefaultMethod))
obj.Props.DefaultMethod = "webauthn";
string[]? plainCodes = null;
if (!wasAlreadyEnabled || obj.Props.RecoveryCodes is null or { Count: 0 })
{
var (codes, hashedCodes) = GenerateRecoveryCodes();
obj.Props.RecoveryCodes = hashedCodes;
obj.Props.RecoveryCodesPepperId = _pepperProvider.PepperId;
plainCodes = codes;
}
obj.Props.FailedAttempts = 0;
obj.Props.LockedUntil = null;
await _redb.SaveAsync(obj).ConfigureAwait(false);
_logger.LogDebug("WebAuthn credential registered: userId={UserId}, key={Key}", userId, key);
return (true, plainCodes, key, null);
}
///
/// MFA-3: starts a WebAuthn assertion ceremony for an authenticated user (login flow or
/// step-up). Returns + an encrypted mfa_state that
/// the caller forwards to the client.
///
///
/// (options, mfaStateToken). When the user has zero registered credentials the returned
/// options' AllowedCredentials list is empty \u2014 the browser will surface a graceful
/// no-credential error, identical to a non-existent userId, preserving username privacy.
///
public async Task<(AssertionOptions Options, string MfaStateToken)?> BeginWebAuthnAssertionAsync(
long userId,
string? username,
string? returnUrl,
CancellationToken ct = default)
{
var obj = await LoadMfaPropsAsync(userId, ct).ConfigureAwait(false);
var creds = obj?.Props?.WebAuthnCredentials;
if (creds is null || creds.Count == 0)
return null;
var options = ResolveWebAuthnMethod().BeginAssertion(creds);
var state = new MfaState
{
Jti = Guid.NewGuid(),
UserId = userId,
Username = username,
Methods = ["webauthn"],
ReturnUrl = returnUrl,
IssuedAt = _timeProvider.GetUtcNow(),
WebAuthnChallenge = options.Challenge,
WebAuthnFlow = "assert",
WebAuthnOptionsJson = JsonSerializer.Serialize(options, s_webAuthnJson),
};
var token = _stateProtector.Protect(state);
return (options, token);
}
///
/// MFA-3: completes a WebAuthn assertion. Caller must hold a transaction with a row-lock
/// on the MFA props (same pattern as ) so concurrent assertions
/// cannot lose each other's updates.
///
///
/// (success, errorCode). success == true means the credential mutations were
/// persisted; errorCode on failure is one of invalid_state /
/// flow_mismatch / replay_detected / locked_out /
/// uv_downgrade / sign_counter_rollback / credential_not_found /
/// verification_failed.
///
public async Task<(bool Success, string? ErrorCode)> CompleteWebAuthnAssertionAsync(
long userId,
AuthenticatorAssertionRawResponse assertionResponse,
MfaState state,
CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(state);
if (state.UserId != userId)
{
_securityLogger.LogWarning("WebAuthn assert rejected (state.UserId mismatch): caller={UserId}", userId);
return (false, "invalid_state");
}
if (!string.Equals(state.WebAuthnFlow, "assert", StringComparison.Ordinal)
|| state.WebAuthnChallenge is null
|| string.IsNullOrEmpty(state.WebAuthnOptionsJson))
{
return (false, "flow_mismatch");
}
var originalOptions = JsonSerializer.Deserialize(
state.WebAuthnOptionsJson, s_webAuthnJson);
if (originalOptions is null)
return (false, "invalid_state");
// Single-use challenge \u2014 reject replays even within the state token's TTL.
var ttl = TimeSpan.FromSeconds(Math.Max(60, ResolveWebAuthnOptions().ChallengeTtlSeconds));
var consumeResult = await ResolveChallengeStore().ConsumeAsync(
state.WebAuthnChallenge, userId, "assert", ttl, ct).ConfigureAwait(false);
if (consumeResult == WebAuthnConsumeResult.Replay)
{
_securityLogger.LogWarning("WebAuthn assert replay detected: userId={UserId}", userId);
return (false, "replay_detected");
}
var obj = await LoadMfaPropsAsync(userId, ct).ConfigureAwait(false);
if (obj?.Props is null)
return (false, "credential_not_found");
var props = obj.Props;
if (IsLockedOut(props))
{
_securityLogger.LogWarning("WebAuthn assert rejected (locked out): userId={UserId}", userId);
return (false, "locked_out");
}
if (props.WebAuthnCredentials is null || props.WebAuthnCredentials.Count == 0)
return (false, "credential_not_found");
WebAuthnCredential? mutated;
try
{
mutated = await ResolveWebAuthnMethod().CompleteAssertionAsync(
assertionResponse, originalOptions, props.WebAuthnCredentials, userId, ct).ConfigureAwait(false);
}
catch (WebAuthnException ex)
{
// Counter rollback / UV downgrade / credential_not_found are *typed* failures;
// surface them but still treat as a failed verify for lockout accounting.
BumpFailedAttempts(props);
await _redb.SaveAsync(obj).ConfigureAwait(false);
return (false, ex.ErrorCode);
}
if (mutated is null)
{
BumpFailedAttempts(props);
await _redb.SaveAsync(obj).ConfigureAwait(false);
return (false, "verification_failed");
}
props.FailedAttempts = 0;
props.LockedUntil = null;
props.LastVerifiedAt = _timeProvider.GetUtcNow();
await _redb.SaveAsync(obj).ConfigureAwait(false);
return (true, null);
}
///
/// MFA-3: lists registered WebAuthn credentials for the given user.
///
public async Task> ListWebAuthnCredentialsAsync(
long userId, CancellationToken ct = default)
{
var obj = await LoadMfaPropsAsync(userId, ct).ConfigureAwait(false);
var creds = obj?.Props?.WebAuthnCredentials;
if (creds is null || creds.Count == 0)
return Array.Empty();
return creds.Select(kv => new WebAuthnCredentialSummary(
kv.Key,
kv.Value.DisplayName,
kv.Value.Aaguid,
kv.Value.RegisteredAt,
kv.Value.LastUsedAt,
kv.Value.UserVerified,
kv.Value.BackupEligible,
kv.Value.BackupState
)).ToList();
}
///
/// MFA-3: renames a single credential (the friendly display label).
///
public async Task RenameWebAuthnCredentialAsync(
long userId, string credentialKey, string? newDisplayName, CancellationToken ct = default)
{
var obj = await LoadMfaPropsAsync(userId, ct).ConfigureAwait(false);
if (obj?.Props?.WebAuthnCredentials is null) return false;
if (!obj.Props.WebAuthnCredentials.TryGetValue(credentialKey, out var cred)) return false;
cred.DisplayName = string.IsNullOrWhiteSpace(newDisplayName) ? null : newDisplayName!.Trim();
await _redb.SaveAsync(obj).ConfigureAwait(false);
return true;
}
///
/// MFA-3: deletes one credential. If this was the last credential and no other MFA method
/// is enabled, the WebAuthn-method subsystem is silently disabled (but Enabled flag is left
/// untouched if e.g. TOTP is still configured).
///
public async Task DeleteWebAuthnCredentialAsync(
long userId, string credentialKey, CancellationToken ct = default)
{
var obj = await LoadMfaPropsAsync(userId, ct).ConfigureAwait(false);
if (obj?.Props?.WebAuthnCredentials is null) return false;
if (!obj.Props.WebAuthnCredentials.Remove(credentialKey)) return false;
if (obj.Props.WebAuthnCredentials.Count == 0)
{
obj.Props.WebAuthnCredentials = null;
// Defer to existing CollectEnabledMethods semantics: Enabled stays true if any other
// method is confirmed; otherwise drop it.
if (CollectEnabledMethods(obj.Props).Length == 0)
{
obj.Props.Enabled = false;
if (string.Equals(obj.Props.DefaultMethod, "webauthn", StringComparison.OrdinalIgnoreCase))
obj.Props.DefaultMethod = null;
}
}
await _redb.SaveAsync(obj).ConfigureAwait(false);
return true;
}
// ── helpers ──
///
/// Encodes a raw credential id as a stable dictionary key (base64url, no padding) suitable
/// for use both as the JSON property name and the URL-path segment in REST endpoints.
///
internal static string EncodeCredentialKey(byte[] rawId)
{
return Convert.ToBase64String(rawId)
.TrimEnd('=')
.Replace('+', '-')
.Replace('/', '_');
}
private void BumpFailedAttempts(MfaProps props)
{
props.FailedAttempts++;
if (props.FailedAttempts >= _maxFailedAttempts)
{
props.LockedUntil = _timeProvider.GetUtcNow() + _lockoutDuration;
_securityLogger.LogWarning(
"MFA lockout activated via WebAuthn: attempts={Attempts}", props.FailedAttempts);
}
}
private IWebAuthnMfaMethod ResolveWebAuthnMethod()
{
if (_methods.TryGetValue("webauthn", out var m) && m is IWebAuthnMfaMethod web)
return web;
throw new InvalidOperationException(
"WebAuthn is not enabled. Set RedbIdentityOptions.WebAuthn.Enabled = true and ensure IFido2 is registered.");
}
///
/// MFA-3: lazy-resolved dependency. We deliberately
/// avoid making it a constructor parameter so that the OTP-only configuration of the
/// service does not have to register a no-op stub when WebAuthn is disabled.
///
private IWebAuthnChallengeStore ResolveChallengeStore()
=> _webAuthnChallengeStore
?? throw new InvalidOperationException(
"IWebAuthnChallengeStore is not registered. Enable RedbIdentityOptions.WebAuthn to wire it up.");
private IdentityWebAuthnOptions ResolveWebAuthnOptions()
=> _webAuthnOptions
?? throw new InvalidOperationException(
"IdentityWebAuthnOptions is not registered. Enable RedbIdentityOptions.WebAuthn to wire it up.");
// Cached-via-DI references injected by the partial constructor extension below.
private IWebAuthnChallengeStore? _webAuthnChallengeStore;
private IdentityWebAuthnOptions? _webAuthnOptions;
///
/// Property setter for DI activation \u2014 called from RedbIdentityServiceExtensions
/// when WebAuthn is enabled. Kept off the primary constructor signature so existing
/// MfaService construction sites (and hundreds of unit tests) do not need new arguments.
///
public void AttachWebAuthn(IWebAuthnChallengeStore challengeStore, IdentityWebAuthnOptions options)
{
_webAuthnChallengeStore = challengeStore;
_webAuthnOptions = options;
}
}
/// MFA-3: client-facing summary of a registered WebAuthn credential.
public sealed record WebAuthnCredentialSummary(
string Key,
string? DisplayName,
string? Aaguid,
DateTimeOffset RegisteredAt,
DateTimeOffset? LastUsedAt,
bool UserVerified,
bool BackupEligible,
bool BackupState);
Path: redb-identity/src/redb.Identity.Core/Services/MfaService.cs
Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.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/MfaService.cs
----
using System.Security.Cryptography;
using System.Text;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using redb.Core;
using redb.Core.Models.Entities;
using redb.Identity.Core.Configuration;
using redb.Identity.Core.Exceptions;
using redb.Identity.Core.Mfa;
using redb.Identity.Core.Models;
namespace redb.Identity.Core.Services;
///
/// Orchestrates MFA operations: delegates to implementations,
/// manages PROPS persistence, lockout, recovery codes, and OTP challenge dispatch.
///
public sealed partial class MfaService
{
private readonly IRedbService _redb;
private readonly IReadOnlyDictionary _methods;
private readonly IReadOnlyDictionary _channels;
private readonly MfaStateProtector _stateProtector;
private readonly MfaSetupTokenProtector _setupTokenProtector;
private readonly RedbIdentityOptions _options;
private readonly ILogger _logger;
private readonly ILogger _securityLogger;
private readonly RecoveryCodePepperProvider _pepperProvider;
private readonly TimeProvider _timeProvider;
private readonly IServerSideOtpStore? _otpStore;
private readonly int _maxFailedAttempts = 5;
private readonly TimeSpan _lockoutDuration = TimeSpan.FromMinutes(15);
private readonly int _recoveryCodeCount = 10;
/// Cap on RecentOtpTimestamps list size to bound storage (B6 sliding window).
private const int RecentOtpTimestampsCap = 50;
/// Sliding-window length for OTP rate limiting (B6).
private static readonly TimeSpan OtpRateLimitWindow = TimeSpan.FromHours(1);
/// How long an e-mail or SMS one-time code stays valid.
private static readonly TimeSpan OtpLifetime = TimeSpan.FromMinutes(5);
public MfaService(
IRedbService redb,
IEnumerable methods,
IEnumerable channels,
MfaStateProtector stateProtector,
MfaSetupTokenProtector setupTokenProtector,
IOptions options,
RecoveryCodePepperProvider pepperProvider,
ILogger logger,
TimeProvider? timeProvider = null,
ILoggerFactory? loggerFactory = null,
IServerSideOtpStore? otpStore = null,
IEmailNotificationChannel? emailNotificationChannel = null)
{
_redb = redb;
_methods = methods.ToDictionary(m => m.MethodId, StringComparer.OrdinalIgnoreCase);
var channelMap = channels.ToDictionary(c => c.ChannelId, StringComparer.OrdinalIgnoreCase);
// E-mail OTP goes out through the host's e-mail channel (SMTP when Smtp.Enabled is on), unless the host
// registered an IMfaDeliveryChannel of its own for "email".
if (emailNotificationChannel is not null && !channelMap.ContainsKey("email"))
channelMap["email"] = new EmailMfaDeliveryChannel(emailNotificationChannel, OtpLifetime);
_channels = channelMap;
_stateProtector = stateProtector;
_setupTokenProtector = setupTokenProtector;
_options = options.Value;
_pepperProvider = pepperProvider;
_logger = logger;
_timeProvider = timeProvider ?? TimeProvider.System;
_otpStore = otpStore;
// E5: security-channel for lockouts, rejected-verify, rate-limits.
_securityLogger = loggerFactory is not null
? Security.IdentitySecurityLog.CreateLogger(loggerFactory)
: logger;
}
/// Whether the user has at least one confirmed MFA method.
public async Task IsMfaEnabledAsync(long userId, CancellationToken ct = default)
{
var obj = await LoadMfaPropsAsync(userId, ct).ConfigureAwait(false);
if (obj?.Props is not { Enabled: true } props) return false;
return props.TotpConfirmed || props.SmsConfirmed || props.EmailConfirmed;
}
/// Returns the list of confirmed MFA method IDs for the user.
public async Task GetEnabledMethodsAsync(long userId, CancellationToken ct = default)
{
var obj = await LoadMfaPropsAsync(userId, ct).ConfigureAwait(false);
if (obj?.Props is not { Enabled: true } props)
return [];
return CollectEnabledMethods(props);
}
///
/// Atomic accessor (B9 / BUG-4): returns both the enabled flag and the confirmed
/// method list from a single MfaProps read, eliminating the TOCTOU window
/// between the prior +
/// pair (each of which fetched the props independently).
///
public async Task<(bool Enabled, string[] Methods)> LoadMfaStatusAsync(long userId, CancellationToken ct = default)
{
var obj = await LoadMfaPropsAsync(userId, ct).ConfigureAwait(false);
if (obj?.Props is not { Enabled: true } props)
return (false, Array.Empty());
var methods = CollectEnabledMethods(props);
// Enabled is true ONLY if at least one method is confirmed — matches the
// semantics of IsMfaEnabledAsync (which checks TotpConfirmed||Sms||Email).
return (methods.Length > 0, methods);
}
private static string[] CollectEnabledMethods(MfaProps props)
{
var result = new List(3);
if (props.TotpConfirmed) result.Add("totp");
if (props.SmsConfirmed && !string.IsNullOrEmpty(props.SmsPhone)) result.Add("sms");
if (props.EmailConfirmed && !string.IsNullOrEmpty(props.OtpEmail)) result.Add("email");
return result.ToArray();
}
///
/// Initiates MFA setup for a method. Returns setup data (QR URI, masked destination, etc.)
/// AND an opaque, encrypted setup token that the client must present back to
/// . Does NOT mutate or save anything
/// to the database — the candidate secret/destination lives only in the setup token until
/// confirm. This eliminates the "two parallel setups race-overwrite the secret" bug (B5).
///
/// E-mail: the one-time code goes to the candidate address now, and the result carries mfa_state, which
/// confirm takes together with the code and the setup token. The only database write is the OTP rate-limit
/// counter on the user's MFA record (created disabled if the user has none yet) and the server-side OTP.
/// SMS is not changed: its setup sends nothing.
///
///
/// Phone/email for SMS/Email; ignored by TOTP.
public async Task SetupAsync(long userId, string methodId, string username, string? destination = null, CancellationToken ct = default)
{
var method = GetMethod(methodId);
var initiation = await method.InitiateSetupAsync(username, destination, ct).ConfigureAwait(false);
// If initiation reported an error (e.g. invalid phone) — return the client payload as-is,
// do not issue a setup token and do not touch the database.
if (initiation.ClientResult.Extra is not null
&& initiation.ClientResult.Extra.ContainsKey("error"))
{
return initiation.ClientResult;
}
var setupJti = Guid.NewGuid();
var clientResult = initiation.ClientResult;
if (string.Equals(method.MethodId, "email", StringComparison.OrdinalIgnoreCase))
{
var (protectedState, error) = await SendEnrollmentCodeAsync(
userId, username, method.MethodId, initiation.Destination!, setupJti, ct).ConfigureAwait(false);
if (error is not null)
return new MfaSetupResult { MethodId = method.MethodId, Extra = error };
var extra = new Dictionary(clientResult.Extra ?? new Dictionary())
{
["mfa_state"] = protectedState!
};
clientResult = clientResult with { Extra = extra };
}
var token = _setupTokenProtector.Protect(new MfaSetupTokenPayload
{
UserId = userId,
MethodId = methodId,
EncryptedSecret = initiation.EncryptedSecret,
Destination = initiation.Destination,
IssuedAt = _timeProvider.GetUtcNow(),
Jti = setupJti
});
_logger.LogDebug("MFA setup token issued: userId={UserId}, method={Method}", userId, methodId);
return clientResult with { SetupToken = token };
}
///
/// Sends the one-time code of an e-mail enrollment to the candidate and returns
/// the protected bound to , or the error the setup answers with
/// (error = description, error_code = OAuth-style code). Rate-limited like a sign-in challenge.
///
private async Task<(string? ProtectedState, Dictionary? Error)> SendEnrollmentCodeAsync(
long userId, string username, string methodId, string destination, Guid setupJti, CancellationToken ct)
{
static Dictionary Fail(string code, string description) =>
new() { ["error"] = description, ["error_code"] = code };
if (!_channels.TryGetValue(methodId, out var channel) || _otpStore is null)
return (null, Fail("no_channel", "No delivery channel is configured for this method"));
var obj = await LoadOrCreateMfaPropsAsync(userId, ct).ConfigureAwait(false);
var retryAfter = CheckOtpRateLimit(obj.Props);
if (retryAfter > 0)
{
_securityLogger.LogWarning("MFA enrollment code rate-limited: userId={UserId}, retryAfter={RetryAfter}s", userId, retryAfter);
return (null, Fail("rate_limited", $"Too many codes requested; retry after {retryAfter} seconds"));
}
// The slot is taken before delivery, success or failure alike (same rule as sign-in challenges).
UpdateOtpRateLimitCounters(obj.Props);
await _redb.SaveAsync(obj).ConfigureAwait(false);
var masked = EmailMfaMethod.MaskEmail(destination);
var issued = await _otpStore.IssueAsync(userId, methodId, masked, OtpLifetime, ct).ConfigureAwait(false);
try
{
await channel.SendCodeAsync(destination, issued.PlaintextCode, ct).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
_logger.LogError(ex, "MFA enrollment code delivery failed: userId={UserId}, channel={Channel}", userId, methodId);
return (null, Fail("delivery_failed", "The verification code could not be delivered"));
}
var state = new MfaState
{
Jti = Guid.NewGuid(),
UserId = userId,
Username = username,
OtpJti = issued.Jti,
OtpDestination = masked,
OtpMethod = methodId,
OtpExpiresAt = issued.ExpiresAt,
SetupJti = setupJti,
};
_logger.LogDebug("MFA enrollment code sent: userId={UserId}, method={Method}", userId, methodId);
return (_stateProtector.Protect(state), null);
}
///
/// Confirms MFA setup by verifying the first code against the candidate secret/destination
/// carried inside . The setup token is the opaque string returned
/// by . Returns recovery codes (plain text, shown once) on success or
/// null if the token is invalid/expired or the code does not match.
///
/// Decrypted MFA state for SMS/Email confirmation; null for TOTP.
public async Task ConfirmSetupAsync(long userId, string methodId, string code, string setupToken, MfaState? state = null, CancellationToken ct = default)
{
var swTotal = System.Diagnostics.Stopwatch.StartNew();
// B7: do NOT throw on unknown methodId — that would distinguish "method exists" from
// "token mismatch" to a probing attacker. Treat unknown methods as a generic failure,
// identical to invalid token / userId mismatch / wrong code.
if (!_methods.TryGetValue(methodId, out var method))
{
_logger.LogWarning("MFA setup confirm rejected: unknown method (userId={UserId}, method={Method})", userId, methodId);
return null;
}
var payload = _setupTokenProtector.Unprotect(setupToken);
if (payload is null)
{
_logger.LogWarning("MFA setup confirm rejected: invalid or expired setup token (userId={UserId})", userId);
return null;
}
// Bind: token must match caller userId AND method.
if (payload.UserId != userId || !string.Equals(payload.MethodId, methodId, StringComparison.OrdinalIgnoreCase))
{
_logger.LogWarning(
"MFA setup confirm rejected: token/caller mismatch (userId={UserId}, tokenUserId={TokenUserId}, method={Method}, tokenMethod={TokenMethod})",
userId, payload.UserId, methodId, payload.MethodId);
return null;
}
// E-mail: the code must be the one sent for THIS setup token (to the candidate address), not a sign-in
// code sent to the confirmed one. SMS keeps its rule unchanged.
if (string.Equals(methodId, "email", StringComparison.OrdinalIgnoreCase)
&& (state?.SetupJti is not { } stateSetupJti || stateSetupJti != payload.Jti))
{
_logger.LogWarning("MFA setup confirm rejected: the code was not sent for this setup token (userId={UserId}, method={Method})",
userId, methodId);
return null;
}
var initiation = new MfaSetupInitiation
{
MethodId = payload.MethodId,
EncryptedSecret = payload.EncryptedSecret,
Destination = payload.Destination,
ClientResult = new MfaSetupResult { MethodId = payload.MethodId }
};
var swLoad = System.Diagnostics.Stopwatch.StartNew();
var obj = await LoadOrCreateMfaPropsAsync(userId, ct).ConfigureAwait(false);
swLoad.Stop();
var swVerify = System.Diagnostics.Stopwatch.StartNew();
if (!await method.ConfirmAndApplyAsync(obj.Props, initiation, code, state, ct).ConfigureAwait(false))
return null;
swVerify.Stop();
var wasAlreadyEnabled = obj.Props.Enabled;
obj.Props.Enabled = true;
if (string.IsNullOrEmpty(obj.Props.DefaultMethod))
obj.Props.DefaultMethod = methodId;
string[] plainCodes;
var swHash = System.Diagnostics.Stopwatch.StartNew();
if (!wasAlreadyEnabled || obj.Props.RecoveryCodes is null or { Count: 0 })
{
var (codes, hashedCodes) = GenerateRecoveryCodes();
obj.Props.RecoveryCodes = hashedCodes;
obj.Props.RecoveryCodesPepperId = _pepperProvider.PepperId;
plainCodes = codes;
}
else
{
// Adding a 2nd method — keep existing recovery codes; client should call regenerate to get new ones if desired.
plainCodes = [];
}
swHash.Stop();
obj.Props.FailedAttempts = 0;
obj.Props.LockedUntil = null;
var swSave = System.Diagnostics.Stopwatch.StartNew();
await _redb.SaveAsync(obj).ConfigureAwait(false);
swSave.Stop();
swTotal.Stop();
_logger.LogDebug(
"MFA_CONFIRM_TIMING load={LoadMs}ms verify={VerifyMs}ms hashCodes={HashMs}ms save={SaveMs}ms total={TotalMs}ms userId={UserId} method={Method} freshCodes={FreshCodes}",
swLoad.ElapsedMilliseconds, swVerify.ElapsedMilliseconds, swHash.ElapsedMilliseconds,
swSave.ElapsedMilliseconds, swTotal.ElapsedMilliseconds,
userId, methodId, plainCodes.Length);
_logger.LogDebug("MFA setup confirmed: userId={UserId}, method={Method}", userId, methodId);
return plainCodes;
}
///
/// Verifies an MFA code during login. Enforces lockout after too many failures.
///
/// Decrypted MFA state for SMS/Email; null for TOTP.
public async Task VerifyAsync(long userId, string methodId, string code, MfaState? state = null, CancellationToken ct = default)
{
// Cross-check: caller must pass userId that matches the encrypted state.
// Defence-in-depth against caller bugs that mix up identities between login and verify.
if (state is not null && state.UserId != userId)
{
_securityLogger.LogWarning("MFA verify rejected (state.UserId != userId): caller={UserId}, state={StateUserId}", userId, state.UserId);
return false;
}
var method = GetMethod(methodId);
var obj = await LoadMfaPropsAsync(userId, ct).ConfigureAwait(false);
if (obj is null)
return false;
var props = obj.Props;
// Check lockout (with clock skew tolerance — B9 / BUG-5).
if (IsLockedOut(props))
{
_securityLogger.LogWarning("MFA verify rejected (locked out): userId={UserId}", userId);
return false;
}
if (await method.VerifyAsync(props, code, state, ct).ConfigureAwait(false))
{
props.FailedAttempts = 0;
props.LockedUntil = null;
props.LastVerifiedAt = _timeProvider.GetUtcNow();
await _redb.SaveAsync(obj).ConfigureAwait(false);
return true;
}
// Failed attempt
props.FailedAttempts++;
if (props.FailedAttempts >= _maxFailedAttempts)
{
props.LockedUntil = _timeProvider.GetUtcNow() + _lockoutDuration;
_securityLogger.LogWarning("MFA lockout activated: userId={UserId}, attempts={Attempts}", userId, props.FailedAttempts);
}
await _redb.SaveAsync(obj).ConfigureAwait(false);
return false;
}
///
/// Verifies a one-time recovery code. The code is consumed (removed) on success.
/// Failed attempts increment and trigger lockout,
/// matching the protection given to TOTP/SMS/Email.
///
public async Task VerifyRecoveryCodeAsync(long userId, string code, CancellationToken ct = default)
{
var obj = await LoadMfaPropsAsync(userId, ct).ConfigureAwait(false);
if (obj is null)
return false;
var props = obj.Props;
// Honour lockout — recovery codes are not a bypass for brute-force protection.
if (IsLockedOut(props))
{
_securityLogger.LogWarning("MFA recovery rejected (locked out): userId={UserId}", userId);
return false;
}
if (props.RecoveryCodes is { Count: > 0 })
{
// Constant-time scan over all unconsumed codes.
// Iterate the full list even after a match to avoid leaking match-position via timing.
var matchIndex = -1;
bool needsRehash = false;
var peppers = _pepperProvider.PeppersFor(props.RecoveryCodesPepperId);
if (peppers.Count == 0)
_securityLogger.LogWarning(
"MFA recovery codes were hashed with pepper {PepperId}, which is no longer configured.",
props.RecoveryCodesPepperId);
for (int i = 0; i < props.RecoveryCodes.Count; i++)
{
var stored = props.RecoveryCodes[i];
bool isMatch = VerifyRecoveryCodeHash(stored, code, peppers, out var legacy);
if (isMatch && matchIndex < 0)
{
matchIndex = i;
needsRehash = legacy;
}
}
if (matchIndex >= 0)
{
props.RecoveryCodes.RemoveAt(matchIndex);
if (needsRehash)
{
_logger.LogDebug(
"MFA recovery code consumed in legacy SHA-256 format (no rehash on used code): userId={UserId}",
userId);
}
props.FailedAttempts = 0;
props.LockedUntil = null;
props.LastVerifiedAt = _timeProvider.GetUtcNow();
await _redb.SaveAsync(obj).ConfigureAwait(false);
_logger.LogDebug("MFA recovery code used: userId={UserId}, remaining={Remaining}", userId, props.RecoveryCodes.Count);
return true;
}
}
// Wrong code — count it the same way as a failed TOTP attempt.
props.FailedAttempts++;
if (props.FailedAttempts >= _maxFailedAttempts)
{
props.LockedUntil = _timeProvider.GetUtcNow() + _lockoutDuration;
_securityLogger.LogWarning("MFA lockout activated via recovery: userId={UserId}, attempts={Attempts}", userId, props.FailedAttempts);
}
await _redb.SaveAsync(obj).ConfigureAwait(false);
return false;
}
/// Disables a specific MFA method for the user.
public async Task DisableAsync(long userId, string methodId, CancellationToken ct = default)
{
var obj = await LoadMfaPropsAsync(userId, ct).ConfigureAwait(false);
if (obj is null)
return;
switch (methodId.ToLowerInvariant())
{
case "totp":
obj.Props.TotpSecret = null;
obj.Props.TotpConfirmed = false;
break;
case "sms":
obj.Props.SmsPhone = null;
obj.Props.SmsConfirmed = false;
break;
case "email":
obj.Props.OtpEmail = null;
obj.Props.EmailConfirmed = false;
break;
}
// If no methods remain confirmed — disable MFA entirely.
var anyConfirmed = obj.Props.TotpConfirmed || obj.Props.SmsConfirmed || obj.Props.EmailConfirmed;
if (!anyConfirmed)
{
obj.Props.Enabled = false;
obj.Props.DefaultMethod = null;
// B9 / BUG-8: archive the recovery hashes instead of nulling them out, so an
// admin can audit «which codes were active when MFA was disabled?». The archived
// hashes are NEVER consulted by VerifyRecoveryCodeAsync (see ArchivedRecoveryCodes
// doc) so this does not weaken the revocation guarantee.
ArchiveRecoveryCodes(obj.Props, reason: "disable");
obj.Props.RecoveryCodes = null;
obj.Props.RecoveryCodesPepperId = null;
}
else if (string.Equals(obj.Props.DefaultMethod, methodId, StringComparison.OrdinalIgnoreCase))
{
// Pick a new default — prefer TOTP > SMS > Email
obj.Props.DefaultMethod = obj.Props.TotpConfirmed ? "totp"
: obj.Props.SmsConfirmed ? "sms"
: "email";
}
obj.Props.FailedAttempts = 0;
obj.Props.LockedUntil = null;
await _redb.SaveAsync(obj).ConfigureAwait(false);
_logger.LogDebug("MFA disabled: userId={UserId}, method={Method}", userId, methodId);
}
/// Returns MFA status for the user: enabled, methods, recovery codes remaining.
public async Task GetStatusAsync(long userId, CancellationToken ct = default)
{
var obj = await LoadMfaPropsAsync(userId, ct).ConfigureAwait(false);
if (obj?.Props is not { } props)
return new MfaStatusResult { Enabled = false, Methods = [], RecoveryCodesRemaining = 0 };
var methods = new List();
if (props.TotpConfirmed) methods.Add("totp");
if (props.SmsConfirmed && !string.IsNullOrEmpty(props.SmsPhone)) methods.Add("sms");
if (props.EmailConfirmed && !string.IsNullOrEmpty(props.OtpEmail)) methods.Add("email");
return new MfaStatusResult
{
Enabled = props.Enabled,
Methods = methods.ToArray(),
RecoveryCodesRemaining = props.RecoveryCodes?.Count ?? 0
};
}
/// Regenerates recovery codes. Old codes are invalidated.
public async Task RegenerateRecoveryCodesAsync(long userId, CancellationToken ct = default)
{
var obj = await LoadMfaPropsAsync(userId, ct).ConfigureAwait(false);
if (obj?.Props is not { Enabled: true })
return null;
var (plainCodes, hashedCodes) = GenerateRecoveryCodes();
// B9 / BUG-8: archive the previous batch before overwriting.
ArchiveRecoveryCodes(obj.Props, reason: "regenerate");
obj.Props.RecoveryCodes = hashedCodes;
obj.Props.RecoveryCodesPepperId = _pepperProvider.PepperId;
await _redb.SaveAsync(obj).ConfigureAwait(false);
_logger.LogDebug("MFA recovery codes regenerated: userId={UserId}", userId);
return plainCodes;
}
/// Encrypts MFA state for the challenge flow (password verified → awaiting MFA code).
public string ProtectState(MfaState state) => _stateProtector.Protect(state);
/// Decrypts and validates MFA state. Returns null if invalid/expired.
public MfaState? UnprotectState(string protectedState) => _stateProtector.Unprotect(protectedState);
///
/// Generates a fresh OTP code for SMS/Email, dispatches it via the matching delivery channel,
/// updates rate-limit counters, and returns a new encrypted MFA state with the code embedded.
///
public async Task CreateChallengeAsync(
long userId, string username, string methodId, string? returnUrl, CancellationToken ct = default)
=> await CreateChallengeAsync(userId, username, methodId, returnUrl, knownMethods: null, ct).ConfigureAwait(false);
///
/// Overload that lets callers reuse the methods array from the original MFA state, avoiding
/// an extra DB roundtrip when the list has not changed.
///
public async Task CreateChallengeAsync(
long userId, string username, string methodId, string? returnUrl,
string[]? knownMethods, CancellationToken ct = default)
{
if (methodId != "sms" && methodId != "email")
return MfaChallengeResult.Failed("method_not_challengeable");
var obj = await LoadMfaPropsAsync(userId, ct).ConfigureAwait(false);
if (obj?.Props is not { Enabled: true } props)
return MfaChallengeResult.Failed("mfa_not_enabled");
// Determine destination
string? destination = methodId == "sms" ? props.SmsPhone : props.OtpEmail;
var confirmed = methodId == "sms" ? props.SmsConfirmed : props.EmailConfirmed;
if (string.IsNullOrEmpty(destination) || !confirmed)
return MfaChallengeResult.Failed("method_not_configured");
// Channel must be registered (host app must wire up SMS/Email senders)
if (!_channels.TryGetValue(methodId, out var channel))
return MfaChallengeResult.Failed("no_channel");
// Rate limit check
var rateLimit = CheckOtpRateLimit(props);
if (rateLimit > 0)
{
_securityLogger.LogWarning("MFA challenge rate-limited: userId={UserId}, retryAfter={RetryAfter}s", userId, rateLimit);
return MfaChallengeResult.Failed("rate_limited", rateLimit);
}
// Reserve the rate-limit slot BEFORE attempting delivery — otherwise an attacker could
// spam SMS/email indefinitely as long as the upstream provider keeps returning errors.
// The slot is consumed on delivery attempt, success or failure alike.
UpdateOtpRateLimitCounters(props);
await _redb.SaveAsync(obj).ConfigureAwait(false);
var masked = methodId == "sms" ? SmsMfaMethod.MaskPhone(destination) : EmailMfaMethod.MaskEmail(destination);
// B3: server-side OTP store. The plaintext code lives only between issue & delivery;
// the state blob carries just a `jti` reference, so the code never appears in URLs,
// Referer headers, HTTP access logs or the encrypted state cookie content.
Guid jti;
string code;
DateTimeOffset expiresAt;
if (_otpStore is not null)
{
var ttl = TimeSpan.FromMinutes(5);
var issued = await _otpStore.IssueAsync(userId, methodId, masked, ttl, ct).ConfigureAwait(false);
jti = issued.Jti;
code = issued.PlaintextCode;
expiresAt = issued.ExpiresAt;
}
else
{
// Fallback for legacy tests that don't register IServerSideOtpStore — still OK because
// the per-method verify path checks state.OtpMethod+state.OtpJti first; legacy path
// uses Jti as a dummy handle and VerifyAndConsume is bypassed.
jti = Guid.NewGuid();
code = GenerateOtpCode();
expiresAt = _timeProvider.GetUtcNow() + TimeSpan.FromMinutes(5);
}
try
{
await channel.SendCodeAsync(destination, code, ct).ConfigureAwait(false);
}
catch (MfaDeliveryException ex)
{
_logger.LogError(ex, "MFA delivery failed: userId={UserId}, channel={Channel}", userId, methodId);
return MfaChallengeResult.Failed("delivery_failed");
}
catch (Exception ex)
{
_logger.LogError(ex, "MFA delivery exception: userId={UserId}, channel={Channel}", userId, methodId);
return MfaChallengeResult.Failed("delivery_failed");
}
// Reuse knownMethods if provided (saves a DB roundtrip when called from MfaChallengeProcessor
// where the original state already carries the method list).
var methods = knownMethods ?? CollectEnabledMethods(props);
var newState = new MfaState
{
Jti = Guid.NewGuid(),
UserId = userId,
Username = username,
Methods = methods,
ReturnUrl = returnUrl,
OtpJti = jti,
OtpDestination = masked,
OtpMethod = methodId,
OtpExpiresAt = expiresAt,
};
var protectedState = _stateProtector.Protect(newState);
_logger.LogDebug("MFA challenge sent: userId={UserId}, method={Method}", userId, methodId);
return MfaChallengeResult.Ok(methodId, protectedState, masked);
}
/// Returns the registered by id (public for processors).
public IMfaMethod GetRegisteredMethod(string methodId) => GetMethod(methodId);
/// Loads MFA props for a user (public so processors can read state for verify).
public async Task LoadPropsAsync(long userId, CancellationToken ct = default)
{
var obj = await LoadMfaPropsAsync(userId, ct).ConfigureAwait(false);
return obj?.Props;
}
// --- Private helpers ---
private IMfaMethod GetMethod(string methodId)
{
if (_methods.TryGetValue(methodId, out var method))
return method;
throw new ArgumentException($"Unknown MFA method: {methodId}", nameof(methodId));
}
private async Task?> LoadMfaPropsAsync(long userId, CancellationToken _)
{
return await _redb.Query()
.WhereRedb(o => o.Key == userId)
.FirstOrDefaultAsync().ConfigureAwait(false);
}
///
/// Returns the redb-object id of the MFA props row for , or 0 if none.
/// Used by callers (e.g. ) to acquire a row-level
/// SELECT ... FOR UPDATE lock via before invoking
/// — serializes concurrent verify attempts and prevents lost-update on
/// / .
///
internal async Task GetMfaObjectIdAsync(long userId, CancellationToken _)
{
return await _redb.Query()
.WhereRedb(o => o.Key == userId)
.Select(o => o.id)
.FirstOrDefaultAsync().ConfigureAwait(false);
}
private async Task> LoadOrCreateMfaPropsAsync(long userId, CancellationToken ct)
{
var obj = await LoadMfaPropsAsync(userId, ct).ConfigureAwait(false);
if (obj is not null)
return obj;
obj = new RedbObject(new MfaProps { UserId = userId });
obj.key = userId;
return obj;
}
private (string[] plain, List hashed) GenerateRecoveryCodes()
{
// Alphabet without ambiguous chars (0/O, 1/I/l)
const string alphabet = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
var plain = new string[_recoveryCodeCount];
var hashed = new string[_recoveryCodeCount];
// Generate plaintext codes serially — UnbiasedRandom uses RandomNumberGenerator.Fill
// on a stackalloc'd byte, which is cheap; the dominant cost is PBKDF2 below.
for (int i = 0; i < _recoveryCodeCount; i++)
plain[i] = GenerateSingleCode(alphabet);
// PBKDF2 is CPU-bound per code (~80–100ms each at production iteration counts).
// 10 codes × 90ms ≈ 900ms serially. Parallel.For distributes across cores; each
// HashCode invocation is independent (its own salt + buffers), so no synchronisation
// is required. Plain[] / hashed[] are written to disjoint indices.
Parallel.For(0, _recoveryCodeCount, i =>
{
hashed[i] = HashCode(plain[i]);
});
return (plain, hashed.ToList());
}
///
/// B9 / BUG-5 helper. Returns whether the user is currently inside the lockout window,
/// applying to bias the comparison
/// toward «still locked» when clocks may be slightly out of sync.
///
private bool IsLockedOut(MfaProps props)
{
if (!props.LockedUntil.HasValue) return false;
var now = _timeProvider.GetUtcNow();
return now < props.LockedUntil.Value + _options.MfaLockoutClockSkew;
}
///
/// B9 / BUG-8 helper. Moves the current into
/// with a timestamp + reason. Caller is
/// responsible for clearing RecoveryCodes afterwards.
///
private void ArchiveRecoveryCodes(MfaProps props, string reason)
{
if (props.RecoveryCodes is not { Count: > 0 } codes) return;
props.ArchivedRecoveryCodes ??= new List();
props.ArchivedRecoveryCodes.Add(new MfaArchivedRecoveryCodeBatch
{
ArchivedAt = _timeProvider.GetUtcNow(),
Reason = reason,
HashedCodes = new List(codes)
});
}
private static string GenerateSingleCode(string alphabet)
{
// Format: XXXX-XXXX (8 chars + dash)
// Use rejection sampling to avoid modulo bias (alphabet.Length=31, 256%31≠0)
var sb = new StringBuilder(9);
for (int i = 0; i < 8; i++)
{
if (i == 4) sb.Append('-');
sb.Append(alphabet[UnbiasedRandom(alphabet.Length)]);
}
return sb.ToString();
}
private static int UnbiasedRandom(int range)
{
// Rejection sampling: discard values >= largest multiple of range that fits in a byte
int limit = 256 - (256 % range);
Span buf = stackalloc byte[1];
int value;
do
{
RandomNumberGenerator.Fill(buf);
value = buf[0];
} while (value >= limit);
return value % range;
}
private string HashCode(string code)
{
// PBKDF2-HMAC-SHA256(password = normalized_code || pepper, salt = per-code random 16B,
// iterations = configured work-factor, length = 32B). Format string embeds iteration count
// so future work-factor increases verify side-by-side.
var normalized = NormalizeRecoveryCode(code);
var salt = RandomNumberGenerator.GetBytes(16);
var iterations = _options.RecoveryCodePbkdf2Iterations;
var hash = Pbkdf2Hash(normalized, salt, iterations, _pepperProvider.Pepper);
return string.Concat(
"pbkdf2$",
iterations.ToString(System.Globalization.CultureInfo.InvariantCulture),
"$",
Convert.ToBase64String(salt),
"$",
Convert.ToBase64String(hash));
}
///
/// Returns true if matches the stored hash.
/// Sets = true when the stored hash is the pre-B4 SHA-256 hex
/// representation (so the caller can log a migration event). Always uses constant-time
/// comparison on the byte representation. A PBKDF2 hash is checked with each of
/// (the set's own pepper, or for a set without a pepper id the current
/// one and then the previous ones); none matches when the list is empty.
///
private bool VerifyRecoveryCodeHash(string stored, string presentedCode, IReadOnlyList peppers, out bool legacyFormat)
{
legacyFormat = false;
var normalized = NormalizeRecoveryCode(presentedCode);
if (stored.StartsWith("pbkdf2$", StringComparison.Ordinal))
{
var parts = stored.Split('$');
if (parts.Length != 4) return false;
if (!int.TryParse(parts[1], System.Globalization.NumberStyles.Integer,
System.Globalization.CultureInfo.InvariantCulture, out var iterations) || iterations <= 0)
return false;
byte[] salt, expected;
try
{
salt = Convert.FromBase64String(parts[2]);
expected = Convert.FromBase64String(parts[3]);
}
catch (FormatException) { return false; }
var match = false;
foreach (var pepper in peppers)
match |= CryptographicOperations.FixedTimeEquals(Pbkdf2Hash(normalized, salt, iterations, pepper, expected.Length), expected);
return match;
}
// Legacy format: hex-encoded SHA-256 of the normalized code (no salt, no pepper).
legacyFormat = true;
var legacyExpected = SHA256.HashData(Encoding.UTF8.GetBytes(normalized));
// Compare to the stored hex string after decoding back to bytes (constant-time on bytes).
if (stored.Length != legacyExpected.Length * 2) return false;
byte[] storedBytes;
try
{
storedBytes = Convert.FromHexString(stored);
}
catch (FormatException) { return false; }
return CryptographicOperations.FixedTimeEquals(storedBytes, legacyExpected);
}
private static byte[] Pbkdf2Hash(string normalizedCode, byte[] salt, int iterations, byte[] pepper, int outputLength = 32)
{
var codeBytes = Encoding.UTF8.GetBytes(normalizedCode);
var pwd = new byte[codeBytes.Length + pepper.Length];
Buffer.BlockCopy(codeBytes, 0, pwd, 0, codeBytes.Length);
Buffer.BlockCopy(pepper, 0, pwd, codeBytes.Length, pepper.Length);
try
{
return Rfc2898DeriveBytes.Pbkdf2(pwd, salt, iterations, HashAlgorithmName.SHA256, outputLength);
}
finally
{
CryptographicOperations.ZeroMemory(pwd);
}
}
private static string NormalizeRecoveryCode(string code) =>
code.Replace("-", "", StringComparison.Ordinal).ToUpperInvariant();
///
/// Returns the number of seconds until the next OTP can be sent, or 0 if allowed now.
/// Combines per-send cooldown and a sliding-window per-hour quota (B6).
///
private int CheckOtpRateLimit(MfaProps props)
{
var now = _timeProvider.GetUtcNow();
// Cooldown
if (props.LastOtpSentAt is { } last)
{
var elapsed = now - last;
if (elapsed < _options.OtpCooldown)
{
var remaining = (int)Math.Ceiling((_options.OtpCooldown - elapsed).TotalSeconds);
return Math.Max(remaining, 1);
}
}
// Sliding-window hourly quota
var timestamps = props.RecentOtpTimestamps;
if (timestamps is null || timestamps.Count == 0)
return 0;
var cutoff = now.ToUnixTimeSeconds() - (long)OtpRateLimitWindow.TotalSeconds;
// Count entries still within the window (do not mutate here — mutation happens in
// UpdateOtpRateLimitCounters under the same row lock).
var insideWindow = 0;
var oldestInside = long.MaxValue;
foreach (var ts in timestamps)
{
if (ts > cutoff)
{
insideWindow++;
if (ts < oldestInside) oldestInside = ts;
}
}
if (insideWindow < _options.OtpMaxPerHour)
return 0;
// Quota reached — caller must wait until the oldest in-window entry leaves the window.
var nextSlotUnix = oldestInside + (long)OtpRateLimitWindow.TotalSeconds;
var waitSeconds = (int)(nextSlotUnix - now.ToUnixTimeSeconds());
return Math.Max(waitSeconds, 1);
}
private void UpdateOtpRateLimitCounters(MfaProps props)
{
var now = _timeProvider.GetUtcNow();
var nowUnix = now.ToUnixTimeSeconds();
var cutoff = nowUnix - (long)OtpRateLimitWindow.TotalSeconds;
// Prune expired timestamps in-place; allocate a fresh list if none yet.
var timestamps = props.RecentOtpTimestamps;
if (timestamps is null)
{
timestamps = new List(4);
props.RecentOtpTimestamps = timestamps;
}
else
{
timestamps.RemoveAll(ts => ts <= cutoff);
}
timestamps.Add(nowUnix);
// Cap list size to bound storage. Drop oldest entries first.
if (timestamps.Count > RecentOtpTimestampsCap)
{
timestamps.RemoveRange(0, timestamps.Count - RecentOtpTimestampsCap);
}
props.LastOtpSentAt = now;
}
/// Generates a 6-digit OTP code using cryptographic RNG.
internal static string GenerateOtpCode()
{
Span buf = stackalloc byte[4];
RandomNumberGenerator.Fill(buf);
var n = BitConverter.ToUInt32(buf) % 1_000_000u;
return n.ToString("D6", System.Globalization.CultureInfo.InvariantCulture);
}
}
Path: redb-identity/src/redb.Identity.Core/Services/MfaSetupInitiation.cs
Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.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/MfaSetupInitiation.cs
----
using redb.Identity.Core.Models;
namespace redb.Identity.Core.Services;
///
/// Pure setup data returned by .
/// Captures everything the orchestrator needs to (a) hand a setup_token back to the
/// client and (b) reconstruct + apply the secret on confirm — without mutating
/// first. This is the B5 fix for the "two parallel setups
/// race-overwrite the secret" bug.
///
public sealed record MfaSetupInitiation
{
public required string MethodId { get; init; }
///
/// Method-private secret to be persisted on confirm. For TOTP this is the encrypted
/// (DataProtection-protected) base32 shared secret; for WebAuthn it would be the
/// credential id payload. Null for methods that don't carry a secret (SMS/Email).
///
public string? EncryptedSecret { get; init; }
/// Destination such as phone or email. Null for TOTP.
public string? Destination { get; init; }
/// Client-facing setup data (QR URI, masked destination, errors, etc.).
public required MfaSetupResult ClientResult { get; init; }
}
Path: redb-identity/src/redb.Identity.Core/Services/MfaSetupTokenProtector.cs
Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.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/MfaSetupTokenProtector.cs
----
using System.Text.Json;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.Extensions.Logging;
using redb.Identity.Core.Models;
using redb.Identity.Contracts.Common;
namespace redb.Identity.Core.Services;
///
/// Encrypts/decrypts an MFA setup token (B5). The setup token carries the candidate
/// secret/destination for an in-progress MFA setup so that the secret is NEVER persisted
/// to until the user proves possession by submitting a valid code
/// during confirm.
///
/// Uses ASP.NET DataProtection with a dedicated purpose so leaks across MFA-state /
/// MFA-secret protectors are impossible. Default TTL is 10 minutes.
///
public sealed class MfaSetupTokenProtector
{
private const string Purpose = "redb.identity.mfa-setup.v1";
private static readonly TimeSpan DefaultMaxAge = TimeSpan.FromMinutes(10);
private readonly IDataProtector _protector;
private readonly TimeProvider _timeProvider;
private readonly ILogger? _logger;
public MfaSetupTokenProtector(IDataProtectionProvider provider)
: this(provider, TimeProvider.System, null)
{
}
public MfaSetupTokenProtector(IDataProtectionProvider provider, TimeProvider? timeProvider)
: this(provider, timeProvider, null)
{
}
public MfaSetupTokenProtector(
IDataProtectionProvider provider,
TimeProvider? timeProvider,
ILogger? logger)
{
ArgumentNullException.ThrowIfNull(provider);
_protector = provider.CreateProtector(Purpose);
_timeProvider = timeProvider ?? TimeProvider.System;
_logger = logger;
}
public string Protect(MfaSetupTokenPayload payload)
{
ArgumentNullException.ThrowIfNull(payload);
if (payload.IssuedAt == default) payload.IssuedAt = _timeProvider.GetUtcNow();
if (payload.Jti == Guid.Empty) payload.Jti = Guid.NewGuid();
var json = JsonSerializer.SerializeToUtf8Bytes(payload);
var encrypted = _protector.Protect(json);
return Convert.ToBase64String(encrypted);
}
///
/// Returns the decrypted payload or null if tampered, malformed, expired, or older than
/// (defaults to 10 minutes).
///
public MfaSetupTokenPayload? Unprotect(string token, TimeSpan? maxAge = null)
{
if (string.IsNullOrEmpty(token)) return null;
try
{
var bytes = Base64Canonical.Decode(token);
var json = _protector.Unprotect(bytes);
var payload = JsonSerializer.Deserialize(json);
if (payload is null || payload.UserId <= 0 || string.IsNullOrEmpty(payload.MethodId))
{
_logger?.LogWarning(
"MfaSetupTokenProtector: decrypted payload was null or had invalid UserId/MethodId.");
return null;
}
var age = _timeProvider.GetUtcNow() - payload.IssuedAt;
if (age > (maxAge ?? DefaultMaxAge))
{
_logger?.LogDebug(
"MfaSetupTokenProtector: setup token expired (age={AgeSeconds}s, max={MaxSeconds}s).",
age.TotalSeconds, (maxAge ?? DefaultMaxAge).TotalSeconds);
return null;
}
return payload;
}
catch (Exception ex)
{
// Tampering or DataProtection key rotation. Public contract preserved (null).
_logger?.LogWarning(ex,
"MfaSetupTokenProtector: failed to decrypt setup token (length={Length}).",
token.Length);
return null;
}
}
}
Path: redb-identity/src/redb.Identity.Core/Services/MfaStateProtector.cs
Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.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/MfaStateProtector.cs
----
using System.Text.Json;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.Extensions.Logging;
using redb.Identity.Contracts.Mfa;
using redb.Identity.Core.Models;
using redb.Identity.Contracts.Common;
namespace redb.Identity.Core.Services;
///
/// Encrypts/decrypts temporary MFA state using ASP.NET DataProtection with TTL enforcement.
/// Same pattern as but for the MFA challenge flow.
///
/// Also implements — a minimal read-only surface in
/// redb.Identity.Contracts that transport facades (HTTP, gRPC, …) consume to render
/// MFA-method selectors without taking a project-reference on Core.
///
///
public sealed class MfaStateProtector : IMfaStateInspector
{
private const string Purpose = "redb.identity.mfa-state";
private static readonly TimeSpan DefaultMaxAge = TimeSpan.FromMinutes(5);
private readonly IDataProtector _protector;
private readonly TimeProvider _timeProvider;
private readonly ILogger? _logger;
public MfaStateProtector(IDataProtectionProvider provider)
: this(provider, TimeProvider.System, null)
{
}
public MfaStateProtector(IDataProtectionProvider provider, TimeProvider? timeProvider)
: this(provider, timeProvider, null)
{
}
public MfaStateProtector(
IDataProtectionProvider provider,
TimeProvider? timeProvider,
ILogger? logger)
{
ArgumentNullException.ThrowIfNull(provider);
_protector = provider.CreateProtector(Purpose);
_timeProvider = timeProvider ?? TimeProvider.System;
_logger = logger;
}
/// Encrypts MFA state into a base64 string for use as a hidden form field or query parameter.
public string Protect(MfaState state)
{
ArgumentNullException.ThrowIfNull(state);
state.IssuedAt ??= _timeProvider.GetUtcNow();
var json = JsonSerializer.SerializeToUtf8Bytes(state);
var encrypted = _protector.Protect(json);
return Convert.ToBase64String(encrypted);
}
///
/// Decrypts and validates MFA state. Returns null if invalid, tampered, or expired.
///
public MfaState? Unprotect(string protectedState, TimeSpan? maxAge = null)
{
if (string.IsNullOrEmpty(protectedState))
return null;
try
{
var encrypted = Base64Canonical.Decode(protectedState);
var json = _protector.Unprotect(encrypted);
var state = JsonSerializer.Deserialize(json);
if (state is null || state.UserId <= 0)
{
_logger?.LogWarning(
"MfaStateProtector: decrypted state was null or had invalid UserId.");
return null;
}
var age = _timeProvider.GetUtcNow() - (state.IssuedAt ?? DateTimeOffset.MinValue);
if (age > (maxAge ?? DefaultMaxAge))
{
_logger?.LogDebug(
"MfaStateProtector: state expired (age={AgeSeconds}s, max={MaxSeconds}s).",
age.TotalSeconds, (maxAge ?? DefaultMaxAge).TotalSeconds);
return null;
}
return state;
}
catch (Exception ex)
{
// Tampering or DataProtection key rotation. Public contract preserved (null).
_logger?.LogWarning(ex,
"MfaStateProtector: failed to decrypt MFA state (length={Length}).",
protectedState.Length);
return null;
}
}
///
string[]? IMfaStateInspector.TryGetMethods(string? protectedState)
{
if (string.IsNullOrEmpty(protectedState))
return null;
var state = Unprotect(protectedState);
return state?.Methods;
}
}
Path: redb-identity/src/redb.Identity.Core/Services/OidcFederatedAuthProvider.cs
Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.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/OidcFederatedAuthProvider.cs
----
using System.Net.Http.Json;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using Microsoft.IdentityModel.JsonWebTokens;
using Microsoft.IdentityModel.Protocols;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Microsoft.IdentityModel.Tokens;
using redb.Identity.Core.Configuration;
using redb.Identity.Contracts.Configuration;
namespace redb.Identity.Core.Services;
///
/// Generic OIDC Relying Party — works with any IdP that exposes
/// .well-known/openid-configuration (Google, Azure AD, Keycloak, etc.).
/// Uses PKCE (S256), validates id_token signature + claims.
///
public sealed class OidcFederatedAuthProvider : IFederatedAuthProvider
{
private readonly FederationProviderConfig _config;
private readonly IHttpClientFactory _httpClientFactory;
private readonly ConfigurationManager _configManager;
private static readonly JsonWebTokenHandler _tokenHandler = new();
public OidcFederatedAuthProvider(
FederationProviderConfig config,
IHttpClientFactory httpClientFactory)
{
_config = config ?? throw new ArgumentNullException(nameof(config));
_httpClientFactory = httpClientFactory ?? throw new ArgumentNullException(nameof(httpClientFactory));
var metadataAddress = config.Authority.TrimEnd('/') + "/.well-known/openid-configuration";
_configManager = new ConfigurationManager(
metadataAddress,
new OpenIdConnectConfigurationRetriever(),
new HttpDocumentRetriever(_httpClientFactory.CreateClient("redb-identity-federation"))
{
RequireHttps = config.Authority.StartsWith("https://", StringComparison.OrdinalIgnoreCase)
});
}
public string ProviderId => _config.ProviderId;
public string DisplayName => _config.DisplayName;
public int Priority => _config.Priority;
public async Task CreateChallengeAsync(
string callbackUrl, string returnUrl, CancellationToken ct = default)
{
var disco = await _configManager.GetConfigurationAsync(ct).ConfigureAwait(false);
// PKCE S256
var codeVerifier = GenerateCodeVerifier();
var codeChallenge = ComputeCodeChallenge(codeVerifier);
var nonce = GenerateNonce();
var state = GenerateNonce(); // opaque, the caller wraps it with DataProtection
var authUrl = disco.AuthorizationEndpoint
+ "?response_type=code"
+ "&client_id=" + Uri.EscapeDataString(_config.ClientId)
+ "&redirect_uri=" + Uri.EscapeDataString(callbackUrl)
+ "&scope=" + Uri.EscapeDataString(string.Join(" ", _config.Scopes))
+ "&state=" + Uri.EscapeDataString(state)
+ "&nonce=" + Uri.EscapeDataString(nonce)
+ "&code_challenge=" + Uri.EscapeDataString(codeChallenge)
+ "&code_challenge_method=S256";
return new FederationChallenge
{
RedirectUri = authUrl,
State = state,
Nonce = nonce,
CodeVerifier = codeVerifier
};
}
public async Task HandleCallbackAsync(
string code, string callbackUrl, string? codeVerifier = null, string? nonce = null,
CancellationToken ct = default)
{
var disco = await _configManager.GetConfigurationAsync(ct).ConfigureAwait(false);
// Exchange authorization code for tokens
var tokenResponse = await ExchangeCodeAsync(disco.TokenEndpoint, code, callbackUrl, codeVerifier, ct)
.ConfigureAwait(false);
if (tokenResponse is null || string.IsNullOrEmpty(tokenResponse.id_token))
return ExternalAuthResult.Failed("Token exchange failed or no id_token received.");
// Validate id_token
var validationResult = await ValidateIdTokenAsync(tokenResponse.id_token, disco, nonce, ct)
.ConfigureAwait(false);
if (!validationResult.IsValid)
return ExternalAuthResult.Failed($"id_token validation failed: {validationResult.Exception?.Message}");
var claims = validationResult.ClaimsIdentity;
var sub = claims.FindFirst("sub")?.Value;
if (string.IsNullOrEmpty(sub))
return ExternalAuthResult.Failed("id_token missing 'sub' claim.");
return ExternalAuthResult.Success(
externalId: sub,
displayName: claims.FindFirst("name")?.Value,
email: claims.FindFirst("email")?.Value,
givenName: claims.FindFirst("given_name")?.Value,
familyName: claims.FindFirst("family_name")?.Value);
}
private async Task ExchangeCodeAsync(
string tokenEndpoint, string code, string callbackUrl,
string? codeVerifier, CancellationToken ct)
{
using var client = _httpClientFactory.CreateClient("redb-identity-federation");
var parameters = new Dictionary
{
["grant_type"] = "authorization_code",
["code"] = code,
["redirect_uri"] = callbackUrl,
["client_id"] = _config.ClientId,
["client_secret"] = _config.ClientSecret
};
if (!string.IsNullOrEmpty(codeVerifier))
parameters["code_verifier"] = codeVerifier;
using var content = new FormUrlEncodedContent(parameters);
using var response = await client.PostAsync(tokenEndpoint, content, ct).ConfigureAwait(false);
if (!response.IsSuccessStatusCode)
return null;
return await response.Content.ReadFromJsonAsync(ct).ConfigureAwait(false);
}
private async Task ValidateIdTokenAsync(
string idToken, OpenIdConnectConfiguration disco,
string? expectedNonce, CancellationToken ct)
{
var validationParams = new TokenValidationParameters
{
ValidIssuer = _config.Authority.TrimEnd('/'),
ValidAudience = _config.ClientId,
IssuerSigningKeys = disco.SigningKeys,
ValidateIssuerSigningKey = true,
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ClockSkew = TimeSpan.FromMinutes(5)
};
var result = await _tokenHandler.ValidateTokenAsync(idToken, validationParams).ConfigureAwait(false);
// Validate nonce if provided
if (result.IsValid && !string.IsNullOrEmpty(expectedNonce))
{
var tokenNonce = result.ClaimsIdentity.FindFirst("nonce")?.Value;
if (tokenNonce != expectedNonce)
{
return new TokenValidationResult
{
IsValid = false,
Exception = new SecurityTokenValidationException("Nonce mismatch in id_token.")
};
}
}
return result;
}
// PKCE helpers
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(Encoding.ASCII.GetBytes(codeVerifier));
return Base64UrlEncoder.Encode(bytes);
}
private static string GenerateNonce()
{
var bytes = new byte[16];
RandomNumberGenerator.Fill(bytes);
return Base64UrlEncoder.Encode(bytes);
}
private sealed class TokenResponse
{
public string? access_token { get; set; }
public string? id_token { get; set; }
public string? token_type { get; set; }
public int expires_in { get; set; }
}
}
Path: redb-identity/src/redb.Identity.Core/Services/OutboundUrlGuard.cs
Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.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/OutboundUrlGuard.cs
----
using System.Net;
using System.Net.Sockets;
namespace redb.Identity.Core.Services;
///
/// Decides whether the server may make an outbound HTTP request to a URL that came from
/// outside — a client's jwks_uri, a JAR request_uri, a webhook target.
///
/// Such a URL is attacker-influenced input. Fetching it unchecked turns the server into a proxy
/// into its own network (SSRF): http://127.0.0.1:9090/admin, http://10.0.0.5/, or
/// the cloud metadata service at 169.254.169.254, which hands out instance credentials to
/// whoever can reach it. The server is inside the perimeter; the caller is not.
///
///
internal static class OutboundUrlGuard
{
/// Why a URL was rejected. means it passed.
internal enum Rejection
{
None,
NotAbsolute,
SchemeNotAllowed,
HttpsRequired,
HostUnresolvable,
PrivateNetworkTarget,
}
///
/// Validates the URL's shape (absolute, allowed scheme) without touching the network.
///
internal static Rejection ValidateShape(string? url, bool requireHttps, out Uri? uri)
{
uri = null;
if (string.IsNullOrWhiteSpace(url)) return Rejection.NotAbsolute;
if (!Uri.TryCreate(url, UriKind.Absolute, out var parsed)) return Rejection.NotAbsolute;
if (parsed.Scheme != Uri.UriSchemeHttps && parsed.Scheme != Uri.UriSchemeHttp)
return Rejection.SchemeNotAllowed;
if (requireHttps && parsed.Scheme != Uri.UriSchemeHttps)
return Rejection.HttpsRequired;
uri = parsed;
return Rejection.None;
}
///
/// Full check: shape, then DNS resolution, then every resolved address against the
/// non-public ranges. Rejects when any resolved address is non-public — a name that
/// answers with both a public and a private address must not slip through on the public one.
///
///
/// This cannot close DNS rebinding on its own: the name is resolved here and again by the
/// HTTP stack, and the answer may differ between the two. Closing that hole means pinning the
/// validated address for the actual connection. The check still removes the whole class of
/// trivially-internal targets, which is what an operator pasting an internal URL — or an
/// attacker with write access to a client record — would reach for first.
///
internal static async ValueTask ValidateAsync(
string? url,
bool requireHttps,
bool allowPrivateNetworkTargets,
CancellationToken cancellationToken = default)
{
var shape = ValidateShape(url, requireHttps, out var uri);
if (shape != Rejection.None || uri is null) return shape;
if (allowPrivateNetworkTargets) return Rejection.None;
IPAddress[] addresses;
if (IPAddress.TryParse(uri.Host, out var literal))
{
addresses = [literal];
}
else
{
try
{
addresses = await Dns.GetHostAddressesAsync(uri.Host, cancellationToken)
.ConfigureAwait(false);
}
catch (Exception e) when (e is SocketException or ArgumentException)
{
return Rejection.HostUnresolvable;
}
}
if (addresses.Length == 0) return Rejection.HostUnresolvable;
foreach (var address in addresses)
{
if (!IsPublic(address)) return Rejection.PrivateNetworkTarget;
}
return Rejection.None;
}
///
/// True when the address is routable on the public internet. Everything else — loopback,
/// RFC 1918, link-local (incl. the 169.254.169.254 metadata address), CGNAT,
/// unique-local IPv6, and IPv4-mapped IPv6 forms of all of those — is treated as internal.
///
internal static bool IsPublic(IPAddress address)
{
// ::ffff:10.0.0.1 must be judged as 10.0.0.1, not as an opaque IPv6 address.
if (address.IsIPv4MappedToIPv6) address = address.MapToIPv4();
if (IPAddress.IsLoopback(address)) return false;
if (address.AddressFamily == AddressFamily.InterNetwork)
{
var b = address.GetAddressBytes();
return b[0] switch
{
0 => false, // 0.0.0.0/8 "this network"
10 => false, // RFC 1918
127 => false, // loopback (belt and braces)
169 when b[1] == 254 => false, // link-local incl. cloud metadata
172 when b[1] >= 16 && b[1] <= 31 => false, // RFC 1918
192 when b[1] == 168 => false, // RFC 1918
100 when b[1] >= 64 && b[1] <= 127 => false, // RFC 6598 CGNAT
>= 224 => false, // multicast + reserved
_ => true,
};
}
if (address.AddressFamily == AddressFamily.InterNetworkV6)
{
if (address.IsIPv6LinkLocal || address.IsIPv6SiteLocal || address.IsIPv6Multicast)
return false;
// fc00::/7 unique local
var b = address.GetAddressBytes();
if ((b[0] & 0xFE) == 0xFC) return false;
// :: and ::1
if (address.Equals(IPAddress.IPv6Any) || address.Equals(IPAddress.IPv6Loopback))
return false;
return true;
}
return false;
}
/// Human-readable reason, for logs and invalid_request_object descriptions.
internal static string Describe(Rejection rejection) => rejection switch
{
Rejection.NotAbsolute => "not an absolute URL",
Rejection.SchemeNotAllowed => "scheme must be http or https",
Rejection.HttpsRequired => "must use https",
Rejection.HostUnresolvable => "host could not be resolved",
Rejection.PrivateNetworkTarget => "resolves to a non-public address",
_ => "ok",
};
}
Path: redb-identity/src/redb.Identity.Core/Services/RecoveryCodePepperProvider.cs
Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.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/RecoveryCodePepperProvider.cs
----
using System.Security.Cryptography;
using System.Text;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using redb.Identity.Core.Configuration;
namespace redb.Identity.Core.Services;
///
/// Provides the server-wide pepper applied during MFA recovery-code hashing
/// (B4 — defence-in-depth on top of per-user salt + PBKDF2) and to the hashes of the
/// password-reset, e-mail-verification and change-e-mail tokens.
///
/// The current pepper () hashes everything new; the previous ones
/// () are only tried on verification, so a rotation keeps
/// what was issued under them. Every pepper has an id () that stored hashes record, so a
/// record is checked against exactly its pepper.
///
/// Singleton lifetime: pepper bytes are decoded once at construction so every
/// instance shares the same value.
///
public sealed class RecoveryCodePepperProvider
{
private static readonly byte[] IdLabel = Encoding.ASCII.GetBytes("redb.identity.pepper-id");
private readonly IReadOnlyList<(string Id, byte[] Pepper)> _previous;
/// Raw pepper bytes (configured or ephemeral). Never empty.
public byte[] Pepper { get; }
/// Id of the current pepper, recorded with every hash made from it.
public string PepperId { get; }
/// True if the pepper was generated at startup (development fallback).
public bool IsEphemeral { get; }
/// Ids of the previous peppers, in configured order.
public IReadOnlyList PreviousPepperIds { get; }
public RecoveryCodePepperProvider(
IOptions options,
ILogger logger)
{
var configured = options.Value.RecoveryCodePepper;
if (!string.IsNullOrEmpty(configured))
{
Pepper = Decode(configured, "RedbIdentityOptions.RecoveryCodePepper");
IsEphemeral = false;
}
else if (!options.Value.AllowEphemeralKeys)
{
throw new InvalidOperationException(
"RedbIdentityOptions.RecoveryCodePepper is not configured. " +
"Set AllowEphemeralKeys=true in development, or provide a stable base64-encoded " +
"pepper (16+ bytes) loaded from a secret store in production.");
}
else
{
Pepper = RandomNumberGenerator.GetBytes(32);
IsEphemeral = true;
logger.LogWarning(
"MFA recovery-code pepper is ephemeral: codes generated in this process cannot be " +
"verified after restart. Set RedbIdentityOptions.RecoveryCodePepper for production.");
}
PepperId = ComputeId(Pepper);
var previous = new List<(string, byte[])>();
var values = options.Value.RecoveryCodePreviousPeppers ?? [];
for (var i = 0; i < values.Length; i++)
{
var name = $"RedbIdentityOptions.RecoveryCodePreviousPeppers[{i}]";
if (string.IsNullOrEmpty(values[i]))
throw new InvalidOperationException($"{name} is empty.");
var bytes = Decode(values[i], name);
var id = ComputeId(bytes);
if (id == PepperId)
throw new InvalidOperationException($"{name} is the current RecoveryCodePepper.");
if (previous.Any(p => p.Item1 == id))
throw new InvalidOperationException($"{name} repeats an earlier entry.");
previous.Add((id, bytes));
}
_previous = previous;
PreviousPepperIds = previous.Select(p => p.Item1).ToArray();
}
private RecoveryCodePepperProvider(byte[] pepper, bool isEphemeral, IEnumerable previous)
{
Pepper = pepper;
IsEphemeral = isEphemeral;
PepperId = ComputeId(pepper);
_previous = previous.Select(p => (ComputeId(p), p)).ToArray();
PreviousPepperIds = _previous.Select(p => p.Id).ToArray();
}
///
/// The peppers a stored hash is checked against. A hash with an id gets exactly its pepper, or none when that
/// pepper is no longer configured; a hash without an id (written before 4.8.0) gets the current pepper, then the
/// previous ones in order.
///
public IReadOnlyList PeppersFor(string? pepperId)
{
if (string.IsNullOrEmpty(pepperId))
return [Pepper, .. _previous.Select(p => p.Pepper)];
if (pepperId == PepperId) return [Pepper];
foreach (var (id, pepper) in _previous)
if (id == pepperId) return [pepper];
return [];
}
///
/// The id of a pepper: the first 8 bytes of HMAC-SHA256(pepper, "redb.identity.pepper-id"), lowercase hex. It
/// tells peppers apart and reveals nothing usable about the value.
///
public static string ComputeId(byte[] pepper) =>
Convert.ToHexStringLower(HMACSHA256.HashData(pepper, IdLabel).AsSpan(0, 8));
/// sha256(pepper || token), lowercase hex: the stored form of the one-time link tokens.
public static string PepperedSha256Hex(byte[] pepper, string token)
{
var tokenBytes = Encoding.UTF8.GetBytes(token);
var input = new byte[pepper.Length + tokenBytes.Length];
Buffer.BlockCopy(pepper, 0, input, 0, pepper.Length);
Buffer.BlockCopy(tokenBytes, 0, input, pepper.Length, tokenBytes.Length);
return Convert.ToHexStringLower(SHA256.HashData(input));
}
///
/// Checks a one-time link token against its stored hash with the peppers gives for the
/// stored pepper id. Every candidate is compared, in constant time.
///
public bool MatchesTokenHash(string token, string storedHash, string? pepperId)
{
var stored = Encoding.ASCII.GetBytes(storedHash);
var match = false;
foreach (var pepper in PeppersFor(pepperId))
match |= CryptographicOperations.FixedTimeEquals(Encoding.ASCII.GetBytes(PepperedSha256Hex(pepper, token)), stored);
return match;
}
private static byte[] Decode(string value, string name)
{
byte[] bytes;
try
{
bytes = Convert.FromBase64String(value);
}
catch (FormatException ex)
{
throw new InvalidOperationException($"{name} must be a valid base64 string.", ex);
}
if (bytes.Length < 16)
throw new InvalidOperationException($"{name} must decode to at least 16 bytes; got {bytes.Length}.");
return bytes;
}
///
/// Test-only factory: builds a provider with a fixed (or random 32-byte) pepper, and optional previous peppers,
/// without going through configuration validation. Use exclusively in unit / integration tests.
///
public static RecoveryCodePepperProvider ForTesting(byte[]? pepper = null, params byte[][] previous) =>
new(pepper ?? RandomNumberGenerator.GetBytes(32), isEphemeral: pepper is null, previous);
}
Path: redb-identity/src/redb.Identity.Core/Services/RedbDpopReplayStore.cs
Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.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/RedbDpopReplayStore.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.Identity.Core.Routes.Processors;
namespace redb.Identity.Core.Services;
///
/// PROPS-backed mirroring
/// . Singleton; resolves
/// through a fresh DI scope per operation to avoid
/// captive-scope-in-singleton.
///
/// Atomicity (RFC 9449 §11.1, at most once): the reservation row carries
/// ValueUnique = SHA-256 of jkt|jti, so the database index decides who wins, not
/// the lookup. Two presentations of one proof racing past FirstOrDefaultAsync both try
/// to insert; the index lets exactly one through and the other gets
/// , reported as a replay. The lookup stays as the
/// fast path — an already-consumed proof is refused without a failing statement — and an
/// expired reservation is refreshed in place rather than inserted a second time.
///
///
/// The key is hashed for the reason the idempotency record's is:
/// jti is chosen by the client and unbounded, while ValueUnique is capped at 440
/// characters. Rows written before the key existed carry none; the lookup still finds them,
/// and the cleanup timer removes them within one TTL.
///
///
public sealed class RedbDpopReplayStore : IDpopReplayStore
{
private readonly IServiceScopeFactory _scopeFactory;
private readonly ILogger _logger;
private readonly TimeProvider _timeProvider;
public RedbDpopReplayStore(
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 TryReserveAsync(string jkt, string jti, TimeSpan ttl, CancellationToken ct = default)
{
if (string.IsNullOrEmpty(jkt) || string.IsNullOrEmpty(jti))
return false;
var now = _timeProvider.GetUtcNow();
var expiresAt = now + (ttl <= TimeSpan.Zero ? TimeSpan.FromMinutes(5) : ttl);
var name = jkt + "|" + jti;
var uniqueKey = IdempotencyKeyHash.Sha256Hex(name);
await using var scope = _scopeFactory.CreateAsyncScope();
var redb = scope.ServiceProvider.GetRequiredService();
// ExecuteAtomicAsync rather than an explicit transaction: it joins the ambient one when
// the route is transacted (the token route is) and opens its own when it is not. An
// explicit BeginTransactionAsync can do neither — the core rejects it under an ambient
// scope — and a mid-logic rollback would discard the whole route: a replayed proof must
// fail the request, not undo everything before it.
return await redb.Context.ExecuteAtomicAsync(async () =>
{
var existing = await redb.Query()
.Where(o => o.Jkt == jkt && o.Jti == jti)
.FirstOrDefaultAsync()
.ConfigureAwait(false);
if (existing is not null)
{
// A live reservation is a replay.
if (existing.Props.ExpiresAt > now)
{
_logger.LogWarning("DPoP proof replay detected: jkt={Jkt} jti={Jti}", jkt, jti);
return false;
}
// Expired — cleanup has not run yet. Refresh the row in place: a second insert
// would hit the unique key and misreport a stale row as a replay. A proof this
// old is refused by the iat window long before it reaches the store, so this
// branch is housekeeping, not the guard.
existing.Props.ConsumedAt = now;
existing.Props.ExpiresAt = expiresAt;
existing.ValueUnique = uniqueKey;
await redb.SaveAsync(existing).ConfigureAwait(false);
return true;
}
var row = new RedbObject(new DpopConsumedJtiProps
{
Jkt = jkt,
Jti = jti,
ConsumedAt = now,
ExpiresAt = expiresAt,
});
row.name = name;
row.ValueUnique = uniqueKey;
try
{
await redb.SaveAsync(row).ConfigureAwait(false);
return true;
}
catch (RedbUniqueViolationException)
{
// The other presenter of this jti inserted between our lookup and our insert.
// The core ran the insert under a savepoint, so the surrounding transaction (the
// token route's, when ambient) is intact and the request is refused cleanly.
_logger.LogWarning("DPoP proof replay detected (concurrent): jkt={Jkt} jti={Jti}", jkt, jti);
return false;
}
}, ct).ConfigureAwait(false);
}
}
Path: redb-identity/src/redb.Identity.Core/Services/RedisDpopReplayStore.cs
Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.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/RedisDpopReplayStore.cs
----
using redb.Route.Redis;
using StackExchange.Redis;
namespace redb.Identity.Core.Services;
///
/// Redis-backed . Uses atomic SET key NX EX ttl
/// so the first writer wins; concurrent replays observe the existing key.
///
internal sealed class RedisDpopReplayStore : IDpopReplayStore, IAsyncDisposable, IDisposable
{
private readonly RedisConnectionFactory _factory;
private readonly string _prefix;
private readonly SemaphoreSlim _connectionLock = new(1, 1);
private IConnectionMultiplexer? _connection;
public RedisDpopReplayStore(RedisConnectionFactory factory, string keyPrefix)
{
_factory = factory ?? throw new ArgumentNullException(nameof(factory));
_prefix = keyPrefix ?? string.Empty;
}
public async Task TryReserveAsync(string jkt, string jti, TimeSpan ttl, CancellationToken ct = default)
{
if (string.IsNullOrEmpty(jkt) || string.IsNullOrEmpty(jti))
return false;
ct.ThrowIfCancellationRequested();
var db = await GetDatabaseAsync(ct).ConfigureAwait(false);
var fullKey = _prefix + jkt + ":" + jti;
var ttlSpan = ttl <= TimeSpan.Zero ? TimeSpan.FromMinutes(5) : ttl;
return await db.StringSetAsync(
fullKey,
"1",
expiry: ttlSpan,
when: When.NotExists).ConfigureAwait(false);
}
private async Task GetDatabaseAsync(CancellationToken ct)
{
if (_connection is { IsConnected: true })
return _connection.GetDatabase(_factory.Database);
await _connectionLock.WaitAsync(ct).ConfigureAwait(false);
try
{
if (_connection is { IsConnected: true })
return _connection.GetDatabase(_factory.Database);
var config = _factory.Build();
_connection = await ConnectionMultiplexer.ConnectAsync(config).ConfigureAwait(false);
return _connection.GetDatabase(_factory.Database);
}
finally
{
_connectionLock.Release();
}
}
public async ValueTask DisposeAsync()
{
if (_connection is not null)
await _connection.DisposeAsync().ConfigureAwait(false);
_connectionLock.Dispose();
}
public void Dispose()
{
_connection?.Dispose();
_connectionLock.Dispose();
}
}
Path: redb-identity/src/redb.Identity.Core/Services/RedisFederationStateNonceStore.cs
Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.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/RedisFederationStateNonceStore.cs
----
using redb.Route.Redis;
using StackExchange.Redis;
namespace redb.Identity.Core.Services;
///
/// Redis-backed implementation of .
/// Uses a per-jti string key with NX semantics so the first call wins atomically;
/// the key is set with the requested TTL so expired jti values can be replayed
/// only after the original state would itself have expired (consistent with
/// ).
///
internal sealed class RedisFederationStateNonceStore : IFederationStateNonceStore, IAsyncDisposable, IDisposable
{
private readonly RedisConnectionFactory _factory;
private readonly string _prefix;
private readonly SemaphoreSlim _connectionLock = new(1, 1);
private IConnectionMultiplexer? _connection;
public RedisFederationStateNonceStore(RedisConnectionFactory factory, string keyPrefix)
{
_factory = factory ?? throw new ArgumentNullException(nameof(factory));
_prefix = keyPrefix ?? string.Empty;
}
public async Task TryConsumeAsync(string jti, TimeSpan ttl, CancellationToken ct = default)
{
if (string.IsNullOrEmpty(jti))
return false;
ct.ThrowIfCancellationRequested();
var db = await GetDatabaseAsync(ct).ConfigureAwait(false);
var fullKey = _prefix + jti;
var ttlSpan = ttl <= TimeSpan.Zero ? TimeSpan.FromMinutes(5) : ttl;
// Atomic SETNX with TTL — first writer wins; everyone else gets false.
return await db.StringSetAsync(
fullKey,
"1",
expiry: ttlSpan,
when: When.NotExists).ConfigureAwait(false);
}
private async Task GetDatabaseAsync(CancellationToken ct)
{
if (_connection is { IsConnected: true })
return _connection.GetDatabase(_factory.Database);
await _connectionLock.WaitAsync(ct).ConfigureAwait(false);
try
{
if (_connection is { IsConnected: true })
return _connection.GetDatabase(_factory.Database);
var config = _factory.Build();
_connection = await ConnectionMultiplexer.ConnectAsync(config).ConfigureAwait(false);
return _connection.GetDatabase(_factory.Database);
}
finally
{
_connectionLock.Release();
}
}
public async ValueTask DisposeAsync()
{
if (_connection is not null)
await _connection.DisposeAsync().ConfigureAwait(false);
_connectionLock.Dispose();
}
public void Dispose()
{
_connection?.Dispose();
_connectionLock.Dispose();
}
}
Path: redb-identity/src/redb.Identity.Core/Services/RedisRateLimitStore.cs
Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.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/RedisRateLimitStore.cs
----
using redb.Identity.Core.Configuration;
using redb.Route.Redis;
using StackExchange.Redis;
namespace redb.Identity.Core.Services;
///
/// C1 — Cluster-global sliding-window counter backed by a Redis sorted set.
/// Activated when is "redis".
/// Uses the same abstraction as
/// .
///
internal sealed class RedisRateLimitStore : IRateLimitStore, IAsyncDisposable, IDisposable
{
private readonly RedisConnectionFactory _factory;
private readonly string _prefix;
private readonly TimeProvider _timeProvider;
private readonly SemaphoreSlim _connectionLock = new(1, 1);
private IConnectionMultiplexer? _connection;
// Sliding-window counter. Mirrors InMemoryRateLimitStore semantics:
// a request is denied iff the bucket already holds >= limit non-expired hits, and the
// current hit is NOT inserted in that case. Returns { allowed (1/0), countAfter, oldestScore }.
private const string IncrLuaScript =
"""
local key = KEYS[1]
local nowTicks = tonumber(ARGV[1])
local windowTicks = tonumber(ARGV[2])
local limit = tonumber(ARGV[3])
local ttl = math.floor(windowTicks / 10000000) + 10
redis.call('ZREMRANGEBYSCORE', key, 0, nowTicks - windowTicks)
local existing = redis.call('ZCARD', key)
if existing >= limit then
local oldest = ''
local oldestEntries = redis.call('ZRANGE', key, 0, 0, 'WITHSCORES')
if #oldestEntries == 2 then oldest = oldestEntries[2] end
redis.call('EXPIRE', key, ttl)
return { 0, existing, oldest }
end
local member = nowTicks .. '-' .. redis.call('INCR', key .. ':seq')
redis.call('ZADD', key, nowTicks, member)
local count = redis.call('ZCARD', key)
redis.call('EXPIRE', key, ttl)
redis.call('EXPIRE', key .. ':seq', ttl)
return { 1, count, '' }
""";
public RedisRateLimitStore(RedisConnectionFactory factory, string keyPrefix, TimeProvider timeProvider)
{
_factory = factory ?? throw new ArgumentNullException(nameof(factory));
_prefix = keyPrefix;
_timeProvider = timeProvider;
}
public async Task TryIncrementAsync(string key, int limit, TimeSpan window, CancellationToken ct = default)
{
ct.ThrowIfCancellationRequested();
var db = await GetDatabaseAsync(ct).ConfigureAwait(false);
var nowTicks = _timeProvider.GetUtcNow().UtcTicks;
var fullKey = _prefix + key;
var raw = await db.ScriptEvaluateAsync(
IncrLuaScript,
new RedisKey[] { fullKey },
new RedisValue[] { nowTicks, window.Ticks, limit }).ConfigureAwait(false);
var arr = (RedisResult[]?)raw;
if (arr is null || arr.Length < 2)
return new RateLimitDecision(true, 0, TimeSpan.Zero);
var allowed = (long)arr[0]! == 1L;
var count = (int)(long)arr[1]!;
var retryAfter = TimeSpan.Zero;
if (!allowed && arr.Length >= 3)
{
var oldestStr = (string?)arr[2];
if (!string.IsNullOrEmpty(oldestStr) && long.TryParse(oldestStr, out var oldestTicks))
{
var elapsed = nowTicks - oldestTicks;
retryAfter = TimeSpan.FromTicks(Math.Max(window.Ticks - elapsed, TimeSpan.TicksPerSecond));
}
}
return new RateLimitDecision(allowed, count, retryAfter);
}
public async Task ResetAsync(string key, CancellationToken ct = default)
{
ct.ThrowIfCancellationRequested();
var db = await GetDatabaseAsync(ct).ConfigureAwait(false);
var fullKey = _prefix + key;
await db.KeyDeleteAsync(new RedisKey[] { fullKey, fullKey + ":seq" }).ConfigureAwait(false);
}
private async Task GetDatabaseAsync(CancellationToken ct)
{
if (_connection is { IsConnected: true })
return _connection.GetDatabase(_factory.Database);
await _connectionLock.WaitAsync(ct).ConfigureAwait(false);
try
{
if (_connection is { IsConnected: true })
return _connection.GetDatabase(_factory.Database);
var config = _factory.Build();
_connection = await ConnectionMultiplexer.ConnectAsync(config).ConfigureAwait(false);
return _connection.GetDatabase(_factory.Database);
}
finally
{
_connectionLock.Release();
}
}
public async ValueTask DisposeAsync()
{
if (_connection is not null)
await _connection.DisposeAsync().ConfigureAwait(false);
_connectionLock.Dispose();
}
public void Dispose()
{
_connection?.Dispose();
_connectionLock.Dispose();
}
}
Path: redb-identity/src/redb.Identity.Core/Services/RoleService.cs
Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.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/RoleService.cs
----
using redb.Core;
using redb.Core.Models.Entities;
using redb.Core.Query;
using redb.Identity.Core.Models;
namespace redb.Identity.Core.Services;
///
/// B.3 — backing implementation for the Roles registry. All shapes go
/// through redb's native LINQ provider so cross-dialect (PG / MSSQL /
/// SQLite) works without per-driver SQL.
///
public sealed class RoleService
{
private readonly IRedbService _redb;
public RoleService(IRedbService redb) => _redb = redb;
// ── Role CRUD ──────────────────────────────────────────────
public async Task> CreateRoleAsync(
string name, string audience, long? applicationId,
string? displayName, string? description,
bool isSystem = false,
CancellationToken ct = default)
{
// Uniqueness check — (Name, Audience, ApplicationId)
var dupe = await _redb.Query()
.Where(p => p.Name == name)
.Where(p => p.Audience == audience)
.Where(p => p.ApplicationId == applicationId)
.FirstOrDefaultAsync()
.ConfigureAwait(false);
if (dupe is not null)
throw new InvalidOperationException(
$"Role '{name}' with audience '{audience}' (app={applicationId?.ToString() ?? "none"}) already exists.");
var obj = new RedbObject
{
name = name,
Props = new RoleProps
{
Name = name,
DisplayName = displayName,
Description = description,
Audience = audience,
ApplicationId = applicationId,
IsSystem = isSystem
}
};
obj.id = await _redb.SaveAsync(obj).ConfigureAwait(false);
return obj;
}
public async Task?> GetRoleAsync(long roleId, CancellationToken ct = default)
=> await _redb.LoadAsync(roleId).ConfigureAwait(false);
public async Task UpdateRoleAsync(
long roleId, string? displayName, string? description, CancellationToken ct = default)
{
var role = await _redb.LoadAsync(roleId).ConfigureAwait(false)
?? throw new InvalidOperationException($"Role {roleId} not found.");
if (displayName is not null) role.Props.DisplayName = displayName;
if (description is not null) role.Props.Description = description;
await _redb.SaveAsync(role).ConfigureAwait(false);
}
public async Task DeleteRoleAsync(long roleId, CancellationToken ct = default)
{
var role = await _redb.LoadAsync(roleId).ConfigureAwait(false)
?? throw new InvalidOperationException($"Role {roleId} not found.");
if (role.Props.IsSystem)
throw new InvalidOperationException("System roles cannot be deleted.");
// Cascade-clean assignments first so we don't leave orphaned rows
// hanging around (foreign-key contract is parent_id → role id).
await CleanAssignmentsAsync(roleId).ConfigureAwait(false);
await _redb.DeleteAsync(role).ConfigureAwait(false);
}
///
/// Paged search across all roles, with optional name pattern + audience
/// filter + application filter. Audience='application' + applicationId
/// supplied narrows to one app's roles.
///
public async Task<(List> Items, int Total)> SearchRolesAsync(
string? namePattern, string? audience, long? applicationId,
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(audience))
query = query.Where(p => p.Audience == audience);
if (applicationId is not null)
query = query.Where(p => p.ApplicationId == applicationId);
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);
}
// ── Assignments ────────────────────────────────────────────
public async Task AssignUserAsync(long roleId, long userId, long? actingUserId, CancellationToken ct = default)
{
// Idempotent — skip if row already exists with same role+user.
var existing = await _redb.Query()
.WhereRedb(o => o.ParentId == roleId)
.WhereRedb(o => o.Key == userId)
.FirstOrDefaultAsync()
.ConfigureAwait(false);
if (existing is not null) return;
var obj = new RedbObject(new UserRoleAssignmentProps
{
AssignedAt = DateTimeOffset.UtcNow,
AssignedByUserId = actingUserId
})
{
name = $"user:{userId}",
key = userId,
parent_id = roleId,
value_long = userId
};
await _redb.SaveAsync(obj).ConfigureAwait(false);
}
public async Task UnassignUserAsync(long roleId, long userId, CancellationToken ct = default)
{
var existing = await _redb.Query()
.WhereRedb(o => o.ParentId == roleId)
.WhereRedb(o => o.Key == userId)
.FirstOrDefaultAsync()
.ConfigureAwait(false);
if (existing is null) return;
await _redb.DeleteAsync(existing).ConfigureAwait(false);
}
public async Task AssignGroupAsync(long roleId, long groupId, long? actingUserId, CancellationToken ct = default)
{
var existing = await _redb.Query()
.WhereRedb(o => o.ParentId == roleId)
.WhereRedb(o => o.Key == groupId)
.FirstOrDefaultAsync()
.ConfigureAwait(false);
if (existing is not null) return;
var obj = new RedbObject(new GroupRoleAssignmentProps
{
AssignedAt = DateTimeOffset.UtcNow,
AssignedByUserId = actingUserId
})
{
name = $"group:{groupId}",
key = groupId,
parent_id = roleId,
value_long = groupId
};
await _redb.SaveAsync(obj).ConfigureAwait(false);
}
public async Task UnassignGroupAsync(long roleId, long groupId, CancellationToken ct = default)
{
var existing = await _redb.Query()
.WhereRedb(o => o.ParentId == roleId)
.WhereRedb(o => o.Key == groupId)
.FirstOrDefaultAsync()
.ConfigureAwait(false);
if (existing is null) return;
await _redb.DeleteAsync(existing).ConfigureAwait(false);
}
private async Task CleanAssignmentsAsync(long roleId)
{
var users = await _redb.Query()
.WhereRedb(o => o.ParentId == roleId)
.ToListAsync()
.ConfigureAwait(false);
foreach (var u in users) await _redb.DeleteAsync(u).ConfigureAwait(false);
var groups = await _redb.Query()
.WhereRedb(o => o.ParentId == roleId)
.ToListAsync()
.ConfigureAwait(false);
foreach (var g in groups) await _redb.DeleteAsync(g).ConfigureAwait(false);
}
// ── Queries (assignees + per-user role set) ────────────────
///
/// Returns (userIds, groupIds) currently assigned to .
///
public async Task<(List UserIds, List GroupIds)> ListAssigneesAsync(long roleId, CancellationToken ct = default)
{
var users = await _redb.Query()
.WhereRedb(o => o.ParentId == roleId)
.ToListAsync()
.ConfigureAwait(false);
var groups = await _redb.Query()
.WhereRedb(o => o.ParentId == roleId)
.ToListAsync()
.ConfigureAwait(false);
return (
users.Where(u => u.value_long.HasValue).Select(u => u.value_long!.Value).Distinct().ToList(),
groups.Where(g => g.value_long.HasValue).Select(g => g.value_long!.Value).Distinct().ToList());
}
///
/// Bulk per-role assignment count for the list page badge.
///
public async Task> CountAssignmentsByRoleAsync(
IEnumerable roleIds, CancellationToken ct = default)
{
var ids = roleIds.Distinct().ToList();
if (ids.Count == 0) return new();
var users = await _redb.Query()
.WhereInRedb(o => o.ParentId, ids.Cast())
.ToListAsync()
.ConfigureAwait(false);
var groups = await _redb.Query()
.WhereInRedb(o => o.ParentId, ids.Cast())
.ToListAsync()
.ConfigureAwait(false);
var counts = new Dictionary();
foreach (var u in users)
{
if (u.parent_id is { } pid) counts[pid] = counts.GetValueOrDefault(pid) + 1;
}
foreach (var g in groups)
{
if (g.parent_id is { } pid) counts[pid] = counts.GetValueOrDefault(pid) + 1;
}
return counts;
}
// ── Scope attachments ──────────────────────────────────────
public async Task AttachScopeAsync(long roleId, long scopeId, long? actingUserId, CancellationToken ct = default)
{
var existing = await _redb.Query()
.WhereRedb(o => o.ParentId == roleId)
.WhereRedb(o => o.Key == scopeId)
.FirstOrDefaultAsync()
.ConfigureAwait(false);
if (existing is not null) return;
var obj = new RedbObject(new RoleScopeAssignmentProps
{
AttachedAt = DateTimeOffset.UtcNow,
AttachedByUserId = actingUserId
})
{
name = $"scope:{scopeId}",
key = scopeId,
parent_id = roleId,
value_long = scopeId
};
await _redb.SaveAsync(obj).ConfigureAwait(false);
}
public async Task DetachScopeAsync(long roleId, long scopeId, CancellationToken ct = default)
{
var existing = await _redb.Query()
.WhereRedb(o => o.ParentId == roleId)
.WhereRedb(o => o.Key == scopeId)
.FirstOrDefaultAsync()
.ConfigureAwait(false);
if (existing is null) return;
await _redb.DeleteAsync(existing).ConfigureAwait(false);
}
///
/// List scope IDs currently attached to .
///
public async Task> ListScopeIdsForRoleAsync(long roleId, CancellationToken ct = default)
{
var rows = await _redb.Query()
.WhereRedb(o => o.ParentId == roleId)
.ToListAsync()
.ConfigureAwait(false);
return rows
.Where(r => r.value_long.HasValue)
.Select(r => r.value_long!.Value)
.Distinct()
.ToList();
}
///
/// Effective scope set for a set of roles — union of every role's
/// attached scopes. Returns the SCOPE NAMES (string), ready to merge
/// into the principal's scope list at token issuance.
///
public async Task> GetEffectiveScopeNamesAsync(
IEnumerable roleIds, CancellationToken ct = default)
{
var ids = roleIds.Distinct().ToList();
if (ids.Count == 0) return new(StringComparer.Ordinal);
var rows = await _redb.Query()
.WhereInRedb(o => o.ParentId, ids.Cast())
.ToListAsync()
.ConfigureAwait(false);
var scopeIds = rows
.Where(r => r.value_long.HasValue)
.Select(r => r.value_long!.Value)
.Distinct()
.ToList();
if (scopeIds.Count == 0) return new(StringComparer.Ordinal);
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 legacy rows.
return scopes
.Select(s => s.Props.ScopeName ?? s.value_string)
.Where(n => !string.IsNullOrEmpty(n))
.Select(n => n!)
.ToHashSet(StringComparer.Ordinal);
}
///
/// Effective role set for a user at token issuance time:
/// direct user assignments ∪ assignments inherited from every group
/// the user belongs to. Filtered by audience and applicationId so an
/// audience='application' role bound to app A doesn't leak into a
/// token issued for app B.
///
public async Task>> GetEffectiveRolesAsync(
long userId,
IEnumerable groupIds,
long? applicationId,
CancellationToken ct = default)
{
var groupIdList = groupIds.Distinct().ToList();
// Direct user assignments → role ids
var userAssignments = await _redb.Query()
.WhereRedb(o => o.Key == userId)
.ToListAsync()
.ConfigureAwait(false);
var roleIds = userAssignments
.Where(u => u.parent_id.HasValue)
.Select(u => u.parent_id!.Value)
.ToHashSet();
// Group → role ids
if (groupIdList.Count > 0)
{
var groupAssignments = await _redb.Query()
.WhereInRedb(o => o.Key, groupIdList.Cast())
.ToListAsync()
.ConfigureAwait(false);
foreach (var g in groupAssignments)
{
if (g.parent_id.HasValue) roleIds.Add(g.parent_id.Value);
}
}
if (roleIds.Count == 0) return new();
// Bulk-load the roles in one round trip, filter on audience.
var roles = await _redb.Query()
.WhereInRedb(o => o.Id, roleIds.Cast())
.ToListAsync()
.ConfigureAwait(false);
return roles.Where(r =>
{
if (r.Props.Audience == "organization") return true;
// audience='application' → only emit when applicationId matches.
return applicationId.HasValue && r.Props.ApplicationId == applicationId.Value;
}).ToList();
}
}
Path: redb-identity/src/redb.Identity.Core/Services/SeedAdminPasswordHostedService.cs
Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.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/SeedAdminPasswordHostedService.cs
----
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using redb.Core;
using redb.Identity.Core.Configuration;
using redb.Route.Abstractions;
namespace redb.Identity.Core.Services;
///
/// Startup seeder that ensures the well-known admin user from the base
/// redb SQL seed (_users.id = 1, login = "admin", empty password)
/// has a usable password on a fresh install. Behaviour:
///
/// - Resolves through a transient scope.
/// - Looks up user by .
/// - If the user is missing → no-op.
/// - If the user has a stored password other than the documented default
/// admin → no-op with one log line: that password belongs to the operator
/// (set via the Tsak dashboard, bootstrap-admin or the management API).
/// - If the stored password is empty, or is still the default admin
/// (a Tsak dashboard sharing the database writes admin/admin before this
/// listener runs), hashes via the
/// configured chain and
/// persists it via .
///
/// Always logs a loud WARNING on startup when the configured password is
/// the documented default admin, regardless of whether a write was needed.
///
/// Implemented as an hooked into
/// rather than an
/// IHostedService because Tsak hosts modules without a generic IHost;
/// route-context lifecycle hooks are the canonical startup extension point and
/// fire on every cold-start AND on every hot-reload of the .tpkg module.
///
///
public sealed class SeedAdminPasswordHostedService : IRouteLifecycleListener
{
private readonly IServiceProvider _serviceProvider;
private readonly IOptions _options;
private readonly ILogger _logger;
public SeedAdminPasswordHostedService(
IServiceProvider serviceProvider,
IOptions options,
ILogger logger)
{
_serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));
_options = options ?? throw new ArgumentNullException(nameof(options));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
public async Task OnContextStarting(IRouteContext context, CancellationToken cancellationToken)
{
var seed = _options.Value.SeedAdmin;
if (!seed.Enabled)
{
_logger.LogDebug("SeedAdmin disabled — skipping default-password seeding");
return;
}
if (string.IsNullOrWhiteSpace(seed.Login) || string.IsNullOrEmpty(seed.Password))
{
_logger.LogWarning(
"SeedAdmin enabled but Login/Password is empty — skipping (login='{Login}')",
seed.Login);
return;
}
WarnIfDefaultPassword(seed);
try
{
using var scope = _serviceProvider.CreateScope();
var redb = scope.ServiceProvider.GetRequiredService();
var user = await redb.UserProvider.GetUserByLoginAsync(seed.Login).ConfigureAwait(false);
if (user is null)
{
_logger.LogInformation(
"SeedAdmin: user '{Login}' not found in _users — nothing to seed",
seed.Login);
return;
}
if (!string.IsNullOrEmpty(user.Password))
{
// A password is already stored. Replace it only while it is still the documented
// default: a host that shares the database with the Tsak dashboard sees the dashboard
// write admin/admin before this listener runs. Any other password belongs to the
// operator and stays.
if (string.Equals(seed.Password, SeedAdminOptions.DefaultPassword, StringComparison.Ordinal))
{
_logger.LogDebug(
"SeedAdmin: user '{Login}' (id={Id}) already has a stored password and no other is configured",
seed.Login, user.Id);
return;
}
var storedIsDefault = await redb.UserProvider
.ValidateUserAsync(seed.Login, SeedAdminOptions.DefaultPassword)
.ConfigureAwait(false) is not null;
if (!storedIsDefault)
{
_logger.LogInformation(
"SeedAdmin: user '{Login}' (id={Id}) already has a changed password, seed skipped",
seed.Login, user.Id);
return;
}
}
var ok = await redb.UserProvider
.SetPasswordAsync(user, seed.Password, currentUser: user)
.ConfigureAwait(false);
if (ok)
{
_logger.LogInformation(
"SeedAdmin: hashed and stored default password for user '{Login}' (id={Id})",
seed.Login, user.Id);
}
else
{
_logger.LogWarning(
"SeedAdmin: SetPasswordAsync returned false for user '{Login}' (id={Id})",
seed.Login, user.Id);
}
}
catch (Exception ex)
{
// Never fail host startup over the convenience seeder. Worst case: the
// operator hits the bootstrap-admin endpoint or sets the password manually.
_logger.LogError(ex,
"SeedAdmin: unexpected failure while seeding password for user '{Login}'",
seed.Login);
}
}
private void WarnIfDefaultPassword(SeedAdminOptions seed)
{
if (!string.Equals(seed.Password, SeedAdminOptions.DefaultPassword, StringComparison.Ordinal))
return;
_logger.LogWarning(
"============================================================");
_logger.LogWarning(
" SECURITY WARNING: SeedAdmin password for '{Login}' is the");
_logger.LogWarning(
" documented default ('admin'). This is intended for FRESH");
_logger.LogWarning(
" development installs only. Rotate it via the management API");
_logger.LogWarning(
" or set Identity:SeedAdmin:Password before exposing this");
_logger.LogWarning(
" host to untrusted networks.");
_logger.LogWarning(
"============================================================");
}
}
Path: redb-identity/src/redb.Identity.Core/Services/SeedBackchannelClientHostedService.cs
Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.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/SeedBackchannelClientHostedService.cs
----
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using OpenIddict.Abstractions;
using redb.Identity.Core.Configuration;
using redb.Route.Abstractions;
namespace redb.Identity.Core.Services;
///
/// W6-0 — sister of . Ensures the
/// client_credentials backchannel service-account OpenIddict application
/// exists on host startup. The Web BFF uses this account to publish
/// (POST /api/v1/identity/revoked-sids) and poll
/// (GET /api/v1/identity/revoked-sids/since) the cluster-wide revoked-sids
/// list for backchannel logout.
///
/// Behaviour:
///
/// - No-op when is false.
/// - No-op when the application already exists (idempotent across restarts).
/// - Logs and skips when is empty —
/// client_credentials requires a confidential client (RFC 6749 §4.4).
/// - Never throws — operators can always provision the client manually via the
/// management API.
///
///
///
public sealed class SeedBackchannelClientHostedService : IRouteLifecycleListener
{
private readonly IServiceProvider _serviceProvider;
private readonly IOptions _options;
private readonly ILogger _logger;
public SeedBackchannelClientHostedService(
IServiceProvider serviceProvider,
IOptions options,
ILogger logger)
{
_serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));
_options = options ?? throw new ArgumentNullException(nameof(options));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
public async Task OnContextStarting(IRouteContext context, CancellationToken cancellationToken)
{
var seed = _options.Value.SeedBackchannelClient;
if (!seed.Enabled)
{
_logger.LogDebug("SeedBackchannelClient disabled — skipping");
return;
}
if (string.IsNullOrWhiteSpace(seed.ClientId))
{
_logger.LogWarning("SeedBackchannelClient enabled but ClientId is empty — skipping");
return;
}
if (string.IsNullOrEmpty(seed.ClientSecret))
{
_logger.LogWarning(
"SeedBackchannelClient enabled but ClientSecret is empty — client_credentials requires a confidential client. Skipping.");
return;
}
try
{
using var scope = _serviceProvider.CreateScope();
var manager = scope.ServiceProvider.GetRequiredService();
var existing = await manager.FindByClientIdAsync(seed.ClientId, cancellationToken).ConfigureAwait(false);
if (existing is not null)
{
_logger.LogDebug(
"SeedBackchannelClient: client '{ClientId}' already exists — leaving untouched",
seed.ClientId);
return;
}
var descriptor = new OpenIddictApplicationDescriptor
{
ClientId = seed.ClientId,
ClientSecret = seed.ClientSecret,
ClientType = OpenIddictConstants.ClientTypes.Confidential,
ConsentType = OpenIddictConstants.ConsentTypes.Implicit,
DisplayName = seed.DisplayName,
ApplicationType = OpenIddictConstants.ApplicationTypes.Web,
};
descriptor.Permissions.Add(OpenIddictConstants.Permissions.Endpoints.Token);
descriptor.Permissions.Add(OpenIddictConstants.Permissions.GrantTypes.ClientCredentials);
foreach (var s in seed.Scopes)
descriptor.Permissions.Add(OpenIddictConstants.Permissions.Prefixes.Scope + s);
await manager.CreateAsync(descriptor, cancellationToken).ConfigureAwait(false);
_logger.LogInformation(
"SeedBackchannelClient: registered backchannel service account '{ClientId}' with scopes [{Scopes}]",
seed.ClientId, string.Join(", ", seed.Scopes));
}
catch (Exception ex)
{
_logger.LogError(ex,
"SeedBackchannelClient: unexpected failure while seeding client '{ClientId}'",
_options.Value.SeedBackchannelClient.ClientId);
}
}
}
Path: redb-identity/src/redb.Identity.Core/Services/SeedWebClientHostedService.cs
Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.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/SeedWebClientHostedService.cs
----
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using OpenIddict.Abstractions;
using redb.Identity.Core.Configuration;
using redb.Route.Abstractions;
namespace redb.Identity.Core.Services;
///
/// Startup seeder that ensures the canonical Web Console OIDC client (default
/// identity-web) exists in the OpenIddict application store. Sister to
/// — together they make a fresh
/// install runnable end-to-end with no manual bootstrap step:
///
/// - hashes the default
/// password for the seeded admin user.
/// - This service registers the OIDC client so the Web BFF can complete
/// /connect/authorize.
///
/// Behaviour:
///
/// - Resolves via a transient scope.
/// - Looks up the client by .
/// - If found → no-op (idempotent across restarts; respects clients
/// created by bootstrap-admin / dynamic registration / management API).
/// - Otherwise creates a Public client (or Confidential when a
/// is supplied) with
/// authorization_code + refresh_token + PKCE-required.
///
/// Convenience for fresh dev/demo deployments only — production should disable
/// this and provision clients explicitly via the management API.
///
/// Implemented as an hooked into
/// — Tsak modules have
/// no generic IHost, so route-context lifecycle is the canonical startup
/// extension point.
///
///
public sealed class SeedWebClientHostedService : IRouteLifecycleListener
{
private readonly IServiceProvider _serviceProvider;
private readonly IOptions _options;
private readonly ILogger _logger;
public SeedWebClientHostedService(
IServiceProvider serviceProvider,
IOptions options,
ILogger logger)
{
_serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));
_options = options ?? throw new ArgumentNullException(nameof(options));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
public async Task OnContextStarting(IRouteContext context, CancellationToken cancellationToken)
{
var seed = _options.Value.SeedWebClient;
if (!seed.Enabled)
{
_logger.LogDebug("SeedWebClient disabled — skipping default OIDC client seeding");
return;
}
if (string.IsNullOrWhiteSpace(seed.ClientId))
{
_logger.LogWarning("SeedWebClient enabled but ClientId is empty — skipping");
return;
}
try
{
using var scope = _serviceProvider.CreateScope();
var manager = scope.ServiceProvider.GetRequiredService();
var existing = await manager
.FindByClientIdAsync(seed.ClientId, cancellationToken)
.ConfigureAwait(false);
if (existing is not null)
{
_logger.LogDebug(
"SeedWebClient: OIDC client '{ClientId}' already exists — leaving untouched",
seed.ClientId);
return;
}
var isPublic = string.IsNullOrEmpty(seed.ClientSecret);
var descriptor = new OpenIddictApplicationDescriptor
{
ClientId = seed.ClientId,
ClientSecret = isPublic ? null : seed.ClientSecret,
ClientType = isPublic
? OpenIddictConstants.ClientTypes.Public
: OpenIddictConstants.ClientTypes.Confidential,
ConsentType = OpenIddictConstants.ConsentTypes.Implicit,
DisplayName = seed.DisplayName,
ApplicationType = OpenIddictConstants.ApplicationTypes.Web,
};
foreach (var uri in seed.RedirectUris)
{
if (Uri.TryCreate(uri, UriKind.Absolute, out var parsed))
descriptor.RedirectUris.Add(parsed);
else
_logger.LogWarning("SeedWebClient: skipping invalid RedirectUri '{Uri}'", uri);
}
foreach (var uri in seed.PostLogoutRedirectUris)
{
if (Uri.TryCreate(uri, UriKind.Absolute, out var parsed))
descriptor.PostLogoutRedirectUris.Add(parsed);
else
_logger.LogWarning("SeedWebClient: skipping invalid PostLogoutRedirectUri '{Uri}'", uri);
}
// Endpoint + grant + response permissions required for code+PKCE+refresh.
var permissions = new List
{
OpenIddictConstants.Permissions.Endpoints.Authorization,
OpenIddictConstants.Permissions.Endpoints.Token,
OpenIddictConstants.Permissions.Endpoints.EndSession,
OpenIddictConstants.Permissions.GrantTypes.AuthorizationCode,
OpenIddictConstants.Permissions.GrantTypes.RefreshToken,
OpenIddictConstants.Permissions.ResponseTypes.Code,
};
// Map scope names to the appropriate OpenIddict permission constants.
// Standard OIDC scopes have dedicated permission constants; everything
// else goes through the generic Scope: prefix.
foreach (var s in seed.Scopes)
{
var perm = s switch
{
"openid" => OpenIddictConstants.Permissions.Prefixes.Scope + "openid",
"profile" => OpenIddictConstants.Permissions.Scopes.Profile,
"email" => OpenIddictConstants.Permissions.Scopes.Email,
"roles" => OpenIddictConstants.Permissions.Scopes.Roles,
"phone" => OpenIddictConstants.Permissions.Scopes.Phone,
"address" => OpenIddictConstants.Permissions.Scopes.Address,
"offline_access" => OpenIddictConstants.Permissions.Prefixes.Scope + "offline_access",
_ => OpenIddictConstants.Permissions.Prefixes.Scope + s,
};
permissions.Add(perm);
}
foreach (var p in permissions)
descriptor.Permissions.Add(p);
// PKCE is mandatory for public clients (and best-practice for confidential).
descriptor.Requirements.Add(
OpenIddictConstants.Requirements.Features.ProofKeyForCodeExchange);
await manager.CreateAsync(descriptor, cancellationToken).ConfigureAwait(false);
_logger.LogInformation(
"SeedWebClient: registered OIDC client '{ClientId}' ({ClientType}) with {RedirectCount} redirect uri(s) and scopes [{Scopes}]",
seed.ClientId,
isPublic ? "public" : "confidential",
seed.RedirectUris.Count,
string.Join(", ", seed.Scopes));
}
catch (Exception ex)
{
// Never fail host startup over the convenience seeder. Operators can
// always provision the client manually via the management API or the
// bootstrap-admin endpoint.
_logger.LogError(ex,
"SeedWebClient: unexpected failure while seeding OIDC client '{ClientId}'",
_options.Value.SeedWebClient.ClientId);
}
}
}
Path: redb-identity/src/redb.Identity.Core/Services/SessionService.cs
Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.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/SessionService.cs
----
using Microsoft.Extensions.Options;
using redb.Core;
using redb.Core.Models.Entities;
using redb.Identity.Core.Configuration;
using redb.Identity.Core.Models;
namespace redb.Identity.Core.Services;
///
/// Manages user login sessions. Sessions track when a user logged into an application.
/// Revoking sessions cascades to revoking all authorizations (which invalidates tokens).
///
public sealed class SessionService
{
private readonly IRedbService _redb;
private readonly TimeProvider _timeProvider;
private readonly TimeSpan _idleTimeout;
private readonly TimeSpan _absoluteTimeout;
public SessionService(IRedbService redb)
: this(redb, TimeProvider.System, null)
{
}
public SessionService(IRedbService redb, TimeProvider? timeProvider)
: this(redb, timeProvider, null)
{
}
public SessionService(IRedbService redb, TimeProvider? timeProvider, IOptions? options)
{
_redb = redb;
_timeProvider = timeProvider ?? TimeProvider.System;
// No DI source → fall back to industry-default 24 h idle / 30 d absolute.
// Same defaults as RedbIdentityOptions; declared twice so a SessionService
// built without options (legacy call sites) doesn't fail-open with
// TimeSpan.Zero.
_idleTimeout = options?.Value.SessionIdleTimeout ?? TimeSpan.FromHours(24);
_absoluteTimeout = options?.Value.SessionAbsoluteTimeout ?? TimeSpan.FromDays(30);
}
///
/// S-track: is this session beyond either timeout? Mirrors the check done
/// at (lazy) and
/// (eager).
///
public bool IsExpired(SessionProps props, DateTimeOffset? createdAt, DateTimeOffset now)
{
if (createdAt is { } c && now - c > _absoluteTimeout) return true;
if (props.LastAccessedAt is { } la && now - la > _idleTimeout) return true;
return false;
}
///
/// Creates a new active session record. ,
/// and are optional device-identification fields populated by
/// the HTTP authentication processors from the calling request's headers.
///
public async Task> CreateAsync(
long userId, long applicationObjectId,
bool mfaVerified = false, string? mfaMethod = null,
string? ipAddress = null, string? userAgent = null, string? deviceLabel = null,
CancellationToken ct = default)
{
var now = _timeProvider.GetUtcNow();
var session = new RedbObject
{
key = userId,
Props = new SessionProps
{
ApplicationObjectId = applicationObjectId,
Status = "active",
MfaVerified = mfaVerified,
MfaMethod = mfaMethod,
IpAddress = ipAddress,
UserAgent = userAgent,
DeviceLabel = deviceLabel,
LastAccessedAt = now,
LastAccessedBy = "create",
}
};
session.id = await _redb.SaveAsync(session).ConfigureAwait(false);
return session;
}
///
/// S-track: bump LastAccessedAt on the given session. Called by
/// on
/// refresh_token grant, by the cookie OnValidatePrincipal handler, and
/// by /connect/userinfo. is a short label
/// stored for diagnostics ("refresh_token", "cookie", "userinfo").
/// No-op (returns false) when the session doesn't exist or is revoked.
///
public async Task TouchAsync(long sessionId, string activity, CancellationToken ct = default)
{
if (sessionId <= 0) return false;
var session = await _redb.LoadAsync(sessionId).ConfigureAwait(false);
if (session is null || session.Props.Status != "active") return false;
session.Props.LastAccessedAt = _timeProvider.GetUtcNow();
session.Props.LastAccessedBy = activity;
await _redb.SaveAsync(session).ConfigureAwait(false);
return true;
}
///
/// Records that obtained tokens through session
/// (). Idempotent. The
/// append runs under a row lock: two authorization requests from the same browser (two tabs, two
/// relying parties) must not lose each other's entry, because a lost entry is a relying party that is
/// never told about the logout. Returns false for an unknown or revoked session.
///
public async Task BindClientAsync(long sessionId, long applicationObjectId, CancellationToken ct = default)
{
if (sessionId <= 0 || applicationObjectId <= 0) return false;
return await _redb.Context.ExecuteAtomicAsync(async () =>
{
await _redb.LockForUpdateAsync([sessionId], ct).ConfigureAwait(false);
var session = await _redb.LoadAsync(sessionId).ConfigureAwait(false);
if (session is null || session.Props.Status != "active") return false;
var bound = session.Props.ClientApplicationIds ?? [];
if (bound.Contains(applicationObjectId)) return true;
session.Props.ClientApplicationIds = [.. bound, applicationObjectId];
await _redb.SaveAsync(session).ConfigureAwait(false);
return true;
}, ct).ConfigureAwait(false);
}
///
/// Checks whether a specific session (by its object ID) has been revoked.
/// Returns true if the session exists and is revoked, false otherwise.
///
public async Task IsSessionRevokedAsync(long sessionObjectId, CancellationToken ct = default)
{
if (sessionObjectId <= 0)
return false;
var session = await _redb.LoadAsync(sessionObjectId)
.ConfigureAwait(false);
return session?.Props.Status == "revoked";
}
///
/// Checks whether the user's sessions have been revoked (indicating explicit logout).
/// Returns true only if revoked sessions exist AND there are zero active ones.
/// If no sessions exist at all (first authorize), returns false (not revoked).
///
public async Task IsFullyRevokedAsync(
long userId, TimeSpan? lookbackWindow = null, CancellationToken ct = default)
{
var sessions = await _redb.Query()
.WhereRedb(o => o.Key == userId)
.ToListAsync()
.ConfigureAwait(false);
// Only consider sessions within the lookback window (default: all).
// Sessions older than the cookie lifetime are irrelevant — any cookie from that era
// has already expired, so revoked sessions from previous login generations don't matter.
if (lookbackWindow.HasValue)
{
var cutoff = _timeProvider.GetUtcNow() - lookbackWindow.Value;
sessions = sessions
.Where(s => s.date_create >= cutoff)
.ToList();
}
// No sessions at all — user hasn't authorized yet, not revoked
if (sessions.Count == 0)
return false;
// If any session is active, not fully revoked
return sessions.All(s => s.Props.Status == "revoked");
}
///
/// Lists all active sessions for a user. Includes application info.
///
/// Application metadata is fetched in a single batched WhereInRedb(o => o.Id, ids)
/// query rather than per-row — a user with many
/// active sessions across multiple clients would otherwise turn this admin endpoint
/// into an O(N) round-trip storm.
///
///
public async Task> ListAsync(long userId, CancellationToken ct = default)
{
var sessions = await _redb.Query()
.WhereRedb(o => o.Key == userId)
.Where(s => s.Status == "active")
.ToListAsync()
.ConfigureAwait(false);
// S-track: lazy-expire any active rows that have crossed either
// timeout. Mark + persist + drop from the result so the caller sees
// only sessions actually still alive. Eager cleanup also runs in
// SessionCleanupProcessor for tenants where the user never lists.
var now = _timeProvider.GetUtcNow();
var stillAlive = new List>(sessions.Count);
foreach (var s in sessions)
{
if (IsExpired(s.Props, s.date_create, now))
{
s.Props.Status = "revoked";
await _redb.SaveAsync(s).ConfigureAwait(false);
}
else
{
stillAlive.Add(s);
}
}
sessions = stillAlive;
// Batch-fetch every distinct ApplicationProps in ONE query to avoid N+1.
var appIds = sessions
.Where(s => s.Props.ApplicationObjectId > 0)
.Select(s => s.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(sessions.Count);
foreach (var session in sessions)
{
string? clientId = null;
string? appName = null;
if (session.Props.ApplicationObjectId > 0
&& appsById.TryGetValue(session.Props.ApplicationObjectId, out var app))
{
clientId = app.Props.ClientId;
appName = app.Name;
}
result.Add(new SessionInfo
{
SessionId = session.id,
UserId = session.key ?? 0,
ApplicationObjectId = session.Props.ApplicationObjectId,
ClientId = clientId,
ApplicationName = appName,
Status = session.Props.Status ?? "active",
CreatedAt = session.date_create,
IpAddress = session.Props.IpAddress,
UserAgent = session.Props.UserAgent,
DeviceLabel = session.Props.DeviceLabel,
LastAccessedAt = session.Props.LastAccessedAt,
LastAccessedBy = session.Props.LastAccessedBy
});
}
return result;
}
///
/// Admin-wide list of recent active sessions across ALL users, paginated.
/// Powers the /admin/sessions browse-by-default page (WSO2-style). The
/// per-user stays the targeted path; this one is
/// the operator's first-look "what's alive right now" view.
///
public async Task<(List Items, int Total)> ListAllActiveAsync(
int offset, int count, CancellationToken ct = default)
{
offset = Math.Max(0, offset);
count = Math.Clamp(count, 1, 200);
var total = (int)await _redb.Query()
.Where(s => s.Status == "active")
.CountAsync()
.ConfigureAwait(false);
var sessions = await _redb.Query()
.Where(s => s.Status == "active")
.OrderByDescendingRedb(o => o.Id)
.Skip(offset)
.Take(count)
.ToListAsync()
.ConfigureAwait(false);
var appIds = sessions
.Where(s => s.Props.ApplicationObjectId > 0)
.Select(s => s.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 items = new List(sessions.Count);
foreach (var s in sessions)
{
string? clientId = null;
string? appName = null;
if (s.Props.ApplicationObjectId > 0
&& appsById.TryGetValue(s.Props.ApplicationObjectId, out var app))
{
clientId = app.Props.ClientId ?? app.value_string;
appName = app.name;
}
items.Add(new SessionInfo
{
SessionId = s.id,
UserId = s.key ?? 0,
ApplicationObjectId = s.Props.ApplicationObjectId,
ClientId = clientId,
ApplicationName = appName,
Status = s.Props.Status,
CreatedAt = s.date_create,
IpAddress = s.Props.IpAddress,
UserAgent = s.Props.UserAgent,
DeviceLabel = s.Props.DeviceLabel,
LastAccessedAt = s.Props.LastAccessedAt,
LastAccessedBy = s.Props.LastAccessedBy
});
}
return (items, total);
}
///
/// Revokes a single session by its object ID.
///
public async Task RevokeAsync(long sessionObjectId, CancellationToken ct = default)
{
var session = await _redb.LoadAsync(sessionObjectId)
.ConfigureAwait(false);
if (session is null || session.Props.Status == "revoked")
return 0;
session.Props.Status = "revoked";
await _redb.SaveAsync(session).ConfigureAwait(false);
return 1;
}
///
/// Revokes all active sessions for a user.
///
/// Mutated rows are persisted in a single batched SaveAsync(IEnumerable<...>)
/// call rather than per-row inside the loop \u2014 a power user with many open device
/// sessions otherwise turned this admin / logout step into an O(N) round-trip storm.
///
///
public async Task RevokeAllAsync(long userId, CancellationToken ct = default)
{
var sessions = await _redb.Query()
.WhereRedb(o => o.Key == userId)
.Where(s => s.Status == "active")
.ToListAsync()
.ConfigureAwait(false);
if (sessions.Count == 0)
return 0;
foreach (var session in sessions)
session.Props.Status = "revoked";
await _redb.SaveAsync(sessions).ConfigureAwait(false);
return sessions.Count;
}
///
/// N7-4 dry-run: returns how many active sessions would
/// revoke plus a small sample of their ids, WITHOUT mutating any rows. Intended as the
/// preview backing for admin destructive-operation confirmation flows.
///
public async Task<(int Count, IReadOnlyList SampleSessionIds)> PreviewRevokeAllAsync(
long userId, CancellationToken ct = default)
{
const int sampleSize = 10;
var ids = await _redb.Query()
.WhereRedb(o => o.Key == userId)
.Where(s => s.Status == "active")
.Select(o => o.Id)
.ToListAsync()
.ConfigureAwait(false);
return (ids.Count, ids.Take(sampleSize).ToList());
}
///
/// Signs the user out everywhere: every active session, every authorization and every valid token of
/// theirs is revoked, so nothing issued to the user keeps working. This is what a password change or
/// reset, an operator's logout, a SCIM deactivation and a user disable rely on.
///
/// Authorizations and tokens are written by the OpenIddict stores and keyed by the user's public
/// subject (value_guid), not by the internal user id the sessions carry in Key. Tokens
/// are revoked on their own, not only through their authorization: the password grant issues refresh
/// tokens with no authorization row, and a revoked authorization leaves an already issued access token
/// valid until it expires, while a revoked token entry is refused at introspection and on refresh.
///
///
/// Every revocation is flushed via batched SaveAsync(IEnumerable<...>) rather than per
/// row: a user with many consents and rotated refresh tokens would otherwise turn this into hundreds
/// of round-trips.
///
///
/// Number of sessions revoked.
public async Task LogoutAsync(long userId, CancellationToken ct = default)
{
// 1. Revoke all active sessions
var sessionCount = await RevokeAllAsync(userId, ct).ConfigureAwait(false);
// 2. Every grant of the user, by public subject.
var subject = await ResolveSubjectAsync(userId).ConfigureAwait(false);
if (subject == Guid.Empty)
return sessionCount;
var auths = await _redb.Query()
.WhereRedb(o => o.ValueGuid == subject)
.Where(a => a.Status != "revoked")
.ToListAsync()
.ConfigureAwait(false);
if (auths.Count > 0)
{
foreach (var auth in auths)
auth.Props.Status = "revoked";
await _redb.SaveAsync(auths).ConfigureAwait(false);
}
var tokens = await _redb.Query()
.WhereRedb(o => o.ValueGuid == subject)
.Where(t => t.Status == "valid")
.ToListAsync()
.ConfigureAwait(false);
if (tokens.Count > 0)
{
foreach (var token in tokens)
Stores.TokenStatus.Set(token, global::OpenIddict.Abstractions.OpenIddictConstants.Statuses.Revoked);
await _redb.SaveAsync(tokens).ConfigureAwait(false);
}
return sessionCount;
}
///
/// The user's public subject GUID \u2014 the sub of every token and the value_guid the
/// OpenIddict stores key authorizations and tokens by. It lives on the UserProps object whose
/// Key is the core user id. when the user has no such object, and
/// then there are no grants to revoke either.
///
private async Task ResolveSubjectAsync(long userId)
{
var userProps = await _redb.Query()
.WhereRedb(o => o.Key == userId)
.FirstOrDefaultAsync()
.ConfigureAwait(false);
return userProps?.value_guid ?? Guid.Empty;
}
/// Session info DTO for API responses.
public sealed class SessionInfo
{
public long SessionId { get; set; }
public long UserId { get; set; }
public long ApplicationObjectId { get; set; }
public string? ClientId { get; set; }
public string? ApplicationName { get; set; }
public string Status { get; set; } = "active";
public DateTimeOffset? CreatedAt { get; set; }
/// Client IP captured at session creation. null for non-HTTP transports.
public string? IpAddress { get; set; }
/// Raw User-Agent header at session creation. Truncated to 512 chars by extractor.
public string? UserAgent { get; set; }
/// Human-friendly device label (e.g. "Chrome 135 on Windows 10") parsed from .
public string? DeviceLabel { get; set; }
/// S-track: last activity timestamp (refresh_token / cookie / userinfo). Null on legacy rows.
public DateTimeOffset? LastAccessedAt { get; set; }
/// S-track: label of the most recent activity that bumped .
public string? LastAccessedBy { get; set; }
}
}
Path: redb-identity/src/redb.Identity.Core/Services/SmsMfaMethod.cs
Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.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/SmsMfaMethod.cs
----
using redb.Identity.Core.Mfa;
using redb.Identity.Core.Models;
namespace redb.Identity.Core.Services;
///
/// SMS OTP MFA method.
/// Stores the user's phone 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 SmsMfaMethod : IMfaMethod
{
private readonly IServerSideOtpStore? _otpStore;
public SmsMfaMethod(IServerSideOtpStore? otpStore = null)
{
_otpStore = otpStore;
}
public string MethodId => "sms";
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"] = "Phone number is required" }
}
});
}
var phone = NormalizePhone(destination);
if (phone is null)
{
return Task.FromResult(new MfaSetupInitiation
{
MethodId = MethodId,
ClientResult = new MfaSetupResult
{
MethodId = MethodId,
Extra = new Dictionary { ["error"] = "Invalid phone number format" }
}
});
}
return Task.FromResult(new MfaSetupInitiation
{
MethodId = MethodId,
Destination = phone,
ClientResult = new MfaSetupResult
{
MethodId = MethodId,
Extra = new Dictionary { ["masked_phone"] = MaskPhone(phone) }
}
});
}
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;
// Atomic apply.
props.SmsPhone = initiation.Destination;
props.SmsConfirmed = 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? NormalizePhone(string input)
{
if (string.IsNullOrWhiteSpace(input)) return null;
var digits = new string(input.Where(c => char.IsDigit(c) || c == '+').ToArray());
var hasPlus = digits.StartsWith('+');
if (hasPlus) digits = digits[1..];
if (digits.Length < 10 || digits.Length > 15) return null;
if (!digits.All(char.IsDigit)) return null;
return "+" + digits;
}
internal static string MaskPhone(string phone)
{
if (string.IsNullOrEmpty(phone) || phone.Length <= 4) return "****";
// Keep leading "+" + first digit, mask middle, keep last 4
var prefix = phone.StartsWith('+') ? phone[..2] : phone[..1];
return prefix + "***" + phone[^4..];
}
}
Path: redb-identity/src/redb.Identity.Core/Services/SmtpEmailNotificationChannel.cs
Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.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/SmtpEmailNotificationChannel.cs
----
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using redb.Identity.Contracts.Routes;
using redb.Identity.Core.Configuration;
using redb.Route.Abstractions;
using redb.Route.Core;
namespace redb.Identity.Core.Services;
///
/// N-4 (Session C): production backed by the
/// redb.Route.Mail SMTP DSL. Renders the requested template through
/// and forwards the resulting message to
/// , which the host route builder wires to a
/// Smtp.Send(...) producer when is true.
///
/// The channel only knows about route URIs and exchange headers — concrete SMTP details
/// (host / port / credentials / TLS) live entirely on the route definition, exactly as
/// the rest of the redb.Route ecosystem expects. This keeps the abstraction transport-
/// agnostic: swapping SMTP for SendGrid is a route change, not a channel change.
///
///
public sealed class SmtpEmailNotificationChannel : IEmailNotificationChannel, IDisposable
{
private readonly IRouteContext _routeContext;
private readonly IEmailTemplateRegistry _registry;
private readonly SmtpOptions _smtp;
private readonly ILogger _logger;
private readonly object _producerLock = new();
private IProducerTemplate? _producer;
private bool _disposed;
public SmtpEmailNotificationChannel(
IRouteContext routeContext,
IEmailTemplateRegistry registry,
IOptions options,
ILoggerFactory? loggerFactory = null)
{
_routeContext = routeContext ?? throw new ArgumentNullException(nameof(routeContext));
_registry = registry ?? throw new ArgumentNullException(nameof(registry));
_smtp = options.Value.Smtp;
_logger = loggerFactory?.CreateLogger() ?? (ILogger)NullLogger.Instance;
}
///
public async Task SendTemplateAsync(
string to,
string templateId,
IReadOnlyDictionary vars,
CancellationToken ct = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(to);
ArgumentException.ThrowIfNullOrWhiteSpace(templateId);
ArgumentNullException.ThrowIfNull(vars);
// Render the template using the host-supplied registry. Locale negotiation lives
// there; this channel only forwards the rendered output to the SMTP route.
var rendered = await _registry.RenderAsync(templateId, locale: null, vars, ct).ConfigureAwait(false);
var message = new Message
{
Body = rendered.HtmlBody ?? rendered.TextBody ?? string.Empty
};
message.Headers["redbMail.To"] = to;
message.Headers["redbMail.Subject"] = rendered.Subject ?? string.Empty;
if (!string.IsNullOrWhiteSpace(_smtp.FromAddress))
message.Headers["redbMail.From"] = _smtp.FromAddress;
// Force the SMTP component to treat the body as HTML and use TextBody as the
// plain-text alternative — see redb.Route.Mail.SmtpComponent.BuildMimeMessage.
message.Headers["redbMail.ContentType"] = "text/html";
if (!string.IsNullOrWhiteSpace(rendered.TextBody))
message.Headers["redbMail.TextBody"] = rendered.TextBody!;
var producer = EnsureProducer();
try
{
await producer.SendAsync(IdentityEndpoints.EmailSend, message).ConfigureAwait(false);
}
catch (Exception ex)
{
// Mirrors PasswordForgotProcessor's expectation that channel implementations
// surface fatal issues but absorb transient ones. We log + rethrow so the
// processor can keep the anti-enumeration contract (it catches and degrades).
// The recipient address is left out: it is personal data, and the template and the
// endpoint are what an operator needs to find a failing mail route.
_logger.LogError(ex,
"SmtpEmailNotificationChannel: send via {Endpoint} failed for template {TemplateId}",
IdentityEndpoints.EmailSend, templateId);
throw;
}
}
private IProducerTemplate EnsureProducer()
{
if (_producer is { IsStarted: true }) return _producer;
lock (_producerLock)
{
if (_disposed) throw new ObjectDisposedException(nameof(SmtpEmailNotificationChannel));
if (_producer is { IsStarted: true }) return _producer;
var p = new ProducerTemplate(_routeContext);
p.Start();
_producer = p;
return _producer;
}
}
public void Dispose()
{
if (_disposed) return;
lock (_producerLock)
{
if (_disposed) return;
_disposed = true;
(_producer as IDisposable)?.Dispose();
_producer = null;
}
}
}
Path: redb-identity/src/redb.Identity.Core/Services/TotpMfaMethod.cs
Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.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/TotpMfaMethod.cs
----
using System.Security.Cryptography;
using OtpNet;
using redb.Identity.Core.Models;
namespace redb.Identity.Core.Services;
///
/// TOTP (RFC 6238) MFA method using Otp.NET.
/// Stateless: receives and operates on its TOTP fields.
///
internal sealed class TotpMfaMethod : IMfaMethod
{
public string MethodId => "totp";
private readonly MfaSecretProtector _secretProtector;
private readonly string _issuerName;
private readonly int _secretLength = 20; // 160 bit per RFC 4226
private readonly int _codeDigits = 6;
private readonly int _periodSeconds = 30;
private readonly int _skewSteps = 1; // ±30s tolerance
public TotpMfaMethod(MfaSecretProtector secretProtector, string issuerName = "redb.Identity")
{
_secretProtector = secretProtector;
_issuerName = issuerName;
}
public Task InitiateSetupAsync(string username, string? destination = null, CancellationToken ct = default)
{
// destination is ignored for TOTP — the secret is generated server-side.
var key = RandomNumberGenerator.GetBytes(_secretLength);
var base32Secret = Base32Encoding.ToString(key);
var encryptedSecret = _secretProtector.Protect(base32Secret);
var qrUri = $"otpauth://totp/{Uri.EscapeDataString(_issuerName)}:{Uri.EscapeDataString(username)}" +
$"?secret={base32Secret}&issuer={Uri.EscapeDataString(_issuerName)}" +
$"&digits={_codeDigits}&period={_periodSeconds}";
var clientResult = new MfaSetupResult
{
MethodId = MethodId,
SecretBase32 = base32Secret,
QrUri = qrUri
};
return Task.FromResult(new MfaSetupInitiation
{
MethodId = MethodId,
EncryptedSecret = encryptedSecret,
ClientResult = clientResult
});
}
public Task ConfirmAndApplyAsync(MfaProps props, MfaSetupInitiation initiation, string code, MfaState? state = null, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(props);
ArgumentNullException.ThrowIfNull(initiation);
if (string.IsNullOrEmpty(initiation.EncryptedSecret))
return Task.FromResult(false);
// Verify the supplied code against the candidate secret WITHOUT touching props yet.
if (!TryVerifyCodeWithSecret(initiation.EncryptedSecret, code, out var step))
return Task.FromResult(false);
// Atomic apply: secret + confirmation flag + replay-protection seed.
props.TotpSecret = initiation.EncryptedSecret;
props.TotpConfirmed = true;
props.LastTotpStep = step;
return Task.FromResult(true);
}
public Task VerifyAsync(MfaProps props, string code, MfaState? state = null, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(props);
// state is ignored for TOTP.
if (!TryVerifyCode(props, code, out var step))
return Task.FromResult(false);
// RFC 6238 §5.2: reject codes from a previously accepted (or earlier) time-step
// to prevent replay within the verification window.
// Caller (B1) must hold a row-lock + transaction so two concurrent verifies for the
// same user serialize on the read-then-write of LastTotpStep.
if (props.LastTotpStep.HasValue && step <= props.LastTotpStep.Value)
return Task.FromResult(false);
props.LastTotpStep = step;
return Task.FromResult(true);
}
private bool TryVerifyCode(MfaProps props, string code, out long step)
{
if (string.IsNullOrEmpty(props.TotpSecret))
{
step = 0;
return false;
}
return TryVerifyCodeWithSecret(props.TotpSecret, code, out step);
}
private bool TryVerifyCodeWithSecret(string encryptedSecret, string code, out long step)
{
step = 0;
if (string.IsNullOrEmpty(encryptedSecret) || string.IsNullOrEmpty(code))
return false;
var base32Secret = _secretProtector.Unprotect(encryptedSecret);
if (base32Secret is null)
return false;
var key = Base32Encoding.ToBytes(base32Secret);
var totp = new Totp(key, step: _periodSeconds, totpSize: _codeDigits);
var window = new VerificationWindow(previous: _skewSteps, future: _skewSteps);
return totp.VerifyTotp(code, out step, window);
}
}
Path: redb-identity/src/redb.Identity.Core/Services/UserProfileService.cs
Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.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/UserProfileService.cs
----
using System.Security.Claims;
using Microsoft.Extensions.Logging;
using redb.Core;
using redb.Core.Models.Contracts;
using redb.Core.Models.Entities;
using redb.Core.Query;
using redb.Identity.Core.Models;
using redb.Identity.Core.OpenIddict;
namespace redb.Identity.Core.Services;
///
/// Default implementation of .
/// Loads Core user + OIDC extension + group memberships in a single call,
/// then builds the ClaimsPrincipal via
/// and enriches with group/role claims via .
///
internal sealed class UserProfileService : IUserProfileService
{
private readonly IRedbService _redb;
private readonly ILogger _logger;
public UserProfileService(IRedbService redb, ILogger logger)
{
_redb = redb;
_logger = logger;
}
public async Task BuildPrincipalAsync(
long userId,
IEnumerable scopes,
bool mfaVerified = false,
string? mfaMethod = null,
OidcClaimsRequest? claimsRequest = null,
CancellationToken ct = default)
{
var coreUser = await _redb.UserProvider.GetUserByIdAsync(userId).ConfigureAwait(false);
if (coreUser is null)
{
_logger.LogWarning("UserProfileService: user {UserId} not found", userId);
return null;
}
if (!coreUser.Enabled)
{
_logger.LogWarning("UserProfileService: user {UserId} is disabled", userId);
return null;
}
// Load OIDC profile extension (may not exist for users without profile data)
var oidcObj = await _redb.Query()
.WhereRedb(o => o.Key == coreUser.Id)
.FirstOrDefaultAsync()
.ConfigureAwait(false);
// The public sub claim is the value_guid on the user's UserProps envelope. If
// the legacy record has none, lazy-create one and persist so subsequent logins
// get the same GUID.
Guid subjectGuid;
if (oidcObj is null)
{
oidcObj = new RedbObject(new UserProps())
{
name = coreUser.Login,
key = coreUser.Id,
value_guid = Guid.NewGuid()
};
await _redb.SaveAsync(oidcObj).ConfigureAwait(false);
subjectGuid = oidcObj.value_guid!.Value;
}
else if (oidcObj.value_guid is null || oidcObj.value_guid == Guid.Empty)
{
oidcObj.value_guid = Guid.NewGuid();
await _redb.SaveAsync(oidcObj).ConfigureAwait(false);
subjectGuid = oidcObj.value_guid.Value;
}
else
{
subjectGuid = oidcObj.value_guid.Value;
}
var scopeList = scopes as IReadOnlyList ?? scopes.ToList();
// Build base principal with standard OIDC claims (incl. amr if MFA verified)
var principal = IdentityPrincipalBuilder.Build(
coreUser, subjectGuid, oidcObj.Props, scopeList, mfaVerified, mfaMethod, claimsRequest);
// Enrich with group/role claims
var resolver = new GroupClaimsResolver(_redb);
await resolver.EnrichPrincipalAsync(principal, userId, scopeList, ct).ConfigureAwait(false);
return principal;
}
///
/// Fast-path overload: caller (e.g. LoginService.AuthenticateAsync) has already
/// loaded the Core user, OIDC props, and resolved the subject GUID — skip the redundant
/// _users + UserProps round-trips. Group memberships are still loaded on
/// demand when groups / roles scopes are requested.
///
public async Task BuildPrincipalAsync(
IRedbUser user,
UserProps? oidcProps,
Guid subjectGuid,
IEnumerable scopes,
bool mfaVerified = false,
string? mfaMethod = null,
CancellationToken ct = default)
{
if (!user.Enabled)
{
_logger.LogWarning("UserProfileService: user {UserId} is disabled", user.Id);
return null;
}
var scopeList = scopes as IReadOnlyList ?? scopes.ToList();
var principal = IdentityPrincipalBuilder.Build(user, subjectGuid, oidcProps, scopeList, mfaVerified, mfaMethod);
var resolver = new GroupClaimsResolver(_redb);
await resolver.EnrichPrincipalAsync(principal, user.Id, scopeList, ct).ConfigureAwait(false);
return principal;
}
}
Path: redb-identity/src/redb.Identity.Core/Services/WebAuthnMfaMethod.cs
Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.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/WebAuthnMfaMethod.cs
----
using System.Globalization;
using System.Security.Cryptography;
using Fido2NetLib;
using Fido2NetLib.Objects;
using Microsoft.Extensions.Options;
using redb.Identity.Core.Configuration;
using redb.Identity.Core.Exceptions;
using redb.Identity.Core.Models;
namespace redb.Identity.Core.Services;
///
/// MFA-3: WebAuthn (FIDO2 / Passkey) MFA method backed by Fido2NetLib v4.
///
/// Wraps with redb-Identity-specific concerns:
///
///
///