Path: redb-identity/src/redb.Identity.Management/Controllers/IdentityControllerBase.cs
Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity
Page: https://redbase.app/src/dev-2026-12-06/redb-identity/src/redb.Identity.Management/Controllers/IdentityControllerBase.cs
----
using Microsoft.Extensions.DependencyInjection;
using redb.Identity.Contracts.Common;
using redb.Identity.Contracts.Routes;
using redb.Identity.Contracts.Validation;
using redb.Route.Abstractions;
using redb.Route.Controllers;
using redb.Route.Components;
using redb.Route.Core;
namespace redb.Identity.Management.Controllers;
///
/// Base controller for Identity management API. Forwards operations to
/// direct-vm://identity-manage-* routes via the route context,
/// preserving WireTap (event dispatch), retry, and error handling.
///
public abstract class IdentityControllerBase : RedbController
{
///
/// Parses a route ID parameter as either a numeric or string key.
/// Numeric IDs are stored under ,
/// string IDs under .
///
protected static object ParseIdBody(string id, string numericKey = "id", string stringKey = "id") =>
long.TryParse(id, out var numericId)
? new Dictionary { [numericKey] = numericId }
: new Dictionary { [stringKey] = id };
///
/// Runs DataAnnotations validation on the request DTO.
/// Returns null if valid; otherwise a problem object the controller method
/// can return as-is — HttpIdentityProcessors in the HTTP facade
/// maps the resulting error = "invalid_request" body to HTTP 400 (E6 / D5).
///
protected static object? ValidateRequest(object? request) => RequestValidator.Validate(request);
///
/// Sends an operation to a direct-vm://identity-manage-* route,
/// preserving route-level cross-cutting concerns (WireTap event dispatch,
/// OnException retry, error handling). Returns the response body.
///
/// B8: propagates the authenticated caller's subject and granted scopes from the outer
/// HTTP exchange (set by ManagementBearerAuthProcessor ) into the inner direct-vm
/// exchange so that RequireSelfOrAdminProcessor can enforce self-vs-admin
/// authorization downstream.
///
///
protected async Task Forward(string endpointUri, string operation, object? body = null)
{
var endpoint = Context.GetEndpoint(endpointUri);
if (IsUnbound(endpointUri))
{
return new ErrorResponse
{
Error = "not_found",
ErrorDescription = "This deployment does not expose the requested endpoint."
};
}
var msg = new Message();
msg.Headers["operation"] = operation;
if (body is not null)
msg.Body = body;
// E2 — propagate the Idempotency-Key header (RFC TBD, de-facto standard) from the
// outer HTTP exchange into the inner direct-vm exchange so that
// IdempotencyProcessor on the route can short-circuit duplicate retries with the
// cached response. Also forward the HTTP method for audit metadata.
if (Exchange?.In is { } httpIn)
{
var idemKey = httpIn.GetHeader("Idempotency-Key")
?? httpIn.GetHeader("idempotency-key");
if (!string.IsNullOrEmpty(idemKey))
msg.Headers["Idempotency-Key"] = idemKey;
var method = httpIn.GetHeader("redbHttp.Method");
if (!string.IsNullOrEmpty(method))
msg.Headers["redbHttp.Method"] = method;
// The caller's address (the transport's, set by the HTTP consumer and its proxy rules, never by the
// caller) and User-Agent, so the audit row of the change says where it came from.
var remote = httpIn.GetHeader("redbHttp.RemoteAddress");
if (!string.IsNullOrEmpty(remote))
msg.Headers["redbHttp.RemoteAddress"] = remote;
var userAgent = httpIn.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 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;
// Propagate auth context (B8 — RequireSelfOrAdminProcessor depends on these).
if (Exchange?.Properties is { } outerProps)
{
if (outerProps.TryGetValue("identity:management-principal", out var principal))
exchange.Properties["identity:management-principal"] = principal;
if (outerProps.TryGetValue("identity:management-subject", out var subject))
exchange.Properties["identity:management-subject"] = subject;
if (outerProps.TryGetValue("identity:management-scopes", out var scopes))
exchange.Properties["identity:management-scopes"] = scopes;
// H3-SSO: the "sid" claim from the caller's access token (optional — only set
// for OIDC session-backed tokens). Required by MeSessionsProcessor's
// revoke-current operation.
if (outerProps.TryGetValue("identity:management-sid", out var sid))
exchange.Properties["identity:management-sid"] = sid;
}
var producer = endpoint.CreateProducer();
try
{
await producer.Process(exchange).ConfigureAwait(false);
// E2 — surface the Idempotency-Replayed marker to the HTTP response so callers can
// tell when they were served from cache (debugging / metrics). Read from Out ?? In
// (Identity convention: business processors answer in In).
var idemSrc = exchange.Out ?? exchange.In;
if (idemSrc?.Headers.TryGetValue("Idempotency-Replayed", out var replayed) == true
&& Exchange?.In is { } outHttp)
{
outHttp.Headers["Idempotency-Replayed"] = replayed;
}
// B2 — propagate response-meta from the inner direct-vm exchange to the outer HTTP
// exchange. Without this, inner OnException handlers (which set e.g.
// redbHttp.ResponseCode=503 on inner.Out) are silently discarded and the caller
// sees HTTP 200 with an error body — a critical contract violation.
PropagateInnerResponse(exchange);
return exchange.Out?.Body ?? exchange.In.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/management HTTP call leaks one connection until MaxPoolSize is hit
// and subsequent calls 503 with NpgsqlException("connection pool exhausted").
await exchange.DisposeAsync().ConfigureAwait(false);
}
}
///
/// True when the operation's route is not bound in this deployment.
///
/// Several Identity features bind their direct-vm:// routes only when enabled —
/// self-service registration, e-mail verification, e-mail change, WebAuthn. The facades mount
/// their controllers unconditionally, so a caller reaching a disabled feature used to arrive at
/// a producer with nothing to call, and the resulting InvalidOperationException surfaced
/// as a generic failure with an unhandled-exception stack trace in the log. What the caller
/// asked for simply does not exist here, and that is what they are told: the standard
/// not_found error document, which
/// turns into 404 on every transport — the answer the client
/// SDK already reads as "this feature is off"
/// (IdentityClient.RegisterAccountAsync maps 404/403 to registration_disabled ).
///
///
/// The question is asked of the registry rather than of a feature flag on purpose. The flag
/// lives in Core's options; the facade binds its own. Copying it across the boundary would put
/// the answer in two places and let them disagree, whereas what is actually bound cannot
/// disagree with itself. Non-direct-vm endpoints are left alone — their components
/// decide reachability themselves.
///
///
private bool IsUnbound(string endpointUri)
{
// Route's own parser, not a hand-rolled split: BaseKey has to be the exact string the
// component keyed the registry with, and that is the parser's business, not this one's.
var uri = EndpointUriParser.Parse(endpointUri);
if (!string.Equals(uri.Scheme, "direct-vm", StringComparison.OrdinalIgnoreCase))
return false;
var registry = Context.GetServiceProvider()?.GetService();
if (registry is null) return false;
// The same lookup DirectVmProducer is about to perform.
return registry.GetProcessor(uri.BaseKey) is null;
}
///
/// Mirrors response meta (HTTP status, content type, error envelopes) from the inner
/// direct-vm exchange to the outer HTTP exchange's Out message. The kernel
/// HttpControllerDispatcher.WriteResult respects pre-set headers, so after this
/// call the dispatcher will not clobber the response code/content-type carried by inner
/// route handlers (OnException, explicit redirects, 202 Accepted, etc.).
///
protected void PropagateInnerResponse(IExchange innerExchange)
{
if (Exchange is null) return;
// Identity pipeline convention: business processors write the response into
// exchange.In. PipelineProcessor is
// Camel-compliant and never synthesises Out from In, so transport-meta headers
// (redbHttp.ResponseCode, Location, ETag, Idempotency-Replayed, ...) may live on
// either side. Reading from Out ?? In keeps the whitelist below universal.
var innerSrc = innerExchange.Out ?? innerExchange.In;
if (innerSrc is null) return;
Exchange.Out ??= Exchange.In.Clone();
var outerOut = Exchange.Out;
// Headers that describe the HTTP response envelope and must survive across the
// facade boundary. This list intentionally covers only transport-level meta; domain
// headers (scim.*) are handled by domain-specific Forward overrides where needed.
CopyHeader(innerSrc, outerOut, "redbHttp.ResponseCode");
CopyHeader(innerSrc, outerOut, "redbHttp.ResponseContentType");
CopyHeader(innerSrc, outerOut, "Content-Type");
CopyHeader(innerSrc, outerOut, "Location");
CopyHeader(innerSrc, outerOut, "ETag");
CopyHeader(innerSrc, outerOut, "Cache-Control");
CopyHeader(innerSrc, outerOut, "Retry-After");
}
private static void CopyHeader(IMessage src, IMessage dst, string key)
{
if (src.Headers.TryGetValue(key, out var val) && val is not null
&& !dst.Headers.ContainsKey(key))
{
dst.Headers[key] = val;
}
}
}