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 Enumerate(object raw) { if (raw is string s) { yield return s; yield break; } if (raw is System.Collections.IEnumerable list) { foreach (var item in list) yield return item; yield break; } yield return raw; } private static object? Convert(FieldDescriptor field, object? raw) { if (raw is null) return null; return field.FieldType switch { FieldType.String => raw as string ?? Stringify(raw), FieldType.Bool => raw switch { bool b => b, string s => bool.Parse(s), _ => System.Convert.ToBoolean(raw, CultureInfo.InvariantCulture), }, FieldType.Int64 or FieldType.SInt64 or FieldType.SFixed64 => raw is long l ? l : System.Convert.ToInt64(raw, CultureInfo.InvariantCulture), FieldType.Int32 or FieldType.SInt32 or FieldType.SFixed32 => raw is int i ? i : System.Convert.ToInt32(raw, CultureInfo.InvariantCulture), FieldType.Double => raw is double d ? d : System.Convert.ToDouble(raw, CultureInfo.InvariantCulture), FieldType.Float => raw is float f ? f : System.Convert.ToSingle(raw, CultureInfo.InvariantCulture), _ => null, }; } // ── Struct conversion ──────────────────────────────────── /// Converts the boundary's loosely typed answer into a google.protobuf.Struct. public static Struct ToStruct(IDictionary source) { var result = new Struct(); foreach (var (key, value) in source) result.Fields[key] = ToValue(value); return result; } private static Value ToValue(object? value) => value switch { null => Value.ForNull(), string s => Value.ForString(s), bool b => Value.ForBool(b), long l => Value.ForNumber(l), int i => Value.ForNumber(i), double d => Value.ForNumber(d), float f => Value.ForNumber(f), decimal m => Value.ForNumber((double)m), IDictionary nested => Value.ForStruct(ToStruct(nested)), System.Collections.IEnumerable list => Value.ForList( list.Cast().Select(ToValue).ToArray()), _ => Value.ForString(value.ToString() ?? string.Empty), }; } Path: redb-identity/src/redb.Identity.Grpc/IdentityGrpcTransportOptions.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/IdentityGrpcTransportOptions.cs ---- using redb.Identity.Contracts.Configuration; namespace redb.Identity.Grpc; /// /// Configuration for the Identity gRPC transport facade. Mirrors /// redb.Identity.Http.IdentityTransportOptions in shape so operators configure both facades the /// same way: transport-local settings here, cross-module state through direct-vm:// into Core. /// public class IdentityGrpcTransportOptions { /// gRPC-specific transport settings (ports, TLS, codec). public GrpcTransportOptions Grpc { get; set; } = new(); /// /// Cross-module shared options (Issuer + Features). Same instance type as /// RedbIdentityOptions.Shared and IdentityTransportOptions.Shared, so a value declared /// once in Identity:* is observed identically by Core and by every facade. /// public IdentitySharedOptions Shared { get; set; } = new(); /// /// Issuer URI of the identity server. Proxy onto . The gRPC facade does not /// rewrite the discovery document, so this is used only where a route needs to know its own identity. /// public Uri Issuer { get => Shared.Issuer; set => Shared.Issuer = value; } /// Cross-module feature toggles. Proxy onto . public IdentityFeatureFlags Features { get => Shared.Features; set => Shared.Features = value; } } /// gRPC listener settings. public class GrpcTransportOptions { /// Bind address. Default 0.0.0.0. public string Host { get; set; } = "0.0.0.0"; /// /// Port for the protocol surface (token, introspect, revoke, userinfo, discovery, jwks). /// Default 5001. /// /// This port is never shared with the HTTP facade: gRPC needs HTTP/2 while the HTTP facade serves /// HTTP/1.1 + HTTP/2, and one Kestrel listener has a single protocol set. The shared host enforces /// this — registering both on one port throws rather than failing later with a framing error. /// /// public int PublicPort { get; set; } = 5001; /// /// Port for the management surface. null means «same as », which is /// the single-node default and needs no extra configuration. /// /// Splitting it matters in production: the protocol surface is called by every relying party, the /// management surface only by admin tooling. Different consumers, different blast radius — so the /// admin port gets firewalled separately. Same semantics as the HTTP facade's /// ManagementPort ?? PublicPort, so both facades are configured alike. /// /// public int? ManagementPort { get; set; } /// Enable TLS. Requires . public bool Ssl { get; set; } /// Path to the PFX certificate used when is true. public string? SslCertPath { get; set; } /// Password for . public string? SslCertPassword { get; set; } /// /// Client-certificate policy (mTLS): NoCertificate (default), AllowCertificate or /// RequireCertificate. Off by default so deployments without a client-certificate PKI are not /// blocked; recommended for the management port in production. /// public string ClientCertificateMode { get; set; } = "NoCertificate"; /// /// Comma-separated SHA-1 thumbprints of accepted client certificates. When set, a certificate whose /// thumbprint is not listed is rejected even if its chain validates. /// public string? AllowedClientThumbprints { get; set; } /// Reply compression: None (default) or Gzip. Requests are always inflated. public string Compression { get; set; } = "None"; /// Max message size in bytes for both directions. Default 4 MB. public int MaxMessageSize { get; set; } = 4 * 1024 * 1024; /// /// Serve grpc.health.v1.Health/Check on every listening port. Standard probe for Kubernetes, /// Consul and Envoy. Default true — the check is unauthenticated and costs two bytes. /// public bool Health { get; set; } = true; /// /// Mirror the resolved client address into redbHttp.RemoteAddress so the IP-keyed processors in /// Core (per-IP throttle, brute-force lockout, device metadata) work behind this facade unchanged. /// Default true: without it those protections silently do nothing for gRPC callers. /// public bool EmitHttpCompatHeaders { get; set; } = true; /// Effective management port — or . public int EffectiveManagementPort => ManagementPort ?? PublicPort; } Path: redb-identity/src/redb.Identity.Grpc/Module/IdentityGrpcConfigBinder.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/Module/IdentityGrpcConfigBinder.cs ---- using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration.Memory; using redb.Route.Abstractions; namespace redb.Identity.Grpc.Module; /// /// Binds the Tsak-merged context configuration into a strongly typed /// for the gRPC facade. /// /// /// Mirrors redb.Identity.Http.Module.IdentityHttpConfigBinder: Tsak hands the merged 5-layer /// config to the module as a nested IDictionary<string, object?> on /// ; we flatten it into entries and /// let IConfiguration.Bind hydrate the POCO, which gives free / nested-object /// handling. /// /// Section name is "IdentityTransport" — the same root the HTTP facade reads, so one section in /// context.json carries both facades: IdentityTransport:Http:* and /// IdentityTransport:Grpc:*. /// /// internal static class IdentityGrpcConfigBinder { /// Top-level config section consumed by the transport facades. public const string SectionName = "IdentityTransport"; /// /// Builds from the context's /// "IdentityTransport" property. Returns defaults when the property is missing, so the module /// runs in development without explicit configuration. /// public static IdentityGrpcTransportOptions Bind(IRouteContext context) { ArgumentNullException.ThrowIfNull(context); var options = new IdentityGrpcTransportOptions(); var raw = context.GetProperty>(SectionName); if (raw is not null && raw.Count > 0) { var flat = new Dictionary(StringComparer.OrdinalIgnoreCase); Flatten(raw, prefix: string.Empty, sink: flat); new ConfigurationBuilder() .Add(new MemoryConfigurationSource { InitialData = flat }) .Build() .Bind(options, opt => opt.BindNonPublicProperties = false); } BindSharedSection(context, options); return options; } /// /// Binds the shared Identity:* section (issuer + feature flags) on top of the module-local /// values. Same source Core and the HTTP facade read, so a toggle declared once is observed /// identically everywhere; a value set explicitly on IdentityTransport:* is overwritten when /// the shared section provides it, matching the HTTP binder's precedence. /// private static void BindSharedSection(IRouteContext context, IdentityGrpcTransportOptions options) { var identitySection = context.GetProperty>("Identity"); if (identitySection is null || identitySection.Count == 0) return; var flat = new Dictionary(StringComparer.OrdinalIgnoreCase); Flatten(identitySection, prefix: string.Empty, sink: flat); var cfg = new ConfigurationBuilder() .Add(new MemoryConfigurationSource { InitialData = flat }) .Build(); // Bind onto the existing instances so keys the shared section omits keep the module-local value. var features = cfg.GetSection("Features"); if (features.Exists()) features.Bind(options.Features); var issuer = cfg["Issuer"]; if (!string.IsNullOrWhiteSpace(issuer) && Uri.TryCreate(issuer, UriKind.Absolute, out var parsed)) options.Issuer = parsed; } private static void Flatten(IDictionary source, string prefix, IDictionary sink) { foreach (var kvp in source) { // Metadata keys ("//" comment blocks) belong to Tsak, not to the options POCO. 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.Grpc/Module/IdentityGrpcModuleHost.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/Module/IdentityGrpcModuleHost.cs ---- using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using redb.Route.Abstractions; namespace redb.Identity.Grpc.Module; /// /// Builds a self-contained child for the identity.grpc Tsak /// context. Mirrors redb.Identity.Http.Module.IdentityHttpModuleHost: the worker's root container /// is built before modules load, so facade-owned services are constructed lazily here from the /// Tsak-merged config. /// /// /// /// Deliberately much smaller than the HTTP host. The gRPC facade serves no browser flows, so it owns no /// cookies, no DataProtection key-ring and no page state — and therefore needs no bridged /// IRedbService. Everything stateful stays in Core and is reached over direct-vm://. /// /// /// Registered here: the host logger factory and clock, the host configuration root (when present), the /// bound , and the itself — the /// latter is the only object able to resolve direct-vm endpoints through the shared registry, so /// brokered calls into Core take it rather than an . /// /// internal static class IdentityGrpcModuleHost { public static ServiceProvider Build(IRouteContext routeContext, IdentityGrpcTransportOptions 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(); services.AddSingleton(rootSp.GetRequiredService()); services.AddLogging(); services.AddSingleton(rootSp.GetService() ?? TimeProvider.System); var hostConfiguration = rootSp.GetService(); if (hostConfiguration is not null) services.AddSingleton(hostConfiguration); services.AddSingleton(Options.Create(options)); services.AddOptions(); // Brokered calls into Core go through the route context, not through DI. services.AddSingleton(routeContext); // Captive-dependency detection at build time, same as the HTTP facade. return services.BuildServiceProvider(new ServiceProviderOptions { ValidateScopes = true, ValidateOnBuild = true, }); } } /// /// Disposes the gRPC-facade child container when the surrounding route context stops. Without it the /// container would leak across Tsak hot-reloads. /// internal sealed class GrpcChildHostDisposeListener : IRouteLifecycleListener { private readonly ServiceProvider _childSp; public GrpcChildHostDisposeListener(ServiceProvider childSp) => _childSp = childSp; public Task OnContextStopped(IRouteContext context, CancellationToken ct) { _childSp.Dispose(); return Task.CompletedTask; } } Path: redb-identity/src/redb.Identity.Grpc/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.Grpc/Module/InitRoute.cs ---- using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using redb.Identity.Grpc.Module; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Grpc; // Tsak resolves the {Module}.config.json file by InitRoute's namespace // (TsakModuleRegistry.DiscoverModulesInAssembly). Keep this namespace aligned with the shipped config // filename `redb.Identity.Grpc.config.json`. // // This module owns ContextName "identity.grpc" — its own RouteContext, separate from Core ("identity") // and from the HTTP facade ("identity.http"). The three communicate exclusively through // `direct-vm://identity-*` brokered messages whose DTOs live in redb.Identity.Contracts; this facade has // zero project-reference on Core (Phase 8 invariant). namespace redb.Identity.Grpc; /// /// Tsak module entry point for the gRPC facade. Discovered by convention: public class InitRoute with a /// static main(IRouteContext). /// public static class InitRoute { public static IRouteContext main(IRouteContext context) { // The gRPC component serves on the shared Kestrel host, the same one Http, As2 and Soap use, so a // gRPC route and an HTTP route in one worker never fight over a port. AddRedbRouteGrpc() would do // this via DI, but a Tsak module gets a context, not a service collection — so wire it by hand and // let the component fall back to the host's shared manager when one is registered. if (!context.HasComponent("grpc")) context.AddComponent(new GrpcComponent()); // One boot path, in a Tsak worker and in a host of its own alike: the binder reads // "IdentityTransport" from the context's configuration and the module host builds a child // ServiceProvider for this facade. var hostSp = context.GetServiceProvider() ?? throw new InvalidOperationException( "IServiceProvider not available on IRouteContext. " + "Ensure the Identity gRPC module is loaded after DI is configured."); var bound = IdentityGrpcConfigBinder.Bind(context); var childSp = IdentityGrpcModuleHost.Build(context, bound); // Ensure the child container outlives the routes but dies with the context. context.AddLifecycleListener(new GrpcChildHostDisposeListener(childSp)); IServiceProvider grpcSp = childSp; var options = grpcSp.GetRequiredService>(); var logger = (grpcSp.GetService() ?? hostSp.GetService()) ?.CreateLogger("redb.Identity.Grpc.InitRoute"); var grpc = options.Value.Grpc; logger?.LogInformation( "[Identity.Grpc.InitRoute] Building gRPC facade routes on {Host}:{Public} (management: {Management})", grpc.Host, grpc.PublicPort, grpc.EffectiveManagementPort); var routeContext = (RouteContext)context; // The protocol surface: token, introspect, revoke, userinfo, discovery, jwks, plus the envelope. routeContext.AddRoutes(new GrpcFacadeRouteBuilder(options)); // The management surface. Registered here and not only in tests: without this line the forty admin // operations exist, are covered, and are unreachable in every real deployment — while the log line // above still announces a management port, so it reads as configured. A live worker showed // `identity.grpc` starting with 7 endpoints instead of 47, which is how this was found. routeContext.AddRoutes(new GrpcManagementRouteBuilder(options)); return context; } } Path: redb-identity/src/redb.Identity.Grpc/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.Grpc/Module/manifest.json ---- { "Name": "redb.Identity.Grpc", "Version": "1.0.0", "EntryPoints": ["redb.Identity.Grpc.dll"], "Dependencies": ["redb.Identity.Core.Module"] } Path: redb-identity/src/redb.Identity.Grpc/Processors/GrpcIdentityProcessors.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/Processors/GrpcIdentityProcessors.cs ---- using System.Diagnostics; using System.Globalization; using System.Runtime.ExceptionServices; using System.Text; using System.Text.Json; using Google.Protobuf; using IMessage = Google.Protobuf.IMessage; using RouteMessage = redb.Route.Abstractions.IMessage; using Grpc.Core; using redb.Identity.Contracts; using redb.Identity.Contracts.Routes; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Grpc; namespace redb.Identity.Grpc.Processors; /// /// Translation steps between the gRPC wire and the direct-vm://identity-* boundary. The /// counterpart of HttpIdentityProcessors in the HTTP facade, and deliberately the same shape: one /// small step per concern, wired in order on the route. /// internal static class GrpcIdentityProcessors { /// /// Parses the protobuf request and hands the boundary the parameter dictionary it expects. /// /// Client credentials need no special step here: when the caller puts client_id / /// client_secret in the message they arrive as parameters, and when it sends /// authorization: Basic metadata instead, the connector copies that header onto the exchange /// and Core's own BasicAuthHelper reads it. Same for a Bearer token on userinfo. Duplicating /// that extraction in the facade would create a second, divergent source of truth. /// /// public static Func MapRequest(MessageParser parser) where TRequest : IMessage { ArgumentNullException.ThrowIfNull(parser); return (exchange, _) => { var payload = exchange.In.Body as byte[] ?? []; TRequest request; try { request = parser.ParseFrom(payload); } catch (InvalidProtocolBufferException ex) { // A malformed message is the caller's error, not ours. Answered by status rather than by // throwing — see Reject for why a throw would not survive. return Reject(exchange, StatusCode.InvalidArgument, $"Malformed {typeof(TRequest).Name}: {ex.Message}"); } exchange.In.Body = IdentityGrpcCodec.ToParameters(request); return Task.CompletedTask; }; } /// /// Encodes the boundary's answer into the response message. Fields the contract names are filled by /// name; everything else lands in rather than being dropped. /// public static Func MapResponse(string overflowField) where TResponse : IMessage, new() { return (exchange, _) => { var response = new TResponse(); if (ReadAnswer(exchange) is { } answer) IdentityGrpcCodec.Populate(response, answer, overflowField); Emit(exchange, response); return Task.CompletedTask; }; } /// /// Encodes an answer that is one document — discovery and JWKS. The document is passed through /// verbatim: it advertises the server's HTTP addresses, and those are the real ones. /// public static Func MapDocumentResponse(string field) where TResponse : IMessage, new() { return (exchange, _) => { var response = new TResponse(); if (ReadAnswer(exchange) is { } answer) IdentityGrpcCodec.PopulateDocument(response, answer, field); Emit(exchange, response); return Task.CompletedTask; }; } /// Exchange property Core and the HTTP facade both use for the correlation id. private const string CorrelationProperty = "identity:correlation-id"; /// Metadata / header key carrying the correlation id, same spelling as the HTTP facade. private const string CorrelationHeader = "X-Correlation-Id"; /// /// Propagates a correlation id across the gRPC ↔ direct-vm boundary: takes the caller's when it sent /// one, otherwise derives it from the ambient W3C trace id, and echoes it back in a trailer so the /// caller can stitch its logs to ours. Mirrors HttpIdentityProcessors.PropagateCorrelationId. /// public static Task PropagateCorrelationId(IExchange exchange, CancellationToken ct) { // First step on every gRPC route: caller metadata and envelope headers land in In.Headers // verbatim, and Core trusts the reserved names (audit attribution, credentials, idempotency // operation). Same list as the HTTP and SOAP facades. redb.Identity.Contracts.Routes.IdentityReservedInboundHeaders.Strip(exchange.In.Headers); var correlationId = exchange.In.GetHeader(CorrelationHeader); if (string.IsNullOrWhiteSpace(correlationId)) correlationId = Activity.Current?.TraceId.ToString() ?? Guid.NewGuid().ToString("N"); exchange.Properties[CorrelationProperty] = correlationId!; // Set on In: the pipeline merges Out into In between steps, and the response mapper carries // trailer headers across when it builds Out. exchange.In.Headers[GrpcHeaders.TrailerPrefix + "x-correlation-id"] = correlationId!; return Task.CompletedTask; } /// /// Names the operation for the steps in Core that key on it — the idempotency cache composes its /// record name from scope, operation, caller and the caller's Idempotency-Key. Over HTTP the /// name comes from the request path; here it is the method address, which is the same thing one /// transport over. Without it every gRPC operation would share the bucket default and two /// different calls carrying one key would collide. /// /// The Idempotency-Key itself needs no step: the caller sends it as metadata and the connector /// puts it on the exchange verbatim. /// /// public static Func TagOperation(string operation) { return (exchange, _) => { exchange.In.Headers["operation"] = operation; return Task.CompletedTask; }; } /// /// Turns an OAuth error into a gRPC status. Without this an invalid_client would reach the /// caller as a successful call carrying an error document — which no generated client inspects. /// /// The machine-readable code and description also go into trailers: a non-OK gRPC response has its /// payload discarded by clients, so the body is not a place to put them. /// /// Wire this BEFORE the response mapper, while the answer is still a dictionary. /// /// /// Merge strategy for the hop into Core, used with Enrich rather than To. /// /// To hands Core the facade's own exchange, and several Core processors end their work with /// exchange.Stop() - the per-IP limiter and the granular guard among them. That flag lives on the /// exchange, so the facade's own pipeline stopped too, and the reply left as a raw dictionary that never /// went through status mapping or protobuf encoding. Precisely the security-relevant answers were the /// ones that lost their status. /// /// /// Enrich sends a CloneLinked copy instead: same exchange id, same DI scope, same /// properties, its own stop flag. Core decides freely and we still get to answer. /// /// public static IExchange AdoptCoreAnswer(IExchange facade, IExchange core) { // A genuine fault Core did not handle stays a fault: rethrown here it reaches the consumer exactly // as it did through To, and becomes a gRPC status there. Swallowing it would answer OK with the // request body still in place. if (core.Exception is not null && !core.ExceptionHandled) ExceptionDispatchInfo.Capture(core.Exception).Throw(); var answer = core.HasOut ? core.Out! : core.In; facade.In.Body = answer.Body; foreach (var header in answer.Headers) facade.In.Headers[header.Key] = header.Value; // Returning the facade exchange, not the clone: the enricher copies `merged.Exception` onward, and // a handled exception - the limiter's marker, for one - is not something to re-raise here. return facade; } public static Task MapErrorToGrpcStatus(IExchange exchange, CancellationToken ct) { var target = exchange.HasOut ? exchange.Out! : exchange.In; var answer = ReadAnswer(exchange); // A status Core decided itself comes first. Rate limiting answers 429, the granular guard 403, a // database outage 503 - all of them through redbHttp.ResponseCode, because that is the vocabulary // every processor in Core speaks. It also carries Retry-After into a trailer, and a non-OK gRPC // reply discards its payload, so a trailer is the only place that advice survives. MapResponseCode(exchange); if (answer is null || !answer.TryGetValue("error", out var errorValue) || errorValue is not string error) { return Task.CompletedTask; } var description = answer.TryGetValue("error_description", out var d) ? d as string : null; // The machine-readable code always travels, whoever decided the status. target.Headers[GrpcHeaders.TrailerPrefix + "error"] = error; if (!string.IsNullOrEmpty(description)) target.Headers[GrpcHeaders.TrailerPrefix + "error-description"] = description!; // Core's own verdict wins. Deriving the status from the error string instead would demote a // rate-limited answer, whose error is `rate_limited` and appears in no RFC 6749 table, to // InvalidArgument, and hide the one signal that tells the caller to back off. if (!target.Headers.ContainsKey(GrpcHeaders.StatusCode)) { // The reading of the error lives in IdentityVerdict, shared with the HTTP and SOAP facades; // only the rendering into the gRPC status space belongs here. Three transports had to answer // the same question, and the copy that drifts is the one that accepts what the others refuse. target.Headers[GrpcHeaders.StatusCode] = (int)ToGrpcStatus(IdentityVerdict.FromOAuthError(error)); } // The error document says more than "upstream answered 429" ever could. target.Headers[GrpcHeaders.StatusDetail] = description ?? error; return Task.CompletedTask; } /// /// Renders the core's verdict in the gRPC status space. This switch is the whole of what is specific /// to this transport; deciding what the verdict is happens once, in /// , and every facade reads it from there. /// private static StatusCode ToGrpcStatus(IdentityVerdictKind kind) => kind switch { IdentityVerdictKind.Ok => StatusCode.OK, IdentityVerdictKind.Unauthenticated => StatusCode.Unauthenticated, IdentityVerdictKind.Forbidden => StatusCode.PermissionDenied, IdentityVerdictKind.NotFound => StatusCode.NotFound, IdentityVerdictKind.Unsupported => StatusCode.Unimplemented, IdentityVerdictKind.Conflict => StatusCode.AlreadyExists, IdentityVerdictKind.PreconditionFailed => StatusCode.FailedPrecondition, IdentityVerdictKind.RateLimited => StatusCode.ResourceExhausted, IdentityVerdictKind.Unavailable => StatusCode.Unavailable, IdentityVerdictKind.Timeout => StatusCode.DeadlineExceeded, IdentityVerdictKind.ServerError => StatusCode.Internal, // gRPC has no status for «the scope is wrong», so it lands where every other malformed request // lands — which is exactly what this facade did before the verdict was named. IdentityVerdictKind.InvalidScope or IdentityVerdictKind.BadRequest => StatusCode.InvalidArgument, // A refusal we cannot read stays unreadable rather than being dressed up as our own failure. IdentityVerdictKind.Unknown => StatusCode.Unknown, _ => StatusCode.InvalidArgument, }; /// /// Translates a redbHttp.ResponseCode set by Core into a gRPC status. The mapping is the one /// the connector applies to the transport-neutral status.code, so both vocabularies land on the /// same answer. /// private static Task MapResponseCode(IExchange exchange) { var source = exchange.HasOut ? exchange.Out! : exchange.In; if (!source.Headers.TryGetValue("redbHttp.ResponseCode", out var raw) || raw is null) return Task.CompletedTask; if (IdentityVerdict.ParseResponseCode(raw) is not { } code) return Task.CompletedTask; var status = ToGrpcStatus(IdentityVerdict.FromStatusCode(code)); if (status == StatusCode.OK) return Task.CompletedTask; source.Headers[GrpcHeaders.StatusCode] = (int)status; // Not `??=`: the header dictionary's indexer throws on a missing key, so a compound assignment // would fail exactly in the common case where no detail has been set yet. if (!source.Headers.ContainsKey(GrpcHeaders.StatusDetail)) source.Headers[GrpcHeaders.StatusDetail] = $"Upstream answered {code}."; // Rate limiting says when to come back; that is actionable and must not be lost with the payload. if (source.Headers.TryGetValue("Retry-After", out var retryAfter) && retryAfter is not null) source.Headers[GrpcHeaders.TrailerPrefix + "retry-after"] = retryAfter; return Task.CompletedTask; } // ── envelope fallback ──────────────────────────────────── /// Exchange property carrying the resolved endpoint for the envelope route. public const string EndpointProperty = "identity:grpc-endpoint"; /// /// Operations reachable through the generic envelope. Deliberately the same six the typed contract /// publishes — the envelope is a second spelling of one surface, not a second surface. /// private static readonly Dictionary EnvelopeOperations = new(StringComparer.OrdinalIgnoreCase) { ["token"] = IdentityEndpoints.Token, ["introspect"] = IdentityEndpoints.Introspect, ["revoke"] = IdentityEndpoints.Revoke, ["userinfo"] = IdentityEndpoints.Userinfo, ["discovery"] = IdentityEndpoints.Discovery, ["jwks"] = IdentityEndpoints.Jwks, }; /// /// Prepares an envelope call: the operation comes from the operation header the caller sets, /// the body is JSON. This is the path for callers that do not want to carry /// identity.v1.proto — scripts, ad-hoc tooling, languages without protobuf tooling at hand. /// public static Task MapEnvelopeRequest(IExchange exchange, CancellationToken ct) { var operation = exchange.In.GetHeader("operation"); if (string.IsNullOrWhiteSpace(operation)) return Reject(exchange, StatusCode.InvalidArgument, $"Envelope calls need an 'operation' header. Known: {string.Join(", ", EnvelopeOperations.Keys)}."); if (!EnvelopeOperations.TryGetValue(operation!, out var endpoint)) return Reject(exchange, StatusCode.Unimplemented, $"Unknown operation '{operation}'. Known: {string.Join(", ", EnvelopeOperations.Keys)}."); exchange.Properties[EndpointProperty] = endpoint; try { exchange.In.Body = ParseJsonParameters(exchange.In.Body); } catch (JsonException ex) { return Reject(exchange, StatusCode.InvalidArgument, $"Envelope body must be a JSON object of request parameters: {ex.Message}"); } return Task.CompletedTask; } /// /// Answers a caller error by setting the status and stopping the route, rather than by throwing. /// /// This is not a style preference. RouteContext collects builder-level exception handlers from /// every builder in the context and wraps each route with them, so Core's catch-all /// (OnException<Exception>().Handled()) would swallow a thrown RpcException and /// replace the answer with its generic server_error document — the caller would see a stringified /// dictionary instead of the status we chose. Setting the status keeps the answer ours. /// /// private static Task Reject(IExchange exchange, StatusCode status, string detail) { exchange.Out = new Message(Array.Empty()); exchange.Out.Headers[GrpcHeaders.StatusCode] = (int)status; exchange.Out.Headers[GrpcHeaders.StatusDetail] = detail; exchange.Stop(); return Task.CompletedTask; } /// Encodes the boundary's answer back as JSON — the envelope's wire format. public static Task MapEnvelopeResponse(IExchange exchange, CancellationToken ct) { var answer = ReadAnswer(exchange) ?? new Dictionary(); exchange.Out ??= new Message(); CarryStatusHeaders(exchange.In, exchange.Out!); exchange.Out!.Body = JsonSerializer.SerializeToUtf8Bytes(answer, EnvelopeJson); return Task.CompletedTask; } private static readonly JsonSerializerOptions EnvelopeJson = new() { DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull, }; /// /// Reads the envelope payload as a flat parameter map. The boundary takes string parameters, so a /// nested JSON object would be meaningless here — numbers and booleans are stringified, which is /// exactly what the form-encoded wire has always done. /// internal static Dictionary ParseJsonParameters(object? body) { var parameters = new Dictionary(StringComparer.Ordinal); var bytes = body as byte[]; if (bytes is null || bytes.Length == 0) return parameters; JsonElement root; // Both failures below surface as JsonException so the caller of this method can turn them into a // status; see MapEnvelopeRequest. root = JsonSerializer.Deserialize(bytes); if (root.ValueKind != JsonValueKind.Object) throw new JsonException("expected an object of request parameters"); foreach (var property in root.EnumerateObject()) { var value = property.Value.ValueKind switch { JsonValueKind.String => property.Value.GetString(), JsonValueKind.Null or JsonValueKind.Undefined => null, _ => property.Value.GetRawText(), }; if (!string.IsNullOrEmpty(value)) parameters[property.Name] = value!; } return parameters; } /// /// Reads the boundary's answer. Identity's convention is that a processor may write into /// Out or back into In, so both are checked — the same fallback the SOAP consumer uses. /// /// /// The answer as a dictionary, whatever shape it arrived in. Core's own processors hand back a /// dictionary; the controller dispatcher and the auth gates hand back serialized JSON. Reading only /// the first shape meant a refusal that came as bytes carried no status at all — the caller saw OK. /// private static IDictionary? ReadAnswer(IExchange exchange) { var body = exchange.HasOut ? exchange.Out!.Body : exchange.In.Body; if (body is IDictionary dictionary) return dictionary; var json = body switch { byte[] bytes when bytes.Length > 0 => bytes, string text when text.Length > 0 => Encoding.UTF8.GetBytes(text), _ => null, }; if (json is null) return null; try { using var document = JsonDocument.Parse(json); if (document.RootElement.ValueKind != JsonValueKind.Object) return null; // Only what the status mapping reads. Materialising the whole document here would copy a // payload we are about to discard anyway: a non-OK gRPC reply carries no body. var answer = new Dictionary(); foreach (var name in ErrorFields) { if (document.RootElement.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.String) { answer[name] = value.GetString(); } } return answer.Count > 0 ? answer : null; } catch (JsonException) { return null; } } private static readonly string[] ErrorFields = ["error", "error_description"]; private static void Emit(IExchange exchange, IMessage response) { exchange.Out ??= new Message(); // The status may have been decided while the answer still sat on In — the pipeline merges Out // into In between steps, so MapErrorToGrpcStatus often writes there. The consumer reads the // status off the Out message, so without carrying these across a failed call would answer OK. CarryStatusHeaders(exchange.In, exchange.Out!); exchange.Out!.Body = response.ToByteArray(); } internal static void CarryStatusHeaders(RouteMessage source, RouteMessage target) { foreach (var (key, value) in source.Headers) { if (value is null) continue; var isStatus = key.Equals(GrpcHeaders.StatusCode, StringComparison.OrdinalIgnoreCase) || key.Equals(GrpcHeaders.StatusDetail, StringComparison.OrdinalIgnoreCase) || key.StartsWith(GrpcHeaders.TrailerPrefix, StringComparison.OrdinalIgnoreCase); if (isStatus && !target.Headers.ContainsKey(key)) target.Headers[key] = value; } } } Path: redb-identity/src/redb.Identity.Grpc/Processors/GrpcManagementProcessors.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/Processors/GrpcManagementProcessors.cs ---- using System.Globalization; using System.Text; using System.Text.Json; using Google.Protobuf; using Google.Protobuf.WellKnownTypes; using Grpc.Core; using redb.Identity.Grpc.Management.V1; using redb.Identity.Management; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Grpc; namespace redb.Identity.Grpc.Processors; /// /// F6 — the management surface over gRPC: authenticate, authorize, then dispatch to the very same /// controller the HTTP facade dispatches to. /// /// Sharing the controllers is the point. They are thin — each action validates its DTO and forwards to a /// direct-vm://identity-manage-* route — but "thin" is not "trivial": which argument is a key, /// which key name a surface uses, when validation runs. Restating that per transport is a second /// declaration of the contract, and the copy that drifts is the one that accepts what the other rejects. /// So the controllers moved to redb.Identity.Management and both facades dispatch the same types. /// /// /// Every gate here fails closed. The authentication and authorization hops run on isolated exchanges (see /// for why), so their exchange.Stop() no /// longer ends this route by itself — the gate is explicit, and it halts unless it positively sees an /// allow. /// /// internal static class GrpcManagementProcessors { /// Property set when a gate refused, read by . private const string RefusedProperty = "identity:grpc-refused"; /// /// Names the call before either gate runs: which controller action serves it, and — for the /// authorization gate — which resource and action it amounts to. /// public static Func Describe(ManagementOperation operation) { return (exchange, _) => { // The controller dispatcher routes on this header rather than on a path. exchange.In.Headers["dispatch-method"] = operation.DispatchMethod; // The same canonical resource identifiers the HTTP facade passes, so the single table in Core // decides for both transports and neither can drift into granting more than the other. exchange.Properties["identity:authz-resource"] = operation.Resource; exchange.Properties["identity:authz-action"] = operation.Writes ? "write" : "read"; return Task.CompletedTask; }; } /// /// Merge strategy for the two gates. Beyond adopting the answer it carries back the /// identity:management-* properties authentication establishes — the isolated exchange is a /// copy, so anything Core writes on it is otherwise lost, and losing those properties would silently /// disarm the self-vs-admin check the controllers rely on downstream. /// public static IExchange AdoptGateDecision(IExchange facade, IExchange core) { GrpcIdentityProcessors.AdoptCoreAnswer(facade, core); foreach (var property in core.Properties) { if (property.Key.StartsWith("identity:", StringComparison.Ordinal)) facade.Properties[property.Key] = property.Value; } // A gate writes an Out only to refuse. Recording it here keeps the decision explicit rather than // re-derived later from a body that has since been merged and moved. if (core.HasOut) facade.Properties[RefusedProperty] = true; return facade; } /// /// The gate. Halts unless the step before it let the request through, translating the refusal into a /// gRPC status first: a refusal delivered as a successful reply carrying an error document would be /// worse than no gate at all, because no generated client inspects it. /// public static Task RequireAuthorized(IExchange exchange, CancellationToken ct) => Decide(exchange, ct, requireAuthentication: false); /// /// The gate after the authentication hop. Unlike it demands positive /// evidence that authentication actually ran — the identity:management-principal the auth /// processor leaves behind — instead of merely finding no refusal. /// /// The difference is not academic. A deployment can wire Core without a management auth processor, /// which leaves direct-vm://identity-auth-management unregistered; the hop then throws /// «No consumer registered», Core's context-level exception handler marks that handled and replaces /// the body with its own error document, and the old gate saw exactly what a successful /// authentication looks like: no refusal. The call only stopped because that handler happened to end /// the pipeline and because the wire encoder happened to refuse the leftover dictionary — two /// unrelated safety nets, neither of them an authentication decision. Absence of a «no» is not a /// «yes». /// /// public static Task RequireAuthenticated(IExchange exchange, CancellationToken ct) => Decide(exchange, ct, requireAuthentication: true); private static async Task Decide(IExchange exchange, CancellationToken ct, bool requireAuthentication) { var refused = exchange.Properties.TryGetValue(RefusedProperty, out var flag) && flag is true; var deniedByCode = ReadResponseCode(exchange) is { } code && code is < 200 or > 299; // Anonymous routes are a deliberate decision by the auth processor, and it says so explicitly. var anonymous = exchange.Properties.TryGetValue("identity:management-anonymous", out var anon) && anon is true; var unauthenticated = requireAuthentication && !anonymous && !exchange.Properties.ContainsKey("identity:management-principal"); if (unauthenticated && !refused && !deniedByCode) { var stated = exchange.HasOut ? exchange.Out! : exchange.In; stated.Headers[GrpcHeaders.StatusCode] = (int)StatusCode.Unauthenticated; stated.Headers[GrpcHeaders.StatusDetail] = "Authentication did not run for this call. The management surface is closed until it does."; stated.Headers[GrpcHeaders.TrailerPrefix + "error"] = "unauthenticated"; exchange.Properties.Remove(RefusedProperty); exchange.Stop(); return; } if (!refused && !deniedByCode) return; await GrpcIdentityProcessors.MapErrorToGrpcStatus(exchange, ct); // Nothing decided a status? Then the refusal came in a shape this code does not recognise, and the // only safe reading of an unrecognised answer from an authorization gate is "no". var target = exchange.HasOut ? exchange.Out! : exchange.In; if (!target.Headers.ContainsKey(GrpcHeaders.StatusCode)) { target.Headers[GrpcHeaders.StatusCode] = (int)StatusCode.PermissionDenied; target.Headers[GrpcHeaders.StatusDetail] = "The request was refused."; } exchange.Properties.Remove(RefusedProperty); exchange.Stop(); } /// /// Unwraps into the JSON object the controller dispatcher binds from. /// Named arguments, not positional: the wire contract must not be the order of C# parameters. /// public static Task MapRequest(IExchange exchange, CancellationToken ct) { try { var bytes = exchange.In.Body as byte[] ?? []; var request = bytes.Length == 0 ? new ManagementRequest() : ManagementRequest.Parser.ParseFrom(bytes); var arguments = request.Arguments ?? new Struct(); // Protobuf's own JSON mapping renders a Struct as a plain JSON object, which is exactly what // the dispatcher expects — no hand-rolled conversion in between to disagree with it. exchange.In.Body = Encoding.UTF8.GetBytes(JsonFormatter.Default.Format(arguments)); return Task.CompletedTask; } catch (InvalidProtocolBufferException ex) { return Reject(exchange, StatusCode.InvalidArgument, $"Request must be an identity.management.v1.ManagementRequest: {ex.Message}"); } } /// /// Turns the controller's answer into a status, using the same table the HTTP facade uses. The /// controllers report failure as an error document with a success status, so without this a refusal /// would arrive as an OK call — and the acceptance test for this phase is that one token yields the /// same verdict on both transports. /// public static Task MapControllerErrorToGrpcStatus(IExchange exchange, CancellationToken ct) { var source = exchange.HasOut ? exchange.Out! : exchange.In; if (source.Body is not byte[] json || json.Length == 0) return Task.CompletedTask; string? error; try { using var document = JsonDocument.Parse(json); if (document.RootElement.ValueKind != JsonValueKind.Object) return Task.CompletedTask; if (!document.RootElement.TryGetProperty("error", out var value) || value.ValueKind != JsonValueKind.String) { return Task.CompletedTask; } error = value.GetString(); } catch (JsonException) { return Task.CompletedTask; // not JSON: nothing to read a verdict out of } if (string.IsNullOrEmpty(error)) return Task.CompletedTask; // A status the dispatcher (or Core) already decided wins — a missing method is NOT_FOUND and an // action that threw is INTERNAL, not INVALID_ARGUMENT. The table, in the package that owns the // controllers, speaks only for error documents that came back as a success. Either way the code // is translated into the gRPC status space by the same path Core's own verdicts go through. source.Headers["redbHttp.ResponseCode"] = ManagementErrorCodes.DecidedErrorStatus(source) ?? ManagementErrorCodes.ToStatusCode(error!); return GrpcIdentityProcessors.MapErrorToGrpcStatus(exchange, ct); } /// /// Wraps the controller's JSON answer as . A deletion answers with /// nothing, which stays nothing rather than becoming an empty object. /// public static Task MapResponse(IExchange exchange, CancellationToken ct) { var body = exchange.HasOut ? exchange.Out!.Body : exchange.In.Body; var response = new ManagementResponse(); var json = body switch { byte[] bytes when bytes.Length > 0 => Encoding.UTF8.GetString(bytes), string text when text.Length > 0 => text, _ => null, }; if (json is not null) response.Result = JsonParser.Default.Parse(json); exchange.Out ??= new Message(); GrpcIdentityProcessors.CarryStatusHeaders(exchange.In, exchange.Out!); exchange.Out!.Body = response.ToByteArray(); return Task.CompletedTask; } private static Task Reject(IExchange exchange, StatusCode status, string detail) { exchange.Out = new Message(Array.Empty()); exchange.Out.Headers[GrpcHeaders.StatusCode] = (int)status; exchange.Out.Headers[GrpcHeaders.StatusDetail] = detail; exchange.Stop(); return Task.CompletedTask; } private static int? ReadResponseCode(IExchange exchange) { var source = exchange.HasOut ? exchange.Out! : exchange.In; if (!source.Headers.TryGetValue("redbHttp.ResponseCode", out var raw) || raw is null) return null; return int.TryParse(raw.ToString(), NumberStyles.Integer, CultureInfo.InvariantCulture, out var code) ? code : null; } } /// /// One management operation as the facade sees it: a wire address, the controller action that serves it, /// and what the authorization gate should be told it amounts to. /// /// gRPC service name, e.g. Users. /// gRPC method name, e.g. List. /// Controller action, qualified: Users.List. /// Canonical resource identifier, e.g. /api/v1/identity/users. /// Whether the operation mutates. Read and write map to different scopes. internal sealed record ManagementOperation( string Service, string Method, string DispatchMethod, string Resource, bool Writes); Path: redb-identity/src/redb.Identity.Grpc/README.md 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/README.md ---- # redb.Identity.Grpc A gRPC facade for redb.Identity: the **service-to-service** protocol surface (`Token`, `Introspect`, `Revoke`, `UserInfo`, `Discovery`, `Jwks`) and the **management** surface (40 admin operations across Users, Applications, Groups, Scopes and Tokens), each on its own port. It is a transport, not a second implementation. Every call is translated and handed to the same `direct-vm://identity-*` routes the HTTP facade uses, so both transports observe one issuer, one client registry, one token store, one set of feature flags and one audit trail. Nothing about the protocol is decided here. ``` gRPC client ──▶ redb.Identity.Grpc ──direct-vm://identity-*──▶ redb.Identity.Core HTTP client ──▶ redb.Identity.Http ──direct-vm://identity-*──▶ ↑ the same routes ``` ## What is in scope, and what is not | Operation | Address | RFC | |---|---|---| | `Token` | `/identity.v1.Identity/Token` | RFC 6749 §3.2 | | `Introspect` | `/identity.v1.Identity/Introspect` | RFC 7662 | | `Revoke` | `/identity.v1.Identity/Revoke` | RFC 7009 | | `UserInfo` | `/identity.v1.Identity/UserInfo` | OIDC Core §5.3 | | `Discovery` | `/identity.v1.Identity/Discovery` | OIDC Discovery 1.0 | | `Jwks` | `/identity.v1.Identity/Jwks` | RFC 7517 | | health probe | `/grpc.health.v1.Health/Check` | gRPC Health Checking Protocol | **Browser flows stay on HTTP** — `authorize`, login, consent, MFA pages, device verification. They need a browser, redirects and a cookie session; a gRPC channel has none of those. **DPoP stays on HTTP** too: RFC 9449 binds its proof to an HTTP method and URL, so a DPoP proof presented over gRPC would be unverifiable by construction. These are boundaries, not gaps — see `doc/gRPC/README.md`. The **management surface** is here too, on a port of its own — see [below](#the-management-surface). Self-service (`/me`, account registration, password recovery, MFA enrolment) is not, and deliberately: it is an end-user flow, not admin tooling. ## Installing The facade ships as its own Tsak module (`.tpkg`) with `ContextName: identity.grpc`, and it has **no compile-time dependency on `redb.Identity.Core`** — it talks to Core over `direct-vm://` only. Deploy it beside `redb.Identity.Core.Module` (its only declared dependency) and, if you serve browsers, beside `redb.Identity.Http`. ```powershell ./scripts/pack-tpkg.ps1 -Module Grpc # or -Module All ``` Hosting it yourself instead of under Tsak is two lines in a route context: ```csharp var context = new RouteContext(serviceProvider, "identity.grpc"); context.AddComponent(new GrpcComponent()); context.AddRoutes(new GrpcFacadeRouteBuilder(Options.Create(transportOptions))); await context.Start(); ``` ## Configuration Settings live in the shared `context.json` under the `identity.grpc` context, in an `IdentityTransport:Grpc:*` section that mirrors the HTTP facade's own section. Shared values — issuer, feature flags — come from the `Identity:*` root that Core reads, so they are declared once. ```jsonc "identity.grpc": { "IdentityTransport": { "Grpc": { "Host": "0.0.0.0", "PublicPort": 5011, "ManagementPort": null, "Ssl": false, "ClientCertificateMode": "NoCertificate", "AllowedClientThumbprints": null, "Compression": "None", "MaxMessageSize": 4194304, "Health": true, "EmitHttpCompatHeaders": true } } } ``` | Key | Default | Meaning | |---|---|---| | `Host` | `0.0.0.0` | Bind address. | | `PublicPort` | `5001` | The protocol surface. **Never share it with the HTTP facade**: gRPC requires HTTP/2 while the HTTP facade serves HTTP/1.1 + HTTP/2, and one listener has a single protocol set. The shared host throws on that conflict rather than failing later with a framing error. | | `ManagementPort` | `null` | `null` = same as `PublicPort` (the single-node default). Split it in production: the protocol surface is called by every relying party, the management surface only by admin tooling — different consumers, different blast radius, firewalled separately. | | `Ssl` | `false` | TLS. Requires `SslCertPath` (PFX) and usually `SslCertPassword`. | | `ClientCertificateMode` | `NoCertificate` | mTLS: `NoCertificate`, `AllowCertificate`, `RequireCertificate`. | | `AllowedClientThumbprints` | `null` | Comma-separated SHA-1 thumbprints. When set, a certificate whose thumbprint is not listed is rejected even if its chain validates. | | `Compression` | `None` | Reply compression: `None` or `Gzip`. Inbound gzip is always accepted regardless of this setting. | | `MaxMessageSize` | `4194304` | Bytes, both directions. Enforced after inflation, so a compression bomb cannot slip past it. | | `Health` | `true` | Serve `grpc.health.v1.Health/Check` on every listening port. Unauthenticated and two bytes long. | | `EmitHttpCompatHeaders` | `true` | Mirror the client address into `redbHttp.RemoteAddress`. **Leave this on** — see below. | ### Why `EmitHttpCompatHeaders` defaults to on Core keys its per-IP throttle, its brute-force lockout and its device metadata on `redbHttp.RemoteAddress`. Those checks **no-op when the header is absent** rather than failing loudly, so turning this off does not disable a feature you can see — it silently stops protecting the gRPC port while every test and dashboard stays green. Callers cannot forge the header: the transport drops inbound metadata carrying a reserved prefix before the route sees it. ## Calling it Generate stubs from `redb.Identity.Contracts/Protos/identity.v1.proto`. That file is the published contract; it is deliberately not compiled into the Contracts assembly, which stays a dependency-free DTO package. ```csharp var channel = GrpcChannel.ForAddress("https://identity.internal:5001"); var identity = new Identity.IdentityClient(channel); var token = await identity.TokenAsync(new TokenRequest { GrantType = "client_credentials", ClientId = "reporting-service", ClientSecret = secret, Scope = "identity:read", }); ``` Client authentication works either way: `client_id` / `client_secret` as message fields, or `authorization: Basic …` as call metadata. Core reads both, so the facade adds no step of its own. The same is true of the `UserInfo` bearer token — `authorization: Bearer …` metadata or the `access_token` field. ### Message shape Requests name what the RFCs name and carry a `map additional` for everything else. That map is not a shortcut: the wire form of these endpoints has always been form-encoded key/value, so extension grants and vendor parameters belong in it. Responses type what the RFCs fix and put the rest in a `google.protobuf.Struct` — `extra` on token and introspection, `claims` on userinfo, `document` on discovery and JWKS. Userinfo claims and introspection members are open sets by design, so typing them would be a lie. Nothing the server returns is dropped. ### Errors A gRPC call either succeeds or carries a status. An OAuth error document arriving as a *successful* call would be invisible to every generated client, so it does not: | Cause | Status | |---|---| | `invalid_client`, `invalid_token` | `UNAUTHENTICATED` | | `access_denied`, `unauthorized_client` | `PERMISSION_DENIED` | | `server_error` | `INTERNAL` | | `temporarily_unavailable` | `UNAVAILABLE` | | any other OAuth error | `INVALID_ARGUMENT` | | rate limited (429) | `RESOURCE_EXHAUSTED` | | scope guard (403) | `PERMISSION_DENIED` | | database outage (503) | `UNAVAILABLE` | A status Core decided itself wins over the error string, because Core's own codes are not all in an RFC table — a rate-limited answer carries `error = "rate_limited"`, which no table names. **Read the trailers.** A non-OK gRPC reply discards its payload, so the machine-readable detail travels there and nowhere else: | Trailer | Contents | |---|---| | `error` | the OAuth error code, e.g. `invalid_client` | | `error-description` | human-readable detail, also in the status message | | `retry-after` | seconds to wait, on `RESOURCE_EXHAUSTED` | | `x-correlation-id` | the id this call was traced under | ```csharp try { await identity.TokenAsync(request); } catch (RpcException ex) when (ex.StatusCode == StatusCode.ResourceExhausted) { var wait = ex.Trailers.GetValue("retry-after"); // seconds } ``` ### Correlation ids and idempotency Send `x-correlation-id` in metadata and it is honoured and echoed back in a trailer; send nothing and one is derived from the ambient trace id. This applies to every operation on both surfaces. `idempotency-key` is **not** universal, and it is worth knowing where the line falls. Core applies its idempotency cache to the management surfaces — users, applications, groups, scopes, tokens and the rest of the admin API — so a retried `Users/Create` returns the original record instead of failing as a duplicate. The protocol operations (`Token`, `Introspect`, `Revoke`, `UserInfo`, `Discovery`, `Jwks`) have no idempotency layer: sending the header there is harmless and does nothing. Each operation is tagged with its own name, so two different operations sharing one key do not collide. ## The envelope fallback The same six operations are reachable without the `.proto` at all, through the connector's generic address. Send a `RedbMessage` whose payload is the JSON body and whose `operation` header names the operation (`token`, `introspect`, `revoke`, `userinfo`, `discovery`, `jwks`): ``` /redb.route.grpc.RedbService/Process + metadata: operation: token ``` The reply is a `RedbMessage` whose payload is the JSON answer. An unknown operation is `UNIMPLEMENTED` and the status message lists the ones that exist. One surface, two spellings — use the typed contract unless carrying a `.proto` is genuinely inconvenient. ## The management surface The admin API, for tooling rather than for relying parties. Forty operations across five services, on `ManagementPort`, generated from [identity.management.v1.proto](../redb.Identity.Contracts/Protos/identity.management.v1.proto). | Service | Operations | |---|---| | `identity.management.v1.Users` | `List` `Search` `Get` `Create` `Update` `Delete` `ChangePassword` `AdminResetPassword` | | `identity.management.v1.Applications` | `List` `Get` `Create` `Update` `RotateSecret` `Delete` | | `identity.management.v1.Groups` | `List` `Search` `Get` `Create` `CreateChild` `Update` `Delete` `Move` `Tree` `Path` `Children` `ListMembers` `AddMember` `UpdateMember` `RemoveMember` `UserGroups` `IsMember` | | `identity.management.v1.Scopes` | `List` `Get` `Create` `Update` `Delete` | | `identity.management.v1.Tokens` | `List` `Revoke` `RevokeBySubject` `Prune` | These dispatch to the same controllers the HTTP management API dispatches to — one package, `redb.Identity.Management`, shared by both facades. The REST endpoint of the same name is therefore the documentation for what a payload contains, and the two transports cannot drift apart on argument names or validation. ### Payload shape Requests carry named arguments; responses carry whatever the operation returned: ```protobuf message ManagementRequest { google.protobuf.Struct arguments = 1; } message ManagementResponse { google.protobuf.Value result = 1; } ``` Argument names are the ones the REST route and query parameters use — `id`, `offset`, `count` — and an operation whose REST form takes a request body puts that body's fields in `arguments` directly. ```csharp var users = new Users.UsersClient(channel); var page = await users.ListAsync( new ManagementRequest { Arguments = Struct.Parser.ParseJson("""{"offset":0,"count":25}""") }, new Metadata { { "authorization", $"Bearer {token}" } }); ``` The payloads are `Struct` and not typed messages on purpose. Forty operations today and 142 on the whole admin surface, over an API that still grows: typing every request and response would make each new field a contract change consumers must regenerate for. The **addresses** are the contract — named, stable, and generated into real client stubs — while the payload stays open. Raw JSON would have been the other way to keep it open, and it would have cost you the generated client. ### Authorization Every call is authenticated with a bearer token and then checked against the granular scope table — the same table in Core that the HTTP management API is checked against, so **the same token yields the same verdict on both transports**. Read and write map to different scopes, and write implies read but never the inverse. | Outcome | Status | |---|---| | no token, or a token that does not validate | `UNAUTHENTICATED` | | valid token without the scope for this surface | `PERMISSION_DENIED`, `insufficient_scope` in a trailer | | the operation's own refusal (`not_found`, `duplicate`, `validation_error`, …) | `NOT_FOUND`, `ALREADY_EXISTS`, `INVALID_ARGUMENT`, … | **Self-service is not here.** `/me`, account registration, password recovery and MFA enrolment are end-user flows reached from a browser or an app session, not admin tooling. Putting them on an admin port would widen that port's blast radius for a caller that does not exist. ### Splitting the ports in production `ManagementPort` defaults to `null`, meaning "share `PublicPort`" — convenient for a single node, wrong for production. Set it, and the admin addresses answer only there; the protocol port returns `UNIMPLEMENTED` for them, which is what makes a firewall rule on the admin port worth writing. ```jsonc "PublicPort": 5011, "ManagementPort": 5012, "Ssl": true, "ClientCertificateMode": "RequireCertificate" ``` ## TLS and mTLS ```jsonc "Ssl": true, "SslCertPath": "/etc/redb/identity-grpc.pfx", "SslCertPassword": "…", "ClientCertificateMode": "RequireCertificate", "AllowedClientThumbprints": "9F2C…A1, 4B77…E0" ``` mTLS is off by default so deployments without a client-certificate PKI are not blocked. It is the recommended setting for the management port in production. Thumbprint pinning is an addition to chain validation, not a replacement: an unlisted certificate is rejected even when its chain is valid. ## Operating it - **Health** — `grpc.health.v1.Health/Check` on every listening port. It answers «is *this* listener serving», which a probe on another port cannot show. - **Route ids** — one method address is one route: `grpc-identity-token`, `grpc-identity-introspect`, `grpc-identity-revoke`, `grpc-identity-userinfo`, `grpc-identity-discovery`, `grpc-identity-jwks`, `grpc-identity-envelope`. Each has its own metrics and lifecycle and can be suspended individually through the control bus. - **Discovery is not rewritten.** The document advertises the server's HTTP endpoints, because those are the real ones. Handing gRPC callers rewritten addresses would point them at endpoints that do not exist. ## Further reading | Document | Contents | |---|---| | `doc/gRPC/README.md` | scope, boundaries, phase map | | `doc/gRPC/ARCHITECTURE.md` | why a facade and not a second implementation; the trust model of `direct-vm://` | | `doc/gRPC/ROADMAP.md` | phases and their order | | `doc/gRPC/CHECKLIST.md` | verifiable state of each phase | | `doc/gRPC/OPEN_QUESTIONS.md` | decisions taken and their reasoning | | `redb.Identity.Contracts/Protos/identity.v1.proto` | the published contract | | `GrpcIdentityInteropTests` | the interop check: an independent `@grpc/grpc-js` client in a container, generated from that contract | Path: redb-identity/src/redb.Identity.Grpc/redb.Identity.Grpc.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.Grpc/redb.Identity.Grpc.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.", "The gRPC facade reads IdentityTransport:Grpc:* there; shared issuer and feature flags come from", "Identity:* — the same section Core and the HTTP facade read." ], "ContextName": "identity.grpc", "AutoStart": true } Path: redb-identity/src/redb.Identity.Grpc/redb.Identity.Grpc.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.Grpc/redb.Identity.Grpc.csproj ---- redb.Identity.Grpc redb.Identity.Grpc gRPC facade for redb.Identity — service-to-service surface: token, introspection, revocation, userinfo, discovery, JWKS. PreserveNewest PreserveNewest