Bundle: redb-identity / src/redb.Identity.Http (src.redb.Identity.Http.txt), 33 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.Http/Controllers/ScimBulkController.cs Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/src/redb.Identity.Http/Controllers/ScimBulkController.cs ---- using redb.Identity.Contracts.Scim; using redb.Identity.Contracts.Routes; using redb.Route.Controllers.Attributes; namespace redb.Identity.Http.Controllers; /// /// SCIM 2.0 Bulk endpoint (RFC 7644 §3.7). /// Forwards to direct-vm://identity-scim-bulk route. /// [Route("Bulk")] public class ScimBulkController : ScimControllerBase { [HttpPost] public async Task Bulk([FromBody] ScimBulkRequest request) { if (ValidateRequest(request) is { } problem) return problem; return await Forward(IdentityEndpoints.ScimBulk, "process", request); } } Path: redb-identity/src/redb.Identity.Http/Controllers/ScimControllerBase.cs Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/src/redb.Identity.Http/Controllers/ScimControllerBase.cs ---- using redb.Identity.Contracts.Validation; using redb.Identity.Management.Controllers; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Identity.Http.Controllers; /// /// SCIM controller base with a Forward() that correctly returns null for deletions /// and propagates SCIM-specific response hints (status code, location). /// public abstract class ScimControllerBase : IdentityControllerBase { /// /// SCIM-aware DataAnnotations validation. Returns null if the DTO is valid; /// otherwise a populated /// with status=400 and scimType=invalidValue, which the SCIM /// status mapper turns into HTTP 400 (E6 / RFC 7644 §3.12). /// protected static new object? ValidateRequest(object? request) => ScimRequestValidator.Validate(request); /// /// Forwards an operation to a direct-vm endpoint, returning the Out.Body directly. /// Unlike the base class, null Out.Body is returned as null (enabling 204 for DELETE). /// Also propagates scim.* headers to the HTTP exchange for post-processor handling. /// protected new async Task Forward(string endpointUri, string operation, object? body = null) { var endpoint = Context.GetEndpoint(endpointUri); var msg = new Message(); msg.Headers["operation"] = operation; if (body is not null) msg.Body = body; // M1: Pass base URL to processor for absolute Meta.Location URIs var httpUrl = Exchange.In.GetHeader("redbHttp.Url"); if (httpUrl is not null && Uri.TryCreate(httpUrl, UriKind.Absolute, out var uri)) msg.Headers["scim.BaseUrl"] = $"{uri.Scheme}://{uri.Authority}"; // Pass If-Match header for ETag precondition checks var ifMatch = Exchange.In.GetHeader("If-Match"); if (!string.IsNullOrEmpty(ifMatch)) msg.Headers["scim.IfMatch"] = ifMatch; // E2 — propagate Idempotency-Key + HTTP method into the inner direct-vm exchange. var idemKey = Exchange.In.GetHeader("Idempotency-Key") ?? Exchange.In.GetHeader("idempotency-key"); if (!string.IsNullOrEmpty(idemKey)) msg.Headers["Idempotency-Key"] = idemKey; var httpMethod = Exchange.In.GetHeader("redbHttp.Method"); if (!string.IsNullOrEmpty(httpMethod)) msg.Headers["redbHttp.Method"] = httpMethod; // The caller's address and User-Agent for the audit row (the transport's address, not the caller's claim). var remote = Exchange.In.GetHeader("redbHttp.RemoteAddress"); if (!string.IsNullOrEmpty(remote)) msg.Headers["redbHttp.RemoteAddress"] = remote; var userAgent = Exchange.In.GetHeader("User-Agent"); if (!string.IsNullOrEmpty(userAgent)) msg.Headers["User-Agent"] = userAgent; // CreateChild gives the inner exchange its own fresh DI scope inherited from the // outer HTTP exchange's scope factory. Without this the inner Exchange has a null // ServiceProvider and SCIM/identity processors fall back to the captive root // IRedbService — single connection serialising all concurrent HTTP requests and // surfacing as NpgsqlOperationInProgressException under load. Falls back to a // bare Exchange when the outer Exchange is unavailable (unit tests). var exchange = Exchange?.CreateChild(msg) ?? new Exchange(msg); exchange.Pattern = ExchangePattern.InOut; var producer = endpoint.CreateProducer(); try { await producer.Process(exchange).ConfigureAwait(false); // B2 — propagate transport-level response meta (redbHttp.ResponseCode, Content-Type, // Location, ETag, ...) from the inner exchange to the outer HTTP exchange so inner // OnException handlers actually affect the HTTP status. Must run before we copy the // SCIM-specific hints below (so domain hints can override transport defaults). PropagateInnerResponse(exchange); // Identity pipeline convention: business processors write the response into // exchange.In.Body; // PipelineProcessor never synthesises Out from In (Camel-compliant). Read from // Out when present, else fall back to In — applies to body and to all hint headers. var responseSource = exchange.Out ?? exchange.In; // Propagate SCIM response hints to HTTP exchange for post-processors if (responseSource is not null) { if (responseSource.Headers.TryGetValue("scim.ResponseCode", out var rc)) Exchange.In.Headers["scim.ResponseCode"] = rc; if (responseSource.Headers.TryGetValue("scim.Location", out var loc)) { // Make Location absolute if base URL is available msg.Headers.TryGetValue("scim.BaseUrl", out var baseUrlObj); var baseUrl = baseUrlObj?.ToString() ?? ""; var absLoc = loc?.ToString()?.StartsWith("/") == true ? $"{baseUrl}{loc}" : loc; Exchange.In.Headers["scim.Location"] = absLoc; } if (responseSource.Headers.TryGetValue("scim.ETag", out var etag)) Exchange.In.Headers["scim.ETag"] = etag; if (responseSource.Headers.TryGetValue("Idempotency-Replayed", out var replayed)) Exchange.In.Headers["Idempotency-Replayed"] = replayed; } // SCIM DELETE → 204 No Content: the delete processor signals via scim.ResponseCode=204 // and leaves no real response body. When Out is absent, In.Body still holds the // original request payload we set via msg.Body=body above, which must NOT be echoed. if (responseSource is not null && responseSource.Headers.TryGetValue("scim.ResponseCode", out var rcCheck) && rcCheck is int code && (code == 204 || code == 304)) return null; // Same protection for the general "no Out produced" case: if In.Body is still the // request payload we passed in (i.e. no processor overwrote it), don't echo it back. if (exchange.Out is null && ReferenceEquals(exchange.In.Body, body)) return null; return responseSource?.Body; } finally { // CRITICAL: dispose the inner exchange so its DI scope (and the scoped // NpgsqlConnection within) is released back to the pool. Without this each // SCIM HTTP call leaks one connection until MaxPoolSize is hit and subsequent // calls 503 with NpgsqlException("connection pool exhausted"). await exchange.DisposeAsync().ConfigureAwait(false); } } } Path: redb-identity/src/redb.Identity.Http/Controllers/ScimDiscoveryController.cs Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/src/redb.Identity.Http/Controllers/ScimDiscoveryController.cs ---- using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using redb.Identity.Contracts.Scim; using redb.Route.Abstractions; using redb.Route.Controllers; using redb.Route.Controllers.Attributes; namespace redb.Identity.Http.Controllers; /// /// SCIM 2.0 discovery endpoints (RFC 7644 §4). /// No authentication required — returns server capabilities. /// [Route("")] public class ScimDiscoveryController : RedbController { [HttpGet("ServiceProviderConfig")] public Task ServiceProviderConfig() { // H1: reflect runtime SCIM Bulk capability + limits per the configured options. var opts = Context.GetServiceProvider()?.GetService>()?.Value; var bulk = new ScimBulkConfig { Supported = opts?.Features.EnableScimBulk ?? false, MaxOperations = opts?.ScimBulk.MaxOperations ?? 1000, MaxPayloadSize = opts?.ScimBulk.MaxPayloadSize ?? 1_048_576 }; var config = new ScimServiceProviderConfig { Bulk = bulk, Meta = new ScimMeta { ResourceType = "ServiceProviderConfig", Location = "/scim/v2/ServiceProviderConfig" } }; return Task.FromResult(config); } /// /// RFC 7643 §4.3 — Enterprise User rides on the User resource type. Not required: a user with no /// department is still a valid user, so a provisioning client is never forced to send it. /// private static ScimSchemaExtension EnterpriseExtension => new() { Schema = ScimConstants.EnterpriseUserSchema, Required = false }; [HttpGet("ResourceTypes")] public Task ResourceTypes() { var types = new ScimListResponse { TotalResults = 2, ItemsPerPage = 2, Resources = [ new ScimResourceType { Id = "User", Name = "User", Endpoint = "/Users", Schema = ScimConstants.UserSchema, Description = "User Account", SchemaExtensions = [EnterpriseExtension], Meta = new ScimMeta { ResourceType = "ResourceType", Location = "/scim/v2/ResourceTypes/User" } }, new ScimResourceType { Id = "Group", Name = "Group", Endpoint = "/Groups", Schema = ScimConstants.GroupSchema, Description = "Group", Meta = new ScimMeta { ResourceType = "ResourceType", Location = "/scim/v2/ResourceTypes/Group" } } ] }; return Task.FromResult(types); } [HttpGet("ResourceTypes/{id}")] public Task ResourceType([FromRoute("id")] string id) { ScimResourceType? rt = id switch { "User" => new ScimResourceType { Id = "User", Name = "User", Endpoint = "/Users", Schema = ScimConstants.UserSchema, Description = "User Account", SchemaExtensions = [EnterpriseExtension], Meta = new ScimMeta { ResourceType = "ResourceType", Location = "/scim/v2/ResourceTypes/User" } }, "Group" => new ScimResourceType { Id = "Group", Name = "Group", Endpoint = "/Groups", Schema = ScimConstants.GroupSchema, Description = "Group", Meta = new ScimMeta { ResourceType = "ResourceType", Location = "/scim/v2/ResourceTypes/Group" } }, _ => null }; if (rt is null) return Task.FromResult(new ScimError { Status = "404", Detail = $"ResourceType '{id}' not found" }); return Task.FromResult(rt); } [HttpGet("Schemas")] public Task Schemas() { var schemas = new ScimListResponse { TotalResults = 3, ItemsPerPage = 3, Resources = [ ScimSchemaDefinitions.UserSchema, ScimSchemaDefinitions.EnterpriseUserSchema, ScimSchemaDefinitions.GroupSchema ] }; return Task.FromResult(schemas); } [HttpGet("Schemas/{id}")] public Task Schema([FromRoute("id")] string id) { ScimSchema? schema = id switch { ScimConstants.UserSchema => ScimSchemaDefinitions.UserSchema, ScimConstants.EnterpriseUserSchema => ScimSchemaDefinitions.EnterpriseUserSchema, ScimConstants.GroupSchema => ScimSchemaDefinitions.GroupSchema, _ => null }; if (schema is null) return Task.FromResult(new ScimError { Status = "404", Detail = $"Schema '{id}' not found" }); return Task.FromResult(schema); } } Path: redb-identity/src/redb.Identity.Http/Controllers/ScimGroupsController.cs Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/src/redb.Identity.Http/Controllers/ScimGroupsController.cs ---- using redb.Identity.Contracts.Scim; using redb.Identity.Contracts.Routes; using redb.Route.Controllers.Attributes; namespace redb.Identity.Http.Controllers; /// /// SCIM 2.0 Groups endpoint (RFC 7644 §3.2–3.5). /// Forwards to direct-vm://identity-scim-groups route. /// [Route("Groups")] public class ScimGroupsController : ScimControllerBase { [HttpGet] public async Task List( [FromQuery("startIndex")] int startIndex = 1, [FromQuery("count")] int count = 25, [FromQuery("filter")] string? filter = null, [FromQuery("sortBy")] string? sortBy = null, [FromQuery("sortOrder")] string? sortOrder = null) { return await Forward(IdentityEndpoints.ScimGroups, "list", new Dictionary { ["startIndex"] = startIndex, ["count"] = count, ["filter"] = filter, ["sortBy"] = sortBy, ["sortOrder"] = sortOrder }); } [HttpGet("{id}")] public async Task Get([FromRoute("id")] string id) { return await Forward(IdentityEndpoints.ScimGroups, "read", new Dictionary { ["id"] = id }); } [HttpPost] public async Task Create([FromBody] ScimGroup group) { if (ValidateRequest(group) is { } problem) return problem; return await Forward(IdentityEndpoints.ScimGroups, "create", group); } [HttpPut("{id}")] public async Task Replace([FromRoute("id")] string id, [FromBody] ScimGroup group) { group.Id = id; if (ValidateRequest(group) is { } problem) return problem; return await Forward(IdentityEndpoints.ScimGroups, "replace", group); } [HttpPatch("{id}")] public async Task Patch([FromRoute("id")] string id, [FromBody] ScimPatchRequest patch) { if (ValidateRequest(patch) is { } problem) return problem; return await Forward(IdentityEndpoints.ScimGroups, "patch", new Dictionary { ["id"] = id, ["patch"] = patch }); } [HttpDelete("{id}")] public async Task Delete([FromRoute("id")] string id) { return await Forward(IdentityEndpoints.ScimGroups, "delete", new Dictionary { ["id"] = id }); } } Path: redb-identity/src/redb.Identity.Http/Controllers/ScimUsersController.cs Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/src/redb.Identity.Http/Controllers/ScimUsersController.cs ---- using redb.Identity.Contracts.Scim; using redb.Identity.Contracts.Routes; using redb.Route.Controllers.Attributes; namespace redb.Identity.Http.Controllers; /// /// SCIM 2.0 Users endpoint (RFC 7644 §3.2–3.5). /// Forwards to direct-vm://identity-scim-users route. /// [Route("Users")] public class ScimUsersController : ScimControllerBase { [HttpGet] public async Task List( [FromQuery("startIndex")] int startIndex = 1, [FromQuery("count")] int count = 25, [FromQuery("filter")] string? filter = null, [FromQuery("sortBy")] string? sortBy = null, [FromQuery("sortOrder")] string? sortOrder = null) { return await Forward(IdentityEndpoints.ScimUsers, "list", new Dictionary { ["startIndex"] = startIndex, ["count"] = count, ["filter"] = filter, ["sortBy"] = sortBy, ["sortOrder"] = sortOrder }); } [HttpGet("{id}")] public async Task Get([FromRoute("id")] string id) { return await Forward(IdentityEndpoints.ScimUsers, "read", new Dictionary { ["id"] = id }); } [HttpPost] public async Task Create([FromBody] ScimUser user) { if (ValidateRequest(user) is { } problem) return problem; return await Forward(IdentityEndpoints.ScimUsers, "create", user); } [HttpPut("{id}")] public async Task Replace([FromRoute("id")] string id, [FromBody] ScimUser user) { user.Id = id; if (ValidateRequest(user) is { } problem) return problem; return await Forward(IdentityEndpoints.ScimUsers, "replace", user); } [HttpPatch("{id}")] public async Task Patch([FromRoute("id")] string id, [FromBody] ScimPatchRequest patch) { if (ValidateRequest(patch) is { } problem) return problem; return await Forward(IdentityEndpoints.ScimUsers, "patch", new Dictionary { ["id"] = id, ["patch"] = patch }); } [HttpDelete("{id}")] public async Task Delete([FromRoute("id")] string id) { return await Forward(IdentityEndpoints.ScimUsers, "delete", new Dictionary { ["id"] = id }); } } Path: redb-identity/src/redb.Identity.Http/Cors/AdditionalOriginsRegistry.cs Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/src/redb.Identity.Http/Cors/AdditionalOriginsRegistry.cs ---- using System.Collections.Immutable; using redb.Identity.Contracts.Cors; namespace redb.Identity.Http.Cors; /// /// Composes a base (which derives origins from /// registered OAuth clients) with an additional set of allowed origins supplied as a CSV /// string from transport options. The CSV callback is evaluated on every read so config /// hot-reload is picked up without restarting. /// /// Lives in the HTTP facade because the additional-origins concept is a transport-level /// fallback (dev/staging cases where browser apps are not yet registered as OAuth clients). /// /// internal sealed class AdditionalOriginsRegistry : IRegisteredClientOriginRegistry { private readonly IRegisteredClientOriginRegistry _inner; private readonly Func _additionalOriginsCsv; public AdditionalOriginsRegistry( IRegisteredClientOriginRegistry inner, Func additionalOriginsCsv) { _inner = inner ?? throw new ArgumentNullException(nameof(inner)); _additionalOriginsCsv = additionalOriginsCsv ?? throw new ArgumentNullException(nameof(additionalOriginsCsv)); } public async ValueTask IsAllowedAsync(string? origin, CancellationToken ct = default) { if (string.IsNullOrEmpty(origin)) return false; var snapshot = await GetAllowedOriginsAsync(ct).ConfigureAwait(false); return snapshot.Contains(origin); } public async ValueTask> GetAllowedOriginsAsync(CancellationToken ct = default) { var baseSet = await _inner.GetAllowedOriginsAsync(ct).ConfigureAwait(false); var csv = _additionalOriginsCsv(); if (string.IsNullOrEmpty(csv)) return baseSet; var builder = baseSet.ToBuilder(); foreach (var raw in csv.Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries)) { if (!Uri.TryCreate(raw, UriKind.Absolute, out var parsed)) continue; if (string.IsNullOrEmpty(parsed.Scheme) || string.IsNullOrEmpty(parsed.Host)) continue; builder.Add(parsed.GetLeftPart(UriPartial.Authority).ToLowerInvariant()); } return builder.ToImmutable(); } public void Invalidate() => _inner.Invalidate(); } Path: redb-identity/src/redb.Identity.Http/Cors/BrokeredRegisteredClientOriginRegistry.cs Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/src/redb.Identity.Http/Cors/BrokeredRegisteredClientOriginRegistry.cs ---- using System.Collections.Immutable; using redb.Identity.Contracts.Cors; using redb.Identity.Contracts.Routes; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Identity.Http.Cors; /// /// Phase 9e. implementation backed by /// the cross-context broker call to direct-vm://identity-cors-check. /// /// Registered in the HTTP-facade child container when the host root has no Core registry /// (i.e. the .tpkg boot path of ). /// In test-fixture mode the Core registry is reachable via DI and the bridge is bypassed. /// /// /// Design notes: /// /// returns an empty set — the snapshot lives /// in Core and is never materialised on the Http side. Diagnostics callers must hit /// Core directly via the management API. /// is a no-op — Core invalidates its own snapshot on /// application mutations; the broker call always sees the freshest data. /// No client-side cache (per Phase 9 §3 decision: MVP without cache; add TTL + /// invalidation broadcast in Phase 10). /// /// /// public sealed class BrokeredRegisteredClientOriginRegistry : IRegisteredClientOriginRegistry { private readonly IRouteContext _routeContext; private IProducerTemplate? _producer; private readonly object _producerLock = new(); public BrokeredRegisteredClientOriginRegistry(IRouteContext routeContext) { _routeContext = routeContext ?? throw new ArgumentNullException(nameof(routeContext)); } public async ValueTask IsAllowedAsync(string? origin, CancellationToken ct = default) { if (string.IsNullOrEmpty(origin)) return false; var producer = EnsureProducer(); var response = await producer .RequestBody(IdentityEndpoints.CorsCheck, new CorsCheckRequest { Origin = origin }) .ConfigureAwait(false); return response?.Allowed ?? false; } public ValueTask> GetAllowedOriginsAsync(CancellationToken ct = default) => new(ImmutableHashSet.Empty); public void Invalidate() { /* no-op: Core owns the snapshot */ } private IProducerTemplate EnsureProducer() { if (_producer is { IsStarted: true }) return _producer; lock (_producerLock) { if (_producer is { IsStarted: true }) return _producer; var p = new ProducerTemplate(_routeContext); p.Start(); _producer = p; return _producer; } } } Path: redb-identity/src/redb.Identity.Http/Cors/RegisteredClientOriginResolver.cs Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/src/redb.Identity.Http/Cors/RegisteredClientOriginResolver.cs ---- using Microsoft.AspNetCore.Http; using redb.Identity.Contracts.Cors; namespace redb.Identity.Http.Cors; /// /// HTTP-side adapter that exposes as a /// per-request CORS origin resolver compatible with RouteCorsOptions.OriginsResolver. /// /// The resolver is intentionally synchronous: RouteCorsOptions.OriginsResolver takes /// a , and the underlying registry exposes an async /// API. We bridge by blocking on the only when it has not /// already completed synchronously \u2014 in steady state the snapshot is in-memory, so this /// path is non-blocking. The first call after /// pays the rebuild cost; subsequent CORS preflights are O(1) hash lookups. /// /// public sealed class RegisteredClientOriginResolver { private readonly IRegisteredClientOriginRegistry _registry; public RegisteredClientOriginResolver(IRegisteredClientOriginRegistry registry) { _registry = registry ?? throw new ArgumentNullException(nameof(registry)); } /// /// Resolves the request's Origin against the registered-client whitelist. /// Returns the original origin string when allowed (so the dispatcher echoes it back /// verbatim) or null when not registered (no CORS headers will be emitted). /// public string? Resolve(HttpRequest request) { var origin = request.Headers["Origin"].ToString(); if (string.IsNullOrEmpty(origin)) return null; var task = _registry.IsAllowedAsync(origin, request.HttpContext.RequestAborted); var allowed = task.IsCompletedSuccessfully ? task.Result // First-call rebuild path: blocking GetAwaiter().GetResult() is acceptable here because // the work is bounded (one OpenIddict ListAsync) and serialised by the registry's // semaphore, so concurrent preflights do not stampede the store. : task.AsTask().GetAwaiter().GetResult(); return allowed ? origin : null; } } Path: redb-identity/src/redb.Identity.Http/Endpoints/BrokeredPostLogoutRedirectValidator.cs Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/src/redb.Identity.Http/Endpoints/BrokeredPostLogoutRedirectValidator.cs ---- using redb.Identity.Contracts.Endpoints; using redb.Identity.Contracts.Routes; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Identity.Http.Endpoints; /// /// Phase 9e. Validates an unauthenticated post_logout_redirect_uri by issuing a /// cross-context broker call to direct-vm://identity-validate-post-logout. Returns /// true when at least one registered OAuth client lists the URI as a post-logout target. /// /// Replaces the previous direct dependency on /// in HttpIdentityProcessors.HandlePostLogoutRedirect; the validator is now passed /// in as a delegate so the facade has zero knowledge of OpenIddict types. /// /// public sealed class BrokeredPostLogoutRedirectValidator { private readonly IRouteContext _routeContext; private IProducerTemplate? _producer; private readonly object _producerLock = new(); public BrokeredPostLogoutRedirectValidator(IRouteContext routeContext) { _routeContext = routeContext ?? throw new ArgumentNullException(nameof(routeContext)); } public async Task IsAllowedAsync(string redirectUri, CancellationToken ct) { if (string.IsNullOrEmpty(redirectUri)) return false; var producer = EnsureProducer(); var response = await producer .RequestBody( IdentityEndpoints.ValidatePostLogoutRedirect, new ValidatePostLogoutRedirectRequest { RedirectUri = redirectUri }) .ConfigureAwait(false); return response?.Allowed ?? false; } private IProducerTemplate EnsureProducer() { if (_producer is { IsStarted: true }) return _producer; lock (_producerLock) { if (_producer is { IsStarted: true }) return _producer; var p = new ProducerTemplate(_routeContext); p.Start(); _producer = p; return _producer; } } } Path: redb-identity/src/redb.Identity.Http/HttpFacadeRouteBuilder.cs Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/src/redb.Identity.Http/HttpFacadeRouteBuilder.cs ---- using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using redb.Identity.Contracts.Routes; using redb.Identity.Contracts.Cors; using redb.Identity.Http.Controllers; using redb.Identity.Management.Controllers; using redb.Identity.Http.Endpoints; using redb.Identity.Http.Security; using redb.Identity.Http.Cors; using redb.Identity.Http.Processors; using redb.Route.Abstractions; using redb.Route.Controllers; using redb.Route.Controllers.Extensions; using redb.Route.Core; using redb.Route.Http; using redb.Identity.Contracts.Configuration; using redb.Identity.Contracts.Federation; using redb.Identity.Contracts.Serialization; namespace redb.Identity.Http; /// /// HTTP facade for redb.Identity. Maps standard OIDC HTTP paths to /// direct-vm://identity-* internal routes and exposes a REST management API /// via -based controllers. /// /// Protocol endpoints (/connect/*, /.well-known/*) use hand-crafted /// processors for precise HTTP ↔ OIDC translation. Management endpoints /// (/api/v1/identity/*) use dispatch. /// /// public class HttpFacadeRouteBuilder : RouteBuilder { /// /// RFC 7591 Dynamic Client Registration endpoint path. Hard-coded here because /// it is referenced both by the route registration and by the discovery document /// patcher; if it ever moves under /api/v1/identity/..., both call sites /// must change together. /// private const string DynamicRegistrationPath = "/connect/register"; private readonly IdentityTransportOptions _transportOptions; private readonly SessionTicketService _ticketService; private readonly BrokeredPostLogoutRedirectValidator? _postLogoutValidator; private readonly Contracts.Mfa.IMfaStateInspector? _mfaStateInspector; private readonly IRegisteredClientOriginRegistry? _originRegistry; // URI scheme and shared TLS query parameters applied to EVERY endpoint below. When // IdentityTransport:Http:Ssl is true these become "https" + "&ssl=true&sslCertPath=…", so all // endpoints on the same host:port agree on TLS (SharedHttpServerManager rejects a mixed // http/https server). Computed once at the top of Configure(). private string _scheme = "http"; private string _sslParams = ""; // Bind address of every listener, from IdentityTransport:Http:Host. private string _host = "0.0.0.0"; public HttpFacadeRouteBuilder( SessionTicketService ticketService, IOptions? transportOptions = null, BrokeredPostLogoutRedirectValidator? postLogoutValidator = null, Contracts.Mfa.IMfaStateInspector? mfaStateInspector = null, IRegisteredClientOriginRegistry? originRegistry = null) { _ticketService = ticketService; _transportOptions = transportOptions?.Value ?? new IdentityTransportOptions(); _postLogoutValidator = postLogoutValidator; _mfaStateInspector = mfaStateInspector; _originRegistry = originRegistry; } protected override void Configure() { var port = _transportOptions.Http.PublicPort; var mgmtPort = _transportOptions.Http.ManagementPort ?? port; _host = _transportOptions.Http.Host; // TLS: compute scheme + ssl query params once, apply uniformly to every From(...) below. if (_transportOptions.Http.Ssl) { var certPath = _transportOptions.Http.SslCertPath ?? throw new InvalidOperationException( "IdentityTransport:Http:SslCertPath is required when IdentityTransport:Http:Ssl=true."); _scheme = "https"; _sslParams = $"&ssl=true&sslCertPath={Uri.EscapeDataString(certPath)}"; if (!string.IsNullOrEmpty(_transportOptions.Http.SslCertPassword)) _sslParams += $"&sslCertPassword={Uri.EscapeDataString(_transportOptions.Http.SslCertPassword)}"; } // C15 / per-route CORS: wire up the registered-client origin resolver before any // route is registered so that the shared HttpComponent picks it up via its // DefaultCors mechanism. The resolver is only consumed for endpoints whose URI // declares cors=true *without* an explicit corsOrigins (see HttpComponent.ApplyCorsDefaults). // For public endpoints (well-known) we inline corsOrigins=*; for management/redirect // endpoints we omit cors entirely. ConfigureCorsResolver(); ConfigureProtocolEndpoints(port); ConfigureDiscoveryEndpoints(port); // Public read-only projection of the federation provider list. Registered BEFORE // ConfigureManagementApi because that one installs a catch-all // /api/v1/identity/{**path} route that would otherwise capture // /api/v1/identity/federation-providers/public and dispatch it to // FederationProvidersController.Get({id="public"}) → "Id is required" error. // Exposed even when no providers are configured (empty array) so callers can rely // on a stable contract. Skipped only when federation is disabled at the feature // flag level. Registered on both the public and management ports (when they differ) // so browser-facing login pages on the public origin and server-to-server callers // on the management origin can both reach it. if (_transportOptions.Features.EnableFederation) { ConfigurePublicFederationProvidersEndpoint(port, routeIdSuffix: "public"); if (mgmtPort != port) ConfigurePublicFederationProvidersEndpoint(mgmtPort, routeIdSuffix: "mgmt"); } ConfigureManagementApi(mgmtPort); ConfigureBootstrapEndpoint(mgmtPort); if (_transportOptions.Features.EnableScim) ConfigureScimApi(mgmtPort); if (_transportOptions.Features.EnableFederation && _transportOptions.FederationProviders.Count > 0) ConfigureFederationEndpoints(port); } /// /// Installs the CORS origin resolver on the shared 's /// DefaultCors. Resolver precedence (first non-null wins): /// /// caller-supplied ; /// registered-client resolver (when /// is true); /// no resolver \u2014 only static /// (passed verbatim to the registry as additional origins). /// /// No-op when CORS is disabled at the transport level. /// private void ConfigureCorsResolver() { if (!_transportOptions.Http.CorsEnabled) return; // The HttpComponent owns the per-server registry (DefaultCors is its property), // so we look it up via the route context's component registry rather than DI \u2014 // it is added by the host with `ctx.AddComponent(new HttpComponent { ... })` and // therefore is not necessarily registered in the IServiceProvider. var component = Context?.GetComponent("http"); if (component is null) return; // Caller-supplied resolver wins outright (it may legitimately want to ignore the // registered-client whitelist). if (_transportOptions.Http.CorsOriginsResolver is { } customResolver) { component.DefaultCors.OriginsResolver = customResolver; return; } if (!_transportOptions.Http.CorsRegisteredClientOriginsEnabled) { // Even when the registered-client whitelist is disabled, AdditionalAllowedOrigins // must still flow through a resolver: the route URI declares cors=true without a // static corsOrigins, so the dispatcher needs *some* policy or the request gets // no headers at all. Build a resolver that consults additional-origins only. var additional = _transportOptions.Http.GetEffectiveAdditionalOrigins(); if (string.IsNullOrEmpty(additional)) return; var allowed = additional .Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries) .Select(o => o.ToLowerInvariant()) .ToHashSet(StringComparer.OrdinalIgnoreCase); component.DefaultCors.OriginsResolver = req => { var origin = req.Headers["Origin"].ToString(); return !string.IsNullOrEmpty(origin) && allowed.Contains(origin) ? origin : null; }; return; } var sp = Context?.GetServiceProvider(); // Phase 9e: prefer the registry passed to the ctor (HTTP-facade child container in // .tpkg mode wires BrokeredRegisteredClientOriginRegistry); fall back to the route // context SP for embedded test-fixture mode where the host registers Core's impl. var registry = _originRegistry ?? sp?.GetService(); // Fallback when the host did not call AddRedbIdentityServer (e.g. a custom test bench): // build a transient registry that only honours AdditionalAllowedOrigins. var effectiveAdditional = _transportOptions.Http.GetEffectiveAdditionalOrigins(); if (registry is null) { // Without an IOpenIddictApplicationManager we cannot derive origins from clients; // fall back to additional-origins-only. if (string.IsNullOrEmpty(effectiveAdditional)) return; var allowed = effectiveAdditional .Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries) .Select(o => o.ToLowerInvariant()) .ToHashSet(StringComparer.OrdinalIgnoreCase); component.DefaultCors.OriginsResolver = req => { var origin = req.Headers["Origin"].ToString(); return !string.IsNullOrEmpty(origin) && allowed.Contains(origin) ? origin : null; }; return; } // Compose: the DI-registered registry knows about OAuth clients; we wrap it so the // additional-origins CSV from transport options is also honoured. The wrapper lives // in this assembly so the facade does not have to instantiate any Core implementation // type directly. var composedRegistry = new AdditionalOriginsRegistry( registry, () => effectiveAdditional); var resolver = new RegisteredClientOriginResolver(composedRegistry); component.DefaultCors.OriginsResolver = resolver.Resolve; } /// /// Builds CORS query params for browser-facing OIDC endpoints (token, userinfo, etc.). /// Emits cors=true WITHOUT a static origin whitelist so that the component-level /// resolver (configured by ) is auto-injected by /// . When CORS is disabled at the transport /// level, returns an empty string. /// private string ClientCorsParams() { if (!_transportOptions.Http.CorsEnabled) return ""; // Credentials are required so that browsers attach the OIDC session cookie to // userinfo / revocation calls. Browsers refuse "*"+credentials, but our resolver // never returns "*", so the runtime guard does not trip. return "&cors=true&corsCredentials=true"; } /// /// Builds CORS query params for unauthenticated public endpoints (/.well-known/*). /// These are safe to expose to any origin: discovery and JWKS are world-readable by /// design (RFC 8414 \u00a73, RFC 7517) and contain no per-user data. /// Emits a wildcard whitelist; the resolver is suppressed because corsOrigins is /// declared explicitly (see ). /// private string PublicCorsParams() { if (!_transportOptions.Http.CorsEnabled) return ""; return "&cors=true&corsOrigins=*"; } /// /// OIDC protocol endpoints: token, authorize, userinfo, introspect, revoke. /// Each HTTP route maps to a corresponding direct-vm://identity-* route. /// private void ConfigureProtocolEndpoints(int port) { var cookieMaxAge = _transportOptions.SessionCookieLifetime; var loginPath = _transportOptions.Paths.Login; var consentPath = _transportOptions.Paths.Consent; var secureCookie = _transportOptions.Issuer.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase); var cookieOpts = _transportOptions.Cookies; var sessionCookieName = cookieOpts.SessionCookieName; var sessionSameSite = cookieOpts.SessionSameSite; var useHostPrefix = cookieOpts.UseHostPrefix; // Token endpoint — POST only, form-encoded client auth From($"{_scheme}:POST:{_host}:{port}/connect/token?inOut=true{_sslParams}{ClientCorsParams()}") .RouteId("http-token") .Process(HttpIdentityProcessors.PropagateCorrelationId) .Process(HttpIdentityProcessors.MapHttpToIdentityHeaders) .Process(HttpIdentityProcessors.MapFormToBody) .To(IdentityEndpoints.Token) .Process(HttpIdentityProcessors.MapOAuthErrorToHttpStatus) .Process(HttpIdentityProcessors.SerializeJsonResponse) .Process(HttpIdentityProcessors.AddNoStoreCacheHeaders); // RFC 6749 §5.1 // Pushed Authorization Request endpoint (RFC 9126 / Z6) — POST only, // form-encoded client auth. Mirrors the Token endpoint pipeline. if (_transportOptions.Features.EnablePushedAuthorization) { From($"{_scheme}:POST:{_host}:{port}/connect/par?inOut=true{_sslParams}{ClientCorsParams()}") .RouteId("http-par") .Process(HttpIdentityProcessors.PropagateCorrelationId) .Process(HttpIdentityProcessors.MapHttpToIdentityHeaders) .Process(HttpIdentityProcessors.MapFormToBody) .To(IdentityEndpoints.PushedAuthorization) .Process(HttpIdentityProcessors.MapOAuthErrorToHttpStatus) .Process(HttpIdentityProcessors.SerializeJsonResponse) .Process(HttpIdentityProcessors.AddNoStoreCacheHeaders); // RFC 6749 §5.1 } // Authorization endpoint — GET (query params) + POST (form body) // Session cookie is read before routing so AttachSessionPrincipalHandler can use it From($"{_scheme}:GET:{_host}:{port}/connect/authorize?inOut=true{_sslParams}") .RouteId("http-authorize-get") .Process(HttpIdentityProcessors.PropagateCorrelationId) .Process((e, ct) => SessionCookieProcessors.ReadSessionCookie(e, ct, _ticketService, cookieMaxAge, sessionCookieName)) .Process(HttpIdentityProcessors.MapQueryToBody) .To(IdentityEndpoints.Authorize) .Process(HttpIdentityProcessors.HandleRedirectResponse) .Process((e, ct) => SessionCookieProcessors.RedirectToLogin(e, ct, loginPath)) .Process((e, ct) => SessionCookieProcessors.RedirectToConsent(e, ct, consentPath, _ticketService)) .Process((e, ct) => SessionCookieProcessors.HandleReauthCookie(e, ct, _ticketService, secureCookie, sessionSameSite, useHostPrefix)) .Process(HttpIdentityProcessors.MapOAuthErrorToHttpStatus) .Process((e, ct) => HttpIdentityProcessors.RenderAuthorizeErrorPage(e, ct, _transportOptions)) .Process(HttpIdentityProcessors.SerializeJsonResponse); From($"{_scheme}:POST:{_host}:{port}/connect/authorize?inOut=true{_sslParams}") .RouteId("http-authorize-post") .Process(HttpIdentityProcessors.PropagateCorrelationId) .Process((e, ct) => SessionCookieProcessors.ReadSessionCookie(e, ct, _ticketService, cookieMaxAge, sessionCookieName)) .Process(HttpIdentityProcessors.MapHttpToIdentityHeaders) .Process(HttpIdentityProcessors.MapFormToBody) .Process(SessionCookieProcessors.CaptureAuthorizeForm) .To(IdentityEndpoints.Authorize) .Process(HttpIdentityProcessors.HandleRedirectResponse) .Process((e, ct) => SessionCookieProcessors.RedirectToLogin(e, ct, loginPath)) .Process((e, ct) => SessionCookieProcessors.RedirectToConsent(e, ct, consentPath, _ticketService)) .Process((e, ct) => SessionCookieProcessors.HandleReauthCookie(e, ct, _ticketService, secureCookie, sessionSameSite, useHostPrefix)) .Process(HttpIdentityProcessors.MapOAuthErrorToHttpStatus) .Process((e, ct) => HttpIdentityProcessors.RenderAuthorizeErrorPage(e, ct, _transportOptions)) .Process(HttpIdentityProcessors.SerializeJsonResponse); // Login page — GET renders form, POST submits credentials → session cookie From($"{_scheme}:GET:{_host}:{port}{loginPath}?inOut=true{_sslParams}") .RouteId("http-login-get") .Process(HttpIdentityProcessors.PropagateCorrelationId) .Process((e, ct) => LoginPageProcessors.RenderLoginPage(e, ct, loginPath, _transportOptions)) .Process(HttpIdentityProcessors.SerializeJsonResponse); // Every form POST the facade renders itself starts with the cross-site guard: // a submission announcing a foreign Origin/Referer is refused before the body is read. From($"{_scheme}:POST:{_host}:{port}{loginPath}?inOut=true{_sslParams}") .RouteId("http-login-post") .Process(HttpIdentityProcessors.PropagateCorrelationId) .Process((e, ct) => AntiForgeryProcessors.RejectCrossSiteFormPost(e, ct, _transportOptions.Issuer, _transportOptions)) .Process(HttpIdentityProcessors.MapFormToBody) .To(IdentityEndpoints.Login) .Process((e, ct) => SessionCookieProcessors.WriteSessionCookie(e, ct, _ticketService, cookieMaxAge, secureCookie, sessionCookieName, sessionSameSite, useHostPrefix)) // B3 §4: materialize body["mfa_state"] as __Host-redb.identity.mfa cookie. // Runs BEFORE HandleLoginResponse so the cookie is placed on the body-carrying // message before the response gets replaced with a 302 (HandleLoginResponse // preserves Set-Cookie via ExtractSetCookie). .Process((e, ct) => MfaCookieProcessors.WriteMfaStateCookie(e, ct, secureCookie, CookieSameSiteMode.Strict, useHostPrefix, TimeSpan.FromMinutes(5))) .Process((e, ct) => LoginPageProcessors.HandleLoginResponse(e, ct, loginPath, _transportOptions)) .Process(HttpIdentityProcessors.SerializeJsonResponse); // MFA TOTP verification page — GET renders form, POST verifies code → session cookie var mfaPath = _transportOptions.Paths.Mfa; var mfaRecoveryPath = _transportOptions.Paths.MfaRecovery; From($"{_scheme}:GET:{_host}:{port}{mfaPath}?inOut=true{_sslParams}") .RouteId("http-mfa-get") .Process(HttpIdentityProcessors.PropagateCorrelationId) // B3 §4: pull mfa_state out of the __Host-redb.identity.mfa cookie so the page // can render without any URL query parameter. .Process(MfaCookieProcessors.ReadMfaStateCookie) .Process((e, ct) => MfaPageProcessors.RenderMfaPage(e, ct, mfaPath, _transportOptions, _mfaStateInspector)) .Process(HttpIdentityProcessors.SerializeJsonResponse); From($"{_scheme}:POST:{_host}:{port}{mfaPath}?inOut=true{_sslParams}") .RouteId("http-mfa-post") .Process(HttpIdentityProcessors.PropagateCorrelationId) .Process((e, ct) => AntiForgeryProcessors.RejectCrossSiteFormPost(e, ct, _transportOptions.Issuer, _transportOptions)) .Process(HttpIdentityProcessors.MapFormToBody) .Process(MfaCookieProcessors.ReadMfaStateCookie) .To(IdentityEndpoints.MfaVerify) .Process((e, ct) => SessionCookieProcessors.WriteSessionCookie(e, ct, _ticketService, cookieMaxAge, secureCookie, sessionCookieName, sessionSameSite, useHostPrefix)) .Process((e, ct) => MfaCookieProcessors.ClearMfaStateCookieOnSuccess(e, ct, secureCookie, CookieSameSiteMode.Strict, useHostPrefix)) .Process((e, ct) => MfaPageProcessors.HandleMfaVerifyResponse(e, ct, mfaPath, _transportOptions)) .Process(HttpIdentityProcessors.SerializeJsonResponse); // MFA recovery code page — GET renders form, POST verifies recovery code → session cookie From($"{_scheme}:GET:{_host}:{port}{mfaRecoveryPath}?inOut=true{_sslParams}") .RouteId("http-mfa-recovery-get") .Process(HttpIdentityProcessors.PropagateCorrelationId) .Process(MfaCookieProcessors.ReadMfaStateCookie) .Process((e, ct) => MfaPageProcessors.RenderMfaRecoveryPage(e, ct, mfaRecoveryPath, mfaPath, _transportOptions)) .Process(HttpIdentityProcessors.SerializeJsonResponse); From($"{_scheme}:POST:{_host}:{port}{mfaRecoveryPath}?inOut=true{_sslParams}") .RouteId("http-mfa-recovery-post") .Process(HttpIdentityProcessors.PropagateCorrelationId) .Process((e, ct) => AntiForgeryProcessors.RejectCrossSiteFormPost(e, ct, _transportOptions.Issuer, _transportOptions)) .Process(HttpIdentityProcessors.MapFormToBody) .Process(MfaCookieProcessors.ReadMfaStateCookie) .To(IdentityEndpoints.MfaRecovery) .Process((e, ct) => SessionCookieProcessors.WriteSessionCookie(e, ct, _ticketService, cookieMaxAge, secureCookie, sessionCookieName, sessionSameSite, useHostPrefix)) .Process((e, ct) => MfaCookieProcessors.ClearMfaStateCookieOnSuccess(e, ct, secureCookie, CookieSameSiteMode.Strict, useHostPrefix)) .Process((e, ct) => MfaPageProcessors.HandleMfaRecoveryResponse(e, ct, mfaRecoveryPath, mfaPath, _transportOptions)) .Process(HttpIdentityProcessors.SerializeJsonResponse); // MFA challenge dispatch — POST sends OTP via SMS/Email, returns new mfa_state with embedded code. // AJAX endpoint (no session cookie set here — that happens after verify). var mfaChallengePath = mfaPath.TrimEnd('/') + "/challenge"; From($"{_scheme}:POST:{_host}:{port}{mfaChallengePath}?inOut=true{_sslParams}") .RouteId("http-mfa-challenge-post") .Process(HttpIdentityProcessors.PropagateCorrelationId) .Process(HttpIdentityProcessors.MapFormToBody) .Process(MfaCookieProcessors.ReadMfaStateCookie) .To(IdentityEndpoints.MfaChallenge) // Refresh __Host-redb.identity.mfa cookie with the new state issued by the challenge. .Process((e, ct) => MfaCookieProcessors.WriteMfaStateCookie(e, ct, secureCookie, CookieSameSiteMode.Strict, useHostPrefix, TimeSpan.FromMinutes(5))) .Process(HttpIdentityProcessors.SerializeJsonResponse); // B9 / BUG-9 — gated MFA method enumeration. Auth0-style: caller must present a // valid encrypted mfa_state (issued by login) to learn which factors are configured. var mfaMethodsPath = mfaPath.TrimEnd('/') + "/methods"; From($"{_scheme}:POST:{_host}:{port}{mfaMethodsPath}?inOut=true{_sslParams}") .RouteId("http-mfa-methods-post") .Process(HttpIdentityProcessors.PropagateCorrelationId) .Process(HttpIdentityProcessors.MapFormToBody) .To(IdentityEndpoints.MfaListMethods) .Process(HttpIdentityProcessors.SerializeJsonResponse); // Consent page — GET renders consent form, POST processes decision From($"{_scheme}:GET:{_host}:{port}{consentPath}?inOut=true{_sslParams}") .RouteId("http-consent-get") .Process(HttpIdentityProcessors.PropagateCorrelationId) .Process((e, ct) => ConsentPageProcessors.RenderConsentPage(e, ct, _ticketService, consentPath, _transportOptions)) .Process(HttpIdentityProcessors.SerializeJsonResponse); From($"{_scheme}:POST:{_host}:{port}{consentPath}?inOut=true{_sslParams}") .RouteId("http-consent-post") .Process(HttpIdentityProcessors.PropagateCorrelationId) .Process((e, ct) => AntiForgeryProcessors.RejectCrossSiteFormPost(e, ct, _transportOptions.Issuer, _transportOptions)) .Process((e, ct) => SessionCookieProcessors.ReadSessionCookie(e, ct, _ticketService, cookieMaxAge, sessionCookieName)) .Process(HttpIdentityProcessors.MapFormToBody) // Consenting user from the session cookie only; parameters from the signed ticket // (our page) or the session-bound form (BFF). No session → 401, pipeline stops. .Process((e, ct) => ConsentPageProcessors.PrepareConsentBody(e, ct, _ticketService, _transportOptions)) .To(IdentityEndpoints.ConsentGrant) .Process((e, ct) => ConsentPageProcessors.HandleConsentResponse(e, ct, _transportOptions)) .Process(HttpIdentityProcessors.SerializeJsonResponse); // Userinfo — GET and POST with Bearer token. AttachBearerChallengeOnError adds // the WWW-Authenticate: Bearer challenge mandated by RFC 6750 §3 on any error // response (missing token, invalid token, etc.). From($"{_scheme}:GET:{_host}:{port}/connect/userinfo?inOut=true{_sslParams}{ClientCorsParams()}") .RouteId("http-userinfo-get") .Process(HttpIdentityProcessors.PropagateCorrelationId) .Process(HttpIdentityProcessors.ExtractBearerToken) .To(IdentityEndpoints.Userinfo) .Process(HttpIdentityProcessors.MapOAuthErrorToHttpStatus) .Process(HttpIdentityProcessors.AttachBearerChallengeOnError) .Process(HttpIdentityProcessors.SerializeJsonResponse); From($"{_scheme}:POST:{_host}:{port}/connect/userinfo?inOut=true{_sslParams}{ClientCorsParams()}") .RouteId("http-userinfo-post") .Process(HttpIdentityProcessors.PropagateCorrelationId) // RFC 6750 §2.2 also allows the access token as a form-encoded body parameter, not just // the Authorization header. Without MapFormToBody the POST body never reached the // handler, so `access_token=…` in the body came back as "missing_token" (the OIDF suite // reports this as "does not appear to support access tokens passed in the POST body"). // The header still wins when both are present — ExtractUserinfoRequestHandler only falls // back to it when the request carries no access_token parameter. .Process(HttpIdentityProcessors.MapFormToBody) .Process(HttpIdentityProcessors.ExtractBearerToken) .To(IdentityEndpoints.Userinfo) .Process(HttpIdentityProcessors.MapOAuthErrorToHttpStatus) .Process(HttpIdentityProcessors.AttachBearerChallengeOnError) .Process(HttpIdentityProcessors.SerializeJsonResponse); // Revocation — client-authenticated From($"{_scheme}:POST:{_host}:{port}/connect/revocation?inOut=true{_sslParams}{ClientCorsParams()}") .RouteId("http-revoke") .Process(HttpIdentityProcessors.PropagateCorrelationId) .Process(HttpIdentityProcessors.MapHttpToIdentityHeaders) .Process(HttpIdentityProcessors.MapFormToBody) .To(IdentityEndpoints.Revoke) // RFC 7009 §2.2.1: an error answers as RFC 6749 §5.2 says (400, 401 for invalid_client); // 200 is for the token itself, valid or not. .Process(HttpIdentityProcessors.MapRevocationErrorToHttpStatus) .Process(HttpIdentityProcessors.SerializeJsonResponse) .Process(HttpIdentityProcessors.AddNoStoreCacheHeaders); // RFC 7009 / 6749 §5.1 // Introspection — client-authenticated From($"{_scheme}:POST:{_host}:{port}/connect/introspect?inOut=true{_sslParams}{ClientCorsParams()}") .RouteId("http-introspect") .Process(HttpIdentityProcessors.PropagateCorrelationId) .Process(HttpIdentityProcessors.MapHttpToIdentityHeaders) .Process(HttpIdentityProcessors.MapFormToBody) .To(IdentityEndpoints.Introspect) .Process(HttpIdentityProcessors.MapOAuthErrorToHttpStatus) .Process(HttpIdentityProcessors.SerializeJsonResponse) .Process(HttpIdentityProcessors.AddNoStoreCacheHeaders); // RFC 7662 / 6749 §5.1 // Logout — GET /connect/logout (OIDC RP-Initiated Logout 1.0 §2: the RP redirects the browser here). // ReadSessionCookie decodes the browser's own session into headers; that session, and nothing the // request says about the user, is what LogoutProcessor ends. Neither verb carries // RejectCrossSiteFormPost, on purpose: an RP-initiated logout is a cross-site request by design // (RP origin → OP), and the request acts only on the cookie the browser sends. A cross-site POST // carries no SameSite=Lax cookie and ends nothing; a cross-site top-level GET does carry it, which // is why a request without a valid id_token_hint for the session's user gets the confirmation page // (RenderLogoutConfirmation) and ends nothing until the page's own state comes back. // Phase 9e: post_logout_redirect_uri validation goes through BrokeredPostLogoutRedirectValidator // (direct-vm broker call into Core). The validator is resolved at route-build time and // captured by the inline lambda below; null in test-fixture mode → falls back to "signed out". var validatePostLogout = _postLogoutValidator is null ? (Func>?)null : _postLogoutValidator.IsAllowedAsync; From($"{_scheme}:GET:{_host}:{port}/connect/logout?inOut=true{_sslParams}{ClientCorsParams()}") .RouteId("http-logout-get") .Process(HttpIdentityProcessors.PropagateCorrelationId) .Process((e, ct) => SessionCookieProcessors.ReadSessionCookie(e, ct, _ticketService, cookieMaxAge, sessionCookieName)) .Process(HttpIdentityProcessors.MapQueryToBody) .Process(HttpIdentityProcessors.PreservePostLogoutRedirectUri) .To(IdentityEndpoints.Logout) .Process((e, ct) => HttpIdentityProcessors.RenderLogoutConfirmation(e, ct, _transportOptions)) .Process((e, ct) => SessionCookieProcessors.ClearSessionCookie(e, ct, secureCookie, sessionCookieName, sessionSameSite, useHostPrefix)) .Process((e, ct) => HttpIdentityProcessors.HandlePostLogoutRedirect(e, ct, _transportOptions, validatePostLogout)) .Process(HttpIdentityProcessors.SerializeJsonResponse); // Logout — POST /connect/logout (form submission) From($"{_scheme}:POST:{_host}:{port}/connect/logout?inOut=true{_sslParams}{ClientCorsParams()}") .RouteId("http-logout") .Process(HttpIdentityProcessors.PropagateCorrelationId) .Process((e, ct) => SessionCookieProcessors.ReadSessionCookie(e, ct, _ticketService, cookieMaxAge, sessionCookieName)) .Process(HttpIdentityProcessors.MapFormToBody) .Process(HttpIdentityProcessors.PreservePostLogoutRedirectUri) .To(IdentityEndpoints.Logout) .Process((e, ct) => HttpIdentityProcessors.RenderLogoutConfirmation(e, ct, _transportOptions)) .Process((e, ct) => SessionCookieProcessors.ClearSessionCookie(e, ct, secureCookie, sessionCookieName, sessionSameSite, useHostPrefix)) .Process((e, ct) => HttpIdentityProcessors.HandlePostLogoutRedirect(e, ct, _transportOptions, validatePostLogout)) .Process(HttpIdentityProcessors.SerializeJsonResponse); // Dynamic Client Registration — POST /connect/register (RFC 7591) if (_transportOptions.Features.EnableDynamicRegistration) { From($"{_scheme}:POST:{_host}:{port}{DynamicRegistrationPath}?inOut=true{_sslParams}{ClientCorsParams()}") .RouteId("http-dynamic-register") .Process(HttpIdentityProcessors.PropagateCorrelationId) .Process(HttpIdentityProcessors.ExtractBearerToken) .To(IdentityEndpoints.DynamicRegister) .Process(HttpIdentityProcessors.SerializeJsonResponse); // Z2 (RFC 7592): Client configuration endpoint — GET/PUT/DELETE /connect/register/{client_id}. // Single catch-all route; the op+id extractor derives operation and client_id from method+path. From($"{_scheme}:{_host}:{port}{DynamicRegistrationPath}/{{**clientId}}?inOut=true{_sslParams}{ClientCorsParams()}") .RouteId("http-dynamic-register-manage") .Process(HttpIdentityProcessors.PropagateCorrelationId) .Process(HttpIdentityProcessors.ExtractBearerToken) .Process(HttpIdentityProcessors.ExtractDynamicRegistrationManagement) .To(IdentityEndpoints.DynamicRegisterManage) .Process(HttpIdentityProcessors.SerializeJsonResponse); } // Device Authorization — POST /connect/deviceauthorization (RFC 8628) if (_transportOptions.Features.EnableDeviceCodeFlow) { From($"{_scheme}:POST:{_host}:{port}/connect/deviceauthorization?inOut=true{_sslParams}{ClientCorsParams()}") .RouteId("http-device") .Process(HttpIdentityProcessors.PropagateCorrelationId) .Process(HttpIdentityProcessors.MapHttpToIdentityHeaders) .Process(HttpIdentityProcessors.MapFormToBody) .To(IdentityEndpoints.Device) .Process(HttpIdentityProcessors.MapOAuthErrorToHttpStatus) .Process(HttpIdentityProcessors.SerializeJsonResponse) .Process(HttpIdentityProcessors.AddNoStoreCacheHeaders); // RFC 8628 / 6749 §5.1 // End-User Verification — POST /connect/device/verify (RFC 8628 §3.3). // ExtractBearerToken is required for the BFF-relayed authentication path: // HandleVerificationRequestHandler accepts either form credentials (direct // host-UI flow) OR an Authorization: Bearer access_token (BFF-relayed flow). From($"{_scheme}:POST:{_host}:{port}/connect/device/verify?inOut=true{_sslParams}") .RouteId("http-verification") .Process(HttpIdentityProcessors.PropagateCorrelationId) .Process(HttpIdentityProcessors.MapHttpToIdentityHeaders) .Process(HttpIdentityProcessors.ExtractBearerToken) .Process(HttpIdentityProcessors.MapFormToBody) .To(IdentityEndpoints.Verification) .Process(HttpIdentityProcessors.MapOAuthErrorToHttpStatus) .Process(HttpIdentityProcessors.SerializeJsonResponse); } } /// /// Discovery and JWKS endpoints (read-only, no auth required). /// /// /// Exposes both OIDC Discovery 1.0 (/.well-known/openid-configuration) and /// RFC 8414 OAuth 2.0 Authorization Server Metadata /// (/.well-known/oauth-authorization-server). Both routes share the same /// document — the OIDC superset is a valid OAuth 2.0 metadata response per /// RFC 8414 §2 (additional fields are allowed). /// private void ConfigureDiscoveryEndpoints(int port) { // OIDC Discovery 1.0 BuildDiscoveryRoute(port, "/.well-known/openid-configuration", "http-discovery"); // RFC 8414 — OAuth 2.0 Authorization Server Metadata (for non-OIDC clients) BuildDiscoveryRoute(port, "/.well-known/oauth-authorization-server", "http-discovery-oauth"); From($"{_scheme}:GET:{_host}:{port}/.well-known/jwks?inOut=true{_sslParams}{PublicCorsParams()}") .RouteId("http-jwks") .Process(HttpIdentityProcessors.PropagateCorrelationId) .To(IdentityEndpoints.Jwks) .Process(HttpIdentityProcessors.SerializeJsonResponse); } private void BuildDiscoveryRoute(int port, string path, string routeId) { var route = From($"{_scheme}:GET:{_host}:{port}{path}?inOut=true{_sslParams}{PublicCorsParams()}") .RouteId(routeId) .Process(HttpIdentityProcessors.PropagateCorrelationId) .To(IdentityEndpoints.Discovery); if (_transportOptions.Features.EnableDynamicRegistration) { var issuer = _transportOptions.Issuer.ToString().TrimEnd('/'); route.Process((e, ct) => { var body = e.HasOut ? e.Out!.Body : e.In.Body; if (body is IDictionary dict) dict["registration_endpoint"] = $"{issuer}{DynamicRegistrationPath}"; return Task.CompletedTask; }); } route.Process(HttpIdentityProcessors.SerializeJsonResponse); } /// /// Management API using -based dispatch. /// All /api/v1/identity/* requests are handled by attribute-routed controllers. /// Bearer token authentication (via ) validates the access token /// and enforces the required management scope before request processing. /// private void ConfigureManagementApi(int port) { var registry = new ControllerRegistry(); registry.RegisterController(typeof(ApplicationsController)); registry.RegisterController(typeof(ConsentsController)); registry.RegisterController(typeof(GroupsController)); registry.RegisterController(typeof(ScopesController)); registry.RegisterController(typeof(SessionsController)); registry.RegisterController(typeof(MeSessionsController)); registry.RegisterController(typeof(RevokedSidsController)); registry.RegisterController(typeof(MeController)); registry.RegisterController(typeof(MePasswordController)); registry.RegisterController(typeof(PasswordRecoveryController)); registry.RegisterController(typeof(AccountRegistrationController)); registry.RegisterController(typeof(MeEmailVerifyController)); registry.RegisterController(typeof(AccountEmailVerifyController)); registry.RegisterController(typeof(MeChangeEmailController)); registry.RegisterController(typeof(AccountChangeEmailController)); registry.RegisterController(typeof(MeMfaController)); registry.RegisterController(typeof(MeWebAuthnController)); registry.RegisterController(typeof(MeConsentsController)); registry.RegisterController(typeof(MeFederatedIdentitiesController)); registry.RegisterController(typeof(TokensController)); registry.RegisterController(typeof(UsersController)); registry.RegisterController(typeof(MfaController)); registry.RegisterController(typeof(AuditController)); registry.RegisterController(typeof(ClaimMappersController)); registry.RegisterController(typeof(ClaimScopesController)); registry.RegisterController(typeof(ClaimDefinitionsController)); registry.RegisterController(typeof(RolesController)); registry.RegisterController(typeof(WebhooksController)); registry.RegisterController(typeof(FederationProvidersController)); registry.RegisterController(typeof(ImpersonationController)); registry.RegisterController(typeof(SigningKeysController)); // SCIM discovery endpoints under management API path (RFC 7644 §4) — unauthenticated var scimDiscoveryRegistry = new ControllerRegistry(); scimDiscoveryRegistry.RegisterController(typeof(ScimDiscoveryController)); From($"{_scheme}:GET:{_host}:{port}/api/v1/identity/scim/v2/ServiceProviderConfig?inOut=true{_sslParams}") .RouteId("http-management-scim-discovery-spc") .Process(HttpIdentityProcessors.PropagateCorrelationId) .Process(HttpIdentityProcessors.StripManagementPrefix) .Process(ScimHttpProcessors.StripScimPrefix) .RedbHttpController(scimDiscoveryRegistry) .Process(ScimHttpProcessors.SerializeScimJsonResponse); From($"{_scheme}:GET:{_host}:{port}/api/v1/identity/scim/v2/ResourceTypes?inOut=true{_sslParams}") .RouteId("http-management-scim-discovery-rt") .Process(HttpIdentityProcessors.PropagateCorrelationId) .Process(HttpIdentityProcessors.StripManagementPrefix) .Process(ScimHttpProcessors.StripScimPrefix) .RedbHttpController(scimDiscoveryRegistry) .Process(ScimHttpProcessors.SerializeScimJsonResponse); // Single-resource discovery. These existed on the public /scim/v2 surface but not here, so a // provisioning client pointed at the management base URL — which is how Okta / Entra are // actually configured: one base URL, and they walk ResourceTypes then fetch each Schema by // id — got a 404 on the very first schema it asked for. Same registry, same controller; only // the route was missing. From($"{_scheme}:GET:{_host}:{port}/api/v1/identity/scim/v2/ResourceTypes/{{**path}}?inOut=true{_sslParams}") .RouteId("http-management-scim-discovery-rt-id") .Process(HttpIdentityProcessors.PropagateCorrelationId) .Process(HttpIdentityProcessors.StripManagementPrefix) .Process(ScimHttpProcessors.StripScimPrefix) .RedbHttpController(scimDiscoveryRegistry) .Process(ScimHttpProcessors.MapScimResponseToHttpStatus) .Process(ScimHttpProcessors.SerializeScimJsonResponse); From($"{_scheme}:GET:{_host}:{port}/api/v1/identity/scim/v2/Schemas?inOut=true{_sslParams}") .RouteId("http-management-scim-discovery-schemas") .Process(HttpIdentityProcessors.PropagateCorrelationId) .Process(HttpIdentityProcessors.StripManagementPrefix) .Process(ScimHttpProcessors.StripScimPrefix) .RedbHttpController(scimDiscoveryRegistry) .Process(ScimHttpProcessors.SerializeScimJsonResponse); From($"{_scheme}:GET:{_host}:{port}/api/v1/identity/scim/v2/Schemas/{{**path}}?inOut=true{_sslParams}") .RouteId("http-management-scim-discovery-schema-id") .Process(HttpIdentityProcessors.PropagateCorrelationId) .Process(HttpIdentityProcessors.StripManagementPrefix) .Process(ScimHttpProcessors.StripScimPrefix) .RedbHttpController(scimDiscoveryRegistry) .Process(ScimHttpProcessors.MapScimResponseToHttpStatus) .Process(ScimHttpProcessors.SerializeScimJsonResponse); // The strip comes first here as on every other route: this catch-all used to skip it, which left // the caller's own session_user_id / user_id / ip_address headers on the exchange for any later // step to trust. HttpRouteReservedHeaderStripTests keeps every route honest about it. var route = From($"{_scheme}:{_host}:{port}/api/v1/identity/{{**path}}?inOut=true{_sslParams}") .RouteId("http-management-api") .Process(HttpIdentityProcessors.PropagateCorrelationId); // Bearer-auth runs in Core's RouteContext via direct-vm. Synchronous, same // exchange — equivalent to inline Process(...) but keeps Http facade free of // any reference to Core's internal processor type. route.To(IdentityEndpoints.AuthManagement); // F5: the scope table lives in Core now, behind direct-vm://identity-authz-check, because a // second transport needed it and two copies of an authorization table drift in the direction // that grants too much. Same call style as the auth step above: synchronous, same exchange. route.Process(GranularScopeGuardProcessor.Describe); route.To(IdentityEndpoints.AuthzCheck); route .Process(HttpIdentityProcessors.StripManagementPrefix) .RedbHttpController(registry) .Process(HttpIdentityProcessors.MapManagementErrorToHttpStatus); } /// /// SCIM 2.0 provisioning API (RFC 7644). /// Discovery endpoints are unauthenticated (RFC 7643 §5). /// Resource endpoints (Users, Groups) require SCIM auth. /// private void ConfigureScimApi(int port) { // Discovery endpoints — no auth required (RFC 7643 §5) var discoveryRegistry = new ControllerRegistry(); discoveryRegistry.RegisterController(typeof(ScimDiscoveryController)); From($"{_scheme}:GET:{_host}:{port}/scim/v2/ServiceProviderConfig?inOut=true{_sslParams}") .RouteId("http-scim-discovery-spc") .Process(HttpIdentityProcessors.PropagateCorrelationId) .Process((e, ct) => { System.Diagnostics.Debug.WriteLine("[SCIM-DISCOVERY-SPC] Route matched!"); return Task.CompletedTask; }) .Process(ScimHttpProcessors.StripScimPrefix) .RedbHttpController(discoveryRegistry) .Process(ScimHttpProcessors.SerializeScimJsonResponse); From($"{_scheme}:GET:{_host}:{port}/scim/v2/ResourceTypes?inOut=true{_sslParams}") .RouteId("http-scim-discovery-rt") .Process(HttpIdentityProcessors.PropagateCorrelationId) .Process(ScimHttpProcessors.StripScimPrefix) .RedbHttpController(discoveryRegistry) .Process(ScimHttpProcessors.SerializeScimJsonResponse); From($"{_scheme}:GET:{_host}:{port}/scim/v2/ResourceTypes/{{**path}}?inOut=true{_sslParams}") .RouteId("http-scim-discovery-rt-id") .Process(HttpIdentityProcessors.PropagateCorrelationId) .Process(ScimHttpProcessors.StripScimPrefix) .RedbHttpController(discoveryRegistry) .Process(ScimHttpProcessors.MapScimResponseToHttpStatus) .Process(ScimHttpProcessors.SerializeScimJsonResponse); From($"{_scheme}:GET:{_host}:{port}/scim/v2/Schemas?inOut=true{_sslParams}") .RouteId("http-scim-discovery-schemas") .Process(HttpIdentityProcessors.PropagateCorrelationId) .Process(ScimHttpProcessors.StripScimPrefix) .RedbHttpController(discoveryRegistry) .Process(ScimHttpProcessors.SerializeScimJsonResponse); From($"{_scheme}:GET:{_host}:{port}/scim/v2/Schemas/{{**path}}?inOut=true{_sslParams}") .RouteId("http-scim-discovery-schema-id") .Process(HttpIdentityProcessors.PropagateCorrelationId) .Process(ScimHttpProcessors.StripScimPrefix) .RedbHttpController(discoveryRegistry) .Process(ScimHttpProcessors.MapScimResponseToHttpStatus) .Process(ScimHttpProcessors.SerializeScimJsonResponse); // Resource endpoints — auth required var scimRegistry = new ControllerRegistry(); scimRegistry.RegisterController(typeof(ScimUsersController)); scimRegistry.RegisterController(typeof(ScimGroupsController)); if (_transportOptions.Features.EnableScimBulk) scimRegistry.RegisterController(typeof(ScimBulkController)); // Strip first, as on every route (see the management catch-all above). var route = From($"{_scheme}:{_host}:{port}/scim/v2/{{**path}}?inOut=true{_sslParams}") .RouteId("http-scim-api") .Process(HttpIdentityProcessors.PropagateCorrelationId) .Process((e, ct) => { System.Diagnostics.Debug.WriteLine("[SCIM-CATCHALL] Route matched!"); return Task.CompletedTask; }); // SCIM bearer-auth runs in Core's RouteContext via direct-vm. route.To(IdentityEndpoints.AuthScim); route.Process(ScimHttpProcessors.StripScimPrefix) .RedbHttpController(scimRegistry) .Process(ScimHttpProcessors.MapScimResponseToHttpStatus) .Process(ScimHttpProcessors.SerializeScimJsonResponse); } /// /// B1 — emergency-admin bootstrap endpoint POST /internal/bootstrap-admin. /// Mounted on the management port (), /// outside the regular /api/v1/identity/ base path so that operators can firewall /// it independently. No bearer-token auth: protection is via the /// X-Bootstrap-Secret header validated by the underlying processor with /// . /// CORS is intentionally disabled — bootstrap is a back-channel admin tool, never /// invoked from a browser. /// private void ConfigureBootstrapEndpoint(int port) { From($"{_scheme}:POST:{_host}:{port}/internal/bootstrap-admin?inOut=true{_sslParams}") .RouteId("http-bootstrap-admin") .Process(HttpIdentityProcessors.PropagateCorrelationId) .To(IdentityEndpoints.BootstrapAdmin) .Process(HttpIdentityProcessors.SerializeJsonResponse); } /// /// Federation endpoints: external-login (challenge) and callback. /// Maps browser redirects to direct-vm://identity-federation-* routes. /// private void ConfigureFederationEndpoints(int port) { var cookieMaxAge = _transportOptions.SessionCookieLifetime; var secureCookie = _transportOptions.Issuer.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase); var callbackPath = _transportOptions.Http.FederationCallbackPath; var issuer = _transportOptions.Issuer.ToString().TrimEnd('/'); var bindingCookieName = _transportOptions.BindingCookieName; var cookieOpts = _transportOptions.Cookies; var sessionCookieName = cookieOpts.SessionCookieName; var sessionSameSite = cookieOpts.SessionSameSite; var bindingSameSite = cookieOpts.BindingSameSite; var useHostPrefix = cookieOpts.UseHostPrefix; // GET /connect/external-login?provider=xxx&returnUrl=yyy → redirect to IdP From($"{_scheme}:GET:{_host}:{port}/connect/external-login?inOut=true{_sslParams}") .RouteId("http-federation-challenge") .Process(HttpIdentityProcessors.PropagateCorrelationId) .Process((e, ct) => { HttpIdentityProcessors.MapQueryToBody(e, ct); var body = e.In.Body as IDictionary; body ??= new Dictionary(); body["callbackUrl"] = $"{issuer}{callbackPath}"; e.In.Body = body; // C9: hand cookie-formatting hints to FederationHttpProcessors so the // binding cookie comes out with the same flags the rest of identity uses. e.Properties["federation-binding-samesite"] = bindingSameSite; e.Properties["federation-binding-host-prefix"] = useHostPrefix; e.Properties["federation-binding-secure"] = secureCookie; return Task.CompletedTask; }) .To(IdentityEndpoints.FederationChallenge) .Process(FederationHttpProcessors.HandleChallengeRedirect) .Process(HttpIdentityProcessors.SerializeJsonResponse); // GET /connect/federation/callback?code=xxx&state=yyy → token exchange + session From($"{_scheme}:GET:{_host}:{port}{callbackPath}?inOut=true{_sslParams}") .RouteId("http-federation-callback") .Process(HttpIdentityProcessors.PropagateCorrelationId) .Process((e, ct) => { HttpIdentityProcessors.MapQueryToBody(e, ct); var body = e.In.Body as IDictionary; body ??= new Dictionary(); body["callbackUrl"] = $"{issuer}{callbackPath}"; e.In.Body = body; e.Properties["federation-binding-samesite"] = bindingSameSite; e.Properties["federation-binding-host-prefix"] = useHostPrefix; e.Properties["federation-binding-secure"] = secureCookie; return Task.CompletedTask; }) .Process((e, ct) => FederationHttpProcessors.ExtractBindingCookie(e, ct, bindingCookieName)) .To(IdentityEndpoints.FederationCallback) .Process((e, ct) => SessionCookieProcessors.WriteSessionCookie(e, ct, _ticketService, cookieMaxAge, secureCookie, sessionCookieName, sessionSameSite, useHostPrefix)) .Process((e, ct) => FederationHttpProcessors.HandleCallbackResponse(e, ct, bindingCookieName)) .Process(HttpIdentityProcessors.SerializeJsonResponse); } /// /// Public read-only listing of federation providers safe for anonymous callers. /// Drives the federation sign-in buttons on third-party UIs (incl. our own /// redb.Identity.Web BFF) without forcing them to mirror the server-side /// FederationProviders configuration. The projection deliberately strips /// ClientSecret, Authority, scope list, and any other field that /// could leak provider configuration. /// private void ConfigurePublicFederationProvidersEndpoint(int port, string routeIdSuffix) { From($"{_scheme}:GET:{_host}:{port}/api/v1/identity/federation-providers/public?inOut=true{_sslParams}") .RouteId($"http-federation-providers-public-{routeIdSuffix}") .Process(HttpIdentityProcessors.PropagateCorrelationId) .Process((e, ct) => { // Skip providers that are still on placeholder credentials — // showing them on /login leads users into a 401 / Google // "OAuth client was not found" path that looks like a server // bug. Once the operator fills in the real ClientId, the // provider re-appears automatically (no restart needed // beyond config reload). static bool IsPlaceholder(string? value) => string.IsNullOrWhiteSpace(value) || string.Equals(value, "REPLACE_ME", StringComparison.OrdinalIgnoreCase) || value.Contains("REPLACE_ME", StringComparison.OrdinalIgnoreCase); var providers = _transportOptions.FederationProviders .Where(p => !IsPlaceholder(p.ClientId) && !IsPlaceholder(p.Authority)) .OrderBy(p => p.Priority) .ThenBy(p => p.ProviderId, StringComparer.Ordinal) .Select(p => new PublicFederationProviderDescriptor( ProviderId: p.ProviderId, DisplayName: p.DisplayName, Kind: p.Kind, Priority: p.Priority)) .ToArray(); e.Out = new Message(); e.Out.Body = System.Text.Json.JsonSerializer.SerializeToUtf8Bytes( providers, IdentityWireProfiles.OAuthOptions); e.Out.Headers[HttpHeaders.ResponseContentType] = "application/json; charset=utf-8"; e.Out.Headers[HttpHeaders.ResponseCode] = 200; // Browsers may safely cache the public list for 60s; revalidate after that. e.Out.Headers["Cache-Control"] = "public, max-age=60"; return Task.CompletedTask; }); } } Path: redb-identity/src/redb.Identity.Http/IdentityTransportOptions.cs Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/src/redb.Identity.Http/IdentityTransportOptions.cs ---- using redb.Identity.Contracts.Configuration; namespace redb.Identity.Http; /// /// Configuration options for Identity HTTP transport facade. /// All HTTP-cosmetic settings (paths, branding, cookies, feature toggles for HTTP routes, /// federation provider list) live here so the facade is operationally independent from /// RedbIdentityOptions in Core. Cross-process state (DataProtection, persistence, /// signing keys, etc.) still flows through direct-vm:// calls into Core. /// public class IdentityTransportOptions { /// HTTP-specific transport settings (ports, CORS). public HttpTransportOptions Http { get; set; } = new(); /// /// Cross-module shared options (Issuer + Features). Same instance type as /// RedbIdentityOptions.Shared (defined in redb.Identity.Contracts). /// In-process test fixtures can simply assign /// transportOptions.Shared = identityOptions.Shared to ensure exact /// alignment instead of mirroring individual properties. /// public IdentitySharedOptions Shared { get; set; } = new(); /// /// Issuer URI for the identity server (used by HTTP discovery + cookie Secure detection). /// Proxy onto .. /// public Uri Issuer { get => Shared.Issuer; set => Shared.Issuer = value; } /// HTTP route paths for interactive pages (login, consent, MFA). public IdentityHttpPaths Paths { get; set; } = new(); /// UI branding for built-in pages (title, logo, colors, custom CSS). public IdentityHttpBranding Branding { get; set; } = new(); /// Cookie security defaults (name prefix, SameSite modes, session cookie name). public IdentityCookieOptions Cookies { get; set; } = new(); /// Lifetime of the session cookie. Default: 8 hours. public TimeSpan SessionCookieLifetime { get; set; } = TimeSpan.FromHours(8); /// /// Name of the cookie that carries the per-flow federation browser-binding secret. /// Default: redb_fed_b. /// public string BindingCookieName { get; set; } = "redb_fed_b"; /// /// Cross-module feature toggles. Proxy onto .. /// public IdentityFeatureFlags Features { get => Shared.Features; set => Shared.Features = value; } /// SCIM bulk-endpoint limits. Effective only when is true. public IdentityScimBulkOptions ScimBulk { get; set; } = new(); /// /// Federation providers exposed on the login page. Provider ClientSecret values /// can be left empty here — the secret-bearing config lives in Core; this list only drives /// the HTTP-visible button rendering and callback dispatch table. /// public List FederationProviders { get; set; } = []; } /// HTTP route paths for interactive pages. public sealed class IdentityHttpPaths { /// Path to the login page. Default: /login. public string Login { get; set; } = "/login"; /// Path to the consent page. Default: /consent. public string Consent { get; set; } = "/consent"; /// Path to the MFA verification page. Default: /mfa. public string Mfa { get; set; } = "/mfa"; /// Path to the MFA recovery code page. Default: /mfa/recovery. public string MfaRecovery { get; set; } = "/mfa/recovery"; } /// UI branding for built-in identity pages. public sealed class IdentityHttpBranding { /// Title shown on the login page. Default: Sign In. public string LoginTitle { get; set; } = "Sign In"; /// URL of a logo image shown above the login form. public string? LogoUrl { get; set; } /// Primary color for buttons and accents. Default: #2563eb. public string PrimaryColor { get; set; } = "#2563eb"; /// Primary color hover state. Default: #1d4ed8. public string PrimaryColorHover { get; set; } = "#1d4ed8"; /// Extra CSS injected into every identity page. public string? CustomCss { get; set; } } /// SCIM bulk-endpoint transport limits. public sealed class IdentityScimBulkOptions { /// Maximum number of operations a single SCIM /Bulk request may carry. Default: 1000. public int MaxOperations { get; set; } = 1000; /// Maximum payload size (bytes) of a single SCIM /Bulk request. Default: 1 MiB. public int MaxPayloadSize { get; set; } = 1_048_576; } /// /// HTTP transport settings (ports, CORS). /// public class HttpTransportOptions { /// /// Bind address of the public and management listeners. Default 0.0.0.0 (every interface); /// 127.0.0.1 keeps them on the loopback, for a host behind a local reverse proxy. /// public string Host { get; set; } = "0.0.0.0"; /// /// Port for public OIDC endpoints (/connect/*, /.well-known/*). /// Default: 8080. /// public int PublicPort { get; set; } = 8080; /// /// Optional separate port for management API (/api/v1/identity/*). /// If null, management API shares . /// Production recommendation: use a separate port (e.g., 8081) behind a firewall. /// public int? ManagementPort { get; set; } /// /// Serve the HTTP facade over HTTPS/TLS natively (Kestrel, via the redb.Route.Http connector) /// instead of plain HTTP. When true, MUST point to a PFX /// certificate — every facade endpoint on (and ) /// is then bound with TLS. Set the Issuer to the matching https://… URL so discovery /// metadata, iss claims and the Secure cookie flag are emitted correctly. /// Default: false (plain http — intended for local development only). /// public bool Ssl { get; set; } /// /// Filesystem path to the PFX (PKCS#12) certificate used when is true. /// The certificate's SAN must cover the host clients use to reach the issuer. /// public string? SslCertPath { get; set; } /// /// Password protecting the PFX in . null when the PFX has no /// password. Supply via an L5 Override env-var in production rather than committing it. /// public string? SslCertPassword { get; set; } /// /// Master switch for CORS on browser-facing OIDC endpoints (/.well-known/*, /// /connect/token, /connect/userinfo, /connect/revocation, /// /connect/introspect, /connect/logout). Required for SPA / native PKCE /// clients calling these endpoints from a browser context. /// /// Endpoints that perform browser redirects (/connect/authorize, /login, /// /mfa, /consent, federation callback) and the management API /// (/api/v1/identity/*, /scim/*) NEVER receive CORS headers regardless of this /// flag — those flows are not initiated from cross-origin fetch/XHR. /// /// Default: false. /// public bool CorsEnabled { get; set; } /// /// When true, the registered-client origin resolver is wired up so that any browser /// Origin matching the redirect / post-logout URI of a registered OAuth application /// is allowed automatically. This is the recommended production setting: as new SPAs are /// onboarded via the management API they receive CORS access without any config change. /// /// When false, only origins listed in (or /// supplied programmatically via ) are allowed. /// /// Default: true. /// public bool CorsRegisteredClientOriginsEnabled { get; set; } = true; /// /// Comma-separated list of origins that should always be allowed in addition to those /// derived from registered clients. Useful for dev/staging fallbacks (e.g. /// "http://localhost:3000, http://localhost:5173") or for browser-facing tooling /// that does not own its own OAuth client registration. /// public string? AdditionalAllowedOrigins { get; set; } /// /// Optional fully-programmatic CORS origin resolver. When set, this delegate completely /// replaces the registered-client resolver and for /// every browser-facing OIDC endpoint. Useful for cases where origin policy is owned by /// an external policy engine. /// public Func? CorsOriginsResolver { get; set; } /// /// Comma-separated allowed-origins list (legacy; pre-C15). /// /// /// Deprecated: a static CSV cannot be combined with the registered-client resolver and /// browsers cannot consume CSV in Access-Control-Allow-Origin. Migrate to /// (same semantics, now matched per-request and /// echoed as a single origin) or for full control. /// [Obsolete("Use AdditionalAllowedOrigins (CSV, properly matched) or CorsOriginsResolver. " + "CorsOrigins is forwarded to AdditionalAllowedOrigins when set.")] public string? CorsOrigins { get; set; } /// /// Path for the OIDC federation callback endpoint. /// External IdPs redirect back to this path after user authentication. /// Default: /connect/federation/callback. /// public string FederationCallbackPath { get; set; } = "/connect/federation/callback"; /// /// Computes the effective additional-origins CSV by concatenating the deprecated /// (if any) with . /// Centralised so the back-compat shim lives in one place. /// internal string? GetEffectiveAdditionalOrigins() { #pragma warning disable CS0618 // legacy field deliberately read here var legacy = CorsOrigins; #pragma warning restore CS0618 if (string.IsNullOrEmpty(legacy)) return AdditionalAllowedOrigins; if (string.IsNullOrEmpty(AdditionalAllowedOrigins)) return legacy; return legacy + "," + AdditionalAllowedOrigins; } } Path: redb-identity/src/redb.Identity.Http/Mfa/BrokeredMfaStateInspector.cs Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/src/redb.Identity.Http/Mfa/BrokeredMfaStateInspector.cs ---- using redb.Identity.Contracts.Mfa; using redb.Identity.Contracts.Routes; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Identity.Http.Mfa; /// /// Phase 9e. implementation backed by the cross-context /// broker call to direct-vm://identity-mfa-methods-from-state. /// /// Registered in the HTTP-facade child container when the host root has no Core inspector /// (i.e. the .tpkg boot path). The synchronous interface is bridged to the async broker /// via + GetAwaiter().GetResult(); this /// path runs only when rendering the MFA UI page, not on the verify hot path. /// /// public sealed class BrokeredMfaStateInspector : IMfaStateInspector { private readonly IRouteContext _routeContext; private IProducerTemplate? _producer; private readonly object _producerLock = new(); public BrokeredMfaStateInspector(IRouteContext routeContext) { _routeContext = routeContext ?? throw new ArgumentNullException(nameof(routeContext)); } public string[]? TryGetMethods(string? protectedState) { if (string.IsNullOrEmpty(protectedState)) return null; try { var producer = EnsureProducer(); var response = producer .RequestBody( IdentityEndpoints.MfaMethodsFromState, new MfaMethodsFromStateRequest { MfaState = protectedState }) .GetAwaiter().GetResult(); return response is { Success: true, Methods.Length: > 0 } ? response.Methods : null; } catch { // Mirrors Core MfaStateProtector behaviour: any decryption / transport // failure surfaces as «no known methods» — UI falls back to the TOTP form. return null; } } private IProducerTemplate EnsureProducer() { if (_producer is { IsStarted: true }) return _producer; lock (_producerLock) { if (_producer is { IsStarted: true }) return _producer; var p = new ProducerTemplate(_routeContext); p.Start(); _producer = p; return _producer; } } } Path: redb-identity/src/redb.Identity.Http/Module/IdentityHttpConfigBinder.cs Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/src/redb.Identity.Http/Module/IdentityHttpConfigBinder.cs ---- using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration.Memory; using redb.Identity.Contracts.Configuration; using redb.Route.Abstractions; namespace redb.Identity.Http.Module; /// /// Binds the Tsak-merged context configuration into a strongly typed /// instance for the HTTP facade. /// /// /// Mirrors redb.Identity.Core.Module.IdentityModuleConfigBinder: Tsak hands us /// the merged 5-layer config as a nested IDictionary<string, object?> /// stored on via SetProperty. We flatten it into /// entries and let IConfiguration.Bind /// hydrate the POCO — gives us free / / /// nested-object handling. /// /// The bound section name is "IdentityTransport", matching the shape declared /// in redb.Identity.Http.config.json (Layer 4). /// /// internal static class IdentityHttpConfigBinder { /// Top-level config section consumed by the HTTP facade. public const string SectionName = "IdentityTransport"; /// /// Core's top-level section. The reverse-proxy list is declared once there /// (Identity:ReverseProxies) and consumed by both Core's per-route processor and, when /// this module has to create the shared HTTP host itself, by the host. /// public const string CoreSectionName = "Identity"; /// /// Copies Identity:ReverseProxies (TrustForwardedFor, KnownProxies, /// KnownNetworks) from onto , so a /// host this module constructs resolves the client address and scheme on every listener with /// the same list Core's processor uses. Nothing is copied unless TrustForwardedFor is /// true. This facade does not reference Core, so the section is read as configuration rather /// than through Core's options type. /// public static void BindTrustedProxies(IRouteContext context, redb.Route.Http.HttpHostingOptions hosting) { ArgumentNullException.ThrowIfNull(context); ArgumentNullException.ThrowIfNull(hosting); var raw = context.GetProperty>(CoreSectionName); if (raw is null || raw.Count == 0) return; var flat = new Dictionary(StringComparer.OrdinalIgnoreCase); Flatten(raw, prefix: string.Empty, sink: flat); var cfg = new ConfigurationBuilder() .Add(new MemoryConfigurationSource { InitialData = flat }) .Build(); if (!cfg.GetValue("ReverseProxies:TrustForwardedFor", false)) return; foreach (var entry in cfg.GetSection("ReverseProxies:KnownProxies").Get() ?? []) hosting.TrustedProxies.Add(entry); foreach (var entry in cfg.GetSection("ReverseProxies:KnownNetworks").Get() ?? []) hosting.TrustedProxies.Add(entry); } /// /// Builds from 's /// "IdentityTransport" property. Returns defaults when the property is /// missing so the module can run in development without explicit configuration. /// public static IdentityTransportOptions Bind(IRouteContext context) { ArgumentNullException.ThrowIfNull(context); var options = new IdentityTransportOptions(); var raw = context.GetProperty>(SectionName); if (raw is null || raw.Count == 0) return options; var flat = new Dictionary(StringComparer.OrdinalIgnoreCase); Flatten(raw, prefix: string.Empty, sink: flat); var cfg = new ConfigurationBuilder() .Add(new MemoryConfigurationSource { InitialData = flat }) .Build(); cfg.Bind(options, opt => opt.BindNonPublicProperties = false); // Cross-module feature flags live in the shared `Identity:Features:*` section so a // single declaration in context.json drives both Core (DI / direct-vm gating) and // Http (route mounting). When operators override `IdentityTransport:Features:*` // explicitly, the latter wins (per-module override semantics). BindSharedFeatureFlags(context, options); // IConfiguration.Bind merges arrays/lists by index; replace lists wholesale // when the operator provided one (matches Core binder semantics). var federationSection = cfg.GetSection("FederationProviders"); if (federationSection.Exists()) { var providers = federationSection.Get>(); if (providers is not null) options.FederationProviders = providers; } return options; } /// /// Reads the shared Identity:Features:* section from the route-context /// properties and binds it onto 's /// . The shared section is the /// authoritative source of feature toggles for both Core and Http; values set on /// IdentityTransport:Features:* (legacy / per-module override) are /// overwritten when the shared section provides them. /// private static void BindSharedFeatureFlags(IRouteContext context, IdentityTransportOptions options) { var identitySection = context.GetProperty>("Identity"); if (identitySection is null || !identitySection.TryGetValue("Features", out var featuresObj) || featuresObj is not IDictionary featuresDict || featuresDict.Count == 0) { return; } var flat = new Dictionary(StringComparer.OrdinalIgnoreCase); Flatten(featuresDict, prefix: "Features", sink: flat); var sharedCfg = new ConfigurationBuilder() .Add(new MemoryConfigurationSource { InitialData = flat }) .Build(); // Bind directly onto the existing Features instance so per-module overrides set // earlier on the same object are preserved when the shared section omits a key. sharedCfg.GetSection("Features").Bind(options.Features); } private static void Flatten(IDictionary source, string prefix, IDictionary sink) { foreach (var kvp in source) { // Skip metadata keys ("//" comment blocks, ContextName, AutoStart) that // are consumed by Tsak itself and are not part of IdentityTransportOptions. if (kvp.Key.StartsWith("//", StringComparison.Ordinal)) continue; var key = prefix.Length == 0 ? kvp.Key : $"{prefix}:{kvp.Key}"; switch (kvp.Value) { case null: sink[key] = null; break; case IDictionary nested: Flatten(nested, key, sink); break; case System.Collections.IEnumerable list when kvp.Value is not string: var idx = 0; foreach (var item in list) { var indexed = $"{key}:{idx}"; if (item is IDictionary nestedItem) Flatten(nestedItem, indexed, sink); else sink[indexed] = item?.ToString(); idx++; } break; default: sink[key] = kvp.Value.ToString(); break; } } } } Path: redb-identity/src/redb.Identity.Http/Module/IdentityHttpModuleHost.cs Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/src/redb.Identity.Http/Module/IdentityHttpModuleHost.cs ---- using Microsoft.AspNetCore.DataProtection; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using redb.Core; using redb.Identity.Contracts.Configuration; using redb.Identity.Contracts.Cors; using redb.Identity.Contracts.Mfa; using redb.Identity.DataProtection; using redb.Identity.Http.Cors; using redb.Identity.Http.Endpoints; using redb.Identity.Http.Mfa; using redb.Identity.Http.Security; using redb.Route.Abstractions; namespace redb.Identity.Http.Module; /// /// Builds a self-contained child for the /// identity.http Tsak context (Phase 9b). /// /// Mirrors redb.Identity.Core.Module.IdentityModuleHost: the Tsak.Worker root /// container is built BEFORE modules are loaded, so all HTTP-facade-internal services /// (, DataProtection key-ring, /// ) are constructed lazily here from /// the Tsak-merged config. /// /// /// /// /// Bridge services from the host root container: /// /// — shared logging plumbing. /// — testable clock (defaults to system). /// — host configuration root. /// — bridged Scoped via the same /// HostRedbScope pattern Core uses, so the DataProtection key-ring writes/reads /// land in the same PROPS store as the rest of Identity. /// /// /// /// HTTP-facade-owned registrations (built fresh in this child container): /// /// AddDataProtection().PersistKeysToRedb() — cluster-wide key-ring. /// — encrypts session-cookie payloads via /// the bridged . /// IOptions<IdentityTransportOptions> — bound by /// . /// /// /// /// Cross-context state (CORS allowed origins, post-logout-redirect validation, MFA-state /// inspection) is NOT registered here — it flows through direct-vm://identity-* /// brokered calls into Core (Phase 9d/9e). /// /// internal static class IdentityHttpModuleHost { public static ServiceProvider Build(IRouteContext routeContext, IdentityTransportOptions options) { ArgumentNullException.ThrowIfNull(routeContext); ArgumentNullException.ThrowIfNull(options); var rootSp = routeContext.GetServiceProvider() ?? throw new InvalidOperationException( "IRouteContext is missing a backing IServiceProvider — cannot bridge host services."); var services = new ServiceCollection(); // 1. Bridge core host services. var loggerFactory = rootSp.GetRequiredService(); services.AddSingleton(loggerFactory); services.AddLogging(); services.AddSingleton(rootSp.GetService() ?? TimeProvider.System); var hostConfiguration = rootSp.GetService(); if (hostConfiguration is not null) services.AddSingleton(hostConfiguration); // 2. IRedbService — bridged Scoped through a host-side scope, identical pattern to // Core's IdentityModuleHost. The DataProtection IXmlRepository (registered in // step 4 below) opens its own scope per StoreElement call via IServiceScopeFactory, // so we MUST hand it the host-side factory (named instance when configured) and // NOT shadow the child container's own IServiceScopeFactory. // // For the HTTP facade the redb instance is selected via the standard Tsak named // redb registry: when the context.json declares Redb:{name}:..., Tsak puts the // scope factory at "redb-factory:{name}". The HTTP facade itself does not own a // RedbInstanceName option (it only needs DataProtection storage); we read it from // a context property "RedbInstanceName" set by the .config.json or fall back to // the default unnamed root provider scope factory. var redbInstanceName = routeContext.GetProperty("RedbInstanceName")?.TrimStart('#'); IServiceScopeFactory hostRedbScopeFactory; if (!string.IsNullOrEmpty(redbInstanceName)) { hostRedbScopeFactory = routeContext.GetFromRegistry("redb-factory:" + redbInstanceName) ?? throw new InvalidOperationException( $"Named IRedbService '{redbInstanceName}' has no scope factory registered " + $"in the route context (key 'redb-factory:{redbInstanceName}'). Did Tsak's " + "RegisterNamedRedbServices run before module initialisation?"); } else { hostRedbScopeFactory = rootSp.GetRequiredService(); } var hostScopeFactoryHolder = new HostRedbScopeFactoryHolder(hostRedbScopeFactory); services.AddSingleton(hostScopeFactoryHolder); services.AddScoped(); services.AddScoped(sp => sp.GetRequiredService().Service); // 3. Options snapshot. services.AddSingleton(Options.Create(options)); services.AddOptions(); // 4. DataProtection key-ring backed by redb PROPS (Phase 9a shared project). // SetApplicationName must match Core's value so both contexts (and any other // facades) use the same purpose-string namespace and can decrypt each other's // payloads — required for the session ticket / federation state cookie story. services.AddDataProtection() .SetApplicationName("redb.identity") .PersistKeysToRedb(); // 5. HTTP-facade-owned services. services.AddSingleton(); // 6. Phase 9e — cross-context broker bridges. The HTTP facade has no // project-reference on Core, so the «is this Origin allowed for CORS?», // «is this post-logout-redirect URI registered?» and «what MFA methods does // this state token carry?» queries are issued via direct-vm:// to Core's // matching processors (registered in IdentityCoreRouteBuilder, see Phase 9d). // The brokered impls take IRouteContext (NOT IServiceProvider) — that is // the only object that can resolve direct-vm endpoints in the SharedVmRegistry. services.AddSingleton(routeContext); services.AddSingleton(sp => new BrokeredRegisteredClientOriginRegistry(sp.GetRequiredService())); services.AddSingleton(sp => new BrokeredMfaStateInspector(sp.GetRequiredService())); services.AddSingleton(sp => new BrokeredPostLogoutRedirectValidator(sp.GetRequiredService())); // E7: enforce captive-dependency detection at build time. return services.BuildServiceProvider(new ServiceProviderOptions { ValidateScopes = true, ValidateOnBuild = true, }); } } /// /// Disposes the HTTP-facade child when the surrounding /// route context stops. Without this the child container would leak across Tsak hot-reloads. /// internal sealed class HttpChildHostDisposeListener : IRouteLifecycleListener { private readonly ServiceProvider _childSp; public HttpChildHostDisposeListener(ServiceProvider childSp) => _childSp = childSp; public Task OnContextStopped(IRouteContext context, CancellationToken ct) { _childSp.Dispose(); return Task.CompletedTask; } } /// /// Per-child-scope wrapper around a host-side that exposes /// with deterministic disposal — identical pattern to /// redb.Identity.Core.Module.HostRedbScope. Required so the redb-backed /// DataProtection repository never captive-captures a Scoped . /// internal sealed class HostRedbScope : IDisposable, IAsyncDisposable { private readonly IServiceScope _hostScope; public IRedbService Service { get; } public HostRedbScope(HostRedbScopeFactoryHolder holder) { _hostScope = holder.Factory.CreateScope(); Service = _hostScope.ServiceProvider.GetRequiredService(); } public void Dispose() => _hostScope.Dispose(); public ValueTask DisposeAsync() => _hostScope is IAsyncDisposable a ? a.DisposeAsync() : new ValueTask(Task.Run(_hostScope.Dispose)); } /// /// Marker holder for the host's . Registered as a /// distinct type (NOT as directly) so the child /// container keeps its own scope factory intact while still being able to reach the /// host one when bridging . /// internal sealed class HostRedbScopeFactoryHolder { public IServiceScopeFactory Factory { get; } public HostRedbScopeFactoryHolder(IServiceScopeFactory factory) => Factory = factory; } Path: redb-identity/src/redb.Identity.Http/Module/IdentityHttpXmlRepositoryInitListener.cs Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/src/redb.Identity.Http/Module/IdentityHttpXmlRepositoryInitListener.cs ---- using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Core; using redb.Identity.DataProtection; using redb.Route.Abstractions; namespace redb.Identity.Http.Module; /// /// HTTP-side mirror of RedbXmlRepositoryInitListener from Core: seeds the /// snapshot from PROPS before the first cookie /// Protect/Unprotect hits the auth hot path. /// /// Identity.Core and Identity.Http run in separate Tsak contexts (Phase 8). /// They share the cluster-wide DataProtection key-ring through redb PROPS (Phase 9a), /// but each context owns its own RedbXmlRepository singleton inside its child /// . Without a context-local init listener, the Http /// repository starts empty and the very first session-cookie request triggers /// KeyManager to mint a fresh key — invalidating every previously issued /// session-ticket and breaking SSO continuity across redeploys. /// /// internal sealed class IdentityHttpXmlRepositoryInitListener : IRouteLifecycleListener { private readonly IServiceProvider _sp; public IdentityHttpXmlRepositoryInitListener(IServiceProvider sp) => _sp = sp; public async Task OnContextStarting(IRouteContext context, CancellationToken ct) { await using var scope = _sp.CreateAsyncScope(); var repo = scope.ServiceProvider.GetRequiredService(); var redb = scope.ServiceProvider.GetRequiredService(); var logger = scope.ServiceProvider .GetRequiredService() .CreateLogger(); // The file key ring the process wrote up to 4.3 goes into redb first (idempotent with the // Core context, which runs the same import), then the snapshot is loaded. await RedbXmlRepository.ImportFileKeyRingsAsync(redb, DefaultFileKeyRing.Directories(), logger, ct) .ConfigureAwait(false); var count = await repo.ReloadAsync(redb, ct).ConfigureAwait(false); logger.LogInformation( "redb.Identity.Http: DataProtection key-ring snapshot loaded ({Count} keys)", count); } } Path: redb-identity/src/redb.Identity.Http/Module/InitRoute.cs Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/src/redb.Identity.Http/Module/InitRoute.cs ---- using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using redb.Identity.Http.Module; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Http; // Tsak resolves the {Module}.config.json file by InitRoute's namespace // (TsakModuleRegistry.DiscoverModulesInAssembly). Keep this namespace aligned // with the shipped config filename `redb.Identity.Http.config.json`. // // Phase 8/9: this module owns ContextName "identity.http" — a separate RouteContext // from redb.Identity.Core ("identity"). The two communicate exclusively through // `direct-vm://identity-*` brokered messages whose DTOs live in // redb.Identity.Contracts. The Http facade has zero project-reference on Core. // // Phase 9b: Http now builds its OWN child IServiceProvider via IdentityHttpModuleHost // (mirrors Core's IdentityModuleHost). The child SP owns SessionTicketService, the // DataProtection key-ring (PersistKeysToRedb, shared cluster-wide) and IdentityTransport // options. Cross-context state (CORS allowed origins, post-logout-redirect validation, // MFA-state inspection) is fetched on-demand via direct-vm:// calls into Core (Phase 9d/9e). namespace redb.Identity.Http; /// /// Tsak module entry point. Builds the HTTP-facade child container and registers /// in the route context. /// Discovered by convention: public class InitRoute with static main(IRouteContext). /// public static class InitRoute { /// /// Host options for a server manager this module has to create itself (no other component /// registered one). Under a Tsak worker the manager comes from the worker's DI and carries the /// worker's own trusted-proxy list, so this path is not taken there. When Identity runs as its /// own host, the proxies it was configured with (Identity:ReverseProxies) are the only /// ones anybody knows about, so they are handed to the host as well: the client address and /// scheme are then right on every listener, not only after Core's per-route processor runs. /// private static HttpHostingOptions HostingOptionsFrom(IRouteContext context) { var hosting = new HttpHostingOptions(); IdentityHttpConfigBinder.BindTrustedProxies(context, hosting); return hosting; } public static IRouteContext main(IRouteContext context) { // Ensure the HttpComponent (scheme "http") AND HttpsComponent (scheme "https") are // registered (may already be by another module). Both share ONE SharedHttpServerManager // so a single host:port server is tracked once regardless of scheme — the facade emits // https: URIs when IdentityTransport:Http:Ssl=true, so the "https" component must exist. if (!context.HasComponent("http")) { var serverManager = new SharedHttpServerManager(HostingOptionsFrom(context)); context.AddComponent(new HttpComponent { ServerManager = serverManager }); context.AddComponent(new HttpsComponent { ServerManager = serverManager }); } else if (!context.HasComponent("https")) { context.AddComponent(new HttpsComponent { ServerManager = new SharedHttpServerManager(HostingOptionsFrom(context)) }); } // One boot path, in a Tsak worker and in a host of its own alike: IdentityHttpConfigBinder reads // "IdentityTransport" from the context's configuration and IdentityHttpModuleHost builds a child // ServiceProvider that owns all HTTP-facade services. var hostSp = context.GetServiceProvider() ?? throw new InvalidOperationException( "IServiceProvider not available on IRouteContext. " + "Ensure the Identity HTTP module is loaded after DI is configured."); var bound = IdentityHttpConfigBinder.Bind(context); var childSp = IdentityHttpModuleHost.Build(context, bound); // Ensure the child container outlives the routes but dies with the context. context.AddLifecycleListener(new HttpChildHostDisposeListener(childSp)); IServiceProvider httpSp = childSp; // Seed the DataProtection key-ring snapshot BEFORE the HTTP facade serves the // first request. Without this, the very first session-cookie Unprotect would // race against an empty in-memory ring and force KeyManager to mint a fresh key // — invalidating any previously issued cookies. context.AddLifecycleListener(new IdentityHttpXmlRepositoryInitListener(httpSp)); // Phase 9b (clean rewire): bearer-auth is now invoked via // `direct-vm://identity-auth-{management,scim}`. Core publishes the consumer, // this facade calls it inline with `.To(...)` — no cross-module static state. var initLogger = (httpSp.GetService() ?? hostSp.GetService()) ?.CreateLogger("redb.Identity.Http.InitRoute"); initLogger?.LogInformation("[Identity.Http.InitRoute] Building HTTP facade routes"); var builder = new HttpFacadeRouteBuilder( httpSp.GetRequiredService(), httpSp.GetRequiredService>(), httpSp.GetService(), httpSp.GetService(), httpSp.GetService()); ((RouteContext)context).AddRoutes(builder); return context; } } Path: redb-identity/src/redb.Identity.Http/Module/manifest.json Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/src/redb.Identity.Http/Module/manifest.json ---- { "Name": "redb.Identity.Http", "Version": "1.0.0", "EntryPoints": ["redb.Identity.Http.dll"], "Dependencies": ["redb.Identity.Core.Module"] } Path: redb-identity/src/redb.Identity.Http/Processors/AntiForgeryProcessors.cs Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/src/redb.Identity.Http/Processors/AntiForgeryProcessors.cs ---- using System.Net; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Http; namespace redb.Identity.Http.Processors; /// /// Cross-site request forgery guard for the facade's own HTML forms (login, consent, MFA). /// /// /// Browsers attach Origin to every cross-site form POST (and Referer to most), /// so a form submitted from a foreign page always announces where it came from. A request /// whose announced origin is neither the issuer nor the host it was addressed to is /// rejected with 403 before any processor acts on the body. A request carrying neither /// header is let through: that is the shape of the web console's BFF, the demo scripts and /// non-browser clients, none of which a foreign page can drive. /// /// /// /// This complements, not replaces, the other layers: the session cookie is /// SameSite=Lax (a cross-site POST does not carry it), the consent form binds the /// user to the session rather than to a form field, and every page answers with /// X-Frame-Options: DENY. An opaque Origin: null is treated as foreign. /// /// internal static class AntiForgeryProcessors { internal static Task RejectCrossSiteFormPost( IExchange e, CancellationToken ct, Uri issuer, IdentityTransportOptions opts) { var announced = e.In.GetHeader("Origin"); if (string.IsNullOrEmpty(announced)) announced = e.In.GetHeader("Referer"); if (string.IsNullOrEmpty(announced)) return Task.CompletedTask; if (IsOwnOrigin(announced, issuer, e.In.GetHeader("Host"))) return Task.CompletedTask; var card = "

