Bundle: redb-identity / src/redb.Identity.Grpc (src.redb.Identity.Grpc.txt), 13 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.Grpc/GrpcFacadeRouteBuilder.cs
Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity
Page: https://redbase.app/src/dev-2026-12-06/redb-identity/src/redb.Identity.Grpc/GrpcFacadeRouteBuilder.cs
----
using Google.Protobuf;
using Microsoft.Extensions.Options;
using redb.Identity.Contracts.Routes;
using redb.Identity.Grpc.Processors;
using redb.Identity.Grpc.V1;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Grpc;
namespace redb.Identity.Grpc;
///
/// gRPC facade for redb.Identity. Maps gRPC method addresses to direct-vm://identity-* routes.
///
/// One method address = one route. The address is the route key, so every operation gets its own
/// RouteId, policies, metrics and lifecycle, and they all share a single port.
///
///
/// Scope is the service-to-service subset of the protocol. Browser flows (authorize, login, consent, MFA
/// pages, device verification) stay on HTTP: they need a browser, redirects and a cookie session. DPoP
/// stays on HTTP too — RFC 9449 binds its proof to the HTTP method and URL.
///
///
public class GrpcFacadeRouteBuilder : RouteBuilder
{
private readonly IdentityGrpcTransportOptions _options;
public GrpcFacadeRouteBuilder(IOptions options)
{
ArgumentNullException.ThrowIfNull(options);
_options = options.Value;
}
/// Package-qualified service name of the published contract.
private const string Service = "/identity.v1.Identity";
protected override void Configure()
{
ConfigureProtocolOperations();
ConfigureGenericFallback();
}
///
/// The service-to-service protocol surface. One method address per operation, so each gets its own
/// route id, policies, metrics and lifecycle — visible individually in the dashboard and suspendable
/// individually through the control bus.
///
private void ConfigureProtocolOperations()
{
var port = _options.Grpc.PublicPort;
// RFC 6749 §3.2. Client authentication is whatever the caller used — fields in the message or
// `authorization: Basic` metadata; Core reads both, so the facade adds no step for it.
Operation(port, "Token", IdentityEndpoints.Token,
TokenRequest.Parser, overflow: "extra");
// RFC 7662.
Operation(port, "Introspect", IdentityEndpoints.Introspect,
IntrospectRequest.Parser, overflow: "extra");
// RFC 7009. A successful revocation carries no payload — the empty message is the answer.
Operation(port, "Revoke", IdentityEndpoints.Revoke,
RevokeRequest.Parser, overflow: "extra");
// OIDC Core §5.3. The Bearer token travels as metadata or as the message field; Core reads both.
Operation(port, "UserInfo", IdentityEndpoints.Userinfo,
UserInfoRequest.Parser, overflow: "claims");
// Discovery and JWKS are documents, passed through verbatim. The discovery document advertises
// the server's HTTP endpoints — those are the real ones, and rewriting them here would hand
// callers addresses that do not exist.
Document(port, "Discovery", IdentityEndpoints.Discovery,
DiscoveryRequest.Parser, field: "document");
Document(port, "Jwks", IdentityEndpoints.Jwks,
JwksRequest.Parser, field: "document");
}
/// Wires one operation: parse → boundary → status → encode.
private void Operation(
int port, string method, string endpoint, MessageParser parser, string overflow)
where TRequest : IMessage
where TResponse : IMessage, new()
{
From(BuildListener(port).Method($"{Service}/{method}"))
.RouteId($"grpc-identity-{method.ToLowerInvariant()}")
.Process(GrpcIdentityProcessors.PropagateCorrelationId)
.Process(GrpcIdentityProcessors.TagOperation(method.ToLowerInvariant()))
.Process(GrpcIdentityProcessors.MapRequest(parser))
.Enrich(endpoint, GrpcIdentityProcessors.AdoptCoreAnswer)
.Process(GrpcIdentityProcessors.MapErrorToGrpcStatus)
.Process(GrpcIdentityProcessors.MapResponse(overflow));
}
/// Wires an operation whose answer is a single pass-through document.
private void Document(
int port, string method, string endpoint, MessageParser parser, string field)
where TRequest : IMessage
where TResponse : IMessage, new()
{
From(BuildListener(port).Method($"{Service}/{method}"))
.RouteId($"grpc-identity-{method.ToLowerInvariant()}")
.Process(GrpcIdentityProcessors.PropagateCorrelationId)
.Process(GrpcIdentityProcessors.TagOperation(method.ToLowerInvariant()))
.Process(GrpcIdentityProcessors.MapRequest(parser))
.Enrich(endpoint, GrpcIdentityProcessors.AdoptCoreAnswer)
.Process(GrpcIdentityProcessors.MapErrorToGrpcStatus)
.Process(GrpcIdentityProcessors.MapDocumentResponse(field));
}
///
/// The generic RedbService address — the envelope fallback for callers that do not want to
/// carry identity.v1.proto. It also opens the port and, with .Health(), mounts
/// grpc.health.v1.Health/Check for Kubernetes / Consul / Envoy probes.
///
private void ConfigureGenericFallback()
{
From(BuildListener(_options.Grpc.PublicPort))
.RouteId("grpc-identity-envelope")
.Process(GrpcIdentityProcessors.PropagateCorrelationId)
// No TagOperation here: the envelope's own `operation` header already names the operation,
// and that is the header Core's idempotency cache reads.
.Process(GrpcIdentityProcessors.MapEnvelopeRequest)
// Enrich, not DynamicRouter: the address is already decided, and the hop has to be isolated
// for the same reason the typed routes isolate theirs - see AdoptCoreAnswer.
.Enrich(
e => e.Properties.Remove(GrpcIdentityProcessors.EndpointProperty, out var endpoint)
? endpoint as string ?? string.Empty
: string.Empty,
GrpcIdentityProcessors.AdoptCoreAnswer)
.Process(GrpcIdentityProcessors.MapErrorToGrpcStatus)
.Process(GrpcIdentityProcessors.MapEnvelopeResponse);
}
///
/// Builds a listener URI from the transport options. Health is mounted on every listening port: the
/// probe answers «is this listener serving», which a probe on another port cannot show.
///
/// Registry key for the TLS material, kept out of the endpoint URI on purpose.
private const string TlsFactoryName = "identity-grpc-tls";
private GrpcBuilder BuildListener(int port)
{
var grpc = _options.Grpc;
var builder = GrpcDsl.Listen($"{grpc.Host}:{port}")
.MaxMessageSize(grpc.MaxMessageSize)
.Health(grpc.Health)
// Core keys its per-IP throttle and brute-force lockout on redbHttp.RemoteAddress. Without
// this bridge those protections silently do nothing for gRPC callers — they no-op when the
// header is absent rather than failing loudly.
.EmitHttpCompatHeaders(grpc.EmitHttpCompatHeaders);
if (!string.IsNullOrWhiteSpace(grpc.Compression)
&& Enum.TryParse(grpc.Compression, ignoreCase: true, out var compression))
{
builder = builder.Compression(compression);
}
if (grpc.Ssl)
{
builder = builder.Ssl();
// TLS material travels through a named connection factory rather than in the endpoint URI.
// Not because the URI would disclose it — SslCertPassword is [Sensitive], so it is redacted
// wherever the URI is rendered — but because this keeps the secret out of the route key
// altogether. The key is handled as a plain string in plenty of places; a value that was
// never put in it cannot be disclosed by a path that forgets to render it through the
// redactor.
Context!.AddToRegistry(TlsFactoryName, new GrpcConnectionFactory
{
Ssl = true,
SslCertPath = grpc.SslCertPath,
SslCertPassword = grpc.SslCertPassword,
});
builder = builder.ConnectionFactory(TlsFactoryName);
// mTLS is opt-in: deployments without a client-certificate PKI must not be blocked. For the
// management port it is the recommended production setting.
if (Enum.TryParse(grpc.ClientCertificateMode, ignoreCase: true, out var mode)
&& mode != GrpcClientCertificateMode.NoCertificate)
{
var thumbprints = (grpc.AllowedClientThumbprints ?? string.Empty)
.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
builder = builder.ClientCertificates(mode, thumbprints);
}
}
else
{
builder = builder.Plaintext();
}
return builder;
}
}
Path: redb-identity/src/redb.Identity.Grpc/GrpcManagementRouteBuilder.cs
Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity
Page: https://redbase.app/src/dev-2026-12-06/redb-identity/src/redb.Identity.Grpc/GrpcManagementRouteBuilder.cs
----
using Microsoft.Extensions.Options;
using redb.Identity.Contracts.Routes;
using redb.Identity.Grpc.Processors;
using redb.Identity.Management.Controllers;
using redb.Route.Controllers;
using redb.Route.Controllers.Extensions;
using redb.Route.Core;
using redb.Route.Grpc;
namespace redb.Identity.Grpc;
///
/// F6 — the management surface over gRPC. One method address per controller action, on the management
/// port, behind bearer authentication and the granular scope table in Core.
///
/// Separate from because the two surfaces are separate in every way
/// that matters operationally: the protocol surface is called by every relying party, the management
/// surface only by admin tooling. Different consumers, different blast radius, and — when
/// ManagementPort is set — a different port to firewall.
///
///
/// The chain is the same for every operation, and its order is the security property: name the call,
/// decode it, authenticate, halt if refused, authorize, halt if refused, only then dispatch. Both gates
/// run on isolated exchanges, so the halt is explicit rather than inherited from Core's
/// exchange.Stop() — see .
///
///
public class GrpcManagementRouteBuilder : RouteBuilder
{
private readonly IdentityGrpcTransportOptions _options;
public GrpcManagementRouteBuilder(IOptions options)
{
ArgumentNullException.ThrowIfNull(options);
_options = options.Value;
}
private const string Package = "/identity.management.v1";
///
/// Canonical resource identifiers — the same strings the HTTP facade passes, because Core's scope
/// table is keyed on them. A wrong one here does not fail loudly: it checks another surface's scopes,
/// or falls through to default-deny. They are constants for that reason.
///
private const string UsersResource = "/api/v1/identity/users";
private const string ApplicationsResource = "/api/v1/identity/applications";
private const string GroupsResource = "/api/v1/identity/groups";
private const string ScopesResource = "/api/v1/identity/scopes";
private const string TokensResource = "/api/v1/identity/tokens";
///
/// The five groups the plan named: 40 operations. Read or write is taken from the controller's own
/// HTTP verb, so the two transports cannot disagree about what mutates; the resource is the surface,
/// so Core's scope table sees exactly what it sees for HTTP.
///
/// Dispatch names are qualified (Users.List) and must stay that way: five controllers now share
/// method names like List and Delete, and an unqualified name resolves to whichever
/// matched first.
///
///
/// Self-service (/me, account, password recovery, MFA enrolment) is deliberately absent. Those
/// are end-user flows reached from a browser or an app session, not admin tooling, and putting them on
/// an admin port would widen that port's blast radius for no caller that exists.
///
///
private static readonly ManagementOperation[] Operations =
[
new("Users", "List", "Users.List", UsersResource, Writes: false),
new("Users", "Search", "Users.Search", UsersResource, Writes: false),
new("Users", "Get", "Users.Get", UsersResource, Writes: false),
new("Users", "Create", "Users.Create", UsersResource, Writes: true),
new("Users", "Update", "Users.Update", UsersResource, Writes: true),
new("Users", "Delete", "Users.Delete", UsersResource, Writes: true),
new("Users", "ChangePassword", "Users.ChangePassword", UsersResource, Writes: true),
new("Users", "AdminResetPassword", "Users.AdminResetPassword", UsersResource, Writes: true),
new("Applications", "List", "Applications.List", ApplicationsResource, Writes: false),
new("Applications", "Get", "Applications.Get", ApplicationsResource, Writes: false),
new("Applications", "Create", "Applications.Create", ApplicationsResource, Writes: true),
new("Applications", "Update", "Applications.Update", ApplicationsResource, Writes: true),
new("Applications", "RotateSecret", "Applications.RotateSecret", ApplicationsResource, Writes: true),
new("Applications", "Delete", "Applications.Delete", ApplicationsResource, Writes: true),
new("Groups", "List", "Groups.List", GroupsResource, Writes: false),
new("Groups", "Search", "Groups.Search", GroupsResource, Writes: false),
new("Groups", "Get", "Groups.Get", GroupsResource, Writes: false),
new("Groups", "Create", "Groups.Create", GroupsResource, Writes: true),
new("Groups", "CreateChild", "Groups.CreateChild", GroupsResource, Writes: true),
new("Groups", "Update", "Groups.Update", GroupsResource, Writes: true),
new("Groups", "Delete", "Groups.Delete", GroupsResource, Writes: true),
new("Groups", "Move", "Groups.Move", GroupsResource, Writes: true),
new("Groups", "Tree", "Groups.Tree", GroupsResource, Writes: false),
new("Groups", "Path", "Groups.Path", GroupsResource, Writes: false),
new("Groups", "Children", "Groups.Children", GroupsResource, Writes: false),
new("Groups", "ListMembers", "Groups.ListMembers", GroupsResource, Writes: false),
new("Groups", "AddMember", "Groups.AddMember", GroupsResource, Writes: true),
new("Groups", "UpdateMember", "Groups.UpdateMember", GroupsResource, Writes: true),
new("Groups", "RemoveMember", "Groups.RemoveMember", GroupsResource, Writes: true),
new("Groups", "UserGroups", "Groups.UserGroups", GroupsResource, Writes: false),
new("Groups", "IsMember", "Groups.IsMember", GroupsResource, Writes: false),
new("Scopes", "List", "Scopes.List", ScopesResource, Writes: false),
new("Scopes", "Get", "Scopes.Get", ScopesResource, Writes: false),
new("Scopes", "Create", "Scopes.Create", ScopesResource, Writes: true),
new("Scopes", "Update", "Scopes.Update", ScopesResource, Writes: true),
new("Scopes", "Delete", "Scopes.Delete", ScopesResource, Writes: true),
new("Tokens", "List", "Tokens.List", TokensResource, Writes: false),
new("Tokens", "Revoke", "Tokens.Revoke", TokensResource, Writes: true),
new("Tokens", "RevokeBySubject", "Tokens.RevokeBySubject", TokensResource, Writes: true),
new("Tokens", "Prune", "Tokens.Prune", TokensResource, Writes: true),
];
protected override void Configure()
{
var registry = new ControllerRegistry();
registry.RegisterController(typeof(UsersController));
registry.RegisterController(typeof(ApplicationsController));
registry.RegisterController(typeof(GroupsController));
registry.RegisterController(typeof(ScopesController));
registry.RegisterController(typeof(TokensController));
var port = _options.Grpc.EffectiveManagementPort;
foreach (var operation in Operations)
{
From(BuildListener(port).Method($"{Package}.{operation.Service}/{operation.Method}"))
.RouteId($"grpc-identity-manage-{operation.DispatchMethod.Replace('.', '-').ToLowerInvariant()}")
.Process(GrpcIdentityProcessors.PropagateCorrelationId)
.Process(GrpcManagementProcessors.Describe(operation))
.Process(GrpcManagementProcessors.MapRequest)
// Authentication: validates the bearer token and leaves identity:management-* behind.
.Enrich(IdentityEndpoints.AuthManagement, GrpcManagementProcessors.AdoptGateDecision)
.Process(GrpcManagementProcessors.RequireAuthenticated)
// Authorization: the granular scope table, shared with the HTTP facade.
.Enrich(IdentityEndpoints.AuthzCheck, GrpcManagementProcessors.AdoptGateDecision)
.Process(GrpcManagementProcessors.RequireAuthorized)
.RedbGrpcController(registry)
.Process(GrpcManagementProcessors.MapControllerErrorToGrpcStatus)
.Process(GrpcManagementProcessors.MapResponse);
}
}
///
/// Builds the management listener. Health is mounted here too: the probe answers «is this
/// listener serving», and when the management port is split off, the protocol port's probe says
/// nothing about it.
///
/// Registry key for the TLS material, kept out of the endpoint URI on purpose.
private const string TlsFactoryName = "identity-grpc-management-tls";
private GrpcBuilder BuildListener(int port)
{
var grpc = _options.Grpc;
var builder = GrpcDsl.Listen($"{grpc.Host}:{port}")
.MaxMessageSize(grpc.MaxMessageSize)
.Health(grpc.Health)
// Core keys its per-IP throttle and brute-force lockout on redbHttp.RemoteAddress, and those
// checks no-op when the header is absent rather than failing loudly.
.EmitHttpCompatHeaders(grpc.EmitHttpCompatHeaders);
if (!string.IsNullOrWhiteSpace(grpc.Compression)
&& Enum.TryParse(grpc.Compression, ignoreCase: true, out var compression))
{
builder = builder.Compression(compression);
}
if (grpc.Ssl)
{
builder = builder.Ssl();
// Same as the protocol listener: TLS material through a named factory, so the secret is
// never part of the route key. See GrpcFacadeRouteBuilder for the reasoning.
Context!.AddToRegistry(TlsFactoryName, new GrpcConnectionFactory
{
Ssl = true,
SslCertPath = grpc.SslCertPath,
SslCertPassword = grpc.SslCertPassword,
});
builder = builder.ConnectionFactory(TlsFactoryName);
// mTLS is opt-in everywhere, and recommended here: this is the admin surface.
if (Enum.TryParse(grpc.ClientCertificateMode, ignoreCase: true, out var mode)
&& mode != GrpcClientCertificateMode.NoCertificate)
{
var thumbprints = (grpc.AllowedClientThumbprints ?? string.Empty)
.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
builder = builder.ClientCertificates(mode, thumbprints);
}
}
else
{
builder = builder.Plaintext();
}
return builder;
}
}
Path: redb-identity/src/redb.Identity.Grpc/IdentityGrpcCodec.cs
Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity
Page: https://redbase.app/src/dev-2026-12-06/redb-identity/src/redb.Identity.Grpc/IdentityGrpcCodec.cs
----
using System.Globalization;
using Google.Protobuf;
using Google.Protobuf.Reflection;
using Google.Protobuf.WellKnownTypes;
namespace redb.Identity.Grpc;
///
/// Translates between the published identity.v1 protobuf contract and the shape the
/// direct-vm://identity-* boundary speaks.
///
/// The boundary takes a Dictionary<string, string> of request parameters and answers with a
/// Dictionary<string, object?> — a typed object, never encoded bytes, which is what lets a
/// facade choose its own wire format (guarded by TransportBoundaryTests in Core).
///
///
/// Mapping is driven by protobuf reflection rather than a hand-written table per message: proto field
/// names are snake_case and already equal the OAuth parameter names (grant_type,
/// client_id, …), so the descriptor is the mapping. Add a field to the contract and it
/// starts flowing without touching this file.
///
///
internal static class IdentityGrpcCodec
{
// ── request: proto → parameters ──────────────────────────
///
/// Flattens a request message into the parameter dictionary the boundary expects. Empty fields are
/// omitted: OAuth distinguishes «absent» from «present and empty», and sending the latter would make
/// the server reject requests it should accept.
///
public static Dictionary ToParameters(IMessage request)
{
ArgumentNullException.ThrowIfNull(request);
var parameters = new Dictionary(StringComparer.Ordinal);
foreach (var field in request.Descriptor.Fields.InFieldNumberOrder())
{
var value = field.Accessor.GetValue(request);
if (field.IsMap)
{
// The extension bag is merged flat — an extension parameter is a parameter.
if (value is System.Collections.IDictionary map)
{
foreach (System.Collections.DictionaryEntry entry in map)
{
var key = entry.Key?.ToString();
if (!string.IsNullOrEmpty(key) && entry.Value is not null)
parameters[key!] = entry.Value.ToString() ?? string.Empty;
}
}
continue;
}
var text = Stringify(value);
if (!string.IsNullOrEmpty(text))
parameters[field.Name] = text!;
}
return parameters;
}
private static string? Stringify(object? value) => value switch
{
null => null,
string s => s,
bool b => b ? "true" : "false",
IFormattable f => f.ToString(null, CultureInfo.InvariantCulture),
_ => value.ToString(),
};
// ── response: parameters → proto ─────────────────────────
///
/// Populates a response message from the boundary's answer. Named fields are filled by proto field
/// name; everything left over goes into (a
/// google.protobuf.Struct), because userinfo claims and introspection extensions are open sets
/// and dropping them silently would lose data the caller asked for.
///
public static void Populate(IMessage response, IDictionary source, string overflowField)
{
ArgumentNullException.ThrowIfNull(response);
ArgumentNullException.ThrowIfNull(source);
var consumed = new HashSet(StringComparer.Ordinal);
foreach (var field in response.Descriptor.Fields.InFieldNumberOrder())
{
if (field.Name == overflowField) continue;
if (!TryGet(source, field.Name, out var raw) || raw is null) continue;
if (TrySet(response, field, raw))
consumed.Add(field.Name);
}
var overflow = response.Descriptor.FindFieldByName(overflowField);
if (overflow is null) return;
var rest = new Dictionary(StringComparer.Ordinal);
foreach (var (key, value) in source)
{
if (consumed.Contains(key)) continue;
rest[key] = value;
}
if (rest.Count > 0)
overflow.Accessor.SetValue(response, ToStruct(rest));
}
///
/// Fills a message whose whole payload is one Struct — discovery and JWKS, where the document
/// is passed through verbatim because its contents are the server's business, not ours.
///
public static void PopulateDocument(IMessage response, IDictionary source, string field)
{
ArgumentNullException.ThrowIfNull(response);
ArgumentNullException.ThrowIfNull(source);
var descriptor = response.Descriptor.FindFieldByName(field)
?? throw new InvalidOperationException(
$"{response.Descriptor.Name} has no field '{field}'.");
descriptor.Accessor.SetValue(response, ToStruct(source));
}
private static bool TryGet(IDictionary source, string key, out object? value)
{
if (source.TryGetValue(key, out value)) return true;
// Tolerate a case difference from a hand-written processor without matching loosely enough to
// pick up an unrelated key.
foreach (var (candidate, candidateValue) in source)
{
if (string.Equals(candidate, key, StringComparison.OrdinalIgnoreCase))
{
value = candidateValue;
return true;
}
}
value = null;
return false;
}
private static bool TrySet(IMessage message, FieldDescriptor field, object raw)
{
try
{
if (field.IsRepeated)
{
if (field.Accessor.GetValue(message) is not System.Collections.IList list) return false;
foreach (var item in Enumerate(raw))
{
var converted = Convert(field, item);
if (converted is not null) list.Add(converted);
}
return true;
}
var value = Convert(field, raw);
if (value is null) return false;
field.Accessor.SetValue(message, value);
return true;
}
catch (Exception ex) when (ex is InvalidCastException or FormatException or OverflowException)
{
// A value the contract cannot hold is not a reason to fail the call — it falls through to the
// overflow Struct, where the caller can still see it.
return false;
}
}
private static IEnumerable