Bundle: redb-identity / src/redb.Identity.DataProtection (src.redb.Identity.DataProtection.txt), 5 files
Snapshot: development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity
Index: https://redbase.app/src/dev-2026-12-06/redb-identity/_index.txt
====
Path: redb-identity/src/redb.Identity.DataProtection/DataProtectionKeyImportProps.cs
Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity
Page: https://redbase.app/src/dev-2026-12-06/redb-identity/src/redb.Identity.DataProtection/DataProtectionKeyImportProps.cs
----
using redb.Core.Attributes;
namespace redb.Identity.DataProtection;
///
/// When the DataProtection key ring moved from the file system into redb (the first start of 4.4 on this
/// database). Only file-ring elements older than this are imported: the Tsak worker, the Tsak dashboard and
/// Identity Web keep writing their own rings to the same default directory, and their later keys are not
/// Identity's. Two nodes writing it at once leave two rows; the earliest one counts.
///
[RedbScheme("identity.dp_key_import")]
public class DataProtectionKeyImportProps
{
/// The moment the key ring started to live in redb.
public DateTimeOffset StartedAt { get; set; }
}
Path: redb-identity/src/redb.Identity.DataProtection/DataProtectionKeyProps.cs
Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity
Page: https://redbase.app/src/dev-2026-12-06/redb-identity/src/redb.Identity.DataProtection/DataProtectionKeyProps.cs
----
using redb.Core.Attributes;
namespace redb.Identity.DataProtection;
///
/// PROPS Props for ASP.NET DataProtection XML key storage.
/// Persists encryption keys across restarts and cluster nodes.
/// Base fields: name = friendly key name.
///
[RedbScheme("identity.dp_key")]
public class DataProtectionKeyProps
{
/// Friendly name for the key.
public string? FriendlyName { get; set; }
/// Serialized XML content of the DataProtection key.
public string? XmlContent { get; set; }
}
Path: redb-identity/src/redb.Identity.DataProtection/RedbDataProtectionBuilderExtensions.cs
Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity
Page: https://redbase.app/src/dev-2026-12-06/redb-identity/src/redb.Identity.DataProtection/RedbDataProtectionBuilderExtensions.cs
----
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.DataProtection.KeyManagement;
using Microsoft.AspNetCore.DataProtection.Repositories;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
namespace redb.Identity.DataProtection;
///
/// DI helpers for persisting ASP.NET DataProtection XML keys in redb PROPS storage.
///
/// Lives in redb.Identity.DataProtection (Phase 9a) so that any Identity facade
/// (Core, Http, gRPC, …) can opt-in to the redb-backed key-ring without taking a
/// project-reference on Core. The key-ring snapshot is then visible across cold
/// starts and cluster nodes — required for cookie / session-ticket continuity.
///
///
public static class RedbDataProtectionBuilderExtensions
{
///
/// Persists ASP.NET DataProtection XML keys in redb.
/// Usage: services.AddDataProtection().PersistKeysToRedb();
///
/// The key manager reads its repository from
/// only; a repository merely registered in DI is ignored and the key ring falls back to the file
/// system of the process user. So the repository is set on the options, as
/// PersistKeysToFileSystem and PersistKeysToDbContext do. An XML encryptor set on
/// the same options (ProtectKeysWith*) keeps working: the repository stores what it is
/// given.
///
///
/// The repository is a Singleton. Persistence opens a fresh
/// scope per call to avoid capturing a Scoped
/// (A1 captive-dependency rule).
///
///
public static IDataProtectionBuilder PersistKeysToRedb(this IDataProtectionBuilder builder)
{
ArgumentNullException.ThrowIfNull(builder);
builder.Services.TryAddSingleton();
builder.Services.TryAddSingleton(
sp => sp.GetRequiredService());
builder.Services.TryAddEnumerable(
ServiceDescriptor.Singleton, RedbKeyManagementOptionsSetup>());
return builder;
}
private sealed class RedbKeyManagementOptionsSetup : IConfigureOptions
{
private readonly RedbXmlRepository _repository;
public RedbKeyManagementOptionsSetup(RedbXmlRepository repository) => _repository = repository;
public void Configure(KeyManagementOptions options) => options.XmlRepository = _repository;
}
}
Path: redb-identity/src/redb.Identity.DataProtection/RedbXmlRepository.cs
Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity
Page: https://redbase.app/src/dev-2026-12-06/redb-identity/src/redb.Identity.DataProtection/RedbXmlRepository.cs
----
using System.Collections.Immutable;
using System.Xml.Linq;
using Microsoft.AspNetCore.DataProtection.Repositories;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using redb.Core;
using redb.Core.Query;
using redb.Core.Models.Entities;
namespace redb.Identity.DataProtection;
///
/// ASP.NET DataProtection XML key repository backed by redb PROPS storage.
/// Each key is stored as a of .
///
/// Snapshot pattern (A1): returns an in-memory
/// snapshot — pure-sync, no I/O on the auth hot path
/// (called per Protect/Unprotect). The snapshot is seeded by a host-side init
/// listener (Core's RedbXmlRepositoryInitListener, or any facade-local equivalent)
/// in OnContextStarting, before any route processes its first exchange.
/// is a rare write (key-ring rotation): it persists via a
/// fresh DI scope and updates the snapshot in-process via
/// .
///
///
/// Lifetime: registered as Singleton so it can be safely consumed by
/// (resolved from the root container by KeyManager).
/// Persistence uses per call, so no Scoped
/// is captured.
///
///
public sealed class RedbXmlRepository : IXmlRepository
{
private readonly IServiceScopeFactory _scopeFactory;
private ImmutableArray _snapshot = ImmutableArray.Empty;
public RedbXmlRepository(IServiceScopeFactory scopeFactory)
{
ArgumentNullException.ThrowIfNull(scopeFactory);
_scopeFactory = scopeFactory;
}
///
public IReadOnlyCollection GetAllElements() => _snapshot;
///
public void StoreElement(XElement element, string friendlyName)
{
ArgumentNullException.ThrowIfNull(element);
// Bridge sync IXmlRepository contract to async redb. NOT on the auth hot path:
// StoreElement is invoked only at key-ring rotation (rare), so the GetAwaiter().GetResult()
// here cannot starve the thread pool the way a per-request bridge would.
StoreElementAsync(element, friendlyName).GetAwaiter().GetResult();
}
private async Task StoreElementAsync(XElement element, string friendlyName)
{
await using var scope = _scopeFactory.CreateAsyncScope();
var redb = scope.ServiceProvider.GetRequiredService();
var obj = new RedbObject
{
name = friendlyName,
Props = new DataProtectionKeyProps
{
FriendlyName = friendlyName,
XmlContent = element.ToString(SaveOptions.DisableFormatting)
}
};
await redb.SaveAsync(obj).ConfigureAwait(false);
// Optimistic in-process snapshot update — visible to subsequent GetAllElements calls
// without waiting for a refresh round-trip. Other cluster nodes pick this key up on
// their next refresh / restart.
ImmutableInterlocked.Update(ref _snapshot, (s, e) => s.Add(e), element);
}
///
/// Replaces the in-memory snapshot wholesale. Called by the host-side init listener
/// during context startup (and by any future periodic refresh route).
///
///
/// Uses a plain assignment: is a struct wrapping a single
/// reference field, and reference-sized writes are atomic on all supported .NET runtimes,
/// so readers of always observe either the old or new array in
/// full (no torn read). cannot be used
/// here because it is constrained to reference types and primitives and throws
/// for value-type generics like ImmutableArray.
///
public void ReplaceSnapshot(ImmutableArray newSnapshot)
=> _snapshot = newSnapshot;
/// Upper bound of persisted elements loaded into the snapshot (most recent first).
public const int MaxElements = 100;
///
/// Reloads the snapshot from redb: the most recent elements, one per key
/// id. Two nodes importing the same key at the same moment can leave two rows for it, and the key
/// manager refuses a ring with a duplicate key id, so duplicates are dropped here.
///
/// The number of elements in the new snapshot.
public async Task ReloadAsync(IRedbService redb, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(redb);
var rows = await redb.Query()
.OrderByDescendingRedb(o => o.DateCreate)
.Take(MaxElements)
.ToListAsync()
.ConfigureAwait(false);
var elements = ImmutableArray.CreateBuilder(rows.Count);
var seen = new HashSet(StringComparer.Ordinal);
foreach (var row in rows)
{
if (string.IsNullOrEmpty(row.Props.XmlContent))
continue;
var element = XElement.Parse(row.Props.XmlContent);
if (seen.Add(IdentityOf(element)))
elements.Add(element);
}
ReplaceSnapshot(elements.ToImmutable());
return elements.Count;
}
///
/// Copies into redb the elements of file-system key rings that redb does not hold yet. Before
/// set the key manager's
/// repository, the key ring silently lived in the default directory of the process user, and
/// everything protected so far (signing keys, MFA secrets, cookies) is encrypted with those keys.
///
/// Idempotent by key id: a key already in redb is skipped, so a later start imports nothing, and
/// cluster nodes that each kept their own file ring each add theirs. Files are left in place. The
/// XML is copied as stored, encrypted elements stay encrypted with their original decryptor.
///
///
/// The number of elements imported.
public static async Task ImportFileKeyRingsAsync(
IRedbService redb, IEnumerable directories, ILogger logger, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(redb);
ArgumentNullException.ThrowIfNull(directories);
ArgumentNullException.ThrowIfNull(logger);
var dirs = directories
.Where(d => !string.IsNullOrWhiteSpace(d))
.Select(Path.GetFullPath)
.Distinct(OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal)
.Where(Directory.Exists)
.ToList();
var cutoff = await GetImportCutoffAsync(redb).ConfigureAwait(false);
if (dirs.Count == 0)
return 0;
var known = new HashSet(StringComparer.Ordinal);
var rows = await redb.Query().ToListAsync().ConfigureAwait(false);
foreach (var row in rows)
{
if (!string.IsNullOrEmpty(row.Props.XmlContent))
known.Add(IdentityOf(XElement.Parse(row.Props.XmlContent)));
}
var total = 0;
foreach (var dir in dirs)
{
var imported = 0;
foreach (var file in Directory.EnumerateFiles(dir, "*.xml").Order(StringComparer.Ordinal))
{
ct.ThrowIfCancellationRequested();
XElement element;
try
{
element = XElement.Load(file);
}
catch (Exception ex)
{
logger.LogWarning(ex, "DataProtection key ring import: {File} is not readable XML, skipped", file);
continue;
}
// Written after the ring moved to redb: another program's key (the Tsak worker,
// dashboard and Identity Web keep their rings in the same default directory).
if (DateOf(element) is { } written && written >= cutoff)
continue;
if (!known.Add(IdentityOf(element)))
continue;
var friendlyName = Path.GetFileNameWithoutExtension(file);
await redb.SaveAsync(new RedbObject
{
name = friendlyName,
Props = new DataProtectionKeyProps
{
FriendlyName = friendlyName,
XmlContent = element.ToString(SaveOptions.DisableFormatting)
}
}).ConfigureAwait(false);
imported++;
}
if (imported > 0)
{
logger.LogWarning(
"DataProtection key ring: imported {Count} element(s) from the file key ring {Directory} into redb. " +
"The key ring now lives in redb only; the files are no longer read or written and can be kept as a backup.",
imported, dir);
}
total += imported;
}
return total;
}
///
/// The moment the ring moved into redb (), recorded on the
/// first call against this database; the earliest record wins when nodes race.
///
private static async Task GetImportCutoffAsync(IRedbService redb)
{
var first = await EarliestCutoffAsync(redb).ConfigureAwait(false);
if (first is { } existing)
return existing;
await redb.SaveAsync(new RedbObject
{
name = "dp-key-ring-in-redb",
Props = new DataProtectionKeyImportProps { StartedAt = DateTimeOffset.UtcNow }
}).ConfigureAwait(false);
return await EarliestCutoffAsync(redb).ConfigureAwait(false) ?? DateTimeOffset.UtcNow;
}
private static async Task EarliestCutoffAsync(IRedbService redb)
{
var rows = await redb.Query().ToListAsync().ConfigureAwait(false);
return rows.Count == 0 ? null : rows.Min(r => r.Props.StartedAt);
}
/// The creation date of a key, the revocation date of a revocation; null when absent.
private static DateTimeOffset? DateOf(XElement element)
{
var date = element.Name.LocalName switch
{
"key" => element.Element("creationDate")?.Value,
"revocation" => element.Element("revocationDate")?.Value,
_ => null
};
return DateTimeOffset.TryParse(date, System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.RoundtripKind, out var parsed) ? parsed : null;
}
/// A key is identified by its id; any other element (a revocation) by its exact XML.
private static string IdentityOf(XElement element)
=> element.Name.LocalName == "key" && element.Attribute("id")?.Value is { Length: > 0 } id
? "key:" + id.ToLowerInvariant()
: "xml:" + element.ToString(SaveOptions.DisableFormatting);
}
///
/// Where ASP.NET Core DataProtection keeps its key ring when no repository is configured, for the
/// one-off import into . Mirrors the framework's internal
/// DefaultKeyStorageDirectories (aspnetcore v10.0.13): the Azure App Service location, then
/// %LOCALAPPDATA%\ASP.NET\DataProtection-Keys on Windows (or when LOCALAPPDATA is set),
/// otherwise $HOME/.aspnet/DataProtection-Keys.
///
public static class DefaultFileKeyRing
{
private const string FolderName = "DataProtection-Keys";
/// The default file key ring directories of the current process, existing or not.
public static IReadOnlyList Directories()
{
var result = new List();
if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("WEBSITE_INSTANCE_ID")) &&
Environment.GetEnvironmentVariable("HOME") is { Length: > 0 } azureHome)
{
result.Add(Path.Combine(azureHome, "ASP.NET", FolderName));
}
var localAppDataSystem = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
var localAppDataEnv = Environment.GetEnvironmentVariable("LOCALAPPDATA");
var home = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
if (OperatingSystem.IsWindows() && !string.IsNullOrEmpty(localAppDataSystem))
result.Add(Path.Combine(localAppDataSystem, "ASP.NET", FolderName));
else if (localAppDataEnv is not null)
result.Add(Path.Combine(localAppDataEnv, "ASP.NET", FolderName));
else if (!string.IsNullOrEmpty(home))
result.Add(OperatingSystem.IsWindows()
? Path.Combine(home, "AppData", "Local", "ASP.NET", FolderName)
: Path.Combine(home, ".aspnet", FolderName));
else if (!string.IsNullOrEmpty(localAppDataSystem))
result.Add(Path.Combine(localAppDataSystem, "ASP.NET", FolderName));
return result;
}
}
Path: redb-identity/src/redb.Identity.DataProtection/redb.Identity.DataProtection.csproj
Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity
Page: https://redbase.app/src/dev-2026-12-06/redb-identity/src/redb.Identity.DataProtection/redb.Identity.DataProtection.csproj
----
redb.Identity.DataProtection
redb.Identity.DataProtection
redb-backed ASP.NET Core DataProtection key repository (RedbXmlRepository) for redb.Identity facades.