Request blocked

" + "

This form was submitted from another site and was not processed.

"; var msg = new Message(IdentityPageTemplates.WrapPage("Request blocked", card, opts)); msg.Headers[HttpHeaders.ResponseContentType] = "text/html; charset=utf-8"; msg.Headers[HttpHeaders.ResponseCode] = (int)HttpStatusCode.Forbidden; HttpIdentityProcessors.AttachSecurityHeaders(msg); e.Out = msg; e.Exception = new UnauthorizedAccessException("Cross-site form submission rejected."); e.ExceptionHandled = true; e.Stop(); return Task.CompletedTask; } /// /// The announced origin is ours when its authority matches the issuer's, or the /// Host the request was addressed to (reverse proxies may present the facade /// under a name other than the issuer). Authorities are compared with the announced /// scheme's default-port rules so https://op and op:443 agree. /// internal static bool IsOwnOrigin(string announced, Uri issuer, string? hostHeader) { if (!Uri.TryCreate(announced, UriKind.Absolute, out var source) || string.IsNullOrEmpty(source.Host)) return false; if (string.Equals(source.Authority, issuer.Authority, StringComparison.OrdinalIgnoreCase)) return true; return !string.IsNullOrWhiteSpace(hostHeader) && Uri.TryCreate($"{source.Scheme}://{hostHeader.Trim()}", UriKind.Absolute, out var addressed) && string.Equals(source.Authority, addressed.Authority, StringComparison.OrdinalIgnoreCase); } } Path: redb-identity/src/redb.Identity.Http/Processors/ConsentPageProcessors.cs Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/src/redb.Identity.Http/Processors/ConsentPageProcessors.cs ---- using System.Net; using redb.Identity.Http.Security; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Http; namespace redb.Identity.Http.Processors; /// /// HTTP processors for rendering the consent page and handling consent submission. /// internal static class ConsentPageProcessors { /// Consent ticket lifetime — the window a user has to act on the consent screen. internal static readonly TimeSpan ConsentTicketMaxAge = TimeSpan.FromMinutes(10); /// /// Renders the consent page from a server-signed ticket (?ct=…) minted by /// . The application name and the /// requested scopes come from the ticket, never from the query string: rendering them from /// the URL let a crafted /consent?app_name=Your%20Bank&client_id=attacker link /// show the operator's own trusted UI for an attacker's client. A missing or invalid ticket /// is refused rather than rendered. /// internal static Task RenderConsentPage( IExchange e, CancellationToken ct, SessionTicketService ticketService, string consentPath = "/consent", IdentityTransportOptions? opts = null) { opts ??= new IdentityTransportOptions(); var query = e.In.GetHeader(HttpHeaders.Query) ?? ""; var @params = ParseQueryParams(query); var ticketValue = @params.GetValueOrDefault("ct") ?? ""; var ticket = ticketService.UnprotectConsent(ticketValue, ConsentTicketMaxAge); if (ticket is null) { var card = "

