Path: redb-identity/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/README.md ---- # redb.Identity > **A transport-agnostic OAuth 2.1 / OpenID Connect server for the redb ecosystem.** > Built on [OpenIddict](https://documentation.openiddict.com/) and [redb.Route](https://github.com/redbase-app/redb-route). Every endpoint is a `direct-vm://` route — call it over HTTP, gRPC, WS-Trust (SOAP), or **straight from another in-process module with zero network overhead**. Ships as `.tpkg` packages for [redb.Tsak](https://github.com/redbase-app/redb-tsak). REDB-backed, cluster-ready, standards-compliant. Documentation and articles: [![License: Apache 2.0](https://img.shields.io/badge/license-Apache_2.0-blue)](https://github.com/redbase-app/redb-identity/blob/main/LICENSE) [![Website](https://img.shields.io/badge/docs-redbase.app-orange)](https://redbase.app) [![.NET](https://img.shields.io/badge/.NET-10%20%7C%2011-purple)](https://dotnet.microsoft.com) [![Providers](https://img.shields.io/badge/storage-PostgreSQL%20%7C%20MSSQL%20%7C%20SQLite-336791)](#provider-matrix-zero-code-changes-between-rows) [![NuGet: redb.Identity.Core](https://img.shields.io/nuget/v/redb.Identity.Core?label=nuget%3A%20Core&color=004880)](https://www.nuget.org/packages/redb.Identity.Core) [![NuGet: redb.Identity.Http](https://img.shields.io/nuget/v/redb.Identity.Http?label=nuget%3A%20Http&color=004880)](https://www.nuget.org/packages/redb.Identity.Http) [![NuGet: redb.Identity.Client](https://img.shields.io/nuget/v/redb.Identity.Client?label=nuget%3A%20Client&color=004880)](https://www.nuget.org/packages/redb.Identity.Client) [![OIDC](https://img.shields.io/badge/OpenID_Connect-Core_1.0-1F4E79)](#openid-connect) [![OAuth](https://img.shields.io/badge/OAuth-2.1_%2B_RFC_6749-4A148C)](#oauth-2x-core) [![DPoP](https://img.shields.io/badge/DPoP-RFC_9449-1565C0)](#oauth-2x-core) [![PAR](https://img.shields.io/badge/PAR-RFC_9126-1565C0)](#oauth-2x-core) [![JAR](https://img.shields.io/badge/JAR-RFC_9101-1565C0)](#oauth-2x-core) [![DCR](https://img.shields.io/badge/DCR-RFC_7591%2F7592-1565C0)](#oauth-2x-core) [![SCIM](https://img.shields.io/badge/SCIM-2.0_(RFC_7643%2F7644)-2E7D32)](#scim-20-rfc-7643--7644) [![FIDO2](https://img.shields.io/badge/FIDO2-WebAuthn_L2-006064)](#mfa) [![Engine](https://img.shields.io/badge/engine-OpenIddict-512BD4)](#) [![Runtime](https://img.shields.io/badge/runtime-redb.Route-FF6F00)](#) --- ## Contents - [TL;DR](#tldr) · [Install](#install) · [Quick start](#quick-start) · [What's new in 4.4](#whats-new-in-44) - [Why redb.Identity exists](#why-redbidentity-exists) · [In-process direct-vm calls](#the-killer-feature-in-process-direct-vm-calls) · [Architecture](#architecture) · [Project structure](#project-structure) - [Endpoint catalogue](#endpoint-catalogue) · [Standards compliance](#standards-compliance) · [Storage model](#storage-model--built-on-the-redb-object-engine) - [Cluster-readiness](#cluster-readiness) · [Observability](#observability) · [Security highlights](#security-highlights) · [Audit event catalogue](#audit-event-catalogue) - [Runnable demos](#runnable-demos-demos) · [Typed SDK](#typed-sdk-iidentityclient) · [Reference BFF](#reference-bff--admin-ui-redbidentityweb) · [Testing](#testing) · [Roadmap](#roadmap-excerpt) Further documents: [DEPLOYMENT.md](DEPLOYMENT.md) (images, archives, ports, secrets), [HTTPS.md](HTTPS.md) (TLS), [UPGRADING.md](UPGRADING.md) (what to change per version), [CHANGELOG.md](CHANGELOG.md), [OPENID_CERTIFICATION.md](OPENID_CERTIFICATION.md), [SECURITY.md](SECURITY.md), [CONTRIBUTING.md](CONTRIBUTING.md). --- ## TL;DR | If you want… | redb.Identity gives you… | |---|---| | A full OIDC / OAuth 2.1 server without ASP.NET coupling | A `direct-vm://`-only core: `token`, `authorize`, `userinfo`, `introspect`, `revoke`, `jwks`, `.well-known/openid-configuration`, PAR, JAR (signed request objects), Device Code, Dynamic Registration. | | To call Identity from another in-process module **with no HTTP** | `To("direct-vm://identity-token")` from your own `RouteBuilder`. Zero serialization, zero loopback, zero TLS handshake, same exchange. | | HTTP / gRPC / WS-Trust endpoints | Drop in the matching facade `.tpkg` (`redb.Identity.Http`, `.Grpc`, `.Soap`). Each facade is a thin transport bridge — no business logic. Message-bus facades are planned, see the [Roadmap](#roadmap-excerpt). | | A drop-in user / group / scope / client / consent / audit / session store | Built-in storage via [redb.Core](https://github.com/redbase-app/redb) typed `*Props` objects. Code-first schemes, no migrations. | | Multi-instance / cluster deployment | DataProtection key-ring + signing keys shared through redb object store. Cleanup timers run leader-only via `.Cluster(true)`. | | Modern MFA | TOTP (RFC 6238) + SMS/Email OTP + WebAuthn (FIDO2) + Recovery codes. E-mail codes go out through the SMTP channel (`Smtp.Enabled`) or the host's own e-mail channel; SMS OTP needs a delivery channel registered by the host, and none ships. | | Self-service for end users | `/me/profile`, `/me/sessions`, `/me/mfa`, `/me/webauthn`, `/me/consents`, `/me/federated`. | | Federation | OIDC / GitHub external providers, stored as redb props objects, admin CRUD. | | Backchannel logout that works across replicas | RFC 8417-style revoked-SID list (`/revoked-sids/add` + `/since`) + push-and-poll fallback. | | SCIM 2.0 provisioning | Users + Groups + Bulk endpoints (RFC 7644). | | RFC compliance | OIDC Core, OAuth 2.1, RFC 7662 (Introspection), RFC 7591/7592 (DCR), RFC 8628 (Device Code), RFC 9126 (PAR), **RFC 9101 (JAR — JWT-Secured Authorization Request, opt-in)**, RFC 9068 (JWT access-token profile — `at+jwt`, full claim set, `aud` issued and verified), RFC 8707 (Resource Indicators), RFC 8693 (Token Exchange, opt-in), RFC 9449 (DPoP), RFC 8417 / OIDC Backchannel Logout. | | Conformance you can check | Exercised against the **official OpenID Foundation conformance suite** (Config OP, Basic OP). Unsigned `alg:none` request objects are refused, as FAPI 2.0 requires. Per-module results: [OPENID_CERTIFICATION.md](OPENID_CERTIFICATION.md). | ## Install ### NuGet packages Add the pieces you need; the storage provider is chosen by the host: ```pwsh # Core OIDC / OAuth 2.1 engine (OpenIddict on redb.Route) + a storage provider dotnet add package redb.Identity.Core dotnet add package redb.Postgres.Pro # or redb.MSSql.Pro / redb.SQLite.Pro # HTTP facade (OIDC + management + SCIM endpoints) dotnet add package redb.Identity.Http # Typed client SDK (IIdentityClient) — for BFFs / services calling Identity dotnet add package redb.Identity.Client ``` | Package | Purpose | |---|---| | [`redb.Identity.Core`](https://www.nuget.org/packages/redb.Identity.Core) | OAuth 2.1 / OIDC engine — OpenIddict pipeline, redb stores, MFA, WebAuthn, federation, signing keys | | [`redb.Identity.Http`](https://www.nuget.org/packages/redb.Identity.Http) | HTTP / HTTPS facade — discovery, token, authorize, userinfo, introspect, JWKS, PAR, DCR, SCIM, `/me`, management | | [`redb.Identity.Grpc`](https://www.nuget.org/packages/redb.Identity.Grpc) | gRPC facade — service-to-service surface (token, introspect, revoke, userinfo, discovery, JWKS) + the management services; `.proto` contracts ship in `redb.Identity.Contracts` under `Protos/` | | [`redb.Identity.Soap`](https://www.nuget.org/packages/redb.Identity.Soap) | WS-Trust facade — `Issue`, `Validate`, `Cancel`, `Renew` over SOAP on the same core routes; WSDL published on GET; TLS required, and its absence is a refusal to start | | [`redb.Identity.Management`](https://www.nuget.org/packages/redb.Identity.Management) | Transport-neutral management + self-service controllers — thin adapters over `direct-vm://identity-manage-*`, shared by every facade | | [`redb.Identity.Contracts`](https://www.nuget.org/packages/redb.Identity.Contracts) | Wire DTOs + route-name constants (shared by Core, Http, Client) | | [`redb.Identity.Client`](https://www.nuget.org/packages/redb.Identity.Client) | Typed HTTP SDK (`IIdentityClient`) + backchannel OIDC client | | [`redb.Identity.DataProtection`](https://www.nuget.org/packages/redb.Identity.DataProtection) | redb-backed ASP.NET Core DataProtection key-ring | | [`redb.Identity.Core.Module`](https://www.nuget.org/packages/redb.Identity.Core.Module) | redb.Tsak `.tpkg` host glue (only when hosting inside a Tsak worker) | | [`redb.Identity.Ldap`](https://www.nuget.org/packages/redb.Identity.Ldap) | LDAP / Active Directory federation provider | | [`redb.Identity.Resource.Dpop`](https://www.nuget.org/packages/redb.Identity.Resource.Dpop) | Resource-server DPoP (RFC 9449) validator for downstream APIs | > The reference BFF + Blazor admin UI (`redb.Identity.Web`) is not a NuGet package: it ships as source in this > repository and as the `redb-identity-web` image. ### Docker images and archives Four images on `ghcr.io/redbase-app`, all signed with cosign: | Image | Contents | |---|---| | `redb-identity-backend` | Tsak Worker + Identity modules (OIDC only) | | `redb-identity-managed` | + Tsak dashboard | | `redb-identity-full` | + Identity Web BFF (login, consent, admin UI) | | `redb-identity-web` | Identity Web BFF only | Each GitHub release also carries a standalone archive per runtime (no Docker) and a modules archive (the `.tpkg` packages + `context.json`) for an existing Tsak worker. Ports, volumes, secrets and signature checks: [DEPLOYMENT.md](DEPLOYMENT.md). ### Upgrading [UPGRADING.md](UPGRADING.md) lists what to check and change for each version; [CHANGELOG.md](CHANGELOG.md) has the full list of changes. --- ## Quick start ### Run the image ```bash docker run -d --name identity -p 5002:5002 -v identity_data:/app/data ghcr.io/redbase-app/redb-identity-backend:latest curl -k https://localhost:5002/.well-known/openid-configuration ``` The image runs on SQLite with a bundled self-signed certificate for `localhost`, so call it with `curl -k`. For a real deployment replace the certificate, set the public issuer and pick the store as described in [DEPLOYMENT.md](DEPLOYMENT.md) and [HTTPS.md](HTTPS.md). ### Host the modules in your own Tsak worker Take the `.tpkg` packages and `context.json` from the modules archive of a release, or build them from source: ```pwsh pwsh scripts/pack-tpkg.ps1 -TsakModules /modules ``` | Package | Tsak context | Contains | |---|---|---| | `redb.Identity.Contracts.tpkg` | `identity.contracts` | The shared DTO assembly every Identity module resolves against | | `redb.Identity.Core.Module.tpkg` | `identity.core` | OIDC engine, redb stores, MFA, federation, signing keys | | `redb.Identity.Http.tpkg` | `identity.http` | HTTP facade: protocol endpoints, management API, SCIM, `/me` | | `redb.Identity.Grpc.tpkg` | `identity.grpc` | gRPC facade (optional) | | `redb.Identity.Soap.tpkg` | `identity.soap` | WS-Trust facade (optional) | The worker loads every package it finds in `modules/` together with `context.json`. ### Host Identity in your own process Without a Tsak worker, reference `redb.Identity.Core.Module`, the facades you serve (for example `redb.Identity.Http`) and one redb provider package; everything else comes with them. For SQLite take `redb.SQLite.Pro`: it runs in C# alone. `redb.SQLite` (Free) needs the native extension its package ships for linux-x64, linux-arm64 and win-x64, so it runs only on those. For PostgreSQL take `redb.Postgres` or `redb.Postgres.Pro`. Then start Identity with one call: ```csharp var services = new ServiceCollection(); services.AddLogging(b => b.AddConsole()); services.AddSingleton(configuration); services.AddRedbPro(o => o.UseSqlite("Data Source=identity.db")); // or AddRedb(o => o.UsePostgres(cs)) services.AddRedbIdentityHost(); // HTTP server manager and direct-vm registry await using var provider = services.BuildServiceProvider(); await using var identity = await RedbIdentityHost.StartAsync(provider, configuration, redb.Identity.Http.InitRoute.main); ``` `configuration` holds the same two sections a worker hands the modules: ```json { "Identity": { "Issuer": "https://id.example.com/", "UsePropsSigningKeyStore": true }, "IdentityTransport": { "Http": { "PublicPort": 5002 } } } ``` `StartAsync` checks the host and the configuration first and fails, naming the missing registration or key, when logging or `AddRedbIdentityHost()` is absent, `Identity:Issuer` is missing or not an absolute URI, no key source is set (`Identity:UsePropsSigningKeyStore` keeps the keys in redb; `Identity:AllowEphemeralKeys` is for development, the keys die with the process) or a facade is given without `IdentityTransport`. Then it runs the core module and the facades in the order given, starts them (schema and seed data on the first start, then the ports open) and fails if a route did not start. It returns the running host; disposing it stops the routes, lets running requests finish, closes the ports and disposes Identity's services. Options registered in your own container (`AddRedbIdentityServer`) are not read and are refused at start: settings come from the sections only. A service that calls the management API needs a client of its own. `Identity:SeedBackchannelClient` creates one at start (`Enabled`, `ClientId`, `ClientSecret`, `Scopes`, for example `identity:manage`); it takes a token with the `client_credentials` grant at `/connect/token`. A management call without a token is answered `401`. ### Configure Settings come from the Tsak layered configuration, one bucket per context. The images and archives ship an annotated `context.json`; the minimum is the issuer, which both the engine and the HTTP facade need: ```jsonc { "Contexts": { "identity.core": { "Identity": { "Issuer": "https://identity.example.com", "Features": { "EnableScim": true, "EnableDeviceCodeFlow": true, "EnablePushedAuthorization": true } } }, "identity.http": { "IdentityTransport": { "Issuer": "https://identity.example.com", "Http": { "PublicPort": 5002 } } } } } ``` Both HTTP listeners bind to `IdentityTransport:Http:Host` (default `0.0.0.0`, every interface); `127.0.0.1` keeps them on the loopback for a host behind a local reverse proxy. The gRPC and SOAP facades take `Host` the same way. Secrets go to environment variables, never to `context.json`: ``` Tsak__Contexts__identity.core__Override__Identity__RecoveryCodePepper=... Tsak__Contexts__identity.core__Override__Identity__FederationProviders__0__ClientSecret=... Tsak__Contexts__identity.core__Override__Identity__Ldap__Providers__0__BindPassword=... ``` ### Rotating the recovery-code pepper `Identity:RecoveryCodePepper` is mixed into the hashes of the MFA recovery codes and of the password-reset, e-mail-verification and change-e-mail links. A new value alone would void every unused recovery code and every open link, so the old value stays listed in `Identity:RecoveryCodePreviousPeppers` for verification: 1. Generate a new value: 32 random bytes, base64 (`openssl rand -base64 32`). 2. On every node at once, set `RecoveryCodePepper` to the new value and add the old one to `RecoveryCodePreviousPeppers` (`Tsak__Contexts__identity.core__Override__Identity__RecoveryCodePreviousPeppers__0=...`), then restart. A node that runs without the old value refuses what was issued under it. 3. Everything new is hashed with the new value. While previous values are listed, the leader logs once after start and then daily, per previous pepper id, how many users still hold recovery codes hashed with it (ids and counts only). 4. Remove an old value, again on every node at once, when its count is 0 and the longest link lifetime has passed since the rotation (24 hours with the default e-mail-verification TTL). Recovery codes do not expire: users who still hold old codes keep them working only while the old value is listed, and lose them when it goes; they can regenerate their codes before that. Several rotations stack: the list holds every value that is still needed. Keep it short: while previous values are listed, a recovery-code attempt against a set without a pepper id (issued before 4.8.0) costs one PBKDF2 per code for the current pepper and one more for each listed value, so remove a value as soon as its count reaches 0. ### First administrator A fresh database has the user `admin` with the password `admin`. Set `Identity:SeedAdmin:Password` before the first start (or `Identity:SeedAdmin:Enabled=false`): Identity applies it while the stored password is empty or still `admin`, and never overwrites a password that was changed. While the configured password is the default, the server logs a warning at every start. When Identity runs in a Tsak worker that shares its database with the Tsak dashboard in cluster mode, the dashboard creates this administrator first, from `Tsak:Web:AdminLogin` and `Tsak:Web:AdminPassword` (admin/admin by default), and both sign in with the same account. Change its password in the Tsak dashboard or in the Identity UI; `Identity:SeedAdmin:Password` replaces it only while it is still admin/admin. For an unattended setup there is a one-time endpoint that creates an administrator, the `identity-admins` group and the Web console client. It is off by default; enable it with `Identity:Bootstrap:Enabled=true` and a secret of at least 32 characters in `Identity:Bootstrap:Secret`: ```bash curl -k -X POST https://localhost:5002/internal/bootstrap-admin \ -H "Content-Type: application/json" -H "X-Bootstrap-Secret: $BOOTSTRAP_SECRET" \ -d '{ "email": "admin@example.com", "password": "..." }' # A second call returns 410 Gone. ``` --- ## What's new in 4.4 Each item links to the migration steps in [UPGRADING.md](UPGRADING.md). - **OpenIddict 7**, with the Microsoft.Extensions and ASP.NET Core 10 packages on every target framework. Sessions and refresh tokens issued by earlier versions stay valid. [OpenIddict 7](UPGRADING.md#openiddict-7) - **`resource` (RFC 8707) is validated** on authorize, PAR and token exchange against the scopes' `Resources`. [resource parameter](UPGRADING.md#resource-parameter) - **JWT client assertions follow rfc7523bis**: `typ` header `client-authentication+jwt` and the issuer as `aud`. [Client assertions](UPGRADING.md#client-assertions-private_key_jwt-client_secret_jwt) - **Token exchange (RFC 8693)** runs on OpenIddict's built-in grant and checks the calling client and the user. - **DPoP-bound tokens at third-party resource servers** need OpenIddict's proof-of-possession check switched off for `cnf.jkt`. [DPoP](UPGRADING.md#dpop-bound-access-tokens-at-third-party-resource-servers) - **The DataProtection key ring lives in redb**; the first start imports the old file ring once. [DataProtection key ring](UPGRADING.md#dataprotection-key-ring) - **Images**: `redb-identity-web` runs as a non-root user and keeps its key ring and log on volumes; the `managed` and `full` compose stacks keep the Tsak key rings on a volume. See [DEPLOYMENT.md](DEPLOYMENT.md). --- ## Why redb.Identity exists Most .NET Identity products force one of three uncomfortable choices: 1. **ASP.NET-bound stacks** (Duende IdentityServer, ASP.NET Identity Core) — every endpoint is an HTTP middleware. Want to call `token` from a Worker Service or a message bus consumer? You have to spin up an HTTP listener and loopback. Want to test the issuance pipeline in isolation? You need `WebApplicationFactory`. 2. **Heavy IAM platforms** (Keycloak, Auth0, Okta) — full-featured, but standalone services with their own runtime, their own admin UI, their own database, their own configuration model, and their own deployment story. Multi-tenant, but not embeddable. 3. **Roll your own** — and re-implement OAuth Code+PKCE, refresh-token rotation, consent storage, session revocation, MFA replay protection, JWKS rotation, key-ring sharing across replicas, RFC 8417 backchannel logout — for the third time this decade. redb.Identity is the missing fourth option: **the IS engine is just a set of `direct-vm://` routes**. The transport is your choice — and "no transport, just call it from the next module over" is a first-class deployment mode. You get the standards conformance and the storage model of a full IS server, but you wire it into your topology the same way you wire any other redb.Route pipeline. | | ASP.NET-bound IS (Duende, OpenIddict samples) | redb.Identity | Standalone IAM (Keycloak / Auth0) | |---|---|---|---| | Call `token` from another in-process module | Loopback HTTP | **`To("direct-vm://identity-token")`** — same exchange, zero copy | Network hop | | Add a new transport (gRPC, MQ, SignalR) | Rewrite endpoints as gRPC services / consumers | Add a facade `.tpkg`, point it at `direct-vm://` | Vendor adapter (if it exists) | | Replace HTTP with gRPC entirely | Major refactor | **Drop the HTTP facade. Keep Core.** | Not possible | | Storage | Custom EF Core schema + migrations | redb `RedbObject` — code-first, no migrations | Vendor schema, vendor migrations | | Multi-replica key sharing | DIY DataProtection persistence + JWKS rotation | Built-in: redb-backed key-ring + signing key store | Built-in (vendor-specific) | | Embeddable in a Tsak worker | No | **Yes — as one or two `.tpkg` packages** | No | | License | Mixed (Duende: commercial) | Apache 2.0 | Mixed | --- ## The killer feature: in-process direct-vm calls Every public endpoint in Identity is registered on a `direct-vm://identity-*` route. `direct-vm` is redb.Route's in-process, cross-`RouteContext`, **zero-copy synchronous** transport. Three consequences fall out for free: ### 1. Other Tsak modules in the same worker call Identity with no network at all ```csharp // Inside another .tpkg module loaded into the same Tsak worker public class CheckoutRoutes : RouteBuilder { private IProducerTemplate _identity = null!; // request-reply into Identity, in-process protected override void Configure() { _identity = new ProducerTemplate(Context!); _identity.Start(); From("rabbitmq:checkout.orders") // Need a service-account access token to call a downstream API? // Just hit Identity's token endpoint right here — same process, no socket. .Process(async (e, ct) => { var token = await _identity.RequestBody( IdentityEndpoints.Token, // "direct-vm://identity-token" new { grant_type = "client_credentials", client_id = "checkout-svc", /* ... */ }); e.In.SetHeader("Authorization", $"Bearer {token!.AccessToken}"); }) .To("http://pricing-api/quote"); } } ``` No HTTP listener. No TLS handshake. No JSON over the loopback. The exchange flows straight from your route into the Identity processor and back, in the same thread, with the same `IExchange` instance. Total cost: a method call plus the existing OpenIddict pipeline work. #### Calling the management routes from your module The management routes (`IdentityEndpoints.ManageUsers`, `ManageGroups`, `ManageApps` and the other `identity-manage-*` routes, MFA, SCIM) never trust the transport: `direct-vm` is shared by every module in the worker, so an exchange that reaches them without a management context is refused with `403 not_authorized`. Your module establishes that context the way the HTTP and gRPC facades do, in four steps on the same exchange: 1. **A token of your own client.** Create a confidential client for the module (console or management API) with the `client_credentials` grant and only the granular scopes it needs, for example `identity:users:read`. Take a token from `IdentityEndpoints.Token` and reuse it until it expires. 2. **Authentication.** Put the token in `Authorization: Bearer` and send the exchange through `IdentityEndpoints.AuthManagement`. It validates the token and leaves the management context (`identity:management-scopes`, `identity:management-subject`) on the exchange, or stops it with `401`. 3. **Authorization.** Set `identity:authz-resource` to the resource the HTTP API names (`/api/v1/identity/users`, `/api/v1/identity/groups`, ...) and `identity:authz-action` to `read` or `write`, and send the exchange through `IdentityEndpoints.AuthzCheck`. It checks the token's scopes against the same table the facades use, or stops the exchange with `403 insufficient_scope`. Skipping this step lets any token with a management scope reach every operation. 4. **The operation.** Set the `operation` header and the request body (the DTOs of `redb.Identity.Contracts`) and send the exchange to the management route. ```csharp From("direct:orders-find-user") .Process(async (e, ct) => { e.In.Headers["Authorization"] = $"Bearer {await _serviceToken.GetAsync(ct)}"; // step 1, cached }) .To(IdentityEndpoints.AuthManagement) // step 2 .Process((e, _) => { e.Properties["identity:authz-resource"] = "/api/v1/identity/users"; e.Properties["identity:authz-action"] = "read"; return Task.CompletedTask; }) .To(IdentityEndpoints.AuthzCheck) // step 3 .Process((e, _) => { e.In.Headers["operation"] = "read"; e.In.Body = new Dictionary { ["id"] = e.In.GetHeader("userId") }; return Task.CompletedTask; }) .To(IdentityEndpoints.ManageUsers); // step 4 ``` A refusal at step 2 or 3 stops the exchange, so the route does not reach the management route. Use the module's own client, not the Web console's `identity-backchannel` service account: that one shares its secret with the console and holds `identity:manage`, the whole management surface. ### 2. Facades are pure transport adapters — pick the ones you need ```csharp // HTTP facade — included From(Http.From("0.0.0.0:5000")) .RedbController(); // POST /connect/token // ↓ The controller's only job is: // exchange.To(IdentityEndpoints.Token) // direct-vm://identity-token // gRPC facade — shipped. One method address is one route, so each operation // gets its own route id, policies, metrics and lifecycle. From(GrpcDsl.Listen("0.0.0.0:5001").Method("/identity.v1.Identity/Token")) .RouteId("grpc-identity-token") .Process(GrpcIdentityProcessors.MapRequest(TokenRequest.Parser)) .Enrich(IdentityEndpoints.Token, GrpcIdentityProcessors.AdoptCoreAnswer) .Process(GrpcIdentityProcessors.MapErrorToGrpcStatus) .Process(GrpcIdentityProcessors.MapResponse("extra")); // WS-Trust facade — shipped. One address for all four operations, because that is // WS-Trust's own shape: the WS-Addressing Action names the operation, not the URL. From(SoapDsl.Listen("/sts").Host("0.0.0.0").Port(5021).Ssl()) .RouteId("soap-identity-sts") .Process(SoapIdentityProcessors.MapRequest) // RST → core parameters .Enrich(e => e.Properties["identity:wstrust-endpoint"] as string, SoapIdentityProcessors.AdoptCoreAnswer) .Process(SoapIdentityProcessors.MapResponse); // → RSTR, or a soap:Fault // RabbitMQ RPC facade (planned) From("rabbitmq:identity.rpc.token") .InOut() .To(IdentityEndpoints.Token); ``` Adding a new transport never touches Core. **There is no business logic in the facades to break.** Removing a transport is `rm facade.tpkg`. ### 3. Standards-bound flows that need a browser still get one — only those The only OAuth interaction that fundamentally requires a browser is the **authorization-code redirect** (and its sibling, the device-code verification URL). Every other endpoint — `token`, `refresh_token`, `introspect`, `revoke`, `userinfo`, `device_code` request, management API, MFA verify, SCIM — is transport-neutral: it works over gRPC or a direct call today, and a message-bus facade (planned, see the [Roadmap](#roadmap-excerpt)) would need no change in Core. | Flow / endpoint | Needs HTTP + browser | Works on any transport | |---|---|---| | `client_credentials` (M2M) | — | yes | | `authorization_code` — redirect to `/authorize` | yes | — | | `authorization_code` — `code → token` exchange | — | yes | | `refresh_token`, `revoke`, `introspect`, `userinfo` | — | yes | | `device_code` — initial request | — | yes | | `device_code` — user verification URL | yes | — | | Management API, SCIM 2.0, audit query | — | yes | --- ## Architecture ### Engine and facade contexts, hosted in one Tsak worker The gRPC and WS-Trust facades (`identity.grpc`, `identity.soap`) sit next to `identity.http` the same way; the `identity.contracts` carrier holds the shared DTO assembly. ``` ┌───────────────────────────────────────────────────────────────────────────────┐ │ Tsak worker │ │ │ │ ┌─────────────────────────────────────────────────────────────────────────┐ │ │ │ RouteContext "identity.core" ← redb.Identity.Core.Module.tpkg │ │ │ │ ────────────────────────────────────────────────────────────────────── │ │ │ │ • IdentityCoreRouteBuilder — ~50 direct-vm:// routes │ │ │ │ • OpenIddict server pipeline (token, authorize, userinfo, ...) │ │ │ │ • redb stores: Users, Apps, Scopes, Tokens, Sessions, Audit, ... │ │ │ │ • DataProtection key-ring in redb (RedbXmlRepository) │ │ │ │ • Signing keys (PropsSigningKeyStore — RSA 2048, encrypted) │ │ │ │ • MFA: TOTP / SMS-Email OTP / WebAuthn / Recovery codes │ │ │ │ • Cleanup timers (.Cluster(true) → leader-only in a cluster): │ │ │ │ identity-token-cleanup / -session-cleanup │ │ │ │ identity-mfa-otp-cleanup / -revoked-sids-cleanup │ │ │ │ identity-mfa-webauthn-challenge-cleanup │ │ │ │ • XML key-ring refresh (NOT cluster-gated — every replica refreshes) │ │ │ └─────────────────────────────────────────────────────────────────────────┘ │ │ ▲ │ │ direct-vm:// (synchronous, in-process, cross-context) │ │ │ │ │ ┌─────────────────────────────────────────────────────────────────────────┐ │ │ │ RouteContext "identity.http" ← redb.Identity.Http.tpkg │ │ │ │ ────────────────────────────────────────────────────────────────────── │ │ │ │ • Kestrel listener → redb.Route.Http → RedbController dispatcher │ │ │ │ • Controllers: ApplicationsController, UsersController, MfaController, │ │ │ │ SessionsController, RevokedSidsController, ScimUsers, │ │ │ │ MeProfileController, MePasswordController, ... │ │ │ │ • OIDC paths: /connect/token, /authorize, /userinfo, /introspect, ... │ │ │ │ • Management API: /api/v1/identity/* (identity:manage scope) │ │ │ │ • Self-service: /me/* (identity:account scope) │ │ │ │ • SCIM 2.0: /scim/v2/Users, /Groups, /Bulk │ │ │ │ • Cross-context brokers: CORS check, post-logout validate, MFA state │ │ │ └─────────────────────────────────────────────────────────────────────────┘ │ │ │ │ ┌─────────────────────────────────────────────────────────────────────────┐ │ │ │ Other Tsak modules (your code) │ │ │ │ ────────────────────────────────────────────────────────────────────── │ │ │ │ • Call IdentityEndpoints.Token / .Userinfo / .ManageUsers / ... │ │ │ │ via direct-vm:// directly — no HTTP needed │ │ │ └─────────────────────────────────────────────────────────────────────────┘ │ └───────────────────────────────────────────────────────────────────────────────┘ │ ▼ ┌────────────────────────────────────┐ │ redb store (Postgres / MSSQL / SQLite)│ │ - Users, Groups, Apps │ │ - Tokens, Authorizations │ │ - Sessions, MFA, Federation │ │ - DataProtection keys, JWKS │ │ - Audit trail │ │ - Idempotency cache │ └───────────────────────────────┘ ``` ### Project-reference isolation ``` redb.Identity.Http ─project-ref→ redb.Identity.Contracts allowed redb.Identity.Http ─project-ref→ redb.Identity.DataProtection allowed redb.Identity.Http ─project-ref→ redb.Identity.Core FORBIDDEN ``` The HTTP facade compiles **without seeing a single type from Identity.Core**. It only sees: - Wire DTOs and endpoint constants (`redb.Identity.Contracts`) - The shared XML key repository (`redb.Identity.DataProtection`) - A few SPI interfaces (`IMfaStateInspector`, `IRegisteredClientOriginRegistry`, `IIdentityClient`) This is what makes the `.tpkg` story honest: the two packages are independently buildable, independently versionable, and Core's internal types never leak across the ABI boundary. CI fails the build if a `using redb.Identity.Core;` shows up anywhere under `redb.Identity.Http/`. ### Anatomy of a token request — three transports, one pipeline ``` ┌────────────────────────────────────────────────────────────────────────────┐ │ Caller │ ├────────────────────────────────────────────────────────────────────────────┤ │ Browser: POST /connect/token (form-encoded) │ │ In-proc: exchange.To("direct-vm://identity-token") │ │ gRPC: client.Token(request) — same direct-vm under the hood │ └────────────────────────────────────────────────────────────────────────────┘ │ ▼ ┌────────────────────────────────────────────────────────────────────────────┐ │ Transport facade (only for non-direct-vm callers) │ │ HTTP: HeaderBridge → CorsCheck → AuthScope → To("direct-vm://identity…") │ └────────────────────────────────────────────────────────────────────────────┘ │ ▼ ┌────────────────────────────────────────────────────────────────────────────┐ │ IdentityCoreRouteBuilder.tokenRoute (RouteId: identity-token) │ │ │ │ WithRedbTx(...) ← atomic write boundary │ │ .Process(trustedProxy) ← sanitize X-Forwarded-For │ │ .Process(perIpThrottle) ← per-IP rate limit (optional) │ │ .OnException ← RFC 6749 error mapping │ │ .Throttle(clientId, ...) ← per-client token bucket │ │ .Traced("identity.token-request") │ │ .Metered(..., │ │ new TokenEndpointProcessor(handler, timeProvider)) │ │ ↑ │ │ OpenIddict server pipeline │ │ ↑ │ │ redb stores (RedbTokenStore, RedbApplicationStore, ...) │ │ .EndTraced() │ │ .WireTap("direct-vm://identity-events") ← audit + outbox (targets) │ └────────────────────────────────────────────────────────────────────────────┘ │ ▼ { access_token, refresh_token, expires_in, ... } ``` The same `TokenEndpointProcessor` runs whether the call came in over HTTP, gRPC, or a direct-vm call from the next module. **One pipeline, one set of tests, one audit trail.** --- ## Project structure ``` redb.Identity/ ├── src/ │ ├── redb.Identity.Core/ OAuth 2.1 / OIDC engine — OpenIddict + processors │ │ + redb stores + MFA + WebAuthn + federation │ │ + DataProtection + signing-key store │ │ (~50 direct-vm:// route registrations) │ ├── redb.Identity.Core.Module/ Thin Tsak entry point (InitRoute.main), │ │ lifecycle listeners, child SP build │ ├── redb.Identity.Contracts/ Wire DTOs (System.Text.Json only), │ │ endpoint URIs, route IDs, feature flags │ ├── redb.Identity.Management/ Transport-neutral management + self-service │ │ controllers over direct-vm://identity-manage-*, │ │ shared by the Http and Grpc facades │ ├── redb.Identity.Http/ HTTP facade — Kestrel + RedbControllers, │ │ project-ref-isolated from Core │ ├── redb.Identity.Grpc/ gRPC facade — the service-to-service subset │ │ (token, introspect, revoke, userinfo, │ │ discovery, jwks) over the same direct-vm │ │ routes; contract in Contracts/Protos │ ├── redb.Identity.Soap/ WS-Trust facade — Issue / Validate / Cancel / │ │ Renew over SOAP on the same core routes │ ├── redb.Identity.DataProtection/ RedbXmlRepository — ASP.NET DP keys in redb │ ├── redb.Identity.Resource.Dpop/ RFC 9449 DPoP resource-server validation │ ├── redb.Identity.Ldap/ LDAP external provider + sync (optional) │ ├── redb.Identity.Client/ Typed C# SDK — IIdentityClient, partial classes │ │ per area (Users, Apps, MFA, SCIM, Audit, …) │ └── redb.Identity.Web/ Reference BFF + Blazor admin UI │ (only refs Contracts + Client — HARDLINE) ├── tests/ Same suite on PostgreSQL · MSSQL · SQLite │ ├── redb.Identity.Tests/ Unit + integration (multi-provider harness) │ ├── redb.Identity.Client.Tests/ SDK transport contract tests │ └── redb.Identity.Web.Tests/ BFF smoke acceptance ├── demos/ Live-server RFC-conformance probes + run_all.ps1 ├── scripts/ │ └── pack-tpkg.ps1 Build + pack the .tpkg modules into a Tsak worker's modules/ ├── context.sample.json Annotated configuration for every Identity context ├── README.md This file ├── DEPLOYMENT.md, HTTPS.md Images, archives, ports, secrets; TLS ├── UPGRADING.md, CHANGELOG.md Migration steps per version; changes ├── Directory.Build.props └── Directory.Packages.props Central package versions (projects name no version) ``` --- ## Endpoint catalogue Every protocol endpoint (`/connect/*`) is *also* registered on `direct-vm://identity-*` for zero-network in-process calls — see [IdentityEndpoints.cs](src/redb.Identity.Contracts/Routes/IdentityEndpoints.cs). ### OAuth 2.1 / OIDC protocol surface (`/connect/*`, `/.well-known/*`) Wired in [HttpFacadeRouteBuilder.cs](src/redb.Identity.Http/HttpFacadeRouteBuilder.cs). | Path | Method | Auth | Purpose | |---|---|---|---| | `/connect/token` | POST | client authentication; grants `authorization_code` / `client_credentials` / `password` / `refresh_token` / `device_code` / token exchange (opt-in) | OAuth 2.1 token endpoint | | `/connect/authorize` | GET, POST | session cookie | Authorization endpoint (browser redirect); validates `resource` (RFC 8707) | | `/connect/par` | POST | `client_credentials` | Pushed Authorization Request (RFC 9126); validates `resource` | | `/connect/userinfo` | GET, POST | Bearer | OpenID Connect userinfo | | `/connect/introspect` | POST | `client_credentials` | RFC 7662 token introspection | | `/connect/revocation` | POST | `client_credentials` | RFC 7009 token revocation | | `/connect/logout` | GET, POST | session cookie (optional) | OIDC RP-Initiated Logout | | `/connect/register` | POST | Bearer (optional) | RFC 7591 Dynamic Client Registration | | `/connect/register/{client_id}` | GET, PUT, DELETE | Bearer | RFC 7592 DCR Management | | `/connect/deviceauthorization` | POST | `client_credentials` | RFC 8628 Device Authorization | | `/connect/device/verify` | POST | anonymous | RFC 8628 §3.3 end-user verification | | `/.well-known/openid-configuration` | GET | anonymous | OIDC Discovery 1.0 | | `/.well-known/oauth-authorization-server` | GET | anonymous | RFC 8414 metadata | | `/.well-known/jwks` | GET | anonymous | JSON Web Key Set | ### Admin REST (`/api/v1/identity/*`) — requires Bearer + `identity:manage` scope | Path | Method | Purpose | Source | |---|---|---|---| | `/applications` (+ `/{id}/rotate-secret`) | GET/POST/PUT/DELETE | OAuth client CRUD + secret rotation | [ApplicationsController.cs](src/redb.Identity.Management/Controllers/ApplicationsController.cs) | | `/users` (+ `/search`, `/{id}/change-password`) | GET/POST/PUT/DELETE | User management | [UsersController.cs](src/redb.Identity.Management/Controllers/UsersController.cs) | | `/groups` (+ `/{id}/children`, `/members`, `/move`) | GET/POST/PUT/DELETE | Hierarchical groups & membership | [GroupsController.cs](src/redb.Identity.Management/Controllers/GroupsController.cs) | | `/scopes` | GET/POST/PUT/DELETE | OAuth scope catalogue | [ScopesController.cs](src/redb.Identity.Management/Controllers/ScopesController.cs) | | `/claim-mappers` | GET/POST/PUT/DELETE | Declarative claim mapping rules | [ClaimMappersController.cs](src/redb.Identity.Management/Controllers/ClaimMappersController.cs) | | `/claim-scopes` (+ `/assignments`) | GET/POST/PUT/DELETE | Reusable Client Scope bundles + per-app assignment | [ClaimScopesController.cs](src/redb.Identity.Management/Controllers/ClaimScopesController.cs) | | `/audit` | GET | Audit log query | [AuditController.cs](src/redb.Identity.Management/Controllers/AuditController.cs) | | `/tokens` | GET/POST/DELETE | Token lifecycle management; the type filter accepts the short and the URI form (`refresh_token`, `urn:ietf:params:oauth:token-type:refresh_token`) | [TokensController.cs](src/redb.Identity.Management/Controllers/TokensController.cs) | | `/consents` | GET/DELETE | User-consent admin | [ConsentsController.cs](src/redb.Identity.Management/Controllers/ConsentsController.cs) | | `/sessions` | GET/POST/DELETE | Admin session control | [SessionsController.cs](src/redb.Identity.Management/Controllers/SessionsController.cs) | | `/mfa` | GET/POST/DELETE | Admin MFA lifecycle | [MfaController.cs](src/redb.Identity.Management/Controllers/MfaController.cs) | | `/federation-providers` | GET/POST/PUT/DELETE | External IdP CRUD (redb-stored) | [FederationProvidersController.cs](src/redb.Identity.Management/Controllers/FederationProvidersController.cs) | | `/revoked-sids` | GET/POST | Backchannel revoked-SIDs delta feed | [RevokedSidsController.cs](src/redb.Identity.Management/Controllers/RevokedSidsController.cs) | ### Self-service (`/me/*`) — requires Bearer + `identity:account` scope `RequireSelfOrAdminProcessor` guards every `/me/*` route: a token with `identity:account` can never mutate another user's data. | Path | Method | Purpose | Source | |---|---|---|---| | `/me` | GET, PUT | Profile read/update | [MeController.cs](src/redb.Identity.Management/Controllers/MeController.cs) | | `/me/password` | PUT | Self-service password change | [MePasswordController.cs](src/redb.Identity.Management/Controllers/MePasswordController.cs) | | `/me/sessions` | GET, DELETE | List/revoke own sessions (SSO) | [MeSessionsController.cs](src/redb.Identity.Management/Controllers/MeSessionsController.cs) | | `/me/mfa` | GET/POST/DELETE | Self-service MFA enroll/disable | [MeMfaController.cs](src/redb.Identity.Management/Controllers/MeMfaController.cs) | | `/me/webauthn` | GET/POST/PATCH/DELETE | WebAuthn credentials (FIDO2) | [MeWebAuthnController.cs](src/redb.Identity.Management/Controllers/MeWebAuthnController.cs) | | `/me/consents` | GET, DELETE | Consent dashboard | [MeConsentsController.cs](src/redb.Identity.Management/Controllers/MeConsentsController.cs) | | `/me/federated-identities` | GET/POST/DELETE | Link/unlink external IdP accounts | [MeFederatedIdentitiesController.cs](src/redb.Identity.Management/Controllers/MeFederatedIdentitiesController.cs) | ### gRPC (`identity.v1.Identity`) A second transport over the same `direct-vm://identity-*` routes, for services rather than browsers. Contract: [identity.v1.proto](src/redb.Identity.Contracts/Protos/identity.v1.proto); usage: [redb.Identity.Grpc/README.md](src/redb.Identity.Grpc/README.md). | Method | Auth | Purpose | |---|---|---| | `/identity.v1.Identity/Token` | client credentials, fields or `authorization: Basic` | RFC 6749 §3.2 | | `/identity.v1.Identity/Introspect` | client credentials | RFC 7662 | | `/identity.v1.Identity/Revoke` | client credentials | RFC 7009 | | `/identity.v1.Identity/UserInfo` | `authorization: Bearer` | OIDC Core §5.3 | | `/identity.v1.Identity/Discovery`, `/Jwks` | anonymous | documents, passed through verbatim | | `/redb.route.grpc.RedbService/Process` | as above | envelope fallback: JSON body + `operation` metadata | | `/grpc.health.v1.Health/Check` | anonymous | k8s / Consul / Envoy probe | Browser flows (`authorize`, login, consent, MFA pages, device verification) and DPoP stay on HTTP by construction: the former need a browser, redirects and a cookie session; RFC 9449 binds a DPoP proof to an HTTP method and URL. Management operations are not on this transport yet. ### SCIM 2.0 (`/scim/v2/*`) | Path | Method | Auth | Purpose | |---|---|---|---| | `/Users` | GET/POST/PUT/PATCH/DELETE | Bearer + `scim` scope | RFC 7644 §3.2–3.5 | | `/Groups` | GET/POST/PUT/PATCH/DELETE | Bearer + `scim` scope | RFC 7644 §3.2–3.5 | | `/Bulk` | POST | Bearer + `scim` scope | RFC 7644 §3.7 | | `/ServiceProviderConfig`, `/ResourceTypes`, `/Schemas` | GET | anonymous | RFC 7643 §5 discovery | ### BFF / convenience (`redb.Identity.Web`) | Path | Method | Purpose | |---|---|---| | `/api/auth/login` | POST | Form-based browser login over BFF | | `/api/auth/logout` | POST | BFF logout | | `/account/login` | GET | Back-compat redirect to `/login` | | `/health` | GET | BFF liveness probe | --- ## Standards compliance RFC compliance is verified by integration tests (`tests/redb.Identity.Tests/`) — every spec below is wired in code, not aspirational. Section references and §-citations live next to the matching assertions. **42 RFCs are cited by number in `src/`, 46 counting `tests/`**; the tables below are exhaustive. ### OAuth 2.x core | RFC | Spec | Coverage | |---|---|---| | **6749** | OAuth 2.0 Authorization Framework | Authorization Code, Client Credentials, Refresh Token, Resource Owner Password Credentials (§4.3, opt-in). RFC 6749 §5.2 error mapping (`invalid_request`/`invalid_grant`/`unsupported_grant_type` → correct HTTP status), §10.5 single-use authorization code (atomic consume), §10.12-style one-time `jti` enforcement. | | **6750** | Bearer Token Usage | `Authorization: Bearer …`. Query-parameter transport (§2.3) explicitly rejected by management API. | | **7009** | Token Revocation | Always 200 (§2.1), idempotent re-revocation, refresh-token rotation. | | **7591** | Dynamic Client Registration | `POST /connect/register`, optional initial access token (§1.2). | | **7592** | DCR Management Protocol | `GET/PUT/DELETE /connect/register/{client_id}` with `registration_access_token`. | | **7521 / 7523** | Assertion Framework + JWT Bearer client authentication | `private_key_jwt` — DCR accepts `token_endpoint_auth_method=private_key_jwt` with inline `jwks` or a `jwks_uri` (see "Client keys at `jwks_uri`" below); `/connect/token` + `/connect/introspect` authenticate via an RS256-signed client assertion (RFC 7521 §4.2 / RFC 7523 §2.2); advertised in discovery `token_endpoint_auth_methods_supported`. Assertions follow draft-ietf-oauth-rfc7523bis: `typ` header `client-authentication+jwt` and the issuer as `aud`, for every endpoint ([UPGRADING.md](UPGRADING.md#client-assertions-private_key_jwt-client_secret_jwt)). Tampered signature → 401 `invalid_client`. Pinned by `demo_private_key_jwt`. | | **7636** | PKCE | `S256` mandated; `plain` rejected per OAuth 2.1 / RFC 7636 §4.2. | | **7662** | Token Introspection | Answers only a client the token concerns: one in its `aud` or the client it was issued to; any other caller gets `active: false` (§2.2). A resource server is put into the audience through the `Resources` of the scopes its callers request. | | **8252** | OAuth 2.0 for Native Apps (BCP 212) | Private-use URI scheme redirect (§7.1); loopback IP redirect (§7.3) on `127.0.0.1` / `[::1]` with any port (`AllowLoopbackRedirectPortWildcard`, on by default); `application_type=native` and `token_endpoint_auth_method=none` accepted by DCR (`Register_NativeApp_SetsApplicationType`). | | **8414** | Authorization Server Metadata | `/.well-known/oauth-authorization-server` (separate from OIDC Discovery, for non-OIDC clients) — verified by `DiscoveryD1ConformanceTests`. | | **8628** | Device Authorization Grant | `/connect/deviceauthorization`, `/connect/device/verify`, configurable `expires_in` / `interval` (§3.2). | | **8693** | Token Exchange (opt-in) | `grant_type=urn:ietf:params:oauth:grant-type:token-exchange` on OpenIddict's built-in grant, switched on by `EnableTokenExchange`; delegation + impersonation. Subject and actor tokens are access tokens; a token bound to a presenter can be exchanged only by that client, and a token of a disabled or deleted user is refused with `invalid_grant`. | | **8707** | Resource Indicators | `resource` on `/connect/authorize`, `/connect/par` and token exchange: an absolute URI listed in a scope's `Resources`, with the client's `rsrc:` permission, otherwise `invalid_target` ([UPGRADING.md](UPGRADING.md#resource-parameter)). The access-token `aud` is composed from the same model (see RFC 9068). | | **9068** | JWT Profile for OAuth 2.0 Access Tokens | `typ: at+jwt` header (OpenIddict's default for access tokens; id_tokens stay `JWT`, internal tokens carry private `oi_*+jwt` types, so token-type confusion is structurally impossible). Required claims `iss`/`exp`/`aud`/`sub`/`client_id`/`iat`/`jti` plus `auth_time`/`acr`/`amr`, `scope`, and `roles`/`groups` under the §2.2.3 SCIM names. `aud` (§2.2/§3) is composed by `AttachAccessTokenResources`: Resources of the granted scopes ∪ the application's `AccessTokenAudiences`, the OP's own audience for `identity:*` scopes, `{issuer}/resources` (or `DefaultAccessTokenAudience`) as the default resource indicator, plus the requesting `client_id` (so the issuing client may introspect its own token — OpenIddict admits only audience members to introspection). The local validation stack behind the management API verifies `aud` (§4) — a token minted for another API is refused with 401. Pinned by `FullStackAccessTokenAudienceTests`. Note: with the default access-token encryption on, external resource servers see a JWE — set `DisableAccessTokenEncryption` for third-party RFC 9068 validation. | | **9101** | JAR — JWT-Secured Authorization Request | `/connect/authorize` accepts a signed `request` object, resolves the client's keys, verifies the signature and takes the parameters from inside the JWT with §6.1 precedence (inner values win; outer values not repeated inside are dropped). `ValidateRequestObjectHandler` **replaces** OpenIddict's built-in `ValidateRequestParameter` / `ValidateRequestUriParameter`, which reject both unconditionally. Opt-in via `Features.EnableJar` (default `false` → `request_not_supported`, byte-identical to releases before the flag existed); `request_uri` fetching is a second switch (`Jar.EnableRequestUri`) behind `OutboundUrlGuard`, and an address is fetched only when it equals one of the client's registered `request_uris` (exact match, fragment included; `Jar.RequireRequestUriRegistration`, default `true`, published as `require_request_uri_registration`), while PAR-issued `urn:ietf:params:oauth:request_uri:` values stay with OpenIddict. Unsigned `alg:none` objects are refused with the flag on or off. Discovery advertises `request_parameter_supported` / `request_uri_parameter_supported` / `request_object_signing_alg_values_supported` only while the flag is on — the server never announces a mode it will not serve. Signing-algorithm mismatch against the client's registered hint is `LogOnly` or `Enforce`. Pinned by `ValidateRequestObjectHandlerTests`. | | **9126** | Pushed Authorization Requests (PAR) | `POST /connect/par`, configurable `Require PAR`, `request_uri` lifetime (§2.2). | | **9449** | DPoP — Demonstrating Proof-of-Possession | Issuance binding (`cnf.jkt`) + `DPoP-Nonce` (§8) with HMAC-signed stateless nonces + resource-server validator (`redb.Identity.Resource.Dpop`). Per-`jkt` replay store (`DpopConsumedJtiProps`). A resource server of your own that validates these tokens with OpenIddict.Validation 7 must skip its proof-of-possession check for `cnf.jkt` and verify the DPoP proof itself ([UPGRADING.md](UPGRADING.md#dpop-bound-access-tokens-at-third-party-resource-servers)). | **Client keys at `jwks_uri`.** A client publishes its public keys either inline (`jwks`) or at an address (`jwks_uri`), never both; dynamic registration accepts either for every auth method, and an inline set, when stored, is the only source. Keys at `jwks_uri` verify the client's `private_key_jwt` assertions at the token and introspection endpoints and its JAR request objects. The set is fetched through `OutboundUrlGuard` before every fetch and cached for `Identity:ClientKeys:CacheLifetime` (12 hours by default). At most one fetch per address starts per `Identity:ClientKeys:MinimumRefreshInterval` (5 minutes by default), whether the cache expired, an assertion named an unknown `kid` (a client rotated its keys) or the last fetch failed; concurrent requests share it, and it ends after `ClientKeys:FetchTimeout`. Redirects are not followed. A failed fetch, or a set without usable signing keys, keeps the last good set; with none, the client is refused with `invalid_client`. At most `ClientKeys:MaxCachedKeySets` addresses (256 by default) are cached at once; expired entries go first, then the least recently used. ### OpenID Connect | Spec | Coverage | |---|---| | **OIDC Core 1.0** | Authorization Code + PKCE, ID Token (RS256), Userinfo, claim mappers, `prompt=login\|consent\|none`, `max_age`, `acr_values`. | | **OIDC Discovery 1.0** | `/.well-known/openid-configuration` — verified by `DiscoveryD1ConformanceTests` against §3 + RFC 8414 §2. | | **OIDC RP-Initiated Logout 1.0** | `/connect/logout` with `post_logout_redirect_uri` allow-list. | | **OIDC Backchannel Logout 1.0 / RFC 8417** | SET event sink (`BackchannelLogoutEndpoint`), push to RPs **plus** pull-based revoked-SID list (`/revoked-sids/add` + `/revoked-sids/since?cursor=`) for multi-replica RPs — survives lost RP nodes and partitions. The push goes only to an address the outbound URL guard accepts (`https`, public), checked at registration and before every POST; `Identity:BackchannelLogout:RequireHttps` and `:AllowPrivateNetworkTargets` relax it for RPs on an internal network. | | **OIDC Form Post Response Mode** | `response_mode=form_post`. | ### OpenID conformance — tested against the official OIDF suite redb.Identity is exercised against the **official OpenID Foundation conformance suite** — the same suite the OIDF uses to certify providers — over native HTTPS, with the Config OP and Basic OP plans. Running that suite (most .NET OAuth stacks never do) surfaced — and fixed — the exact RFC-precision points hand-rolled servers trip on: errors delivered via the *registered* `redirect_uri` only (RFC 6749 §4.1.2.1), `400 invalid_grant` on code reuse (§5.2), `Cache-Control: no-store` on token responses (§5.1), boolean `email_verified` (OIDC §5.1), session-id-keyed `prompt=login` / `max_age` re-authentication (§3.1.2.1), and id_token hygiene. Per-module breakdown: **[`OPENID_CERTIFICATION.md`](OPENID_CERTIFICATION.md)**. ### JOSE / JWT cryptography | RFC | Spec | Coverage | |---|---|---| | **7515** | JSON Web Signature | RS256 / ES256 issuance + validation. | | **7517** | JSON Web Key + JWKS | `/.well-known/jwks` — verified by `JwksHttpContractTests` (RFC 7517 §5 top-level `keys` array). | | **7518** | JSON Web Algorithms | Algorithm allow-list, asymmetric proofs only (matches RFC 9449 §4.2). | | **7519** | JSON Web Token | ID tokens, access tokens, DPoP proofs. | | **7638** | JWK Thumbprint | SHA-256 thumbprint, base64url-encoded — used as DPoP `jkt` per RFC 9449 §10 (`DpopProofValidator.ComputeJktAsync`, `DpopFullCycleTests`). | | **7800** | PoP Key Semantics for JWTs | `cnf` claim with `jkt` (DPoP proof-of-possession-bound access tokens — `AttachDpopConfirmationClaimHandler`). | | **8176** | Authentication Method Reference Values | `amr` claim values (`pwd`, `mfa`, `otp`, `face`, `fpt`, `hwk`, etc.) emitted by `IdentityPrincipalBuilder`, plus the standardised `mfa` marker per §2. | ### SCIM 2.0 (RFC 7643 / 7644) | Surface | Notes | |---|---| | `/scim/v2/Users` (CRUD + PATCH) | RFC 7644 §3 | | `/scim/v2/Groups` (CRUD + PATCH) | RFC 7644 §3 | | `/scim/v2/Bulk` | RFC 7644 §3.7, partial-success semantics | | `/scim/v2/ServiceProviderConfig`, `/Schemas`, `/ResourceTypes` | Unauthenticated per RFC 7643 §5 | | Attribute names | Verbatim per RFC 7643 §7 — `IdentityCodecProfilesTests` pins that no naming policy mangles them. | | Wire serialization | UTF-8 JSON per RFC 8259 §8.1; null attributes omitted per RFC 7644 §3.8. | ### MFA | RFC / Spec | Coverage | |---|---| | **4226** | HOTP — the basis for TOTP (20-byte HMAC-SHA1 key per §4). | | **6238** | TOTP — with atomic verification (`SELECT FOR UPDATE` + `FailedAttempts++`) and replay protection per §5.2 (a code from an already-accepted step is rejected even within skew). Pinned by `TotpReplayTests`. | | **WebAuthn Level 2 / FIDO2** | Registration + assertion (Fido2NetLib), consumed-challenge cleanup timer, per-credential admin. | | SMS / Email OTP, Recovery codes | One-shot, marked consumed in the same transaction as session creation. | ### Federation & directory | Spec | Coverage | |---|---| | **OIDC** external providers | Per-provider redb CRUD, `IdentityCookie` state binding. | | **GitHub OAuth** | First-class adapter on top of the federation provider. | | **LDAP** (binding) | Search + bind authentication. | | **RFC 4514** | LDAP DN string representation — CN extraction in `LdapGroupMapper`. | | **RFC 4515** | LDAP search filter escaping (`LdapExternalUserProviderTests`). | ### HTTP / transport hygiene | RFC | Coverage | |---|---| | **6265 / 6265bis** | `SameSite=Lax\|Strict\|None`; `__Host-` prefix only emitted when `Secure=true` per §4.1.3.2; empty-value cookie treated as delete directive per §5.2.2. Pinned by `CookieDefaultsTests` + `IdentityCookieFormatterTests`. | | **6585** | Additional HTTP Status Codes — `429 Too Many Requests` + `Retry-After` on rate-limited `/connect/token`, `/connect/par`, `/connect/register` (§4). Pinned by `demo_throttle_rfc6585`. | | **7230** | HTTP/1.1 Message Syntax — Bearer-header OWS tolerance (`ManagementBearerAuthProcessor`, `BearerParsingD6Tests`). | | **7231** | HTTP/1.1 Semantics — `Retry-After` delta-seconds format (§7.1.3) emitted by rate-limit responses (`RateLimitMetricsAndRetryAfterTests`). | | **7232** | HTTP Conditional Requests — `ETag` / `If-Match` → 412 on stale resource (SCIM, per RFC 7644 §3.14 + RFC 7232 §4.2 — `ScimEtagTests`). | | **7234** | HTTP Caching — `Cache-Control` on metadata endpoints (§5.2). | | **7235** | HTTP/1.1 Authentication — quoted-string escaping in `WWW-Authenticate` Bearer challenges (§2.1) on userinfo error responses. | | **7807 / 9457** | `application/problem+json` for HTTP error responses — surfaced by the SDK as `ApiException`. | | **8259** | UTF-8 JSON wire format — locked `JsonSerializerOptions` profiles in `Contracts`. | ### Cryptographic primitives & hardening (OWASP-aligned) | Primitive | Coverage | |---|---| | **Argon2id** | Password hashing — PHC string format with unpadded base64 per **RFC 7693 §3.5** (`Argon2idPasswordHasher`). | | **PBKDF2 / RFC 2898** | Secret derivation for MFA shared-secret encryption (`MfaService` via `Rfc2898DeriveBytes.Pbkdf2(SHA-256)`). | | Recovery codes | One-shot, pepper-encrypted, marked consumed in the same transaction as session creation. | | Brute-force defense | Per-IP rate limits, per-`(IP+user)` failure ceiling with security-channel logger. | | Trusted proxies | `X-Forwarded-For` sanitized BEFORE rate-limit / lockout sees it. | | **SSRF guard on outbound fetches** | `OutboundUrlGuard` refuses loopback, **RFC 1918** private ranges, link-local (including the `169.254.169.254` cloud metadata address) and **RFC 6598** CGNAT space. It gates every address a client can make the server contact: `jwks_uri` (`ClientKeyResolver`), JAR `request_uri` (`ValidateRequestObjectHandler`) and `backchannel_logout_uri` (`BackchannelLogoutDispatcher`). The connection itself goes only to an address the server's own lookup approved at connect time, and redirects are not followed. With an outbound proxy configured, the check by name before the request is the server's only check and the proxy's policy decides where the request ends. Private targets are reachable only by explicit opt-in (`ClientKeysOptions`), for single-network test hosts. Pinned by `OutboundUrlGuardTests`. | | Idempotency | Cache placed AFTER authorization — revoked tokens can't unlock cached responses. An answer that carries a one-time secret (a member marked `[OneTimeSecret]`) is recorded without its body; a repeat answers `{"replayed":true,"secretWithheld":true,...}`. Expired records are deleted by the timer route `identity-idempotency-cleanup` (`Identity:IdempotencyCleanupInterval`, hourly; `Identity:IdempotencyCleanupBatchSize`). | | Revoked access tokens | The management API, SCIM and the account endpoints check each access token against its stored entry, one read per request: a token revoked at `/connect/revocation`, or a token of a deleted client, is refused with `401` at once, not at its expiry. There is no setting for it. | | Self-vs-admin | `RequireSelfOrAdminProcessor` on every `/me/*` route. | | Constant-time comparisons | All secret comparisons. | | **Facade pages: framing, CSRF, consent binding** | Every response through the facade's serializer carries `X-Frame-Options: DENY`, `Content-Security-Policy: frame-ancestors 'none'`, `X-Content-Type-Options: nosniff`, `Referrer-Policy` — the same set the web console's `SecurityHeadersMiddleware` emits. Form POSTs (`/login`, `/consent`, `/mfa`, `/mfa/recovery`) refuse a foreign `Origin`/`Referer` with 403 before reading the body (`AntiForgeryProcessors`; origin-less callers — the console's BFF, demos, API clients — pass). The consent page renders only from a server-signed ticket (`/consent?ct=…`, minted by the authorize endpoint — app name and scopes never come from the URL, so a crafted link cannot dress an attacker's client in a familiar name), and the decision is bound to the session cookie: no session → 401, a ticket minted for another user → 403, the form carries no `user_id`. Pinned by `FullStackFacadeFormHardeningTests`. | ### Tally **42 RFCs cited by number in production code.** Reproduce with: ```sh grep -rhoE 'RFC[ -]?[0-9]{4}' --include=*.cs src | tr -d ' -' | sort -u ``` > 1918, 4226, 4514, 4515, 6238, 6265, 6598, 6749, 6750, 7009, 7230, 7234, 7235, 7515, 7517, 7519, 7521, 7523, 7591, 7592, 7636, 7638, 7643, 7644, 7662, 7693, 7800, 7807, 8176, 8252, 8259, 8414, 8417, 8628, 8693, 8705, 8707, 9068, 9101, 9126, 9449, 9457 **Four more are cited only from `tests/`** (46 across `src` + `tests`), because the RFC is what the assertion pins rather than something the production path names: > 5737 (TEST-NET-1 — unreachable-host LDAP resilience), 7231 (`Retry-After` delta-seconds format), 7232 (`ETag` / `If-Match` → 412 on SCIM), 7239 (`unknown` as a legal proxy identifier in `X-Forwarded-For` parsing). **Two are implemented without the number appearing as text**, so the `grep` above does not see them — the behaviour is real, the citation just lives elsewhere: - **RFC 2898** (PBKDF2) — used through the framework API, `Rfc2898DeriveBytes.Pbkdf2(SHA-256)` in `MfaService`, so the class name carries the number instead of a comment. - **RFC 6585** (`429 Too Many Requests`) — emitted by `RateLimitProcessor.EmitTooManyRequests` with a `Retry-After` header; the number is spelled out in the demo that pins it, `demo_throttle_rfc6585`. One entry in the list above is a **reference, not a feature**: RFC 8705 is named where Identity explains that OpenIddict's own proof-of-possession check knows only certificate-bound tokens (`x5t#S256`); mutual-TLS client authentication is not implemented, see *Not implemented yet* below. Additional standards referenced without an explicit RFC tag in the source: OIDC Core 1.0, OIDC Discovery 1.0, OIDC RP-Initiated Logout 1.0, OIDC Backchannel Logout 1.0, OIDC Form Post Response Mode, WebAuthn Level 2 / FIDO2, SCIM 2.0, OAuth 2.1 PKCE-required profile, RFC 7515 / 7518 / 7519 (transitively via OpenIddict / `Microsoft.IdentityModel.Tokens`). ### Not implemented yet None are blockers for the core IS profile; PRs welcome: - RFC 8705 — Mutual-TLS client authentication + certificate-bound access tokens - RFC 9207 — `iss` parameter in authorization response - RFC 9396 — RAR (Rich Authorization Requests) - RFC 9470 — Step-up Authentication Challenge - FAPI 2.0 profile, CIBA, OIDC Federation 1.0 --- ## Storage model — built on the REDB object engine > redb.Identity does not own a database schema. It is built on top of **[REDB](https://github.com/redbase-app/redb)** — the typed object / props storage engine that ships with this repo (`redb.Core`, `redb.Core.Pro`, `redb.Postgres`, `redb.Postgres.Pro`, `redb.MSSql`, `redb.MSSql.Pro`, `redb.SQLite`, `redb.SQLite.Pro`). This is the single biggest architectural difference vs every other .NET identity server. ### What this buys you over an EF-Core-on-tables identity server | Property | redb.Identity | Typical EF-Core identity server (IdentityServer/OpenIddict-EF/ASP.NET Identity) | |---|---|---| | **Storage engines** | Postgres, MSSQL **and** SQLite from one codebase — swap by changing the provider package the host loads | One provider per build; switching requires re-writing the EF model + migrations | | **Schema evolution** | No migrations. Add a property to a `*Props` class — the redb scheme picks it up at next `InitializeAsync` | Generate migration, review SQL, run `Update-Database`, hope rollback works | | **Custom claims / per-tenant extensions** | `Dictionary? CustomClaims` on `UserProps` — each key becomes a queryable, indexed props row | `jsonb`/`nvarchar(max)` blob; you write your own GIN / computed-column indexes | | **Multi-provider federation links** | `Dictionary` on User — native props rows, hot reverse-lookup via `value_string = "{provider}:{sub}"` | One-to-many join table, scaffolding per provider | | **Hot + cold attribute split** | Hot keys (login, password, status) stay in the relational `_users` table; cold OIDC profile lives in props rows linked by `RedbObject.key = _users._id`. No over-indexed wide rows, no JSON-blob lookups | Either everything in one wide table, or normalised into 8 satellite tables | | **Multi-tenant data isolation** | a named redb instance (`Identity:RedbInstanceName`; the images ship `identity-sqlite`, with `identity-pg` and `identity-mssql` predefined) that can target a separate database or the one of your business module | Single `DbContext`; isolation requires separate ASP.NET apps | | **Caching tier** | `Global*Cache` in `redb.Core` makes scheme + struct lookups O(1) in-process | Bring your own (`IDistributedCache` plumbing) | ### Provider matrix (zero code changes between rows) | Engine | Open-source package | Pro package | Notes | |---|---|---|---| | PostgreSQL 15+ | `redb.Postgres` | `redb.Postgres.Pro` | Battle-tested production target; `LISTEN/NOTIFY`-aware caches in Pro | | Microsoft SQL Server 2019+ | `redb.MSSql` | `redb.MSSql.Pro` | Full parity for OAuth / SCIM / MFA / WebAuthn; Service Broker hooks in Pro | | SQLite 3.44+ | `redb.SQLite` | `redb.SQLite.Pro` | Single-file / embedded target for dev, edge and small deployments; same schemes, same contracts | > Identity references only the `redb.Core` OSS abstraction — **the host worker picks the provider**, Identity code never names one. The **same** test suite runs on PostgreSQL, MSSQL **and** SQLite; a single `REDB_PROVIDER` env-var picks the engine. ### The 33 typed redb schemes that compose redb.Identity All defined via `[RedbScheme("identity.*")]` in [src/redb.Identity.Core/Models/](src/redb.Identity.Core/Models/) (+ DataProtection). The `identity.*` value is the scheme's alias; the database stores the scheme under the class's full name (`_schemes._name`, for example `redb.Identity.Core.Models.UserProps`), so SQL against `_schemes` uses that name. Enumerate them with: ```sh grep -rhoE '\[RedbScheme\("[^"]+"' --include=*.cs src | sed 's/.*("//; s/"$//' | sort ``` | Domain | Schemes | |---|---| | OAuth / OIDC core | `identity.application`, `identity.scope`, `identity.token`, `identity.authorization`, `identity.session`, `identity.idempotency_record` | | Users & groups | `identity.user`, `identity.group`, `identity.group_member`, `identity.password_history` | | Roles & assignments | `identity.role`, `identity.user_role_assignment`, `identity.group_role_assignment`, `identity.role_scope_assignment` | | Account-lifecycle tokens | `identity.password_reset_token`, `identity.email_verification_token`, `identity.change_email_token` | | MFA / WebAuthn | `identity.mfa`, `identity.mfa_otp`, `identity.webauthn_consumed_challenge` | | Federation | `identity.federation_provider`, `identity.federated_identity` | | Claims engine | `identity.claim_definition`, `identity.claim_mapper`, `identity.claim_scope`, `identity.claim_scope_assignment` | | DPoP / replay | `identity.dpop_consumed_jti` | | Webhooks | `identity.webhook_subscription` | | Cluster / cleanup | `identity.revoked_sid`, `identity.system_flag` | | Crypto / DP-keys | `identity.signing_key`, `identity.dp_key`, `identity.dp_key_import` (when the file key ring was moved into redb) | > **Audit is deliberately not one of them.** It used to be `identity.audit_event`, one props object per event. It now lives in a flat relational table, `identity_audit_log`, provisioned by `IdentityAuditLogTableInitListener`: an audit row is append-only, never queried by prop, and always read as a time-ordered range, so a multi-row props write bought nothing and cost a scan on every query. It is the one place where the object engine was the wrong shape, and saying so is more useful than pretending otherwise. ### What a "table" looks like — zero migrations, full IntelliSense ```csharp // src/redb.Identity.Core/Models/UserProps.cs [RedbScheme("identity.user")] public class UserProps { // Standard OIDC profile claims public string? GivenName { get; set; } public string? FamilyName { get; set; } public string? Picture { get; set; } public bool EmailVerified { get; set; } // Structured OIDC address (§5.1.1) — nested redb object, not JSON public AddressClaim? Address { get; set; } // Arbitrary tenant-specific claims — each pair becomes its own props row, // queryable and indexable without ALTER TABLE. public Dictionary? CustomClaims { get; set; } // Multi-provider federation links — native props rows, hot reverse lookup // uses RedbObject.value_string = "{providerId}:{sub}". public Dictionary? ExternalIdentities { get; set; } public string? ScimExternalId { get; set; } // RFC 7643 §3.1 } ``` To add a property to your User — a `LoyaltyTier`, a `ManagerSubject`, a `DepartmentCode` — you literally just add it to the class. No migration, no DBA call, no downtime. redb reads/writes it the next instant; once it's in production data, queries can filter and project it. ### Bootstrap & isolation - **Schema sync.** `IdentitySchemaInitListener` walks `[RedbScheme]`-marked types in loaded assemblies on `InitializeAsync()` and reconciles the redb scheme metadata. - **TOCTOU-safe unique indexes.** `IdentityUniqueIndexesInitListener` applies partial unique indexes that the cleanup races depend on (ClientId, ScopeName, MFA-per-user, idempotency keys, federated `{providerId}:{sub}`). - **Per-context isolation.** Identity always resolves a **named** redb instance (`Identity:RedbInstanceName`; `identity-sqlite` in the images, `identity-pg` and `identity-mssql` predefined) — it can coexist with other modules' redb usage in the same Tsak worker without sharing connections, transactions, or caches. A call into Identity from inside your own transaction therefore runs on a second connection: call Identity outside the transaction. Or, point it at a dedicated DB and your business data never sees an OAuth row. --- ## Cluster-readiness Identity is designed for N-replica deployments where leadership rotates without coordination across the runtime. | Concern | Mechanism | |---|---| | DataProtection key-ring across replicas | `RedbXmlRepository` — redb-persisted XML keys, registered as the ring's repository, so every node reads and writes the same ring. Every replica refreshes its in-memory snapshot every `XmlRepositoryRefreshInterval` (default 12 h, half of the 24 h DataProtection refresh of the active key). **Not** cluster-gated by design — every node must catch keys rotated by others. | | OAuth signing keys across replicas | `PropsSigningKeyStore` — RSA 2048 PEMs, DataProtection-encrypted at rest, bootstrapped under a distributed lock so only one replica generates the first key. Off by default (`UsePropsSigningKeyStore=false`); switch it on for multi-replica. | | Cleanup timers (tokens / sessions / MFA OTP / WebAuthn challenges / revoked SIDs) | Registered with `.Cluster(true)` — leader-only in a clustered Tsak deployment, silently ignored in standalone. Even without the marker, every cleanup uses `IBackgroundDeletionService` (claim pattern), so concurrent execution is safe — `.Cluster(true)` is belt-and-suspenders + log-noise reduction. | | MFA atomicity under concurrency | `SELECT FOR UPDATE` on the MFA row + `FailedAttempts++` inside the same transaction. TOTP replay window enforced per RFC 6238 §5.2. | | Backchannel logout across replicas | `/revoked-sids/add` writes the revocation; `/revoked-sids/since?cursor=` lets every RP replica pull deltas. Push-and-poll, not push-only — survives lost RP nodes and broken network partitions. | | OpenIddict per-request scoping | `RedbRouteOpenIddictServerHandler` captures `IServiceScopeFactory` and opens a fresh per-request scope — works correctly under .tpkg child SP isolation. | --- ## Observability First-class OpenTelemetry surface, structured security log, and Tsak-aggregated health probes — all wired in-tree, no extra package required. ### Metrics — meter `RedbIdentity` Consume from any OTel pipeline: ```csharp builder.Services.AddOpenTelemetry() .WithMetrics(m => m.AddMeter("RedbIdentity")); ``` Defined in [IdentityMetrics.cs](src/redb.Identity.Core/Metrics/IdentityMetrics.cs): | Instrument | Type | Tags | What it tells you | |---|---|---|---| | `identity.login.attempts` | Counter | — | Password login throughput | | `identity.login.failures` | Counter | `reason` | Bad-password / unknown-user / locked / mfa-required | | `identity.mfa.verifications` | Counter | `method`, `result` | TOTP / SMS / email / recovery code outcomes | | `identity.mfa.lockouts` | Counter | `method` | MFA brute-force lockouts triggered | | `identity.tokens.issued` | Counter | `grant_type`, `token_type` | Tokens minted by OpenIddict | | `identity.tokens.errors` | Counter | `error` | `invalid_grant`, `invalid_client`, `invalid_dpop_proof`, … | | `identity.rate_limit.rejections` | Counter | `endpoint`, `key_dimension` | Throttled requests (per-IP / per-client / per-user) | | `identity.password.verify.duration` | Histogram (ms) | `algorithm` | Hash-verify wall-clock (BCrypt / PBKDF2 / Argon2) — catches CPU regressions | | `identity.unique_violation` | Counter | `scheme`, `column` | DB unique-index hits (TOCTOU guard fired) | | `identity.audit.write_failures` | Counter | `event_type` | Audit events whose row could not be written; a gap in the audit trail | ### Security log channel All audit-grade events route through a dedicated logger category so SIEM can subscribe without sifting routine logs: - **Category:** `RedbIdentity.Security` - **Source:** [IdentitySecurityLog.cs](src/redb.Identity.Core/Security/IdentitySecurityLog.cs) - **Wired into:** `LoginService`, `MfaService`, `IdentityCoreRouteBuilder`, `BootstrapAdminProcessor`, rate-limit / RBAC rejections ### Health checks — module `identity` Surface under Tsak's aggregated `/api/health/{startup,live,ready}`. Defined in [IdentityHealthContributor.cs](src/redb.Identity.Core/Health/IdentityHealthContributor.cs). | Probe | Healthy when … | Failure semantics | |---|---|---| | `db` | `IRedbService.GetDbVersionAsync()` returns non-empty | Unhealthy — storage unreachable | | `signing-keys` | ≥ 1 signing credential registered with OpenIddict | Unhealthy — token issuance would fail | | `data-protection` | Active key-ring exposes ≥ 1 key | Degraded — cookies still work on bootstrap key | --- ## Security highlights | Surface | Defense | |---|---| | Token endpoint | Per-IP rate limit + per-`client_id` throttle (token bucket) + RFC 6749 error mapping | | Login endpoint | Per-IP rate limit + per-`(IP+username)` failure ceiling with security-channel logger | | Facade HTML forms | `X-Frame-Options: DENY` + `frame-ancestors 'none'` on every page (no clickjacking of the consent "Allow"); cross-site `Origin`/`Referer` on `/login`, `/consent`, `/mfa*` → 403; consent page renders only from a server-signed ticket and the decision is bound to the session cookie, never to a form field | | Reserved headers | Never trusted from the wire on any transport: `IdentityReservedInboundHeaders` (Contracts) names the internal-only headers (`session_*`, `reauth_marked_sid`, `client_id`, `client_secret`, `access_token`, `user_id`, `ip_address`, `user_agent`) and each facade — HTTP, gRPC (metadata and envelope headers), SOAP — strips them as its first step, so only the cookie / `Authorization` / Basic / body / path / transport can set them. A forged `session_user_id` cannot impersonate a user and a forged `ip_address`/`user_id`/`client_id` cannot sign the audit log. `operation` is stripped on HTTP only — the gRPC envelope route lets the caller name it by design | | Audit attribution | `client_id` comes from Basic **or** the form body, so form-authenticated and public PKCE clients are attributed too; a management or account call records the acting client in `client_id` and the token's subject (client id, or the user's public subject) in `actor_subject`; `ip_address` falls back to the transport's proxy-sanitized `redbHttp.RemoteAddress` and `user_agent` to the real `User-Agent`; on SQLite the `timestamp` column is `REAL` (Julian day), matching how the provider encodes `DateTimeOffset` | | Consent page | Renders and grants only from a server-signed consent ticket (`?ct=…`); app name and scopes come from the ticket, not the URL (no trusted-UI phishing), and the ticket is bound to the session user (no cross-session replay). Pinned by `FullStackFacadeFormHardeningTests` | | MFA verify | DB row-lock + `IdempotentConsumer` keyed by `(jti, code)` — defeats retransmit / captured-request replay | | Recovery codes | One-shot — marked consumed in the same transaction as session creation | | Role scopes | A scope attached to a role is an entitlement, never an addition: it reaches a token only when the client requests it and holds the `scp:` permission, and a gated scope (`AdminScopeEntitlement`: `identity:*`, `scim`, `GatedScopes`) stays only for users whose roles carry it. An administrator signing in to some other application gives it no management scope. Pinned by `RoleScopeAugmentationTests` | | Self vs admin | `RequireSelfOrAdminProcessor` on every `/me/*` route — a token with `identity:account` can never mutate another user's MFA, password, sessions, or consents | | Idempotency | Cache placed AFTER authorization so a revoked token cannot unlock cached responses; one-time secrets are never kept in it, and expired records are deleted hourly | | Trusted proxies | `TrustedProxyResolverProcessor` — `redbHttp.RemoteAddress` is sanitized BEFORE any rate-limit / lockout sees it | | Password history | Configurable depth, rejects reuse | | Federation | OIDC + GitHub, secrets server-side, never returned over the wire | | Audit | Flat `identity_audit_log` table + optional external targets (Kafka / Elasticsearch / RabbitMQ / log), sent through the delivery outbox with retries | | DPoP | RFC 9449 — issuance binding + resource-server `redb.Identity.Resource.Dpop` for downstream APIs | | Secrets | Never in `context.json` — only via Tsak override env-vars (`Tsak__Contexts__identity.core__Override__Identity__*`) | --- ## Audit event catalogue **109 typed audit events across 7 categories** — single source of truth in [IdentityAuditEventIds.cs](src/redb.Identity.Contracts/Routes/IdentityAuditEventIds.cs), with `IdentityAuditCategories.CategoryOf(eventType)` as the one mapping from event to bucket. Every event lands in the flat `identity_audit_log` table (see the storage section — audit is the one part of Identity that is deliberately relational, not props) and, if configured, goes through the delivery outbox to Kafka / Elasticsearch / RabbitMQ / log (see Audit targets below). Plaintext secrets are never persisted to audit — rotations log a `ClientSecretRotated` marker only. | Category | Count | Examples | |---|---:|---| | `authentication` | 14 | `UserLoggedIn`, `UserLoggedOut`, `LoginFailed`, `PasswordChanged`, the password-reset chain (`Requested` / `TokenIssued` / `Completed` / `Failed`), email verification (`Sent` / `Completed` / `Failed`), email change (`Requested` / `Completed` / `Failed`) | | `authorization` | 14 | `TokenIssued`, `TokenRevoked`, `TokenIntrospected`, `AuthorizationGranted`, `ConsentGranted` / `Revoked` / `AllConsentsRevoked`, `DeviceCodeIssued` / `Verified` / `Denied`, `ParRequestAccepted` / `Rejected`, `DpopBindingApplied`, `DpopReplayDetected` | | `admin` | 42 | `ClientRegistered` / `Updated` / `Deleted` / `SecretRotated`, `Scope*`, `ClaimMapper*`, `ClaimScope*` (+ `Assigned` / `Unassigned`), `User*`, `Group*` (+ `Moved`), `Member*`, the role registry (`RoleCreated` / `Updated` / `Deleted`, `RoleAssignedUser` / `Group`, `RoleScopeAttached` / `Detached`) and webhook subscriptions (`Created` / `Updated` / `Deleted` / `SecretRotated`) | | `federation` | 9 | `FederationChallengeInitiated`, `FederationStateValidationFailed`, `FederatedUserLoggedIn`, `FederatedIdentityLinked` / `Unlinked`, `FederatedEmailConflict`, `FederationProvider*` | | `mfa` | 10 | `MfaEnrolled`, `MfaDisabled`, `MfaChallengeIssued`, `MfaVerifyFailed`, `MfaRecoveryCodeUsed` / `CodesDownloaded`, `MfaWebAuthnRegistered` / `Asserted` / `Revoked` / `SignCounterAnomaly` | | `scim` | 9 | `ScimUserCreated` / `Replaced` / `Patched` / `Deleted`, `ScimGroupCreated` / `Replaced` / `Patched` / `Deleted`, `ScimBulkProcessed` | | `system` | 13 | `SessionRevoked` / `AllSessionsRevoked` / `SessionsPruned`, `SidRevoked` / `RevokedSidsPruned`, `MfaOtpPruned`, `IdempotencyRecordsPruned`, `TokenCleanupRan` / `TokensPruned`, `TokensRevokedByUser`, plus the dry-run markers `AllSessionsRevocationPreviewed` / `TokensPrunePreviewed` / `IdempotencyRecordsPrunePreviewed` | ### Webhook delivery Every event goes to the webhook subscriptions that match it through an outbox table, `identity_delivery_outbox`, which a delivery worker reads (the timer route `identity-webhook-delivery`, leader-only under a Tsak cluster; each row is also leased by the database clock, so several nodes never send one row at the same time). - **At least once.** An event reaches the outbox after the request that caused it has committed, in the same pass that writes its audit row; the rare event lost when the process stops between the two has neither an audit row nor a delivery. A delivery whose success was not recorded (the node stopped between the answer and the status update) is sent again. Every attempt of one delivery carries the same `X-RedbIdentity-Delivery` id, and the body is the event with its `eventId`: a receiver deduplicates by either. Nothing here is exactly-once. - **No order.** Retries and parallel sending mean two events for one subscriber may arrive in either order. Order by the event's `timestamp`, not by arrival. - **Retries and timeout per subscription:** `timeoutMs` bounds each attempt, `maxAttempts` and `retryBackoffMs` (doubling, at most 30 s between attempts) decide the retries; after the last one the row is `failed`. A subscription deleted or disabled before its delivery is not sent to; its row ends `cancelled` and stays so: enabling the subscription again later does not send it (only events after that). - **Signature:** `X-RedbIdentity-Signature: sha256=`, computed when the request is sent, with the subscription's secret at that moment. No secret is stored in the outbox. - **Polling:** the worker looks for due rows every `Identity:Delivery:PollInterval` (default 2 s) and reads at most `BatchSize` (default 50) per pass; a claimed row stays reserved to its node for `Lease` (default 60 s, raised to a subscription's timeout plus a margin when that is longer). - **Fairness:** `Identity:Delivery:MaxParallel` (default 8) requests at once per node, at most `MaxParallelPerDestination` (default 2) of them to one subscriber, so one that hangs does not hold up the others. - **Cost:** an event no subscription wants writes nothing; the list of enabled subscriptions is cached for `Identity:Delivery:SubscriptionCache` (default 30 s; a change through the management API applies at once on the node that made it). Meter `RedbIdentity`: `identity.delivery.attempts` (tags `kind`, `result`) and `identity.delivery.enqueue_failures` (tags `event_type`, `kind`). ### Audit targets The external audit targets of `Identity:Audit:Targets` (Kafka, Elasticsearch, RabbitMQ, an SQL table, a log) get their events through the same outbox and worker, one row per event and enabled target, with `kind` `audit` and the target's `Name` as the destination. A target that is down or slow therefore holds up nothing and loses nothing: its rows wait and are retried while the events route goes on. The same rules as for webhooks apply: at least once (a consumer deduplicates by `eventId`, or by the `event_id` header in an SQL target with a unique key on it), no order, and the fairness limits per target. - Every enabled target needs a `Name`, unique among them (at most 200 characters); the start stops otherwise. - Per target: `TimeoutMs` (default 10000) bounds an attempt, `MaxAttempts` (default 10) and `RetryBackoffMs` (default 1000, doubling, at most 60 s between attempts) decide the retries; after the last one the row is `failed`. - A target removed from the configuration or disabled before its delivery gets nothing: its rows end `cancelled`. Renaming a target is the same as removing it for the rows written under the old name. - The message is unchanged: the event as JSON in the body (`application/json`), and the headers `event_id`, `event_type`, `timestamp`, `user_id`, `client_id`, `actor_subject`, `ip_address`, `user_agent`, `details` and `event-type` for parameter binding. `actor_subject` is the subject of the token that made a management change; an SQL target with a table of its own keeps working as before and stores it by adding a column and binding the header. ### Running the outbox - **Size.** One row per event and destination: an event that two subscriptions and one audit target want writes three rows. A row is about 400 bytes of columns plus its payload: the event's JSON for a webhook, about twice that for an audit target (the body and the `details` header are kept as sent). Daily volume is events per day times destinations per event; 100 000 events a day with three destinations each make 300 000 rows a day. - **Retention.** The timer route `identity-delivery-cleanup` (hourly, `Identity:Delivery:CleanupInterval`, leader-only) deletes delivered rows after `DeliveredRetention` (default 7 days) and failed or cancelled rows after `FailedRetention` (default 30 days), `CleanupBatchSize` rows per statement (default 1000). A pending row is never deleted, however old. With the defaults the table holds about a week of traffic. - **Inspection and redelivery.** `GET /api/v1/identity/webhooks/deliveries` lists the rows newest first, without their payload; filters `status`, `kind` (`webhook`, `audit`), `destination` (a subscription id or a target name), `offset`, `count` (at most 200). `POST /api/v1/identity/webhooks/deliveries/{id}/redeliver` sends a failed or cancelled row again from its first attempt; `409` for a pending or delivered row, `404` for an unknown id. A redelivery is audited as `WebhookDeliveryRedelivered` (category `admin`, details carry the row id `OutboxId`). Scopes: `identity:webhooks:read` and `identity:webhooks:write`. - **Backlog.** Gauges `identity.delivery.pending` (rows not finished) and `identity.delivery.oldest_pending_age` (seconds since the oldest of them was written), read from the table at most every 15 s on every node. The module reports `Degraded` when the oldest pending row is older than `Identity:Delivery:DegradedAfter` (default 5 minutes): the worker is not running, or a destination has been failing that long. Nothing is lost while it is degraded. - **Back pressure.** Events leave their routes on wire taps that share the thread pool profile `identity-audit`: at most `Identity:Audit:TapConcurrency` (default 8) events per route in the events route at once, up to 1000 more waiting; past that the request that raised the event runs it itself, so a slow audit write slows requests down instead of piling up work. > Notable security events to wire into your SIEM first: `LoginFailed`, `MfaVerifyFailed`, `MfaWebAuthnSignCounterAnomaly`, `DpopReplayDetected`, `FederationStateValidationFailed`, `FederatedEmailConflict`, `ClientSecretRotated`, `AllSessionsRevoked`, `AllConsentsRevoked`. --- ## Runnable demos (`demos/`) Beyond the xUnit suite, `demos/` holds **self-contained PowerShell probes** that drive a **live** Identity server over its real HTTP surface — one `demo_*.ps1` per protocol contract. They double as executable RFC documentation and as a black-box regression net: each script sets up its own client (via DCR), runs the flow end-to-end, and asserts the wire-level result (status codes, headers, token/JWKS shape, replay rejection, …). Most print an `N/N PASS` line and exit non-zero on the first broken assertion. A sampling of what they pin (see the directory for the full set): | Demo | Contract exercised | |---|---| | `demo_discovery_jwks.ps1` | OIDC Discovery + JWKS shape, RFC 8414 metadata | | `demo_client_credentials.ps1` / `demo_password_ropc.ps1` / `demo_authcode_pkce.ps1` | Core grants + PKCE (`S256`) | | `demo_private_key_jwt.ps1` | `private_key_jwt` client auth (RFC 7521 / 7523) | | `demo_dpop.ps1` | DPoP proof binding + replay (RFC 9449) | | `demo_par.ps1` / `demo_par_per_client.ps1` | Pushed Authorization Requests (RFC 9126) | | `demo_throttle_rfc6585.ps1` | `429 Too Many Requests` + `Retry-After` (RFC 6585) | | `demo_backchannel_logout.ps1` | OIDC Back-Channel Logout + `logout_token` fan-out | | `demo_scim.ps1` / `demo_scim_bulk.ps1` / `demo_scim_etag.ps1` | SCIM 2.0 CRUD + Bulk + ETag concurrency (RFC 7643 / 7644) | | `demo_mfa_totp.ps1` / `demo_mfa_recovery_codes.ps1` | TOTP (RFC 6238) + one-shot recovery codes | | `demo_federation_e2e.ps1` / `demo_federation_github.ps1` | OIDC + GitHub federation, provision-on-first-login | | `demo_jwks_rotation.ps1` | Live JWKS key rotation / retire against a running server | | `demo_roles_registry.ps1` / `demo_claim_definitions.ps1` / `demo_webhooks.ps1` | Roles, declarative claim schema, signed outbound webhooks | ### Run them all ```pwsh cd demos pwsh -File .\run_all.ps1 # run every demo_*.ps1 in canonical order pwsh -File .\run_all.ps1 -Only mfa # only demos whose name matches "mfa" pwsh -File .\run_all.ps1 -StopOnFail # bail out on the first failing demo ``` `run_all.ps1` executes each demo in its own `pwsh` child process (a hard failure in one can't abort the rest), streams stdout live, captures a per-demo transcript to `demos/_logs/.log`, and prints a final pass/fail summary table. Browser-in-the-loop demos (e.g. `demo_device_code.ps1`) are skipped unless `-IncludeInteractive` is passed. Point the demos at a running server with `IDENTITY_BASE` (default `https://127.0.0.1:5002`), started per the [Quick start](#quick-start) above. --- ## Typed SDK (`IIdentityClient`) `BaseUrl` is the address of the management API (`/api/v1/identity/*`); `Authority` is the issuer, and the token and every other protocol address (introspection, revocation, userinfo, discovery, JWKS) come from its discovery document. They may be the same address; with a separate management port they differ. `Authority` is required: without it the host does not start. ```csharp services.AddIdentityClient(options => { options.BaseUrl = new Uri("https://id.example.org"); // the management API (/api/v1/identity/*) options.Authority = new Uri("https://id.example.org"); // the issuer: token and the other protocol endpoints options.ClientId = "my-svc"; options.ClientSecret = builder.Configuration["IdentitySvcSecret"]!; options.Scopes = ["identity:manage"]; }); services.AddClientCredentialsTokenProvider(); public class UserSync(IIdentityClient identity) { private DateTimeOffset? _cursor; public async Task RunAsync(CancellationToken ct) { var page = await identity.ListUsersAsync(offset: 0, count: 100, ct: ct); foreach (var user in page.Items) Console.WriteLine(user.Login); // Backchannel revocations: pull the entries since the last cursor var since = await identity.GetRevokedSidsSinceAsync(_cursor, ct); foreach (var entry in since.Entries) Console.WriteLine(entry.Sid); _cursor = since.NextCursor; } } ``` Partial classes group endpoints by area: `Users`, `Groups`, `Applications`, `Scopes`, `ClaimMappers`, `Federation`, `Sessions`, `Tokens`, `Mfa`, `Audit`, `Account`, `Token`, `Scim`, `Info`, `RevokedSids`. The client sends the token of the registered `IAccessTokenProvider`. `AddClientCredentialsTokenProvider()` registers `ClientCredentialsAccessTokenProvider`, for daemons, CLIs and hosted services; a host that acts for a signed-in user registers its own provider (the console of the `full` and `web` images replays the user's bearer). Every HTTP error is normalized to RFC 7807 `ProblemDetails` and surfaced as `ApiException`. --- ## Reference BFF + admin UI (`redb.Identity.Web`) A reference Blazor Server app demonstrating the HARDLINE BFF pattern: - Project references **only** `redb.Identity.Contracts` + `redb.Identity.Client` — no `Identity.Core`, no `Identity.Http` - All Identity calls go through `IIdentityClient` — **never** a raw `HttpClient` - OIDC Authorization Code + PKCE, `SaveTokens=true`, `SameSite=Lax` - Backchannel logout sink + `IRevokedSidsCache` (push + 60s poll fallback for multi-replica RPs) Pages cover both self-service (`/Me/*`) and admin (`/Admin/*`) surfaces: | Self-service | Admin | |---|---| | Profile, Password, MFA (TOTP), WebAuthn credentials, Sessions, Federated identities, Consents | Users (CRUD + password reset), Groups (tree + members), Applications (CRUD + scopes), Scopes, Claim Mappers, Federation providers, Sessions (revoke single/all), Tokens (prune), Audit (15 event types + JsonViewer), SCIM browser, Settings (health / discovery / JWKS) | --- ## Testing ```pwsh # default provider (SQLite) dotnet test tests\redb.Identity.Tests\redb.Identity.Tests.csproj --nologo # pick the storage engine with one env-var — the same suite runs on all three $env:REDB_PROVIDER = "postgres" # or "mssql" or "sqlite" (default) $env:REDB_USE_PRO = "true" # Pro tier (ChangeTracking); "false" for Free dotnet test tests\redb.Identity.Tests\redb.Identity.Tests.csproj --nologo ``` Provider selection is a runtime env-var; no Identity source changes between providers. | Project | Notes | |---|---| | `redb.Identity.Tests` | Unit + integration; real PostgreSQL / MSSQL / SQLite via `HttpIdentityFixture` for HTTP E2E | | `redb.Identity.Client.Tests` | SDK transport / serialization contract | | `redb.Identity.Web.Tests` | BFF smoke acceptance | Key invariants pinned by tests (non-exhaustive): - **Cluster-route marking**: only cleanup routes are `.Cluster(true)` (`ClusteredRouteMarkingTests`) - **Multi-replica key-ring**: two `RedbXmlRepository` instances against the same DB see each other's keys - **Key-ring import**: a file key ring from before the move into redb is imported once, and only keys older than the move - **MFA concurrency**: parallel verify never double-spends a recovery code, atomic `FailedAttempts++` - **TOTP replay**: identical code rejected within RFC 6238 §5.2 window - **DataProtection at rest**: AES-GCM via DP, not plaintext PEMs - **Project-reference isolation**: zero `using redb.Identity.Core;` under `redb.Identity.Http/` - **DTO validation boundary**: comprehensive `DtoValidationTests` over every wire DTO --- ## Roadmap (excerpt) Shipped today: HTTP facade, **gRPC facade**, **SOAP / WS-Trust facade**, LDAP / Active Directory federation, full management API, SCIM 2.0, MFA (TOTP / SMS / Email OTP / WebAuthn), federation (OIDC + GitHub), backchannel logout (push + pull), DPoP, PAR, DCR, JAR (opt-in), impersonation, outgoing webhooks, audit (`identity_audit_log` + external targets through the outbox), NuGet packages, signed Docker images and release archives. Planned facades & integrations (same `.tpkg` pattern, no Core changes): - `redb.Identity.Rmq` / `.Amqp` / `.IbmMq` — message-bus RPC facades - `redb.Identity.SignalR` — push of audit events to subscribed clients - `redb.Identity.Kafka` — event-only sink (Kafka has no RPC) Planned protocol work, in rough order of demand: - Formal [OpenID Certification](https://openid.net/certification/) submission; conformance results in [`OPENID_CERTIFICATION.md`](OPENID_CERTIFICATION.md) - SAML 2.0 — **not implemented** in either direction (no IdP, no SP) - Risk-adaptive authentication and trusted-device records — the inputs (session IP, user agent, device label, failure counters, audit trail) are already stored; the scoring and step-up policy on top of them are not - The RFCs listed under *Not implemented yet* above --- ## Contributing & license - License: [Apache 2.0](https://github.com/redbase-app/redb-identity/blob/main/LICENSE) - Engine: [OpenIddict](https://documentation.openiddict.com/) (Apache 2.0) - Runtime: [redb.Route](https://github.com/redbase-app/redb-route) - Container: [redb.Tsak](https://github.com/redbase-app/redb-tsak) - Storage: [redb.Core](https://github.com/redbase-app/redb) Contributions are welcome: see [CONTRIBUTING.md](CONTRIBUTING.md). Report vulnerabilities as described in [SECURITY.md](SECURITY.md).