Request expired

" + "

This authorization request is missing or has expired. Start again from the application.

"; e.Out = new Message(IdentityPageTemplates.WrapPage("Request expired", card, opts)); e.Out.Headers[HttpHeaders.ResponseContentType] = "text/html; charset=utf-8"; e.Out.Headers[HttpHeaders.ResponseCode] = (int)HttpStatusCode.BadRequest; return Task.CompletedTask; } var scopeItems = string.IsNullOrEmpty(ticket.Scopes) ? "" : string.Join("\n", ticket.Scopes.Split(' ', StringSplitOptions.RemoveEmptyEntries) .Select(s => $"
  • {WebUtility.HtmlEncode(s)}
  • ")); var cardContent = $$"""

    Authorize Application

    {{WebUtility.HtmlEncode(ticket.AppName)}} is requesting access to your account.

    {{(string.IsNullOrEmpty(scopeItems) ? "" : $"

    Requested permissions:

    \n
      {scopeItems}
    ")}}
    """; e.Out = new Message(); e.Out.Body = IdentityPageTemplates.WrapPage("Authorize", cardContent, opts); e.Out.Headers[HttpHeaders.ResponseContentType] = "text/html; charset=utf-8"; e.Out.Headers[HttpHeaders.ResponseCode] = 200; return Task.CompletedTask; } /// /// Prepares the body for the Core ConsentGrantProcessor behind direct-vm://identity-consent-grant. /// Maps the decision to the body the Core ConsentGrantProcessor expects. /// /// The user is always the one the session cookie identifies (session_user_id header /// set by ReadSessionCookie) — never a form field. The form used to carry /// user_id and this processor preferred it over the session, while /// ReadSessionCookie lets a cookie-less request through: an anonymous cross-site POST /// could record any user's consent for any client. Without a session the POST is refused /// with 401 and nothing downstream runs. /// /// /// Two callers, one gate. Our own consent page submits a server-signed ticket (ct): /// the client id and scopes come from the ticket, and the ticket must have been minted for /// the session's user (a ticket cannot be replayed under someone else's session). The /// console's BFF (RecordConsentGrantAsync) has no ticket — it renders its own screen /// and posts client_id/scopes with the session cookie; that path stays /// session-bound as before. /// /// internal static Task PrepareConsentBody( IExchange e, CancellationToken ct, SessionTicketService ticketService, IdentityTransportOptions opts) { // Session first, body shape second — a non-form body must not slip past the gate. long userId = 0; if (e.In.Headers.TryGetValue(SessionCookieProcessors.SessionUserIdHeader, out var hdr)) { if (hdr is long hl) userId = hl; else if (hdr is string hs && long.TryParse(hs, out var hp)) userId = hp; } if (userId <= 0) return RejectConsent(e, opts, HttpStatusCode.Unauthorized, "Sign in required", "Your session has expired or is missing. Sign in again to review this request.", "Consent decision without a session."); if (e.In.Body is not IDictionary form) return RejectConsent(e, opts, HttpStatusCode.BadRequest, "Invalid request", "The consent decision must be submitted as a form.", "Consent decision with a non-form body."); var decision = form.TryGetValue("decision", out var d) ? d?.ToString() : null; string? clientId; string? scopes; string? returnUrl; var ticketValue = form.TryGetValue("ct", out var ctv) ? ctv?.ToString() : null; if (!string.IsNullOrEmpty(ticketValue)) { // Our own consent page: parameters come from the signed ticket, not the form. var ticket = ticketService.UnprotectConsent(ticketValue, ConsentTicketMaxAge); if (ticket is null) return RejectConsent(e, opts, HttpStatusCode.BadRequest, "Request expired", "This authorization request is missing or has expired. Start again from the application.", "Consent decision with an invalid ticket."); if (ticket.UserId != userId) return RejectConsent(e, opts, HttpStatusCode.Forbidden, "Request blocked", "This authorization request was issued for a different session.", "Consent ticket replayed under another session."); clientId = ticket.ClientId; scopes = ticket.Scopes; returnUrl = ticket.ReturnUrl; } else { // BFF path (RecordConsentGrantAsync): no ticket, session-bound, form-supplied params. clientId = form.TryGetValue("client_id", out var cid) ? cid?.ToString() : null; scopes = form.TryGetValue("scopes", out var sc) ? sc?.ToString() : null; returnUrl = form.TryGetValue("returnUrl", out var ru) ? ru?.ToString() : null; } // Stash decision + returnUrl in Properties for HandleConsentResponse e.Properties["consent_decision"] = decision ?? "allow"; if (returnUrl is not null) e.Properties["consent_return_url"] = returnUrl; e.In.Body = new Dictionary { ["userId"] = userId, ["clientId"] = clientId, ["scopes"] = scopes }; return Task.CompletedTask; } private static Task RejectConsent( IExchange e, IdentityTransportOptions opts, HttpStatusCode code, string title, string message, string reason) { var msg = new Message(IdentityPageTemplates.WrapPage(title, $"

    {title}

    {message}

    ", opts)); msg.Headers[HttpHeaders.ResponseContentType] = "text/html; charset=utf-8"; msg.Headers[HttpHeaders.ResponseCode] = (int)code; HttpIdentityProcessors.AttachSecurityHeaders(msg); e.Out = msg; e.Exception = new UnauthorizedAccessException(reason); e.ExceptionHandled = true; e.Stop(); return Task.CompletedTask; } /// /// Handles consent POST response. On success, redirects back to the original authorize URL. /// On deny, redirects to the client with error=access_denied. /// internal static Task HandleConsentResponse(IExchange e, CancellationToken ct, IdentityTransportOptions opts) { var decision = e.Properties.TryGetValue("consent_decision", out var d) ? d?.ToString() : "allow"; var returnUrl = e.Properties.TryGetValue("consent_return_url", out var r) ? r?.ToString() : null; if (decision == "deny") { var cardContent = "

    Access Denied

    You denied the application's request.

    "; e.Out = new Message(); e.Out.Body = IdentityPageTemplates.WrapPage("Access Denied", cardContent, opts); e.Out.Headers[HttpHeaders.ResponseContentType] = "text/html; charset=utf-8"; e.Out.Headers[HttpHeaders.ResponseCode] = 200; return Task.CompletedTask; } // Allow — check ConsentGrant response and redirect to original authorize URL var body = (e.HasOut ? e.Out!.Body : e.In.Body) as IDictionary; var success = body is not null && body.TryGetValue("success", out var s) && s is true; if (success && !string.IsNullOrEmpty(returnUrl) && LoginPageProcessors.IsValidReturnUrl(returnUrl)) { e.Out = new Message(); e.Out.Headers[HttpHeaders.ResponseCode] = 302; e.Out.Headers["Location"] = returnUrl; return Task.CompletedTask; } if (success) { e.Out = new Message(); e.Out.Body = new Dictionary { ["message"] = "Consent granted" }; return Task.CompletedTask; } return Task.CompletedTask; } private static Dictionary ParseQueryParams(string query) { var dict = new Dictionary(StringComparer.Ordinal); foreach (var pair in query.Split('&', StringSplitOptions.RemoveEmptyEntries)) { var eqIdx = pair.IndexOf('='); if (eqIdx <= 0) continue; var key = Uri.UnescapeDataString(pair[..eqIdx]); var value = Uri.UnescapeDataString(pair[(eqIdx + 1)..]); dict[key] = value; } return dict; } } Path: redb-identity/src/redb.Identity.Http/Processors/FederationHttpProcessors.cs Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/src/redb.Identity.Http/Processors/FederationHttpProcessors.cs ---- using System.Net; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Http; using redb.Identity.Contracts.Configuration; namespace redb.Identity.Http.Processors; /// /// HTTP processors for federation challenge (redirect to IdP) and callback (redirect after token exchange). /// internal static class FederationHttpProcessors { /// /// Reads the per-flow browser-binding secret from the inbound Cookie header /// (if any) and stashes it on so the core /// callback processor can hand it to FederationStateProtector.UnprotectAsync. /// internal static Task ExtractBindingCookie(IExchange e, CancellationToken ct, string cookieName) { if (string.IsNullOrEmpty(cookieName)) return Task.CompletedTask; if (!e.In.Headers.TryGetValue("Cookie", out var raw) || raw is not string cookieHeader) return Task.CompletedTask; // Parse RFC 6265: name=value; name2=value2 ... foreach (var part in cookieHeader.Split(';')) { var span = part.AsSpan().Trim(); var eq = span.IndexOf('='); if (eq <= 0) continue; var name = span[..eq].ToString(); if (string.Equals(name, cookieName, StringComparison.Ordinal)) { e.Properties["federation-binding-secret"] = span[(eq + 1)..].ToString(); break; } } return Task.CompletedTask; } /// /// Converts a successful challenge response (with redirect_uri) into an HTTP 302 redirect. /// On error, renders JSON error response. When the core processor minted a per-flow /// browser-binding secret, attaches it as a Secure HttpOnly SameSite=Lax cookie. /// internal static Task HandleChallengeRedirect(IExchange e, CancellationToken ct) { var body = (e.HasOut ? e.Out!.Body : e.In.Body) as IDictionary; if (body is null) return Task.CompletedTask; if (body.TryGetValue("redirect_uri", out var uri) && uri is string redirectUri && !string.IsNullOrEmpty(redirectUri)) { e.Out = new Message(); e.Out.Headers[HttpHeaders.ResponseCode] = 302; e.Out.Headers["Location"] = redirectUri; AttachBindingCookieIfNeeded(e, redirectUri); return Task.CompletedTask; } // Error — pass through for JSON serialization if (body.TryGetValue("error", out _)) { e.Out ??= new Message(); e.Out.Body = body; e.Out.Headers[HttpHeaders.ResponseCode] = 400; } return Task.CompletedTask; } private static void AttachBindingCookieIfNeeded(IExchange e, string redirectUri) { if (!e.Properties.TryGetValue("federation-binding-secret", out var sObj) || sObj is not string secret) return; if (!e.Properties.TryGetValue("federation-binding-cookie-name", out var nObj) || nObj is not string name) return; // Cookie comes back to us on the callback, so use the configured issuer-scheme flag // (stashed on the exchange by HttpFacadeRouteBuilder), falling back to the IdP // redirect scheme if the property isn't set (older callers). var secure = e.Properties.TryGetValue("federation-binding-secure", out var scObj) && scObj is bool sc ? sc : redirectUri.StartsWith("https://", StringComparison.OrdinalIgnoreCase); var sameSite = e.Properties.TryGetValue("federation-binding-samesite", out var ssObj) && ssObj is CookieSameSiteMode ss ? ss : CookieSameSiteMode.Lax; var useHostPrefix = e.Properties.TryGetValue("federation-binding-host-prefix", out var hpObj) && hpObj is bool hp && hp; IdentityCookieFormatter.AddSetCookie(e.Out!.Headers, IdentityCookieFormatter.Build( name, secret, maxAgeSeconds: 600, secure: secure, sameSite: sameSite, useHostPrefix: useHostPrefix)); } /// /// After callback processing: redirects to returnUrl on success, /// or renders an error page on failure. Always clears the per-flow binding cookie. /// internal static Task HandleCallbackResponse( IExchange e, CancellationToken ct, string bindingCookieName) { var body = (e.HasOut ? e.Out!.Body : e.In.Body) as IDictionary; if (body is null) return Task.CompletedTask; var success = body.TryGetValue("success", out var s) && s is true; var returnUrl = body.TryGetValue("returnUrl", out var r) ? r?.ToString() : null; if (success && !string.IsNullOrEmpty(returnUrl) && LoginPageProcessors.IsValidReturnUrl(returnUrl)) { e.Out = new Message(); e.Out.Headers[HttpHeaders.ResponseCode] = 302; e.Out.Headers["Location"] = returnUrl; CarrySessionAndClearBinding(e, bindingCookieName); return Task.CompletedTask; } if (success) { // No valid returnUrl — show success message e.Out = new Message(); e.Out.Body = new Dictionary { ["message"] = "Login successful" }; CarrySessionAndClearBinding(e, bindingCookieName); return Task.CompletedTask; } // Error — render error page var errorDesc = body.TryGetValue("error_description", out var ed) ? ed?.ToString() : "Authentication failed"; e.Out = new Message(); e.Out.Body = IdentityPageTemplates.WrapPage("Authentication Error", $"""

    Authentication Error

    {WebUtility.HtmlEncode(errorDesc)}

    Back to Home """, new IdentityTransportOptions()); e.Out.Headers[HttpHeaders.ResponseContentType] = "text/html; charset=utf-8"; e.Out.Headers[HttpHeaders.ResponseCode] = 200; AppendClearBindingCookie(e, bindingCookieName); return Task.CompletedTask; } private static void CarrySessionAndClearBinding(IExchange e, string bindingCookieName) { // Carry session cookie set by SessionCookieProcessors earlier in the pipeline. if (e.In.Headers.TryGetValue("Set-Cookie", out var session)) e.Out!.Headers["Set-Cookie"] = session; AppendClearBindingCookie(e, bindingCookieName); } private static void AppendClearBindingCookie(IExchange e, string bindingCookieName) { if (string.IsNullOrEmpty(bindingCookieName)) return; // Mirror the Set flags so the browser actually deletes the matching cookie. var sameSite = e.Properties.TryGetValue("federation-binding-samesite", out var ssObj) && ssObj is CookieSameSiteMode ss ? ss : CookieSameSiteMode.Lax; var useHostPrefix = e.Properties.TryGetValue("federation-binding-host-prefix", out var hpObj) && hpObj is bool hp && hp; // Issuer-scheme drives Secure for the clear; if we set it Secure we must clear it Secure. var secure = e.Properties.TryGetValue("federation-binding-secure", out var scObj) && scObj is bool sc && sc; var clear = IdentityCookieFormatter.Build( bindingCookieName, value: string.Empty, maxAgeSeconds: 0, secure: secure, sameSite: sameSite, useHostPrefix: useHostPrefix); // A separate line, never folded into the session cookie with ", ": the browser would read the // fold as one cookie whose last Max-Age is this clear's 0, and delete the session it just got. IdentityCookieFormatter.AddSetCookie(e.Out!.Headers, clear); } } Path: redb-identity/src/redb.Identity.Http/Processors/GranularScopeGuardProcessor.cs Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/src/redb.Identity.Http/Processors/GranularScopeGuardProcessor.cs ---- using redb.Route.Abstractions; namespace redb.Identity.Http.Processors; /// /// N7-1 — per-path scope guard for the management API. Runs after /// ManagementBearerAuthProcessor has validated the bearer token and stashed /// identity:management-scopes, and BEFORE StripManagementPrefix so the /// raw /api/v1/identity/{...} path is still visible. /// /// F5: the decision itself moved to Core, behind direct-vm://identity-authz-check, when a second /// transport was about to need the same table. What is left here is the part that is genuinely about /// HTTP — naming the resource and the action — and even that is a fallback: Core reads /// redbHttp.Path and redbHttp.Method directly when nothing states them, so the path is not /// carried twice and cannot drift from itself. /// /// /// The rules are unchanged and live in AuthorizationCheckProcessor: anonymous short-circuit, /// identity:manage bypass, identity:account self-service branch, read-only admin on /// GET-class methods, per-prefix scopes with write implying read, and default-deny for anything unmapped. /// /// internal static class GranularScopeGuardProcessor { /// /// Names the resource and action for the check that follows. Kept as a step of its own rather than /// folded into the route so the HTTP-specific half of the contract stays visible at the call site. /// internal static Task Describe(IExchange e, CancellationToken ct) { var path = e.In.GetHeader("redbHttp.Path") ?? string.Empty; var method = (e.In.GetHeader("redbHttp.Method") ?? "GET").ToUpperInvariant(); e.Properties["identity:authz-resource"] = path; e.Properties["identity:authz-action"] = method is "GET" or "HEAD" or "OPTIONS" ? "read" : "write"; return Task.CompletedTask; } } Path: redb-identity/src/redb.Identity.Http/Processors/HttpIdentityProcessors.cs Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/src/redb.Identity.Http/Processors/HttpIdentityProcessors.cs ---- using System.Diagnostics; using redb.Identity.Management; using System.Net; using System.Text; using System.Text.Json; using redb.Identity.Contracts.Serialization; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Http; using redb.Identity.Contracts.Common; namespace redb.Identity.Http.Processors; /// /// HTTP-specific processors that translate between HTTP semantics and /// the transport-agnostic direct-vm://identity-* exchange format. /// All methods are stateless and suitable for use as inline route processors. /// internal static class HttpIdentityProcessors { /// /// E5 — propagates a correlation id across the HTTP ↔ direct-vm boundary. /// /// Reads X-Correlation-Id from the request; if absent, /// derives it from (W3C trace-id, which redb.Route /// already attaches via RouteActivitySource), falling back to a new GUID. /// Stores the value under "identity:correlation-id" so /// downstream processors (and logger wrappers) /// can enrich their output uniformly. /// Sets X-Correlation-Id as an output header so the /// response echoes the same value to the caller (RFC-style trace handoff). /// /// Safe to run first on every HTTP route — does not consume or mutate body/headers /// beyond the single correlation header. /// /// /// Header names that carry internal, server-derived identity/authorization state. They are /// set by trusted processors from validated sources — the session cookie /// (ReadSessionCookie), the Authorization header (ExtractBearerToken), /// Basic auth or the form body (MapHttpToIdentityHeaders), the request path /// (ExtractDynamicRegistrationManagement). The HTTP consumer copies EVERY request /// header into the exchange verbatim (only redbHttp.* is filtered), and /// ReadSessionCookie returns without clearing these when no cookie is present — so a /// client sending a header literally named session_user_id would otherwise be trusted /// as an authenticated principal by AttachSessionPrincipalHandler. The audit trio /// (user_id, ip_address, user_agent) is read by /// EventDispatchProcessor from the WireTap copy of the business exchange — the same /// headers — so a client could sign the security log with someone else's user id and a /// fabricated address. Stripped on ingress so only the trusted processors can populate them. /// /// /// Removes the internal-only headers a client must never supply /// ( — the list is /// shared with the gRPC and SOAP facades). Invoked from — /// the first processor on every HTTP route — so no route can forget it; a per-route opt-in is /// exactly how such a gap reappears. /// internal static void StripReservedInboundHeaders(IExchange e) { redb.Identity.Contracts.Routes.IdentityReservedInboundHeaders.Strip(e.In.Headers); // HTTP-only: the operation is derived from the request method and path // (ExtractDynamicRegistrationManagement); over gRPC the caller names it by design. e.In.Headers.Remove("operation"); } internal static Task PropagateCorrelationId(IExchange e, CancellationToken ct) { StripReservedInboundHeaders(e); var requestId = e.In.GetHeader("X-Correlation-Id"); if (string.IsNullOrWhiteSpace(requestId)) { requestId = Activity.Current?.TraceId.ToString() ?? Guid.NewGuid().ToString("N"); } e.Properties["identity:correlation-id"] = requestId; return Task.CompletedTask; } /// /// Extracts client authentication from HTTP request: /// 1. Basic auth header → client_id + client_secret headers /// 2. Form-encoded body → client_id + client_secret headers (if not already set) /// Also propagates Content-Type for downstream processors. /// internal static Task MapHttpToIdentityHeaders(IExchange e, CancellationToken ct) { var authHeader = e.In.GetHeader(HttpHeaders.Authorization); // A Basic value that is not canonical base64 maps no credentials: the request goes on // without them and the token endpoint answers it as an unauthenticated client. if (authHeader?.StartsWith("Basic ", StringComparison.OrdinalIgnoreCase) == true && Base64Canonical.TryDecode(authHeader[6..].Trim(), out var credentials)) { var decoded = Encoding.UTF8.GetString(credentials); var parts = decoded.Split(':', 2); e.In.Headers["client_id"] = Uri.UnescapeDataString(parts[0]); if (parts.Length > 1) e.In.Headers["client_secret"] = Uri.UnescapeDataString(parts[1]); } // Propagate Content-Type so OpenIddict handlers can detect form vs JSON var contentType = e.In.GetHeader(HttpHeaders.ContentType); if (contentType is not null) e.In.Headers["Content-Type"] = contentType; // Step 2: form-encoded client authentication (RFC 6749 §2.3.1). OpenIddict reads these // from the body itself, so token issuance never needed them as headers — but the audit // envelope (EventDispatchProcessor) attributes events by the client_id header, and until // this step existed every form-authenticated client (public PKCE ones included) was // audited with client_id NULL. Basic wins when both are present; the body is parsed here // without being replaced (MapFormToBody runs later and owns that). if (!e.In.Headers.ContainsKey("client_id") && contentType?.StartsWith("application/x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase) == true) { var raw = e.In.Body switch { byte[] bytes => Encoding.UTF8.GetString(bytes), string text => text, _ => null }; if (!string.IsNullOrEmpty(raw)) { var form = ParseFormUrlEncoded(raw); if (form.TryGetValue("client_id", out var cid) && cid is string { Length: > 0 } cidText) e.In.Headers["client_id"] = cidText; if (form.TryGetValue("client_secret", out var sec) && sec is string { Length: > 0 } secText) e.In.Headers["client_secret"] = secText; } } return Task.CompletedTask; } /// /// Extracts Bearer token from Authorization header and sets it as a header /// for downstream userinfo/introspect processing. /// internal static Task ExtractBearerToken(IExchange e, CancellationToken ct) { // WWW-Authenticate is a response header. A copy sent by the client is dropped here, so the one // on In after the endpoint call can only be the challenge Core chose (AttachBearerChallengeOnError). e.In.Headers.Remove("WWW-Authenticate"); var authHeader = e.In.GetHeader(HttpHeaders.Authorization); if (authHeader?.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase) == true) { e.In.Headers["access_token"] = authHeader[7..]; } return Task.CompletedTask; } /// /// Maps HTTP query parameters to the exchange body as a dictionary. /// Used for GET /connect/authorize where params arrive as query string. /// internal static Task MapQueryToBody(IExchange e, CancellationToken ct) { var query = e.In.GetHeader(HttpHeaders.Query); if (string.IsNullOrEmpty(query)) return Task.CompletedTask; var dict = ParseFormUrlEncoded(query); e.In.Body = dict; return Task.CompletedTask; } /// /// Maps form-encoded POST body to exchange body as a dictionary. /// Used for POST /connect/authorize with form submission. /// internal static Task MapFormToBody(IExchange e, CancellationToken ct) { if (e.In.Body is byte[] bytes) { var text = Encoding.UTF8.GetString(bytes); e.In.Body = ParseFormUrlEncoded(text); } else if (e.In.Body is string formBody && !string.IsNullOrEmpty(formBody)) { e.In.Body = ParseFormUrlEncoded(formBody); } return Task.CompletedTask; } /// /// Handles redirect responses from the authorize endpoint. /// Converts redirect_uri output header into HTTP 302 + Location header. /// internal static Task HandleRedirectResponse(IExchange e, CancellationToken ct) { var msg = EnsureOut(e); var redirectUri = msg.GetHeader("redirect_uri"); if (redirectUri is not null) { msg.Headers[HttpHeaders.ResponseCode] = 302; msg.Headers["Location"] = redirectUri; } return Task.CompletedTask; } /// /// Strips the /api/v1/identity/ prefix from redbHttp.Path /// so the controller registry can match paths like applications/{id}. /// internal static Task StripManagementPrefix(IExchange e, CancellationToken ct) { const string prefix = "/api/v1/identity/"; var path = e.In.GetHeader(HttpHeaders.Path); if (path?.StartsWith(prefix, StringComparison.OrdinalIgnoreCase) == true) { e.In.Headers[HttpHeaders.Path] = "/" + path[prefix.Length..]; } return Task.CompletedTask; } /// /// Z2 (RFC 7592): extracts client_id from the /connect/register/{client_id} /// path segment and derives the operation header from the HTTP method /// (GET→read, PUT→update, DELETE→delete). Unsupported methods get no /// operation header; the core processor returns invalid_request. /// internal static Task ExtractDynamicRegistrationManagement(IExchange e, CancellationToken ct) { const string prefix = "/connect/register/"; var path = e.In.GetHeader(HttpHeaders.Path); if (path is not null && path.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) { var segment = path[prefix.Length..].TrimEnd('/'); // Strip any query string just in case. var q = segment.IndexOf('?'); if (q >= 0) segment = segment[..q]; if (segment.Length > 0) e.In.Headers["client_id"] = Uri.UnescapeDataString(segment); } var method = e.In.GetHeader(HttpHeaders.Method); var op = method?.ToUpperInvariant() switch { "GET" => "read", "PUT" => "update", "DELETE" => "delete", _ => null }; if (op is not null) e.In.Headers["operation"] = op; return Task.CompletedTask; } // ── Private helpers ── private static Dictionary ParseFormUrlEncoded(string encoded) { var dict = new Dictionary(StringComparer.Ordinal); foreach (var pair in encoded.Split('&', StringSplitOptions.RemoveEmptyEntries)) { var eqIdx = pair.IndexOf('='); if (eqIdx < 0) { dict[Decode(pair)] = null; continue; } var key = Decode(pair[..eqIdx]); var value = Decode(pair[(eqIdx + 1)..]); dict[key] = value; } return dict; // In application/x-www-form-urlencoded, '+' encodes space static string Decode(string s) => Uri.UnescapeDataString(s.Replace('+', ' ')); } private static string Encode(string value) => System.Net.WebUtility.HtmlEncode(value); /// /// Maps OAuth2 error codes in the response body to proper HTTP status codes (RFC 6749 §5.2). /// Must be called BEFORE which converts to byte[]. /// internal static Task MapOAuthErrorToHttpStatus(IExchange e, CancellationToken ct) { // Check In.Body (after PipelineProcessor merge, Out→In happens before this step) var body = e.HasOut ? e.Out!.Body : e.In.Body; string? error = null; if (body is IDictionary dictN && dictN.TryGetValue("error", out var errN)) error = errN as string; else if (body is IDictionary dictV && dictV.TryGetValue("error", out var errV)) error = errV as string; if (error is null) return Task.CompletedTask; var statusCode = error switch { "invalid_client" => 401, "invalid_token" => 401, "invalid_request" => 400, "invalid_grant" => 400, "invalid_scope" => 400, "unsupported_grant_type" => 400, "unsupported_response_type" => 400, "unauthorized_client" => 400, "access_denied" => 400, "server_error" => 500, "temporarily_unavailable" => 503, _ => 400 }; // Set on In — survives PipelineProcessor merge and EnsureOut (which creates new Out // from In.Body but does not copy headers). We must set it on In so downstream // processors inherit it. SerializeJsonResponse will propagate it to Out. e.In.Headers[HttpHeaders.ResponseCode] = statusCode; return Task.CompletedTask; } /// /// Revocation status (RFC 7009): an error answers as maps it /// (§2.2.1), except invalid_token: a token the server does not know or no longer honours is /// answered with 200 (§2.2), since there is nothing left to revoke. /// internal static async Task MapRevocationErrorToHttpStatus(IExchange e, CancellationToken ct) { await MapOAuthErrorToHttpStatus(e, ct).ConfigureAwait(false); var body = e.HasOut ? e.Out!.Body : e.In.Body; var error = body switch { IDictionary dictN when dictN.TryGetValue("error", out var errN) => errN as string, IDictionary dictV when dictV.TryGetValue("error", out var errV) => errV as string, _ => null }; if (error == "invalid_token") e.In.Headers[HttpHeaders.ResponseCode] = 200; } /// /// Renders an authorization error as an HTML page for browsers, leaving the JSON body /// untouched for API clients. /// /// RFC 6749 §4.1.2.1: when redirect_uri is missing, unregistered or malformed, the /// authorization server MUST NOT redirect — it has no trustworthy place to send the user, so /// it must inform the resource owner itself. The end user is sitting in a browser at that /// moment, and a raw JSON error object is not "informing the resource owner". Same for a bad /// client_id, an unsupported response_type, and every other authorize-time /// failure that cannot be bounced back to the client. /// /// /// Content negotiation, not a blanket switch: we only render HTML when the request actually /// prefers it (Accept: text/html). Machine callers that ask for JSON — or send no /// Accept at all — keep the exact OAuth error object they had before, so nothing on the API /// side changes shape. Wire AFTER (so the status code /// is already decided) and BEFORE (which would otherwise /// turn the dictionary into JSON bytes). /// /// internal static Task RenderAuthorizeErrorPage( IExchange e, CancellationToken ct, IdentityTransportOptions opts) { var body = e.HasOut ? e.Out!.Body : e.In.Body; string? error = null, description = null, uri = null; if (body is IDictionary dictN) { if (dictN.TryGetValue("error", out var v)) error = v as string; if (dictN.TryGetValue("error_description", out var d)) description = d as string; if (dictN.TryGetValue("error_uri", out var u)) uri = u as string; } else if (body is IDictionary dictV) { if (dictV.TryGetValue("error", out var v)) error = v as string; if (dictV.TryGetValue("error_description", out var d)) description = d as string; if (dictV.TryGetValue("error_uri", out var u)) uri = u as string; } if (string.IsNullOrEmpty(error)) return Task.CompletedTask; if (!PrefersHtml(e)) return Task.CompletedTask; var status = e.In.Headers.TryGetValue(HttpHeaders.ResponseCode, out var rc) ? rc : 400; var details = new StringBuilder(); details.Append("

    ") .Append(WebUtility.HtmlEncode( string.IsNullOrEmpty(description) ? "The authorization request could not be completed." : description)) .Append("

    "); // The error code is what an operator greps their logs for, and what the client developer // has to look up in the spec — surface it verbatim rather than burying it. details.Append("

    ").Append(WebUtility.HtmlEncode(error)).Append("

    "); if (!string.IsNullOrEmpty(uri)) { var safe = WebUtility.HtmlEncode(uri); details.Append("

    ") .Append("More about this error

    "); } // Deliberately no "go back" / "retry" link: the whole point of §4.1.2.1 is that we do not // trust the URI we were handed, so we must not offer to navigate to it. var card = $"

    Authorization Error

    {details}"; var msg = EnsureOut(e); msg.Body = IdentityPageTemplates.WrapPage("Authorization Error", card, opts); msg.ContentType = "text/html; charset=utf-8"; msg.Headers[HttpHeaders.ResponseContentType] = "text/html; charset=utf-8"; msg.Headers[HttpHeaders.ResponseCode] = status; e.In.Headers[HttpHeaders.ResponseContentType] = "text/html; charset=utf-8"; return Task.CompletedTask; } /// /// True when the caller is a browser rendering a page rather than a client consuming an API: /// Accept lists text/html and does not rank an explicit application/json /// above it. A missing or wildcard-only Accept counts as "not a browser" so that curl, SDKs /// and the conformance suite's HTTP client keep receiving JSON. /// private static bool PrefersHtml(IExchange e) { var accept = e.In.GetHeader(HttpHeaders.Accept); if (string.IsNullOrEmpty(accept)) return false; var html = accept.IndexOf("text/html", StringComparison.OrdinalIgnoreCase); if (html < 0) return false; var json = accept.IndexOf("application/json", StringComparison.OrdinalIgnoreCase); return json < 0 || html < json; } /// /// RFC 6750 §3 — userinfo (and other protected-resource) error responses MUST include /// the WWW-Authenticate header with a Bearer challenge. OpenIddict's /// default userinfo error response omits it (it's an authorization-server response /// shape, not a protected-resource one). Wire this processor AFTER /// on userinfo routes to attach the spec-mandated /// challenge whenever the body carries an error field. /// internal static Task AttachBearerChallengeOnError(IExchange e, CancellationToken ct) { var body = e.HasOut ? e.Out!.Body : e.In.Body; string? error = null; string? errorDescription = null; if (body is IDictionary dictN) { if (dictN.TryGetValue("error", out var errN)) error = errN as string; if (dictN.TryGetValue("error_description", out var dN)) errorDescription = dN as string; } else if (body is IDictionary dictV) { if (dictV.TryGetValue("error", out var errV)) error = errV as string; if (dictV.TryGetValue("error_description", out var dV)) errorDescription = dV as string; } if (string.IsNullOrEmpty(error)) return Task.CompletedTask; // Core already chose the challenge (the DPoP scheme for a DPoP-bound token, RFC 9449 §7.1): keep it. // ExtractBearerToken drops a client-sent copy before the endpoint call, so this one is Core's. if ((e.HasOut && e.Out!.Headers.ContainsKey("WWW-Authenticate")) || e.In.Headers.ContainsKey("WWW-Authenticate")) return Task.CompletedTask; // RFC 7235 §2.1 quoted-string rules: backslash → \\, quote → \" var safeError = error.Replace("\\", "\\\\").Replace("\"", "\\\""); var challenge = $"Bearer realm=\"identity\", error=\"{safeError}\""; if (!string.IsNullOrEmpty(errorDescription)) { var safeDesc = errorDescription.Replace("\\", "\\\\").Replace("\"", "\\\""); challenge += $", error_description=\"{safeDesc}\""; } // Place on In so it survives the EnsureOut step in SerializeJsonResponse. e.In.Headers["WWW-Authenticate"] = challenge; return Task.CompletedTask; } /// /// Serializes the response body to JSON bytes when it is a dictionary. /// Required because HttpConsumer.WriteResponse calls ToString() /// on non-byte/stream bodies, which would produce a type name for dictionaries. /// internal static Task SerializeJsonResponse(IExchange e, CancellationToken ct) { var msg = EnsureOut(e); // Propagate ContentType from In (EnsureOut only copies Body, not metadata). // Without this, an upstream HTML response (e.g. form_post) loses its content-type // and HttpConsumer falls back to the default application/json. msg.ContentType ??= e.In.ContentType; if (!msg.Headers.ContainsKey(HttpHeaders.ResponseContentType) && e.In.Headers.TryGetValue(HttpHeaders.ResponseContentType, out var rct)) { msg.Headers[HttpHeaders.ResponseContentType] = rct; } if (msg.Body is IDictionary dict) { // Final HTTP serialization for OIDC/OAuth/DCR responses. Uses the locked // OAuth profile (RFC 6749 §5.1, UTF-8, ignore nulls) — bypasses the configurable // Route codec registry so user config cannot reshape the OAuth wire format. msg.Body = JsonSerializer.SerializeToUtf8Bytes(dict, IdentityWireProfiles.OAuthOptions); // Core-level content type keeps the value transport-agnostic for Rabbit/Kafka façades. msg.ContentType ??= IdentityWireProfiles.OAuthMediaType; msg.Headers.TryAdd(HttpHeaders.ResponseContentType, IdentityWireProfiles.OAuthMediaType); } // E5: echo the propagated correlation id on every response so the caller can // stitch its own log entries to ours. Stored as an exchange property by // PropagateCorrelationId at the head of every HTTP route. if (e.Properties.TryGetValue("identity:correlation-id", out var corrObj) && corrObj is string corr && !string.IsNullOrEmpty(corr)) { msg.Headers.TryAdd("X-Correlation-Id", corr); } // Propagate ResponseCode from In if not already set on Out // (EnsureOut creates Out from In.Body only, not headers) if (!msg.Headers.ContainsKey(HttpHeaders.ResponseCode) && e.In.Headers.TryGetValue(HttpHeaders.ResponseCode, out var rc)) { msg.Headers[HttpHeaders.ResponseCode] = rc; } // Propagate Set-Cookie from In if not already set on Out // (PipelineProcessor merges Out→In between steps, so headers set by earlier // post-processors end up on In; EnsureOut doesn't copy them to new Out) if (!msg.Headers.ContainsKey("Set-Cookie") && e.In.Headers.TryGetValue("Set-Cookie", out var sc)) { msg.Headers["Set-Cookie"] = sc; } // Propagate WWW-Authenticate (RFC 6750 §3) for protected-resource error responses. // AttachBearerChallengeOnError on the userinfo routes sets it on In; the merge // between processors only carries it forward, EnsureOut doesn't copy headers, so // we explicitly forward it here. if (!msg.Headers.ContainsKey("WWW-Authenticate") && e.In.Headers.TryGetValue("WWW-Authenticate", out var wa)) { msg.Headers["WWW-Authenticate"] = wa; } // Propagate Location header for redirects (302) if (!msg.Headers.ContainsKey("Location") && e.In.Headers.TryGetValue("Location", out var loc)) { msg.Headers["Location"] = loc; } // D1/D2: propagate Cache-Control so response caching directives set by // endpoint processors (Discovery, JWKS) reach the HTTP writer. The pipeline // merges Out→In between steps, so a header set on Out by an earlier .To() // lands on In by the time this post-processor runs; EnsureOut won't copy it. if (!msg.Headers.ContainsKey("Cache-Control") && e.In.Headers.TryGetValue("Cache-Control", out var cc)) { msg.Headers["Cache-Control"] = cc; } // Z4 P2 (RFC 9449 §8): propagate DPoP-Nonce set by ApplyTokenResponseHandler so // that clients can adopt the rotated nonce on subsequent proofs. Same Out→In // merge concern as Cache-Control above. if (!msg.Headers.ContainsKey("DPoP-Nonce") && e.In.Headers.TryGetValue("DPoP-Nonce", out var dpopNonce)) { msg.Headers["DPoP-Nonce"] = dpopNonce; } AttachSecurityHeaders(msg); return Task.CompletedTask; } /// /// Browser-protection baseline on every response that ends in /// — all page routes and the OAuth/OIDC protocol /// endpoints. The facade serves its own login / consent / MFA pages, and until now /// nothing forbade framing them — the consent form in an invisible frame is a textbook /// clickjacking target. Same set the web console's SecurityHeadersMiddleware /// emits; only the frame directive of CSP is used because the page templates rely on /// inline styles. Harmless on JSON and redirects, so it is applied uniformly rather than /// per page route — a forgotten route is exactly how such a gap reappears. Rejections /// that stop the pipeline before the serializer must call this themselves. /// internal static void AttachSecurityHeaders(IMessage msg) { msg.Headers.TryAdd("X-Frame-Options", "DENY"); msg.Headers.TryAdd("Content-Security-Policy", "frame-ancestors 'none'"); msg.Headers.TryAdd("X-Content-Type-Options", "nosniff"); msg.Headers.TryAdd("Referrer-Policy", "strict-origin-when-cross-origin"); } /// /// RFC 6749 §5.1/§5.2 — the token endpoint MUST send Cache-Control: no-store and /// Pragma: no-cache on every response so intermediaries never cache issued tokens. /// Wire this AFTER on the token endpoint (and the other /// token-bearing endpoints: PAR, introspection, revocation, device authorization). It is /// deliberately NOT applied to discovery/JWKS, which are cacheable by design. /// internal static Task AddNoStoreCacheHeaders(IExchange e, CancellationToken ct) { var msg = e.HasOut ? e.Out! : e.In; msg.Headers["Cache-Control"] = "no-store"; msg.Headers["Pragma"] = "no-cache"; return Task.CompletedTask; } /// /// Renders the logout confirmation page when the core answered confirm_required: the request /// carried the browser's session but neither a valid id_token_hint for its user nor the state of /// a page this server showed. The form posts that state back to /connect/logout together with /// the relying party's own parameters, so the redirect back to it still happens after confirmation. /// Stops the route here: the session cookie is not cleared and no redirect is performed until the /// End-User confirms. /// internal static Task RenderLogoutConfirmation(IExchange e, CancellationToken ct, IdentityTransportOptions opts) { if (!e.Properties.TryGetValue("logout_confirm_required", out var flag) || flag is not true) return Task.CompletedTask; if (e.In.Body is not IDictionary answer) throw new InvalidOperationException("Logout confirmation was requested without the core's answer body."); var fields = new StringBuilder(); foreach (var name in new[] { "logout_state", "post_logout_redirect_uri", "state", "client_id" }) { if (answer.TryGetValue(name, out var value) && value is string text && !string.IsNullOrEmpty(text)) fields.Append($"\n"); } var card = $$"""

    Sign out

    Do you want to sign out of your account?

    {{fields}}
    """; var msg = new Message(IdentityPageTemplates.WrapPage("Sign out", card, opts)); msg.Headers[HttpHeaders.ResponseContentType] = "text/html; charset=utf-8"; msg.Headers[HttpHeaders.ResponseCode] = 200; AttachSecurityHeaders(msg); e.Out = msg; e.Stop(); return Task.CompletedTask; } /// /// Handles post-logout redirect per OIDC RP-Initiated Logout §2. /// If the response contains post_logout_redirect_uri, validates it against /// registered application URIs and redirects (302) only if valid. /// Otherwise renders a simple "logged out" HTML page. /// /// /// Saves the relying party's post_logout_redirect_uri and state from the body to exchange /// properties before To() replaces the body. The state goes back to the RP verbatim on the redirect /// (RP-Initiated Logout 1.0 §3). /// internal static Task PreservePostLogoutRedirectUri(IExchange e, CancellationToken ct) { if (e.In.Body is IDictionary body) { if (body.TryGetValue("post_logout_redirect_uri", out var uri) && uri is string s && !string.IsNullOrEmpty(s)) e.Properties["post_logout_redirect_uri"] = s; if (body.TryGetValue("state", out var stateValue) && stateValue is string state && !string.IsNullOrEmpty(state)) e.Properties["post_logout_state"] = state; } return Task.CompletedTask; } internal static async Task HandlePostLogoutRedirect( IExchange e, CancellationToken ct, IdentityTransportOptions opts, Func>? validator) { var msg = EnsureOut(e); // Read redirect URI from exchange properties (preserved before To() replaced the body) var redirectUri = e.Properties.TryGetValue("post_logout_redirect_uri", out var uriObj) ? uriObj?.ToString() : null; if (!string.IsNullOrEmpty(redirectUri)) { // Validate redirect URI against registered applications (open redirect protection). // Phase 9e: validation is now delegated to a Func passed in from the route builder // so this processor has zero compile-time knowledge of OpenIddict / Core types. // The Func is backed by BrokeredPostLogoutRedirectValidator (direct-vm broker call) // in .tpkg mode, or by a direct OpenIddict adapter in test-fixture mode. var isValid = false; if (validator is not null) isValid = await validator(redirectUri, ct).ConfigureAwait(false); if (isValid) { // RP-Initiated Logout 1.0 §3: the RP's state is returned as a query parameter, unchanged. var location = redirectUri; if (e.Properties.TryGetValue("post_logout_state", out var stateObj) && stateObj is string state && state.Length > 0) location += (redirectUri.Contains('?') ? "&" : "?") + "state=" + Uri.EscapeDataString(state); msg.Headers[HttpHeaders.ResponseCode] = 302; msg.Headers["Location"] = location; return; } // Invalid or unregistered URI — fall through to "signed out" page } // No redirect — render a "signed out" page using shared template var cardContent = "

    Signed Out

    You have been signed out successfully.

    "; msg.Body = IdentityPageTemplates.WrapPage("Signed Out", cardContent, opts); msg.Headers[HttpHeaders.ResponseContentType] = "text/html; charset=utf-8"; msg.Headers[HttpHeaders.ResponseCode] = 200; } /// /// Ensures exists, creating it from the In body if needed. /// Post-processors should always write to Out (response), not mutate In (request). /// private static IMessage EnsureOut(IExchange e) { if (e.HasOut) return e.Out!; e.Out = new Message(e.In.Body); return e.Out; } /// /// Post-processor for the management API controller route. /// Inspects the serialized JSON response body for an "error" field /// and maps it to the appropriate HTTP status code. /// Must be chained AFTER .RedbHttpController() which sets status 200. /// The pipeline merges controller Out→In before this step, so body is on e.In.Body. /// internal static Task MapManagementErrorToHttpStatus(IExchange e, CancellationToken ct) { if (e.In.Body is not byte[] json || json.Length == 0) return Task.CompletedTask; // The dispatcher (or Core, through the controller) already said which error this is: leave it. // The table below is for controller error documents that arrived wrapped in a 200. if (ManagementErrorCodes.DecidedErrorStatus(e.In) is not null) return Task.CompletedTask; try { var reader = new Utf8JsonReader(json); // Only inspect root-level JSON objects (arrays = list responses, skip them) if (!reader.Read() || reader.TokenType != JsonTokenType.StartObject) return Task.CompletedTask; string? error = null; while (reader.Read()) { // Only check top-level properties (depth 1 = directly inside root object) if (reader.CurrentDepth == 1 && reader.TokenType == JsonTokenType.PropertyName && reader.ValueTextEquals("error"u8)) { if (reader.Read() && reader.TokenType == JsonTokenType.String) error = reader.GetString(); break; } // Skip nested structures entirely if (reader.TokenType is JsonTokenType.StartObject or JsonTokenType.StartArray) reader.Skip(); } if (error is null) return Task.CompletedTask; // The table moved to redb.Identity.Management when a second transport needed the same // verdicts: the package that owns the controllers owns what their error codes mean, and one // table cannot drift from itself. var statusCode = ManagementErrorCodes.ToStatusCode(error); // Create Out to override the pipeline's restored lastOut (which has status 200). // Body is already serialized byte[] JSON from the controller dispatcher. e.Out = new Message(e.In.Body); e.Out.Headers[HttpHeaders.ResponseCode] = statusCode; e.Out.Headers[HttpHeaders.ResponseContentType] = "application/json"; } catch (JsonException) { // Not valid JSON — skip status mapping } return Task.CompletedTask; } } Path: redb-identity/src/redb.Identity.Http/Processors/IdentityCookieFormatter.cs Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/src/redb.Identity.Http/Processors/IdentityCookieFormatter.cs ---- using redb.Identity.Contracts.Configuration; namespace redb.Identity.Http.Processors; /// /// C9 — single point that formats every Set-Cookie header Identity emits, so /// security flags (Secure / HttpOnly / SameSite / name prefix) /// stay consistent across session, federation-binding, and clear flows. /// internal static class IdentityCookieFormatter { /// /// Builds a Set-Cookie header value with consistent flags. /// /// Cookie name without any prefix. /// Cookie value (already URL-safe — caller's responsibility). /// Cookie lifetime; pass 0 to clear. /// When true, the Secure flag is appended. /// SameSite mode. /// When true AND is true, /// the cookie name is prefixed with __Host-. The prefix is silently dropped /// over plain http to avoid emitting a cookie that browsers would reject. public static string Build( string bareName, string value, int maxAgeSeconds, bool secure, CookieSameSiteMode sameSite, bool useHostPrefix = false) { if (string.IsNullOrEmpty(bareName)) throw new ArgumentException("Cookie name is required.", nameof(bareName)); // __Host- requires Secure + Path=/ + no Domain (RFC 6265bis §4.1.3.2). // Strip the prefix when not over https — otherwise the browser silently drops // the cookie and the user appears to be perpetually logged out. var canPrefix = useHostPrefix && secure; var name = canPrefix ? "__Host-" + bareName : bareName; var sb = new System.Text.StringBuilder(96); sb.Append(name).Append('=').Append(value); sb.Append("; Path=/"); sb.Append("; Max-Age=").Append(maxAgeSeconds); sb.Append("; HttpOnly"); if (secure) sb.Append("; Secure"); sb.Append("; SameSite=").Append(SameSiteToken(sameSite)); return sb.ToString(); } /// /// Returns both candidate names (prefixed and bare) so cookie readers can match /// either while a deployment is rolling out the __Host- prefix. /// public static (string prefixed, string bare) Candidates(string bareName) => ("__Host-" + bareName, bareName); /// /// Adds a cookie to the response message, keeping any already there. /// /// Two cookies must leave as two Set-Cookie lines. Joined into one value they are read by a /// browser as a single cookie — it does not split on commas (RFC 6265 §3) — with every attribute of /// the second appended to the first, and of several Max-Age attributes the last wins. The /// federation callback once folded a session cookie with the binding cookie's expiry that way, and /// the browser deleted the session as it arrived. Assigning the header instead of adding to it loses /// the first cookie outright. The HTTP consumer writes an array value as one line per entry, so a /// second cookie turns the value into an array; a single cookie stays the plain string every reader of /// the header already expects. /// /// public static void AddSetCookie(IDictionary headers, string cookie) { ArgumentNullException.ThrowIfNull(headers); ArgumentException.ThrowIfNullOrEmpty(cookie); if (!headers.TryGetValue("Set-Cookie", out var existing) || existing is null or string { Length: 0 }) { headers["Set-Cookie"] = cookie; return; } headers["Set-Cookie"] = existing switch { string single => new[] { single, cookie }, string[] several => [.. several, cookie], // Identity only ever writes strings built by Build; anything else is not ours to reinterpret. _ => throw new InvalidOperationException( $"Set-Cookie already holds a {existing.GetType().Name}; expected a string or string[]."), }; } private static string SameSiteToken(CookieSameSiteMode mode) => mode switch { CookieSameSiteMode.Strict => "Strict", CookieSameSiteMode.Lax => "Lax", CookieSameSiteMode.None => "None", _ => "Lax" }; } Path: redb-identity/src/redb.Identity.Http/Processors/IdentityPageTemplates.cs Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/src/redb.Identity.Http/Processors/IdentityPageTemplates.cs ---- using System.Net; namespace redb.Identity.Http.Processors; /// /// Shared HTML page templates for identity UI pages (login, consent, logout). /// Uses base styles from for consistent branding. /// internal static class IdentityPageTemplates { /// /// Wraps inner HTML content in the standard identity page shell /// (head, body, card container, logo, shared CSS). /// internal static string WrapPage(string title, string cardContent, IdentityTransportOptions opts) { var logoHtml = string.IsNullOrEmpty(opts.Branding.LogoUrl) ? "" : $""""""; var customCss = string.IsNullOrEmpty(opts.Branding.CustomCss) ? "" : opts.Branding.CustomCss; return $$""" {{WebUtility.HtmlEncode(title)}} — redb.Identity
    {{logoHtml}} {{cardContent}}
    """; } } Path: redb-identity/src/redb.Identity.Http/Processors/LoginPageProcessors.cs Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/src/redb.Identity.Http/Processors/LoginPageProcessors.cs ---- using System.Net; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Http; namespace redb.Identity.Http.Processors; /// /// HTTP processors for rendering the login page and handling redirect after login. /// internal static class LoginPageProcessors { /// /// Renders a login HTML form using the shared page template. /// Preserves returnUrl from the query string as a hidden field. /// internal static Task RenderLoginPage( IExchange e, CancellationToken ct, string loginPath = "/login", IdentityTransportOptions? opts = null) { opts ??= new IdentityTransportOptions(); var query = e.In.GetHeader(HttpHeaders.Query) ?? ""; var returnUrl = ""; foreach (var part in query.Split('&', StringSplitOptions.RemoveEmptyEntries)) { var eqIdx = part.IndexOf('='); if (eqIdx > 0 && part[..eqIdx] == "returnUrl") { returnUrl = Uri.UnescapeDataString(part[(eqIdx + 1)..]); break; } } var cardContent = $$"""

    {{WebUtility.HtmlEncode(opts.Branding.LoginTitle)}}

    {{BuildFederationButtons(opts, returnUrl)}} """; e.Out = new Message(); e.Out.Body = IdentityPageTemplates.WrapPage(opts.Branding.LoginTitle, cardContent, opts); e.Out.Headers[HttpHeaders.ResponseContentType] = "text/html; charset=utf-8"; e.Out.Headers[HttpHeaders.ResponseCode] = 200; return Task.CompletedTask; } /// /// After successful login: redirects the user to returnUrl. /// If MFA is required: redirects to the MFA page with encrypted state. /// If login failed: renders the login form again with an error message. /// internal static Task HandleLoginResponse( IExchange e, CancellationToken ct, string loginPath = "/login", IdentityTransportOptions? opts = null) { opts ??= new IdentityTransportOptions(); // After PipelineProcessor merges Out→In, the body is on In; if Out is present, use it. var body = (e.HasOut ? e.Out!.Body : e.In.Body) as IDictionary; if (body is null) return Task.CompletedTask; var mfaRequired = body.TryGetValue("mfa_required", out var mfa) && mfa is true; if (mfaRequired) { // Capture upstream Set-Cookie (session + MFA-state cookies) BEFORE we replace // e.Out, otherwise `e.Out = new Message()` would drop them. var upstreamCookie = ExtractSetCookie(e); var mfaUrl = opts.Paths.Mfa; // NOTE: HTTP transport (HttpConsumer) only copies response headers when Body is non-null, // so an empty byte[] body is required for the Location header to reach the client. e.Out = new Message(); e.Out.Body = Array.Empty(); e.Out.Headers[HttpHeaders.ResponseCode] = 302; e.Out.Headers["Location"] = mfaUrl; if (upstreamCookie is not null) e.Out.Headers["Set-Cookie"] = upstreamCookie; return Task.CompletedTask; } var success = body.TryGetValue("success", out var s) && s is true; var returnUrl = body.TryGetValue("returnUrl", out var r) ? r?.ToString() : null; if (success && !string.IsNullOrEmpty(returnUrl)) { if (IsValidReturnUrl(returnUrl)) { // HttpConsumer skips header copying when Body is null; supply an empty // byte[] so Location/Set-Cookie reach the client. e.Out = new Message(); e.Out.Body = Array.Empty(); e.Out.Headers[HttpHeaders.ResponseCode] = 302; e.Out.Headers["Location"] = returnUrl; if (e.In.Headers.TryGetValue("Set-Cookie", out var cookie)) e.Out.Headers["Set-Cookie"] = cookie; return Task.CompletedTask; } } if (success) { e.Out = new Message(); e.Out.Body = new Dictionary { ["message"] = "Login successful" }; if (e.In.Headers.TryGetValue("Set-Cookie", out var cookie)) e.Out.Headers["Set-Cookie"] = cookie; return Task.CompletedTask; } // Login failed — render form again with error var errorDesc = body.TryGetValue("error_description", out var ed) ? ed?.ToString() : "Invalid credentials"; var cardContent = $$"""

    {{WebUtility.HtmlEncode(opts.Branding.LoginTitle)}}

    {{WebUtility.HtmlEncode(errorDesc)}}

    {{BuildFederationButtons(opts, returnUrl ?? "")}} """; e.Out = new Message(); e.Out.Body = IdentityPageTemplates.WrapPage(opts.Branding.LoginTitle, cardContent, opts); e.Out.Headers[HttpHeaders.ResponseContentType] = "text/html; charset=utf-8"; e.Out.Headers[HttpHeaders.ResponseCode] = 200; return Task.CompletedTask; } /// /// Validates returnUrl against open redirect attacks: only a path on this server passes. /// /// Three rules, and the last is not decoration. The value starts with a single /; its second /// character is neither / nor \, either of which makes it protocol-relative (another /// host); and it carries no control character anywhere. A browser removes ASCII tab and newline from /// a URL before resolving it (WHATWG URL, "remove all ASCII tab or newline from input"), so /// /\t/evil.example passes the first two rules and still lands on //evil.example — /// straight after the user typed their password here. ASP.NET Core's IsLocalUrl rejects control /// characters for exactly this reason. Every redirect point (login, MFA, federation, consent) calls /// this method, so the rule holds wherever the value ends up. /// /// internal static bool IsValidReturnUrl(string? url) { if (string.IsNullOrEmpty(url)) return false; if (!url.StartsWith('/')) return false; if (url.Length > 1 && (url[1] == '/' || url[1] == '\\')) return false; foreach (var c in url) { if (char.IsControl(c)) return false; } return true; } /// /// Reads any Set-Cookie value that upstream processors (session/mfa cookie /// writers) may have placed on the current message. Checks Out first (where /// they typically land), then In (post-pipeline merge). Returns null /// when no cookie is present. /// internal static object? ExtractSetCookie(IExchange e) { if (e.HasOut && e.Out!.Headers.TryGetValue("Set-Cookie", out var o) && o is not null) return o; if (e.In.Headers.TryGetValue("Set-Cookie", out var i) && i is not null) return i; return null; } /// /// Builds federation provider buttons (e.g. "Login with Google") for the login page. /// Returns empty string if federation is disabled or no providers are configured. /// private static string BuildFederationButtons(IdentityTransportOptions opts, string returnUrl) { if (!opts.Features.EnableFederation || opts.FederationProviders.Count == 0) return ""; var sb = new System.Text.StringBuilder(); sb.AppendLine("""
    — or —
    """); sb.AppendLine("""
    """); foreach (var provider in opts.FederationProviders.OrderBy(p => p.Priority)) { var href = $"/connect/external-login?provider={Uri.EscapeDataString(provider.ProviderId)}&returnUrl={Uri.EscapeDataString(returnUrl)}"; sb.AppendLine($"""{WebUtility.HtmlEncode(provider.DisplayName)}"""); } sb.AppendLine("
    "); return sb.ToString(); } } Path: redb-identity/src/redb.Identity.Http/Processors/MfaCookieProcessors.cs Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/src/redb.Identity.Http/Processors/MfaCookieProcessors.cs ---- using redb.Route.Abstractions; using redb.Route.Http; using redb.Identity.Contracts.Configuration; namespace redb.Identity.Http.Processors; /// /// B3 §4: HTTP-facade processors that materialize the mfa_state as an /// HttpOnly __Host-redb.identity.mfa cookie. /// /// Core processors (redb.Identity.Core/Routes/Processors) stay transport-agnostic /// — they emit / consume mfa_state as a body field and these facade processors /// bridge that field to/from the cookie. Keeps the core free of /// Request/Response/Cookie types while still meeting B3 DoD /// ("mfa_state is no longer in the URL; cookie __Host-redb.identity.mfa"). /// /// internal static class MfaCookieProcessors { /// Bare cookie name (__Host- prefix applied automatically over https). internal const string BareCookieName = "redb.identity.mfa"; /// /// Ingress: if the request carries the __Host-redb.identity.mfa (or bare) /// cookie, copies its value into body["mfa_state"] (when the body is an /// and lacks a non-empty value there) so /// every downstream body-reading core processor picks it up transparently. The /// cookie value is also stashed in exchange.Properties["mfa-state-from-cookie"] /// so GET-page renderers can fall back to it when the query string lacks mfa_state. /// internal static Task ReadMfaStateCookie(IExchange e, CancellationToken ct) { var cookieHeader = e.In.GetHeader("Cookie"); if (string.IsNullOrEmpty(cookieHeader)) return Task.CompletedTask; var (prefixed, bare) = IdentityCookieFormatter.Candidates(BareCookieName); var value = ParseCookieValue(cookieHeader, prefixed) ?? ParseCookieValue(cookieHeader, bare); if (string.IsNullOrEmpty(value)) return Task.CompletedTask; e.Properties["mfa-state-from-cookie"] = value; if (e.In.Body is IDictionary body) { var existing = body.TryGetValue("mfa_state", out var cur) ? cur?.ToString() : null; if (string.IsNullOrEmpty(existing)) body["mfa_state"] = value; } return Task.CompletedTask; } /// /// Egress for login + challenge: if the core response body carries a non-empty /// mfa_state, emits Set-Cookie __Host-redb.identity.mfa=.... Caller /// wires this right after the core endpoint on POST /login (mfa-required case) /// and POST /mfa/challenge (OTP re-issue). /// internal static Task WriteMfaStateCookie( IExchange e, CancellationToken ct, bool secure, CookieSameSiteMode sameSite, bool useHostPrefix, TimeSpan maxAge) { var msg = e.HasOut ? (IMessage)e.Out! : e.In; var state = BodyState(msg); if (string.IsNullOrEmpty(state)) return Task.CompletedTask; IdentityCookieFormatter.AddSetCookie(msg.Headers, IdentityCookieFormatter.Build( BareCookieName, value: state, maxAgeSeconds: (int)maxAge.TotalSeconds, secure: secure, sameSite: sameSite, useHostPrefix: useHostPrefix)); return Task.CompletedTask; } /// /// Egress for verify + recovery success: if the core response body has /// success == true, emits a Max-Age=0 deletion cookie. No-op on failure /// (leaves the cookie intact so the user can retry). /// internal static Task ClearMfaStateCookieOnSuccess( IExchange e, CancellationToken ct, bool secure, CookieSameSiteMode sameSite, bool useHostPrefix) { var msg = e.HasOut ? (IMessage)e.Out! : e.In; if (msg.Body is not IDictionary body) return Task.CompletedTask; if (!body.TryGetValue("success", out var s) || s is not true) return Task.CompletedTask; IdentityCookieFormatter.AddSetCookie(msg.Headers, IdentityCookieFormatter.Build( BareCookieName, value: string.Empty, maxAgeSeconds: 0, secure: secure, sameSite: sameSite, useHostPrefix: useHostPrefix)); return Task.CompletedTask; } // ── helpers ── private static string? BodyState(IMessage msg) => msg.Body is IDictionary d && d.TryGetValue("mfa_state", out var v) ? v?.ToString() : null; private static string? ParseCookieValue(string cookieHeader, string name) { foreach (var part in cookieHeader.Split(';', StringSplitOptions.TrimEntries)) { var eqIdx = part.IndexOf('='); if (eqIdx <= 0) continue; if (part[..eqIdx].Trim().Equals(name, StringComparison.Ordinal)) return part[(eqIdx + 1)..].Trim(); } return null; } } Path: redb-identity/src/redb.Identity.Http/Processors/MfaPageProcessors.cs Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/src/redb.Identity.Http/Processors/MfaPageProcessors.cs ---- using System.Net; using redb.Identity.Contracts.Mfa; using redb.Identity.Http.Security; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Http; namespace redb.Identity.Http.Processors; /// /// HTTP processors for MFA verification pages (TOTP code entry, recovery code entry). /// Follows the same pattern as . /// internal static class MfaPageProcessors { /// /// Renders the MFA verification page. /// Reads mfa_state from the query string and derives the list of configured /// methods server-side by decrypting the state via /// (B9 / BUG-9). The methods are no longer accepted from a query parameter — that would /// echo factor-mix information into the browser history / referer. /// When multiple methods are available, renders a selector + JS that calls /mfa/challenge /// for SMS/Email; TOTP is shown directly. Single TOTP method falls back to the legacy form. /// internal static Task RenderMfaPage( IExchange e, CancellationToken ct, string mfaPath = "/mfa", IdentityTransportOptions? opts = null, IMfaStateInspector? inspector = null) { opts ??= new IdentityTransportOptions(); // B3 §4: the encrypted state lives in the __Host-redb.identity.mfa cookie. The // MfaCookieIngressProcessor (ReadMfaStateCookie) stashes it in exchange.Properties // when the request carries a cookie. Falling back to the query string preserves // back-compat for clients still on the pre-B3 ?mfa_state=... transport. var mfaState = (e.Properties.TryGetValue("mfa-state-from-cookie", out var fromCookie) ? fromCookie?.ToString() : null) ?? ExtractMfaStateFromQuery(e) ?? ""; // B9 / BUG-9: derive methods from the encrypted state (server-trusted) instead of // the URL (caller-supplied). Falls back to TOTP-only if state is missing/invalid — // the verify endpoint will reject the bad state with a clear error anyway. // Phase 9e: inspector is supplied by the route builder (BrokeredMfaStateInspector // in .tpkg mode, direct MfaStateProtector in test-fixture mode); fall back to // per-exchange DI lookup for back-compat. string[] methods = Array.Empty(); if (!string.IsNullOrEmpty(mfaState)) { inspector ??= e.ServiceProvider?.GetService(typeof(IMfaStateInspector)) as IMfaStateInspector; var decoded = inspector?.TryGetMethods(mfaState); if (decoded is { Length: > 0 } m) methods = m.Where(x => x == "totp" || x == "sms" || x == "email").Distinct().ToArray(); } var hasRecovery = true; var multipleOrChallenge = methods.Length > 1 || methods.Any(m => m == "sms" || m == "email"); var cardContent = multipleOrChallenge ? BuildMethodSelector(mfaPath, mfaState, methods, hasRecovery, opts) : BuildTotpForm(mfaPath, mfaState, hasRecovery, opts); e.Out = new Message(); e.Out.Body = IdentityPageTemplates.WrapPage("Verification Code", cardContent, opts); e.Out.Headers[HttpHeaders.ResponseContentType] = "text/html; charset=utf-8"; e.Out.Headers[HttpHeaders.ResponseCode] = 200; return Task.CompletedTask; } /// /// Renders the MFA recovery code entry form. /// Reached via "Use recovery code" link from the TOTP page. /// internal static Task RenderMfaRecoveryPage( IExchange e, CancellationToken ct, string mfaRecoveryPath = "/mfa/recovery", string mfaPath = "/mfa", IdentityTransportOptions? opts = null) { opts ??= new IdentityTransportOptions(); // B3 §4: prefer cookie-provided state; fall back to legacy query param. var mfaState = (e.Properties.TryGetValue("mfa-state-from-cookie", out var fromCookie) ? fromCookie?.ToString() : null) ?? ExtractMfaStateFromQuery(e) ?? ""; var cardContent = BuildRecoveryForm(mfaRecoveryPath, mfaPath, mfaState, opts); e.Out = new Message(); e.Out.Body = IdentityPageTemplates.WrapPage("Recovery Code", cardContent, opts); e.Out.Headers[HttpHeaders.ResponseContentType] = "text/html; charset=utf-8"; e.Out.Headers[HttpHeaders.ResponseCode] = 200; return Task.CompletedTask; } /// /// Handles the response after TOTP verification attempt. /// On success: redirect to returnUrl (session cookie already set by upstream processor). /// On failure: re-render the form with an error message. /// internal static Task HandleMfaVerifyResponse( IExchange e, CancellationToken ct, string mfaPath = "/mfa", IdentityTransportOptions? opts = null) { opts ??= new IdentityTransportOptions(); var body = (e.HasOut ? e.Out!.Body : e.In.Body) as IDictionary; if (body is null) return Task.CompletedTask; var success = body.TryGetValue("success", out var s) && s is true; var returnUrl = body.TryGetValue("returnUrl", out var r) ? r?.ToString() : null; if (success && !string.IsNullOrEmpty(returnUrl)) { if (LoginPageProcessors.IsValidReturnUrl(returnUrl)) { e.Out = new Message(); e.Out.Headers[HttpHeaders.ResponseCode] = 302; e.Out.Headers["Location"] = returnUrl; if (e.In.Headers.TryGetValue("Set-Cookie", out var cookie)) e.Out.Headers["Set-Cookie"] = cookie; return Task.CompletedTask; } } if (success) { e.Out = new Message(); e.Out.Body = new Dictionary { ["message"] = "MFA verification successful" }; if (e.In.Headers.TryGetValue("Set-Cookie", out var cookie)) e.Out.Headers["Set-Cookie"] = cookie; return Task.CompletedTask; } // Failed — re-render form with error var mfaState = body.TryGetValue("mfa_state", out var st) ? st?.ToString() ?? "" : ""; var errorDesc = body.TryGetValue("error_description", out var ed) ? ed?.ToString() : "Invalid verification code"; var cardContent = BuildTotpForm(mfaPath, mfaState, hasRecovery: true, opts, errorDesc); e.Out = new Message(); e.Out.Body = IdentityPageTemplates.WrapPage("Verification Code", cardContent, opts); e.Out.Headers[HttpHeaders.ResponseContentType] = "text/html; charset=utf-8"; e.Out.Headers[HttpHeaders.ResponseCode] = 200; return Task.CompletedTask; } /// /// Handles the response after recovery code verification attempt. /// Same redirect/re-render pattern as . /// internal static Task HandleMfaRecoveryResponse( IExchange e, CancellationToken ct, string mfaRecoveryPath = "/mfa/recovery", string mfaPath = "/mfa", IdentityTransportOptions? opts = null) { opts ??= new IdentityTransportOptions(); var body = (e.HasOut ? e.Out!.Body : e.In.Body) as IDictionary; if (body is null) return Task.CompletedTask; var success = body.TryGetValue("success", out var s) && s is true; var returnUrl = body.TryGetValue("returnUrl", out var r) ? r?.ToString() : null; if (success && !string.IsNullOrEmpty(returnUrl)) { if (LoginPageProcessors.IsValidReturnUrl(returnUrl)) { e.Out = new Message(); e.Out.Headers[HttpHeaders.ResponseCode] = 302; e.Out.Headers["Location"] = returnUrl; if (e.In.Headers.TryGetValue("Set-Cookie", out var cookie)) e.Out.Headers["Set-Cookie"] = cookie; return Task.CompletedTask; } } if (success) { e.Out = new Message(); e.Out.Body = new Dictionary { ["message"] = "Recovery code accepted" }; if (e.In.Headers.TryGetValue("Set-Cookie", out var cookie)) e.Out.Headers["Set-Cookie"] = cookie; return Task.CompletedTask; } // Failed — re-render form with error var mfaState = body.TryGetValue("mfa_state", out var st) ? st?.ToString() ?? "" : ""; var errorDesc = body.TryGetValue("error_description", out var ed) ? ed?.ToString() : "Invalid recovery code"; var cardContent = BuildRecoveryForm(mfaRecoveryPath, mfaPath, mfaState, opts, errorDesc); e.Out = new Message(); e.Out.Body = IdentityPageTemplates.WrapPage("Recovery Code", cardContent, opts); e.Out.Headers[HttpHeaders.ResponseContentType] = "text/html; charset=utf-8"; e.Out.Headers[HttpHeaders.ResponseCode] = 200; return Task.CompletedTask; } // ── HTML builders ── private static string BuildTotpForm( string mfaPath, string mfaState, bool hasRecovery, IdentityTransportOptions opts, string? error = null) { var errorHtml = string.IsNullOrEmpty(error) ? "" : $"""

    {WebUtility.HtmlEncode(error)}

    """; // B3 §4: mfa_state lives in the __Host-redb.identity.mfa cookie, never in URLs. var recoveryLink = hasRecovery ? $"""

    Use a recovery code

    """ : ""; _ = mfaState; // state travels in the cookie; kept in signature for form re-render on error return $$"""

    Verification Code

    Enter the 6-digit code from your authenticator app

    {{errorHtml}}
    {{recoveryLink}} """; } private static string BuildRecoveryForm( string mfaRecoveryPath, string mfaPath, string mfaState, IdentityTransportOptions opts, string? error = null) { var errorHtml = string.IsNullOrEmpty(error) ? "" : $"""

    {WebUtility.HtmlEncode(error)}

    """; // B3 §4: no mfa_state in URLs / form inputs — cookie carries it. _ = mfaState; return $$"""

    Recovery Code

    Enter one of your recovery codes

    {{errorHtml}}

    Back to authenticator code

    """; } /// /// Builds a method-selector view: lets the user pick TOTP / SMS / Email. /// TOTP is verified inline; SMS/Email triggers an AJAX call to /mfa/challenge /// which sends the OTP and returns a new mfa_state; the form then swaps to OTP entry. /// private static string BuildMethodSelector( string mfaPath, string mfaState, string[] methods, bool hasRecovery, IdentityTransportOptions opts) { var primary = opts.Branding.PrimaryColor; var hasSms = methods.Contains("sms"); var hasEmail = methods.Contains("email"); var hasTotp = methods.Contains("totp"); var buttons = new System.Text.StringBuilder(); if (hasTotp) { buttons.Append($""""""); } if (hasSms) { buttons.Append($""""""); } if (hasEmail) { buttons.Append($""""""); } // B3 §4: no mfa_state in URLs — the __Host-redb.identity.mfa cookie carries it. var recoveryLink = hasRecovery ? $"""

    Use a recovery code

    """ : ""; var challengePath = mfaPath.TrimEnd('/') + "/challenge"; var encodedMfaPath = WebUtility.HtmlEncode(mfaPath); var encodedChallengePath = WebUtility.HtmlEncode(challengePath); _ = mfaState; // retained in signature for future form re-render; state travels via cookie return $$"""

    Verification Required

    Choose a verification method

    {{buttons}}
    {{recoveryLink}} """; } /// /// Legacy-compat helper: extracts mfa_state from the raw query string. Used /// only as a fallback when the cookie is absent (e.g. direct link during rollout). /// private static string? ExtractMfaStateFromQuery(IExchange e) { var query = e.In.GetHeader(HttpHeaders.Query); if (string.IsNullOrEmpty(query)) return null; foreach (var part in query.Split('&', StringSplitOptions.RemoveEmptyEntries)) { var eqIdx = part.IndexOf('='); if (eqIdx <= 0) continue; if (part[..eqIdx] == "mfa_state") return Uri.UnescapeDataString(part[(eqIdx + 1)..]); } return null; } } Path: redb-identity/src/redb.Identity.Http/Processors/ScimHttpProcessors.cs Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/src/redb.Identity.Http/Processors/ScimHttpProcessors.cs ---- using System.Text.Json; using redb.Identity.Contracts.Scim; using redb.Identity.Contracts.Serialization; using redb.Route.Abstractions; namespace redb.Identity.Http.Processors; /// /// SCIM-specific HTTP processors for /scim/v2/* routes. /// Handles error-to-status mapping, content type, and response serialization. /// internal static class ScimHttpProcessors { /// /// Maps SCIM response body to appropriate HTTP status codes. /// Runs AFTER RedbHttpController (which serializes to byte[] and sets 200), /// so must parse the serialized JSON to detect ScimError responses. /// Also handles custom scim.ResponseCode/Location headers set by processors. /// internal static Task MapScimResponseToHttpStatus(IExchange exchange, CancellationToken ct) { var msg = exchange.HasOut ? exchange.Out! : exchange.In; var body = msg.Body; // Check for processor-set custom response code (e.g. 201 Created) if (exchange.In.Headers.TryGetValue("scim.ResponseCode", out var customCode) && customCode is int code) { msg.Headers["redbHttp.ResponseCode"] = code; if (exchange.In.Headers.TryGetValue("scim.Location", out var loc) && loc is string location) msg.Headers["Location"] = location; if (exchange.In.Headers.TryGetValue("scim.ETag", out var etagCustom) && etagCustom is string etagVal) msg.Headers["ETag"] = etagVal; if (!exchange.HasOut) exchange.Out = msg; return Task.CompletedTask; } // RedbHttpController serializes results to byte[]; parse to detect ScimError if (body is byte[] jsonBytes && jsonBytes.Length > 2) { try { using var doc = JsonDocument.Parse(jsonBytes); if (doc.RootElement.TryGetProperty("status", out var statusEl) && doc.RootElement.TryGetProperty("schemas", out _)) { var statusStr = statusEl.GetString(); if (statusStr is not null && int.TryParse(statusStr, out var errCode) && errCode >= 400) { msg.Headers["redbHttp.ResponseCode"] = errCode; // Pipeline merges Out→In between steps and restores lastOut at the end. // If we only set the header on In (post-merge), lastOut retains the // original 200 from WriteResult. Force-set Out so Pipeline tracks our override. if (!exchange.HasOut) exchange.Out = msg; } } } catch (JsonException) { /* not valid JSON — leave default status */ } } else if (body is ScimError err && int.TryParse(err.Status, out var status)) { msg.Headers["redbHttp.ResponseCode"] = status; if (!exchange.HasOut) exchange.Out = msg; } // Propagate ETag header for normal (200 OK) responses. // Must set exchange.Out so PipelineProcessor captures it as lastOut; // otherwise the restored Out from RedbHttpController won't have the ETag. if (exchange.In.Headers.TryGetValue("scim.ETag", out var etag) && etag is string etagStr && !msg.Headers.ContainsKey("ETag")) { msg.Headers["ETag"] = etagStr; if (!exchange.HasOut) exchange.Out = msg; } return Task.CompletedTask; } /// /// Sets Content-Type: application/scim+json on the response /// and serializes the body to JSON if it's not already a string/byte[]. /// internal static Task SerializeScimJsonResponse(IExchange exchange, CancellationToken ct) { var msg = exchange.HasOut ? exchange.Out! : exchange.In; // Set the transport-agnostic Message.ContentType so non-HTTP consumers // (RabbitMQProducer, Kafka, …) carry the SCIM media type natively. // The HTTP header mirror is kept for HttpConsumer override semantics. msg.ContentType = ScimConstants.MediaType; msg.Headers["redbHttp.ResponseContentType"] = ScimConstants.MediaType; if (msg.Body is not null and not string and not byte[]) { // Go through the IMessageSerializer facade rather than the raw static options // so the wire format is observably identical to what external callers get // when they resolve "application/scim+json" from IDataFormatRegistry. // Serialize() returns byte[]; HttpProducer accepts that as payload. // SCIM wire serialization (RFC 7644 §3) — locked options live in Contracts so // the HTTP facade can serialize without taking a project-reference on Core. msg.Body = JsonSerializer.SerializeToUtf8Bytes(msg.Body, IdentityWireProfiles.ScimOptions); } return Task.CompletedTask; } /// /// Strips the SCIM base path prefix (/scim/v2) from the request path /// so that dispatch /// sees controller-relative paths like /Users/123. /// internal static Task StripScimPrefix(IExchange exchange, CancellationToken ct) { var path = exchange.In.GetHeader("redbHttp.Path"); if (path is not null) { const string prefix = "/scim/v2"; if (path.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) exchange.In.Headers["redbHttp.Path"] = path[prefix.Length..]; } return Task.CompletedTask; } } Path: redb-identity/src/redb.Identity.Http/Processors/SessionCookieProcessors.cs Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/src/redb.Identity.Http/Processors/SessionCookieProcessors.cs ---- using redb.Identity.Http.Security; using redb.Route.Abstractions; using redb.Route.Http; using redb.Identity.Contracts.Configuration; namespace redb.Identity.Http.Processors; /// /// HTTP processors for reading and writing encrypted session cookies. /// The cookie contains an encrypted ticket with userId + username (self-contained, no DB lookup). /// internal static class SessionCookieProcessors { internal const string DefaultCookieName = "redb.identity.session"; internal const string SessionUserIdHeader = "session_user_id"; internal const string SessionUsernameHeader = "session_username"; internal const string SessionIdHeader = "session_id"; // Re-authentication marker (prompt=login / max_age). A DataProtection-signed cookie carrying // the instant re-auth was forced; on the return trip the authorize handler compares it to the // session's auth_time to decide whether the End-User re-authenticated. See HandleReauthCookie. internal const string ReauthCookieName = "redb.identity.reauth"; internal const string ReauthMarkedSidHeader = "reauth_marked_sid"; // in: session id active when re-auth was forced (0 = none) internal const string ReauthSetProperty = "reauth_set"; // out: exchange prop = session id to mark (long) internal const string ReauthClearProperty = "reauth_clear"; // out: exchange prop = true private static readonly TimeSpan ReauthMarkerMaxAge = TimeSpan.FromMinutes(10); // POST /connect/authorize carries the request in the form body, not in the query string. The // body is replaced by the authorize response before RedirectToLogin and RedirectToConsent run, // so the form is kept here, encoded as a query, for the return trip. internal const string AuthorizeFormQueryProperty = "identity:authorize-form-query"; /// /// Keeps the parameters of a form-encoded authorization request (OIDC Core 3.1.2.1, POST) as a /// query string, so the login and consent pages return to GET /connect/authorize with /// the same request. Runs after . /// internal static Task CaptureAuthorizeForm(IExchange e, CancellationToken ct) { if (e.In.Body is IDictionary form && form.Count > 0) { e.Properties[AuthorizeFormQueryProperty] = string.Join("&", form.Select(kv => kv.Value is null ? Uri.EscapeDataString(kv.Key) : $"{Uri.EscapeDataString(kv.Key)}={Uri.EscapeDataString(kv.Value.ToString() ?? string.Empty)}")); } return Task.CompletedTask; } /// /// The authorization request the browser made, as a local path: the form of a POST request, /// otherwise the query string of a GET request. /// private static string OriginalAuthorizeUrl(IExchange e) { var path = e.In.GetHeader(HttpHeaders.Path) ?? "/connect/authorize"; var query = e.Properties.TryGetValue(AuthorizeFormQueryProperty, out var fq) && fq is string formQuery && formQuery.Length > 0 ? formQuery : e.In.GetHeader(HttpHeaders.Query); return string.IsNullOrEmpty(query) ? path : $"{path}?{query}"; } /// /// Reads the session cookie from the HTTP request, decrypts it, and sets /// session_user_id and session_username headers on the exchange. /// Must run before routing to the authorize endpoint. Tries both the bare name /// and the __Host- prefixed variant so deployments can flip /// without a forced re-login window. /// internal static Task ReadSessionCookie( IExchange e, CancellationToken ct, SessionTicketService ticketService, TimeSpan maxAge, string bareCookieName) { var cookieHeader = e.In.GetHeader("Cookie"); if (string.IsNullOrEmpty(cookieHeader)) return Task.CompletedTask; // Re-auth marker (prompt=login / max_age): decode it up-front so the authorize handler can // tell whether the End-User re-authenticated since it forced re-auth. Independent of the // session cookie (it must survive the new session that /login creates). var (reauthPrefixed, reauthBare) = IdentityCookieFormatter.Candidates(ReauthCookieName); var reauthValue = ParseCookieValue(cookieHeader, reauthPrefixed) ?? ParseCookieValue(cookieHeader, reauthBare); if (reauthValue is not null) { var reauth = ticketService.UnprotectReauth(reauthValue, ReauthMarkerMaxAge); if (reauth.HasValue) e.In.Headers[ReauthMarkedSidHeader] = reauth.Value.MarkedSessionId; } var (prefixed, bare) = IdentityCookieFormatter.Candidates(bareCookieName); var ticketValue = ParseCookieValue(cookieHeader, prefixed) ?? ParseCookieValue(cookieHeader, bare); if (ticketValue is null) return Task.CompletedTask; var ticket = ticketService.Unprotect(ticketValue, maxAge); if (ticket is null) return Task.CompletedTask; e.In.Headers[SessionUserIdHeader] = ticket.UserId; e.In.Headers[SessionUsernameHeader] = ticket.Username; if (ticket.SessionId > 0) e.In.Headers[SessionIdHeader] = ticket.SessionId; return Task.CompletedTask; } /// /// Writes / clears the re-authentication marker cookie on the authorize response, driven by /// exchange properties the OpenIddict authorize handler set: /// /// (session id, 0 = none) → the handler is forcing re-auth /// (prompt=login or max_age); mint a signed redb.identity.reauth cookie binding the /// currently-active session so the return trip can prove the End-User signed in again. /// → re-auth was satisfied; consume the marker (expire /// the cookie) so a stale marker can never satisfy a LATER prompt=login (would be a bypass). /// /// Runs after the redirect processors so it appends its Set-Cookie to the final response (login /// redirect, consent redirect, or the success code redirect). /// internal static Task HandleReauthCookie( IExchange e, CancellationToken ct, SessionTicketService ticketService, bool secure, CookieSameSiteMode sameSite, bool useHostPrefix) { string? setCookie = null; if (e.Properties.TryGetValue(ReauthSetProperty, out var rs) && rs is long markedSessionId) { var marker = ticketService.ProtectReauth(markedSessionId); setCookie = IdentityCookieFormatter.Build( ReauthCookieName, marker, maxAgeSeconds: (int)ReauthMarkerMaxAge.TotalSeconds, secure: secure, sameSite: sameSite, useHostPrefix: useHostPrefix); } else if (e.Properties.TryGetValue(ReauthClearProperty, out var rc) && rc is true) { setCookie = IdentityCookieFormatter.Build( ReauthCookieName, value: string.Empty, maxAgeSeconds: 0, secure: secure, sameSite: sameSite, useHostPrefix: useHostPrefix); } if (setCookie is null) return Task.CompletedTask; var msg = e.HasOut ? e.Out! : e.In; // Added, not assigned. No response on this route carries another cookie today, but losing this // one to a later assignment is the bypass named above, so it must never depend on that. IdentityCookieFormatter.AddSetCookie(msg.Headers, setCookie); return Task.CompletedTask; } /// /// Writes the session cookie to the HTTP response after successful login. /// Reads userId/username from the current message body (In or Out, depending on pipeline merge state). /// internal static Task WriteSessionCookie( IExchange e, CancellationToken ct, SessionTicketService ticketService, TimeSpan maxAge, bool secure, string bareCookieName, CookieSameSiteMode sameSite, bool useHostPrefix) { // After PipelineProcessor merges Out→In, the body is on In; if Out is present, use it. var msg = e.HasOut ? (IMessage)e.Out! : e.In; var body = msg.Body as IDictionary; if (body is null) return Task.CompletedTask; if (body.TryGetValue("success", out var s) && s is true && body.TryGetValue("userId", out var uid) && uid is long userId && body.TryGetValue("username", out var uname) && uname is string username) { var sessionId = body.TryGetValue("sessionId", out var sid) && sid is long sId ? sId : 0L; var ticket = ticketService.Protect(userId, sessionId, username); IdentityCookieFormatter.AddSetCookie(msg.Headers, IdentityCookieFormatter.Build( bareCookieName, ticket, maxAgeSeconds: (int)maxAge.TotalSeconds, secure: secure, sameSite: sameSite, useHostPrefix: useHostPrefix)); } return Task.CompletedTask; } /// /// Clears the session cookie (for logout). Mirrors the flags used by /// so the browser actually deletes the matching cookie. /// internal static Task ClearSessionCookie(IExchange e, CancellationToken ct, bool secure, string bareCookieName, CookieSameSiteMode sameSite, bool useHostPrefix) { var msg = e.Out ?? e.In; IdentityCookieFormatter.AddSetCookie(msg.Headers, IdentityCookieFormatter.Build( bareCookieName, value: string.Empty, maxAgeSeconds: 0, secure: secure, sameSite: sameSite, useHostPrefix: useHostPrefix)); return Task.CompletedTask; } /// /// Redirects to the login page when the authorize endpoint returns login_required. /// Constructs /login?returnUrl=<original-authorize-url>. /// internal static Task RedirectToLogin( IExchange e, CancellationToken ct, string loginPath) { // OIDC §3.1.2.6: prompt=none MUST NOT trigger any interactive UI. When the // OpenIddict handler rejected with login_required for that reason, it sets the // `prompt_none` flag — let the standard redirect-to-redirect_uri error response // (already wired by HandleRedirectResponse) flow through unchanged. if (e.Properties.TryGetValue("prompt_none", out var pn) && pn is true) return Task.CompletedTask; // PipelineProcessor merges Out→In and nulls Out between steps, so the body // produced by the upstream OpenIddict processor lives on In by the time we run. var rawBody = e.HasOut ? e.Out!.Body : e.In.Body; if (rawBody is not IDictionary body) return Task.CompletedTask; if (!body.TryGetValue("error", out var err) || err?.ToString() != "login_required") return Task.CompletedTask; var originalUrl = OriginalAuthorizeUrl(e); var redirectUrl = $"{loginPath}?returnUrl={Uri.EscapeDataString(originalUrl)}"; var msg = e.HasOut ? e.Out! : e.In; // Empty byte[] body (not null) so HttpConsumer.WriteResponse enters the // header-copying branch and emits the Location header for the 302. msg.Body = Array.Empty(); msg.Headers[HttpHeaders.ResponseCode] = 302; msg.Headers["Location"] = redirectUrl; return Task.CompletedTask; } /// /// Redirects to the consent page when the authorize endpoint returns consent_required. /// The consent parameters travel in a server-signed ticket (/consent?ct=…), never as /// query fields: the page used to render app_name/scopes from the URL, so a /// crafted link could show the operator's trusted UI attributing an attacker's client to a /// familiar name (). /// internal static Task RedirectToConsent( IExchange e, CancellationToken ct, string consentPath, SessionTicketService ticketService) { // Same merge consideration as RedirectToLogin: body may live on In after Out→In merge. var rawBody = e.HasOut ? e.Out!.Body : e.In.Body; if (rawBody is not IDictionary body) return Task.CompletedTask; if (!body.TryGetValue("error", out var err) || err?.ToString() != "consent_required") return Task.CompletedTask; // Read consent details from exchange properties (set by HandleAuthorizationRequestHandler) var clientId = e.Properties.TryGetValue("consent_client_id", out var cid) ? cid?.ToString() : null; var appName = e.Properties.TryGetValue("consent_app_name", out var an) ? an?.ToString() : null; var scopes = e.Properties.TryGetValue("consent_scopes", out var sc) ? sc?.ToString() : null; var userId = e.Properties.TryGetValue("consent_user_id", out var uid) ? uid?.ToString() : null; if (clientId is null) return Task.CompletedTask; // The original authorize URL for the post-consent redirect. var originalUrl = OriginalAuthorizeUrl(e); var scopesArr = string.IsNullOrEmpty(scopes) ? Array.Empty() : scopes!.Split(' ', StringSplitOptions.RemoveEmptyEntries); var msg = e.HasOut ? e.Out! : e.In; // Header-driven content negotiation: a BFF that wants to render its own native // consent UI sends X-Identity-Delegate-Consent: 1. We answer with a machine- // readable 400 JSON body instead of the browser 302 to /consent — the BFF then // hosts its own /consent Razor page and POSTs to /me/consents to grant. var delegateHeader = e.In.GetHeader("X-Identity-Delegate-Consent"); if (string.Equals(delegateHeader, "1", StringComparison.Ordinal) || string.Equals(delegateHeader, "true", StringComparison.OrdinalIgnoreCase)) { msg.Body = new Dictionary { ["error"] = "consent_required", ["clientId"] = clientId, ["appName"] = appName ?? clientId, ["scopes"] = scopesArr, ["userId"] = userId ?? "", ["returnUrl"] = originalUrl }; msg.Headers[HttpHeaders.ResponseCode] = 400; msg.Headers["Content-Type"] = "application/json; charset=utf-8"; return Task.CompletedTask; } var consentUserId = userId is not null && long.TryParse(userId, out var parsedUid) ? parsedUid : 0; var consentTicket = ticketService.ProtectConsent(new ConsentTicket( UserId: consentUserId, ClientId: clientId, AppName: appName ?? clientId, Scopes: scopes ?? "", ReturnUrl: originalUrl)); var redirectUrl = $"{consentPath}?ct={Uri.EscapeDataString(consentTicket)}"; msg.Body = Array.Empty(); msg.Headers[HttpHeaders.ResponseCode] = 302; msg.Headers["Location"] = redirectUrl; return Task.CompletedTask; } private static string? ParseCookieValue(string cookieHeader, string name) { foreach (var part in cookieHeader.Split(';', StringSplitOptions.TrimEntries)) { var eqIdx = part.IndexOf('='); if (eqIdx <= 0) continue; if (part[..eqIdx].Trim().Equals(name, StringComparison.Ordinal)) return part[(eqIdx + 1)..].Trim(); } return null; } } Path: redb-identity/src/redb.Identity.Http/Security/SessionTicketService.cs Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/src/redb.Identity.Http/Security/SessionTicketService.cs ---- using Microsoft.AspNetCore.DataProtection; using Microsoft.Extensions.Logging; using redb.Identity.Contracts.Common; namespace redb.Identity.Http.Security; /// /// Encrypts/decrypts session tickets using ASP.NET DataProtection. /// A session ticket is a compact encrypted blob containing the user ID, session ID, and username. /// Cookie-based: self-contained, no DB lookup on every request (except revocation check). /// public sealed class SessionTicketService { private const string Purpose = "redb.identity.session"; private const string ReauthPurpose = "redb.identity.reauth"; private const string ConsentPurpose = "redb.identity.consent"; private const byte Version1 = 1; private const byte Version2 = 2; private readonly IDataProtector _protector; private readonly IDataProtector _reauthProtector; private readonly IDataProtector _consentProtector; private readonly TimeProvider _timeProvider; private readonly ILogger? _logger; public SessionTicketService(IDataProtectionProvider provider) : this(provider, TimeProvider.System, null) { } public SessionTicketService(IDataProtectionProvider provider, TimeProvider? timeProvider) : this(provider, timeProvider, null) { } public SessionTicketService( IDataProtectionProvider provider, TimeProvider? timeProvider, ILogger? logger) { ArgumentNullException.ThrowIfNull(provider); _protector = provider.CreateProtector(Purpose); _reauthProtector = provider.CreateProtector(ReauthPurpose); _consentProtector = provider.CreateProtector(ConsentPurpose); _timeProvider = timeProvider ?? TimeProvider.System; _logger = logger; } /// /// Signs a re-authentication marker capturing WHICH session was active when the OP forced /// re-authentication (prompt=login / max_age), together with the instant it did so (for /// expiry only). DataProtection-encrypted so a client cannot forge it. On the return trip /// re-auth is satisfied once the ACTIVE session id differs from this one — i.e. the End-User /// signed in again (a fresh /login always mints a new session). Keying on the session id /// rather than the second-precision auth_time avoids a same-second window where an /// unchanged session could otherwise be treated as re-authenticated. /// is 0 when re-auth was forced with no active session (logged-out prompt=login). A /// distinct protector purpose keeps it non-interchangeable with session tickets. /// public string ProtectReauth(long markedSessionId) { var payload = new byte[16]; BitConverter.TryWriteBytes(payload.AsSpan(0, 8), markedSessionId); BitConverter.TryWriteBytes(payload.AsSpan(8, 8), _timeProvider.GetUtcNow().UtcTicks); return Convert.ToBase64String(_reauthProtector.Protect(payload)); } /// /// Verifies and decodes a re-authentication marker produced by . /// Returns the marked session id (and the instant it was requested), or null when the /// marker is missing, tampered, or older than . /// public ReauthMarker? UnprotectReauth(string marker, TimeSpan maxAge) { if (string.IsNullOrEmpty(marker)) return null; try { var payload = _reauthProtector.Unprotect(Base64Canonical.Decode(marker)); if (payload.Length < 16) return null; var markedSessionId = BitConverter.ToInt64(payload, 0); var requestedAt = new DateTimeOffset(BitConverter.ToInt64(payload, 8), TimeSpan.Zero); if (_timeProvider.GetUtcNow() - requestedAt > maxAge) return null; return new ReauthMarker(markedSessionId, requestedAt); } catch (Exception ex) { _logger?.LogWarning(ex, "SessionTicketService: failed to decrypt reauth marker."); return null; } } /// /// Mints a signed consent ticket. The authorization server issues it (after it has /// decided consent is required) so that the consent page can render — and be granted — /// only from server-supplied, tamper-proof parameters. Before this, the page rendered /// app_name/scopes straight from the query string, so a crafted /// /consent?app_name=Your%20Bank&client_id=attacker link showed the /// operator's own trusted UI attributing an attacker's client to a familiar name. The /// ticket also carries the user it was minted for, so the grant POST can refuse a ticket /// replayed under a different session. A distinct protector purpose keeps it /// non-interchangeable with session tickets. /// public string ProtectConsent(ConsentTicket ticket) { ArgumentNullException.ThrowIfNull(ticket); var withStamp = ticket with { IssuedAt = _timeProvider.GetUtcNow() }; var payload = System.Text.Json.JsonSerializer.SerializeToUtf8Bytes(withStamp); return Convert.ToBase64String(_consentProtector.Protect(payload)); } /// /// Verifies and decodes a consent ticket produced by . /// Returns null when the ticket is missing, tampered, or older than /// . /// public ConsentTicket? UnprotectConsent(string ticket, TimeSpan maxAge) { if (string.IsNullOrEmpty(ticket)) return null; try { var payload = _consentProtector.Unprotect(Base64Canonical.Decode(ticket)); var decoded = System.Text.Json.JsonSerializer.Deserialize(payload); if (decoded is null) return null; if (_timeProvider.GetUtcNow() - decoded.IssuedAt > maxAge) return null; return decoded; } catch (Exception ex) { _logger?.LogWarning(ex, "SessionTicketService: failed to decrypt consent ticket."); return null; } } /// /// Creates an encrypted session ticket for the given user and session. /// Format v2: [version:1][userId:8][sessionId:8][issuedUtcTicks:8][usernameUtf8:rest] /// public string Protect(long userId, long sessionId, string username) { ArgumentNullException.ThrowIfNull(username); var usernameBytes = System.Text.Encoding.UTF8.GetBytes(username); var payload = new byte[1 + 8 + 8 + 8 + usernameBytes.Length]; payload[0] = Version2; BitConverter.TryWriteBytes(payload.AsSpan(1, 8), userId); BitConverter.TryWriteBytes(payload.AsSpan(9, 8), sessionId); BitConverter.TryWriteBytes(payload.AsSpan(17, 8), _timeProvider.GetUtcNow().UtcTicks); usernameBytes.CopyTo(payload.AsSpan(25)); var encrypted = _protector.Protect(payload); return Convert.ToBase64String(encrypted); } /// /// Decrypts a session ticket. Returns null if the ticket is invalid, tampered, or expired. /// Supports both v1 (no sessionId) and v2 (with sessionId) formats for rolling upgrade. /// public SessionTicket? Unprotect(string ticket, TimeSpan maxAge) { if (string.IsNullOrEmpty(ticket)) return null; try { var encrypted = Base64Canonical.Decode(ticket); var payload = _protector.Unprotect(encrypted); if (payload.Length < 17) return null; var version = payload[0]; if (version == Version2 && payload.Length >= 25) { var userId = BitConverter.ToInt64(payload, 1); var sessionId = BitConverter.ToInt64(payload, 9); var issuedTicks = BitConverter.ToInt64(payload, 17); var issuedAt = new DateTimeOffset(issuedTicks, TimeSpan.Zero); if (_timeProvider.GetUtcNow() - issuedAt > maxAge) return null; var username = System.Text.Encoding.UTF8.GetString(payload, 25, payload.Length - 25); return new SessionTicket(userId, username, issuedAt, sessionId); } if (version == Version1) { var userId = BitConverter.ToInt64(payload, 1); var issuedTicks = BitConverter.ToInt64(payload, 9); var issuedAt = new DateTimeOffset(issuedTicks, TimeSpan.Zero); if (_timeProvider.GetUtcNow() - issuedAt > maxAge) return null; var username = System.Text.Encoding.UTF8.GetString(payload, 17, payload.Length - 17); return new SessionTicket(userId, username, issuedAt, SessionId: 0); } return null; } catch (Exception ex) { // Tampered ciphertext OR DataProtection key rotation. Return null to keep the // public contract intact (treated as "no valid session"), but make sure operators // see decrypt failures \u2014 a sustained run is a security signal. _logger?.LogWarning(ex, "SessionTicketService: failed to decrypt session ticket (length={Length}).", ticket.Length); return null; } } } /// /// Decrypted session ticket data. /// public sealed record SessionTicket(long UserId, string Username, DateTimeOffset IssuedAt, long SessionId = 0); /// /// Server-signed consent parameters. Every field is set by the authorization server, never /// by the browser: and are what the page displays, /// and are what the grant records, and /// is the user it was minted for (the grant POST requires the session to /// match). is stamped by . /// public sealed record ConsentTicket( long UserId, string ClientId, string AppName, string Scopes, string ReturnUrl, DateTimeOffset IssuedAt = default); /// /// Decrypted re-authentication marker: the session that was active when re-auth was forced /// (0 = none / logged out) and the instant it was requested (expiry only). /// public readonly record struct ReauthMarker(long MarkedSessionId, DateTimeOffset RequestedAt); Path: redb-identity/src/redb.Identity.Http/redb.Identity.Http.config.example.json Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/src/redb.Identity.Http/redb.Identity.Http.config.example.json ---- { "//": [ "redb.Identity.Http module configuration template (Tsak Layer 4: {Module}.config.json).", "This file ships inside the .tpkg and provides the HTTP transport defaults for the", "Identity HTTP facade. Phase 8: the facade runs in its OWN RouteContext", "('identity.http') and exchanges with redb.Identity.Core ('identity') exclusively", "through `direct-vm://identity-*` brokered messages whose DTOs live in", "redb.Identity.Contracts. The two modules no longer share a context or DI.", "", "Override any value via the standard Tsak 5-layer pipeline:", " Layer 1 (host appsettings): Tsak:Contexts:default:IdentityTransport:*", " Layer 2 (per-context): Tsak:Contexts:{contextName}:IdentityTransport:*", " Layer 3 (context.json): same shape as below, merged before this file", " Layer 4 (THIS file): defaults shipped with the .tpkg", " Layer 5 (Override, wins): Tsak:Contexts:{contextName}:Override:IdentityTransport:*", "", "Environment-variable overrides use the standard .NET IConfiguration mapping, e.g.:", " Tsak__Contexts__identity__Override__IdentityTransport__Http__PublicPort=8443", " Tsak__Contexts__identity__Override__IdentityTransport__Http__CorsEnabled=true", "", "PRODUCTION CHECKLIST (per docs/IDENTITY_DEPLOYMENT.md):", " \u2022 Bind PublicPort behind a TLS-terminating reverse proxy (nginx/HAProxy/ALB).", " \u2022 Set ManagementPort to a separate value (e.g. 8081) and firewall it off from", " the public internet \u2014 the management API is admin-only and never exposes CORS.", " \u2022 Keep CorsRegisteredClientOriginsEnabled=true so onboarding new SPAs via the", " management API automatically grants them CORS access \u2014 no config redeploys.", " \u2022 Use AdditionalAllowedOrigins ONLY for dev/staging fallbacks that have no", " OAuth client of their own. NEVER set it to '*'." ], "ContextName": "identity.http", "AutoStart": true, "//RedbInstanceName": [ "Phase 9b: identifies the named IRedbService the HTTP facade uses to back the", "shared cluster-wide DataProtection key-ring. MUST point at the SAME database as", "redb.Identity.Core's RedbInstanceName so cookies issued by either context decrypt", "with either. The HTTP facade has no project-reference on Core \u2014 the only thing it", "shares with Core is the DP key-ring (rows in the PROPS store) plus the application", "name 'redb.identity' set in IdentityHttpModuleHost.", "Override path: Tsak__Contexts__identity.http__Override__RedbInstanceName=." ], "RedbInstanceName": "identity-pg", "//Redb": [ "Named IRedbService instances. Tsak's RegisterNamedRedbServices reads this section", "after context.json/{Module}.config.json merge and registers each entry under", "'redb-factory:{name}' in the route-context registry. The HTTP facade's child", "container resolves the factory whose name matches RedbInstanceName above.", "", "PRODUCTION: keep ConnectionString out of source control \u2014 supply via Layer-5:", " Tsak__Contexts__identity.http__Override__Redb__identity-pg__ConnectionString=", "", "DEPLOYMENT TIP: place a shared 'context.json' (Layer 3) in the same Libs/ folder as", "redb.Identity.Core.tpkg + redb.Identity.Http.tpkg containing only the Redb section;", "both .tpkg will pick it up via Tsak's per-folder context.json merge, eliminating", "the duplicated block here." ], "Redb": { "identity-pg": { "Provider": "postgres", "UsePro": true, "ConnectionString": "Host=localhost;Port=5432;Username=postgres;Password=1;Database=redb;Pooling=true", "EnsureCreated": true } }, "IdentityTransport": { "Http": { "//": [ "PublicPort \u2014 OIDC protocol + discovery endpoints (token, userinfo, .well-known/*).", "ManagementPort \u2014 admin API (/api/v1/identity/*, /scim/*). Null = share PublicPort.", " Production strongly recommends a separate, firewalled port.", "CorsEnabled \u2014 master switch. Required for SPA / native PKCE clients calling", " token / userinfo / revocation from a browser context.", " Discovery (/.well-known/*) always uses '*' when CorsEnabled=true;", " browser-redirect endpoints (authorize, login, logout-form) and", " the management API NEVER receive CORS headers regardless.", "CorsRegisteredClientOriginsEnabled \u2014 when true (default), the resolver allows any", " browser Origin matching a registered OAuth application's redirect", " or post-logout URI. New SPAs onboarded via the management API", " gain CORS access without any config change.", "AdditionalAllowedOrigins \u2014 CSV of origins always allowed (dev/staging fallbacks).", " Per-request matched and echoed as a single origin (browsers reject", " CSV in Access-Control-Allow-Origin).", "EnableDeviceCodeFlow \u2014 mounts /connect/deviceauthorization and /connect/device/verify.", " Must also be enabled in Identity:EnableDeviceCodeFlow.", "FederationCallbackPath \u2014 path used for IdP redirect-back when EnableFederation=true." ], "PublicPort": 8080, "//ManagementPort": "Production: separate port for admin API, e.g. 8081 (firewalled).", "ManagementPort": null, "CorsEnabled": false, "CorsRegisteredClientOriginsEnabled": true, "//AdditionalAllowedOrigins": "CSV of origins (no trailing slash). Example: 'https://app.dev.local,https://staging.example.com'. NEVER use '*'.", "AdditionalAllowedOrigins": null, "EnableDeviceCodeFlow": true, "FederationCallbackPath": "/connect/federation/callback" }, "Features": { "EnablePushedAuthorization": true } } } Path: redb-identity/src/redb.Identity.Http/redb.Identity.Http.config.json Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/src/redb.Identity.Http/redb.Identity.Http.config.json ---- { "//": [ "Tsak Layer 4 stub — module identity only.", "All business config lives in the EXTERNAL Libs/context.json (Layer 3),", "alongside the .tpkg files. See: redb.Identity.Http.config.example.json for", "the full annotated template (reference, NOT shipped)." ], "ContextName": "identity.http", "AutoStart": true } Path: redb-identity/src/redb.Identity.Http/redb.Identity.Http.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.Http/redb.Identity.Http.csproj ---- redb.Identity.Http redb.Identity.Http HTTP / HTTPS facade for redb.Identity — OIDC discovery, token, authorize, userinfo, introspect, revoke, JWKS, PAR, DCR, SCIM, /me and management endpoints. PreserveNewest