↑↓ to navigate Enter to open "…" all these words ANDOR to combine

Onboarding guide

12. API Hosting, Middleware, Idempotency & DTO/Contract Mapping

What this group covers. This is the ASP.NET Core edge of the framework: the layer that turns an HTTP request into a domain call and turns a Result back into an HTTP response. Almost everything here lives in MMCA.Common.API (the presentation layer that sits above Infrastructure in the dependency flow, see primer §1), with a handful of transport-agnostic collaborators in MMCA.Common.Application (ICorrelationContext, IEntityDTOMapper<TEntity, TEntityDTO, TIdentifierType>), MMCA.Common.Infrastructure (CorrelationContext, OutboundAddressPolicy), and MMCA.Common.Shared (the DTO vocabulary and SupportedCultures). The group has seven interlocking concerns: the composition root that registers the whole edge; the middleware pipeline every request flows through, itself expressed as ordered data rather than a hard-coded call sequence; the error translation that keeps every failure shaped like RFC 9457 Problem Details; the controller hierarchy that hands a module ready-made CRUD, export, auth, recovery, and service-discovery endpoints; the write-safety controls (idempotency keys and conditional writes) that make a retried or racing write predictable; the contract surface (DTO/request mapping, JSON conversion, model binding, correlation, tenancy, feature gating, output caching); and the well-known endpoints that make an extracted service self-describing. Read the group as the reusable ASP.NET host a downstream service (Store, ADC, Helpdesk, or an extracted microservice) drops into place so its own code is nothing but modules. Its central rubric column is [Rubric §9, API & Contract Design] (consistent, versioned, standardized contracts and error shapes), with heavy supporting roles for [Rubric §12, Performance & Scalability], [Rubric §11, Security], [Rubric §13, Observability & Operability], [Rubric §7, Microservices Readiness], and (since ADR-027) [Rubric §27, Internationalization].

The composition root: AddAPI, the builder extensions, and the module-host pair. A host wires the edge through two static extension classes. DependencyInjection's AddAPI (MMCA.Common/Source/Presentation/MMCA.Common.API/DependencyInjection.cs:45) registers MVC controllers with the global UnhandledResultFailureFilter (DependencyInjection.cs:50), the internal OversizeFormResourceFilter at its own filter order (:53, so a form body over the endpoint's limit answers 413 rather than model binding's 400) and ReturnHttpNotAcceptable = false (:49), wires two JSON converter factories into the serializer options, the EnumerationJsonConverterFactory (DependencyInjection.cs:60, registered here because a concrete enumeration does not inherit the base class's [JsonConverter] attribute) and StronglyTypedIdJsonConverterFactory (DependencyInjection.cs:66, registered for the same reason so a wrapped identifier serializes as the bare primitive it wraps, ADR-115), adds the XML formatters (DependencyInjection.cs:68), optionally installs the ModuleControllerFeatureProvider when a ModulesSettings instance is supplied (DependencyInjection.cs:70-74), binds IdempotencySettings with ValidateDataAnnotations().ValidateOnStart() when configuration is supplied (DependencyInjection.cs:76-82, ADR-070), registers the two scoped action filters IdempotencyFilter and OwnerOrAdminFilter (DependencyInjection.cs:87-88, scoped because they depend on scoped services), turns on feature management with targeting through CurrentUserTargetingContextAccessor and the DisabledFeatureHandler (DependencyInjection.cs:108-110), and registers the edge error-localization boundary (AddErrorLocalization, called at DependencyInjection.cs:113 and declared at :125, with AddErrorResources<TResource> at :144 for each module's own .resx set). Three sibling methods on the same class complete the picture: AddCommonExceptionHandlers (DependencyInjection.cs:157) registers the Problem Details service and the four exception handlers in most-specific-first order (:162-165), AddServerAuthSessionCookie (DependencyInjection.cs:182) registers the Blazor Server host's SSR cookie reader (CookieTokenReader, :187) plus the singleton CookieSessionRefresher (:193, singleton so its in-flight map is shared across requests), and AddModuleHealthChecks (DependencyInjection.cs:230) turns ModuleLoader discovery results into module-{Name} health checks, tagged module so /health?tag=module filters them (Healthy for enabled modules at :229-235, Degraded for the disabled ones at :237-244). WebApplicationBuilderExtensions (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/WebApplicationBuilderExtensions.cs:24, a partial class split across that file plus WebApplicationBuilderExtensions.RateLimiting.cs and WebApplicationBuilderExtensions.Authentication.cs) carries the identical builder-side setup every service shares: header-based API versioning through the api-version header (AddCommonApiVersioning, line 39, reader at line 48, v1.0 assumed when the header is absent at line 46, ADR-046), rate limiting (AddCommonRateLimiting, three overloads at WebApplicationBuilderExtensions.RateLimiting.cs:389, :392, and :414), Brotli and Gzip compression at CompressionLevel.Fastest (AddCommonResponseCompression, line 68, both providers pinned to Fastest at lines 77 and 82 because these are dynamic per-request payloads on fractional vCPUs), OpenAPI (line 101), CORS (line 132, ADR-082, with the two policy names as constants at lines 27 and 30 and the allow-any-origin policy selected only in Development by the pipeline's CORS step, MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/Pipeline/MiddlewarePipelineBuilder.cs:90-92), and the two JWT bearer registrations: in-process AddCommonAuthentication (WebApplicationBuilderExtensions.Authentication.cs:142) for the Identity host and AddForwardedJwtBearer (WebApplicationBuilderExtensions.Authentication.cs:52) for extracted services that validate against a remote JWKS. Two smaller helpers keep a service host's Program.cs honest. ModuleHostExtensions's AddModuleHost (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/ModuleHostExtensions.cs:51) collapses the settings-bind plus loader construction every module-hosting service repeated verbatim, and answers with a ModuleHostContext (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/ModuleHostContext.cs:21) carrying the bound settings, the loader, and RegisterModules (ModuleHostContext.cs:69) as a step the host hands to its own application pipeline: discovery is deliberately not run inside AddModuleHost, because it has to sit between AddApplication() and AddApplicationDecorators() at a host-chosen position (ModuleHostContext.cs:13-19, ADR-014). JwtAuthorityExtensions (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/Auth/JwtAuthorityExtensions.cs:15) reads the authority every non-issuer service validates against and throws when the AppHost never injected it (GetRequiredJwtAuthority, :36, throwing at :41-43), because a host that boots without one answers every authenticated request with a 401 that looks like a token problem instead of a wiring problem. JwtAudience (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/Auth/JwtAudience.cs:17) applies the same rule to the audience those hosts hand to AddForwardedJwtBearer: RequireConfigured (:28-32) returns the value read from Jwt:Audience (ConfigKey, :20) or throws naming the key and its Jwt__Audience environment-variable form, and the intended call shape carries no ?? fallback, so a hard-coded default can never boot a service with an audience nobody configured (JwtAudience.cs:8-15, a shape ForwardedJwtAudienceTestsBase pins in each consumer). Only one DI ordering rule is load-bearing in the whole host, and it belongs to the CQRS pipeline group, not here: AddApplicationDecorators (MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.cs:101) must run last so Scrutor can decorate handlers that are already registered. The API registrations themselves are order-independent. This is the [Rubric §9, API & Contract Design] and [Rubric §12, Performance & Scalability] story: versioning, compression, rate limiting, and CORS are configured once and inherited by every service instead of copy-pasted per host.

The request pipeline is data, not prose. Middleware order is behavior in ASP.NET Core, so the framework does not leave it to each host's Program.cs, and it no longer even leaves it as a fixed sequence of Use... calls. WebApplicationExtensions's UseCommonMiddlewarePipeline (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/WebApplicationExtensions.cs:28) and its Action<MiddlewarePipelineBuilder> overload (WebApplicationExtensions.cs:40) both route through one private ApplyPipeline that seeds the defaults, lets the host adjust them, validates the result, and only then applies each step (WebApplicationExtensions.cs:164-174). The steps themselves are MiddlewarePipelineStep records (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/Pipeline/MiddlewarePipelineStep.cs:21), each a stable Name plus an Action<WebApplication> Configure delegate, both null-validated on construction (MiddlewarePipelineStep.cs:27 and :30); because a step is inert data until someone runs it, the whole order is assertable without building a host. MiddlewarePipelineBuilder (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/Pipeline/MiddlewarePipelineBuilder.cs:15) owns the list: CreateDefault (MiddlewarePipelineBuilder.cs:31) seeds the eighteen framework steps in order (:34-150) and InsertBefore, InsertAfter, Replace, and Remove (:161, :178, :198, :219) let a host address any of them by name, which is why MiddlewarePipelineStepNames (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/Pipeline/MiddlewarePipelineStepNames.cs:14) is public contract rather than an implementation detail: renaming a constant there is a breaking change, and the declaration order of those constants (:17-74) is the runtime order. Read it top to bottom and you have the edge: exception handler, correlation id, request localization, pre-forwarded capture, forwarded headers, HTTPS redirection, response compression, routing, CORS, authentication, tenant resolution, rate limiting, the soft-deleted-user filter, authorization, output cache, the JWKS and OIDC discovery endpoints, and finally the controllers. Four of those adjacencies are load-bearing, and Build (MiddlewarePipelineBuilder.cs:256) re-checks them before a single step is applied (the Require... calls start at :254): the pre-forwarded capture must run immediately before UseForwardedHeaders or the captured scheme and host are no longer the ones the connection saw; authentication must run immediately before tenant resolution because the claim strategy reads HttpContext.User; authentication must precede the rate limiter (ADR-019) because GlobalRateLimitPartition keys on the authenticated principal and an unauthenticated pipeline would see every request as anonymous; and forwarded headers must precede the HTTPS redirect so the redirect decision reads the proxy-reported scheme. A violation throws InvalidOperationException at startup with the offending order printed (:320-321 and :335-336), and an invariant binds only when both of its steps are still present (:315 and :330), so dropping a whole capability stays legal while reordering a pair does not. Two more decisions are worth internalizing from the default step list. The HTTPS redirect is wrapped in a UseWhen that skips only cleartext HTTP/2 (MiddlewarePipelineBuilder.cs:70-72, through the public IsCleartextHttp2 predicate at :350), because extracted gRPC services speak HTTP/2 cleartext (h2c) and a 307 would break the call; the exemption is keyed on the protocol Kestrel negotiated rather than on the Content-Type, because this step runs before routing and a header is caller-supplied, so a forged application/grpc cannot buy a plaintext response while every browser-reachable request (HTTP/1.1, or HTTP/2 over TLS) is still redirected (:79-84). And the forwarded-headers step (:69) takes its options from CommonForwardedHeaders (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/CommonForwardedHeaders.cs:27), the framework's one forwarded-headers posture: X-Forwarded-For, X-Forwarded-Proto, and X-Forwarded-Host by default (DefaultHeaders, :33-34), with the known-proxy and known-network allowlists cleared (Create, :42, clearing at :49-50) so cloud reverse proxies are trusted regardless of their internal IPs. That is safe only because the posture assumes the ingress is the only thing that can reach the container (CommonForwardedHeaders.cs:19-20). Server-rendered UI hosts adopt the identical posture through CommonForwardedHeadersExtensions's UseCommonUiForwardedHeaders (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/CommonForwardedHeadersExtensions.cs:24), called first in the UI pipeline before anything reads the scheme, the host, or the client address, so every host behind the same ingress reads them the same way (CommonForwardedHeaders.cs:6-11); the gateway keeps its own dependency-free copy of the values because it does not reference this package (:23-24). Hosts freeze their own resulting order with the opt-in fitness function MiddlewarePipelineOrderTestsBase (MMCA.Common/Source/Hosting/MMCA.Common.Testing/Conformance/MiddlewarePipelineOrderTestsBase.cs:31), whose default expectation is the framework list verbatim (:40-57), so a reorder fails a fast unit test instead of surfacing as an unreachable jwks_uri or a rate cap that never engages (ADR-079). Alongside the pipeline, UseCommonRequestLocalization (WebApplicationExtensions.cs:53) builds the culture options from SupportedCultures (MMCA.Common/Source/Core/MMCA.Common.Shared/Globalization/SupportedCultures.cs:9: en-US as the default at line 12 and the full en-US plus es list at line 18, with the qps-Ploc pseudo locale at line 28 added in Development only, WebApplicationExtensions.cs:60-63) so edge error localization runs under the caller's culture, and the companion MapCultureEndpoint (WebApplicationExtensions.cs:83) serves the GET /culture/set switch that Blazor UI hosts map; its bool httpOnly overload (WebApplicationExtensions.cs:96) controls the culture cookie's HttpOnly flag, which the parameterless form leaves off because a WebAssembly client reads the cookie on startup, while a Server-only host can turn it on (:97 and :109) (ADR-027). Turning order into inspectable, validated data is [Rubric §12, Performance & Scalability], [Rubric §14, Testability] and [Rubric §34, Architecture Governance] in one move.

Rate limiting: one always-on partition, one named policy, and an optional shared counter. The global limiter is active on every request and rejects with 429 above RateLimitingSettings.GlobalPermitLimit (default 300 requests per minute, MMCA.Common/Source/Presentation/MMCA.Common.API/RateLimiting/RateLimitingSettings.cs:28) per authenticated user: GlobalRateLimitPartition (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/WebApplicationBuilderExtensions.RateLimiting.cs:166) routes anonymous traffic to AnonymousPartition (line 83), and health, liveness, /.well-known/*, and gRPC traffic bypass the limiter outright (IsRateLimitBypassed, lines 67-71). The gRPC arm of that exemption is keyed on the routed endpoint rather than on the request's Content-Type (IsGrpcEndpoint, line 128): a header is caller-supplied, so stamping application/grpc on an ordinary request would otherwise hand any authenticated account the no-limiter partition, and endpoint metadata comes from the host's own MapGrpcService registrations instead (the predicate runs after UseRouting, which the pipeline order guarantees). Anonymous callers are exempt everywhere except a real-time hub path, where AnonymousPartition meters them per client IP at RateLimitingSettings.AnonymousHubPermitLimit (default 60, RateLimitingSettings.cs:95) over the configured HubPathPrefixes (default /hubs, RateLimitingSettings.cs:87, matched by IsAnonymousHubRequest at WebApplicationBuilderExtensions.RateLimiting.cs:106) and otherwise returns a no-limiter partition (WebApplicationBuilderExtensions.RateLimiting.cs:96): a gateway cannot meter /hubs at the edge, because the hub authenticates from a query-string token the edge cannot read (ADR-024), so an anonymous negotiate flood would be counted nowhere at all. Because the global limiter otherwise no-ops for anonymous callers and account lockout is per-email, a password spray (one password, many email addresses) from a single source would otherwise be unthrottled. The framework closes that gap with the named auth-ip policy (RateLimitPolicyAuthIp, WebApplicationBuilderExtensions.RateLimiting.cs:28), whose partition selector AuthIpRateLimitPartition (line 326) is a per-client-IP window defaulting to 30 requests per minute (RateLimitingSettings.cs:35) and fails open on an unattributable IP (line 331) rather than collapsing every such request into one shared bucket, which would throttle the in-process test server to a standstill. Unlike the other named limiters, this one is not left for each app to attach: AuthControllerBase carries [EnableRateLimiting(WebApplicationBuilderExtensions.RateLimitPolicyAuthIp)] on both LoginAsync (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/AuthControllerBase.cs:78) and RegisterAsync (AuthControllerBase.cs:103), and PasswordResetAuthControllerBase<TForgotPasswordCommand, TResetPasswordCommand> carries it on both recovery endpoints (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/PasswordResetAuthControllerBase.cs:78 and :102), as does EmailConfirmationControllerBase<TSendCommand, TConfirmCommand> on both of its anonymous actions (EmailConfirmationControllerBase.cs:81 and :109), so every consumer inherits spray protection by construction, while RefreshAsync (AuthControllerBase.cs:164-166) is deliberately left unthrottled because refresh is periodic and automatic and Blazor Server circuits issue it server-side from one shared host IP. A consumer that inherits the base without calling AddCommonRateLimiting fails at startup on an unregistered policy, which is the loud failure rather than the silent one. Two knobs sit on top of that baseline, both reachable only through the IConfiguration overload (WebApplicationBuilderExtensions.RateLimiting.cs:418) that binds the RateLimiting section. Algorithm (RateLimitingSettings.cs:49) selects the RateLimitAlgorithm enum (MMCA.Common/Source/Presentation/MMCA.Common.API/RateLimiting/RateLimitAlgorithm.cs:8): FixedWindow is the default and cheapest but lets a caller spend an allowance twice across a boundary (RateLimitAlgorithm.cs:10-15), while SlidingWindow divides the same one-minute window into SegmentsPerWindow segments (default 4, RateLimitingSettings.cs:58) and smooths that burst away at the cost of one counter per segment. And Distributed (RateLimitingSettings.cs:68) swaps the in-memory counter for RedisFixedWindowRateLimiter (MMCA.Common/Source/Presentation/MMCA.Common.API/RateLimiting/RedisFixedWindowRateLimiter.cs:52), so a limit means the same thing behind a load balancer as it does on one node. All three choices funnel through one private factory, CreateLimitedPartition (WebApplicationBuilderExtensions.RateLimiting.cs:246), which takes the Redis path only when an IConnectionMultiplexer is actually registered and otherwise falls through to the in-memory limiters rather than failing startup (the multiplexer probe at line 275, the fall-through reasoning at lines 296-298). The Redis limiter is worth reading for its deliberate compromises. It stores one counter per partition per window under rl:{partitionKey}:{unixMinute} (RedisFixedWindowRateLimiter.cs:200), where the framework partition key leads with the application namespace so two applications sharing one Redis do not share a counter (:26-30). The increment and the 65 second TTL (KeyTtlSeconds, line 57) run as one Lua script, RedisCounterScript.Increment (MMCA.Common/Source/Build/Redis/RedisCounterScript.cs:24-27, evaluated at RedisFixedWindowRateLimiter.cs:212-215), so no failure between them can leave a key with no expiry, and only the increment that creates the key sets the TTL, because re-stamping it on every request would slide the window forward for a caller who keeps hitting it (RedisCounterScript.cs:18-22). That script is one internal source file linked into both the API package and Infrastructure's counter store, because Infrastructure must not reference API and the script is too small to justify a public type (RedisCounterScript.cs:9-13). The skew past the window length means clock drift between instances cannot hand a partition a fresh allowance mid-window (RedisFixedWindowRateLimiter.cs:55-57). The increment is not transactional with the permit decision, so a simultaneous burst can overshoot slightly, accepted in exchange for one round trip per request (:34-36). The synchronous AttemptAcquireCore never decides (lines 174-178): the ASP.NET Core middleware calls it first on every request, so granting there would admit every request uncounted and deciding there would block a request thread on a Redis round trip, which is why it returns a not-acquired lease and the real decision happens in AcquireAsyncCore (line 181, reasoning at :158-170). By default any Redis fault permits the request and logs at most one warning per window across the process (lines 211-230), because rate limiting protects capacity and must never itself become the reason a healthy request is rejected. RedisRateLimitLease (RedisFixedWindowRateLimiter.cs:305) is the lease type it hands out: Acquired and Undecided are shared statics (lines 297 and 304) so a permitted request allocates nothing, while Rejected (line 328) allocates per call because it carries the time until the partition's window resets (TimeUntilNextWindow, line 271) as RetryAfter metadata, which the rate-limiter OnRejected callback turns into the 429's Retry-After header (:286-290); a request larger than the whole allowance is rejected with no hint, since no later window could hold it (lines 187-192). The auth-ip policy is the one exception to failing open: with Distributed on it shares the Redis counter like every other partition, but it is built with countLocallyOnRedisFault: true (WebApplicationBuilderExtensions.RateLimiting.cs:347), so a Redis fault answers from a per-instance count of the same window (AcquireLocally, RedisFixedWindowRateLimiter.cs:256) rejected with the same Retry-After hint, until Redis answers again (:44-47): a login throttle that fails open for the length of an outage is a worse trade than one that keeps counting locally (ADR-019 for the layering, and ADR-029 for the brute-force half). Four small internal types sit under all of this. RedisOutageCircuit (MMCA.Common/Source/Build/Redis/RedisOutageCircuit.cs:27, taken per connection at RedisFixedWindowRateLimiter.cs:143) opens for ten seconds after a Redis fault (OpenDuration, RedisOutageCircuit.cs:30), so callers go straight to their fallback instead of each waiting about six seconds for the client to give up, then lets exactly one caller probe Redis while the rest keep the fallback (:13-19). ClientAddressKey (MMCA.Common/Source/Build/RateLimiting/ClientAddressKey.cs:31) is the one key every per-IP partition uses: it unmaps an IPv4-mapped address to IPv4 and masks an IPv6 address to its /64 prefix (IPv6PrefixLength, :34), because an IPv6 subscriber holds a whole /64 and rotating the low bits would otherwise buy a fresh window per request (:14-19); it is deliberately not the idempotency filter's anonymous subject, which keeps replays apart rather than limiting anything (:22-23). RetryAfterRejection (MMCA.Common/Source/Build/RateLimiting/RetryAfterRejection.cs:19) is the OnRejected wrapper every MMCA limiter installs, so each 429 carries a Retry-After header whenever the rejecting lease has a hint (:8-11). And McpCallerKey (MMCA.Common/Source/Presentation/MMCA.Common.API/RateLimiting/McpCallerKey.cs:23) gives the endpoint-wide mcp policy (McpRateLimitPartition, WebApplicationBuilderExtensions.RateLimiting.cs:203) and the per-tool MCP limit the same caller key: the user id, else the identity name, else the client address key, else one shared Unattributable bucket (McpCallerKey.cs:16-21, constant at :26), so an unattributable caller is limited rather than waved through. This is [Rubric §11, Security] and [Rubric §12, Performance & Scalability] handled once at the edge.

Correlation, tenancy, and the soft-deleted-user gate: three ambient facts established once. CorrelationIdMiddleware (MMCA.Common/Source/Presentation/MMCA.Common.API/Middleware/CorrelationIdMiddleware.cs:20) reads the X-Correlation-ID request header (the constant lives at CorrelationIdMiddleware.cs:23), falling back to the current W3C trace id then ASP.NET's TraceIdentifier (lines 41-43), after cutting a caller-supplied value to MaxLength (64, the width of the persisted correlation columns, line 26) and discarding it unless every character is printable ASCII (Sanitize, lines 61-64), so a hostile header is neither echoed back nor persisted. It writes the id onto the scoped ICorrelationContext (MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/ICorrelationContext.cs:8, implemented by CorrelationContext, which self-seeds from the correlation id of the enclosing background hop when one is being delivered and otherwise from a new GUID, MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Context/CorrelationContext.cs:13), and echoes it back through Response.OnStarting (CorrelationIdMiddleware.cs:46-50). That single id is what the CQRS logging decorators read (MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Decorators/LoggingCommandDecorator.cs:18 and :24) and stamp onto every log scope through the Command {CommandName} [Module: {ModuleName}] [CorrelationId: {CorrelationId}] scope definition (LoggingCommandDecorator.cs:99-100), so one request is traceable end to end, and by module. TenantResolutionMiddleware (MMCA.Common/Source/Presentation/MMCA.Common.API/Middleware/TenantResolutionMiddleware.cs:37) is the HTTP half of ADR-073: it tries each configured strategy in order (claim, then header; the TenantResolutionStrategy.Host option is defined but deliberately returns null rather than being guessed at, lines 105-121) and publishes the winner on the scoped ITenantContext that the persistence query filter, save interceptor, and per-tenant database routing all read (line 70). Two decisions mirror the soft-deleted-user middleware below. It is wired unconditionally but inert by default, because TenancySettings resolves to defaults with Enabled false in a host that never called AddMultiTenancy (line 62). And it fails closed: with Tenancy:RequireTenant on, a request that resolves no tenant is rejected at line 83 and answered 400 with an RFC 9457 body naming the claim and header it looked at (lines 133-146), because an unscoped request would read across every tenant, which is the exact outcome tenancy exists to prevent; an explicit RequireTenant opt-out lets the request run as a system caller instead (lines 75-81), and health, liveness, and discovery paths are excluded so probes still answer before any tenant exists (lines 89-94). SoftDeletedUserMiddleware (MMCA.Common/Source/Presentation/MMCA.Common.API/Middleware/SoftDeletedUserMiddleware.cs:40) enforces business rule BR-133: an authenticated caller whose account was soft-deleted is rejected with a bare 401 (lines 113 and 165), checked first against a deleted-user marker read from the shared cache store rather than this replica's local copy (GetFromSharedStoreAsync, SoftDeletedUserMiddleware.cs:94-96), because whichever replica handled the delete is the one that wrote it. The marker lives at least 20 minutes (SoftDeletedUserCache.MarkerDuration, MMCA.Common/Source/Core/MMCA.Common.Application/Auth/SoftDeletedUserCache.cs:44, the default 15-minute access-token lifetime plus the library's 5-minute clock skew), and longer on a host whose access-token lifetime plus skew exceeds that (MarkerDurationFor, SoftDeletedUserCache.cs:54-58, written at SoftDeletedUserMiddleware.cs:154 through the host's ITokenService lifetime, lines 177-180), so it outlives any access token issued before the delete, and the database answer is cached only when it says deleted: a cached "not deleted" would sit in each replica's local copy and outlive a delete made on another replica (lines 127-129) (ADR-047). It resolves ISoftDeletedUserValidator lazily from RequestServices (line 117) instead of as an InvokeAsync parameter, so a service that does not host Identity still honors the marker and otherwise passes the request through (lines 118-124) rather than 500-ing on every call: an explicit nod to the [Rubric §7, Microservices Readiness] extraction path. And unlike tenancy it fails open: a cache read that throws falls back to the validator query (lines 98-106), and a validator query that throws lets the request continue (lines 137-143), because failing closed would turn any cache or database blip into a total outage for every authenticated request, while the exposure it buys back is bounded by the access-token lifetime. All three middlewares are [Rubric §13, Observability & Operability] (correlation), [Rubric §11, Security] (deleted-account lockout), and [Rubric §8, Data Architecture] (tenant scoping) concerns handled once at the edge instead of in every controller.

Errors become Problem Details, through two channels and one table. Failures reach the client two ways. Thrown exceptions are caught by the handler chain registered in AddCommonExceptionHandlers (DependencyInjection.cs:157-165, the four AddExceptionHandler calls at :162-165), evaluated most-specific-first: OperationCanceledExceptionHandler (499 Client Closed Request, OperationCanceledExceptionHandler.cs:54), DbUpdateExceptionHandler (409 at line 41 with a deliberately generic detail so database schema names never leak, DbUpdateExceptionHandler.cs:60-62, after counting a concurrency conflict on ConcurrencyConflictMetrics at :36-39), ValidationExceptionHandler (400 at line 33 with FluentValidation errors grouped by property name into the errors extension, ValidationExceptionHandler.cs:46-54), and finally GlobalExceptionHandler (MMCA.Common/Source/Presentation/MMCA.Common.API/Middleware/GlobalExceptionHandler.cs:42), which is the 500 catch-all (line 102) plus two special cases. A CrossTenantWriteException is answered 400 with a fixed title and detail that name nothing the exception carries (constants at :36 and :44-46, handled at :54-72), because echoing a tenant id back tells an unauthorized caller which tenant owns the row it just tried to write, and it is logged as a warning rather than an error because a tenant-scoped API refusing an untenanted write is routine. A BadHttpRequestException raised by Kestrel or model binding keeps the status it already carries (413 Payload Too Large for a body over the endpoint's limit, typically 400 otherwise) and is likewise logged as a warning, because a malformed or oversize request is a caller fault (handled from :74). Business failures that travel as Result.Failure rather than as exceptions are mapped by ApiControllerBase's HandleFailure (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/ApiControllerBase.cs:50), which falls back to a 500 when the error list is empty (lines 54-60) and otherwise derives the status from the most severe error present rather than the first (line 63), so an aggregate built by Result.Combine cannot be downgraded by error ordering: a 403 or a 500 travelling alongside a validation error still answers 403 or 500, and equal ranks keep the earliest error (the ranking is documented at ApiControllerBase.cs:36-45 and lives in ErrorTypeSeverity in MMCA.Common.Shared, so the gRPC edge classifies the same aggregate identically). The safety net UnhandledResultFailureFilter (MMCA.Common/Source/Presentation/MMCA.Common.API/Middleware/UnhandledResultFailureFilter.cs:22, an IAlwaysRunResultFilter) catches any action that accidentally returned a failed Result as a 200 body, logs a warning, and rewrites it as the correct error (lines 28-49). All of those paths converge on ErrorHttpMapping (MMCA.Common/Source/Presentation/MMCA.Common.API/Middleware/ErrorHttpMapping.cs:14), whose FrozenDictionary<ErrorType, int> (lines 20-32) is the single source of truth mapping each ErrorType (Validation, Invariant and Failure to 400, NotFound to 404, Conflict to 409, Unauthorized to 401, Forbidden to 403, UnprocessableEntity to 422, TooManyRequests to 429, Unexpected to 500) to a status code, with 400 as the fallback for anything unmapped (lines 38-39) and the list-taking overload at lines 51-52 applying the severity ranking. Its BuildErrorsExtension (line 62) localizes each Error's human message at the edge through IErrorLocalizer (MMCA.Common/Source/Presentation/MMCA.Common.API/Localization/IErrorLocalizer.cs:9), keyed by the stable Code, leaving Code, Type, Source, and Target verbatim so clients can still branch on them, and leaving the original English message untouched when no localizer is registered (line 66). ErrorLocalizer (MMCA.Common/Source/Presentation/MMCA.Common.API/Localization/ErrorLocalizer.cs:13) walks the registered ErrorResourceSource (MMCA.Common/Source/Presentation/MMCA.Common.API/Localization/ErrorResourceSource.cs:13) list in registration order (lines 23-30: the framework's own ErrorResources (MMCA.Common/Source/Presentation/MMCA.Common.API/Resources/ErrorResources.cs:9) anchor first, then each module's resources added through AddErrorResources, DependencyInjection.cs:144) and falls back to the caller's message when no source knows the code (line 32). This is [Rubric §9, API & Contract Design] (one consistent RFC 9457 shape) meeting the [Rubric §1, SOLID] discipline of never duplicating the mapping, and [Rubric §27, Internationalization] at the one boundary where a machine-readable code becomes human prose.

The controller hierarchy: generic CRUD earned by inheritance. A module gets working endpoints by subclassing one generic base and supplying its type parameters (ADR-034). ApiControllerBase is the root: [ApiController], HandleFailure, nothing else. EntityControllerBase<TEntity, TEntityDTO, TIdentifierType> (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/EntityControllerBase.cs:33) adds the read surface (GetAllAsync at line 110, paged at line 154, lookup at line 317, GetByIdAsync at line 361) over an IEntityQueryService<TEntity, TEntityDTO, TIdentifierType>, with field projection through a fields query parameter, X-Pagination header metadata (written at line 188), and a page size clamped to MaxPageSize (resolved per request from IOptions<ApplicationSettings>, defaulting to 500 and clamped again to the query pipeline's own EntityQueryPipeline.MaxUnboundedResultLimit, so the pagination metadata and the export loop never assume a page size the pipeline does not serve, lines 52-66). That header has exactly one owner: PaginationHeaderExtensions (MMCA.Common/Source/Presentation/MMCA.Common.API/Pagination/PaginationHeaderExtensions.cs:12), a public static class whose extension(HttpResponse) block (line 19) adds AppendPaginationHeader (line 27), holds the header name as HeaderName (line 17), and serializes the page's PaginationMetadata with JsonSerializerOptions.Web, so camelCase property names (line 32). A controller that serves a page outside EntityControllerBase therefore emits the identical header instead of re-declaring the name and the serializer settings (PaginationHeaderExtensions.cs:7-11). AggregateRootEntityControllerBase<TEntity, TEntityDTO, TIdentifierType, TCreateRequest> (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/AggregateRootEntityControllerBase.cs:29) extends it with an [Idempotent] POST create (lines 75-76) that returns 201 with a Location resolved before the result is returned (lines 91-98): the named by-id route (GetByIdRouteName, defaulting to Get{EntityName}ById at line 57) when the derived controller declares it, and otherwise the new id appended to the collection path the POST was made to, where the inherited GET {id} answers. The Location is never left to the result, because a CreatedAtRoute naming an undeclared route throws only when the result executes, after the entity was saved, which would answer a 500 for a create that had succeeded (AggregateRootEntityControllerBase.cs:67-74). Its DELETE dispatches DeleteEntityCommand<TEntity, TIdentifierType> and returns 204 (lines 106-119), and CrudEntityControllerBase<TEntity, TEntityDTO, TIdentifierType, TCreateRequest, TUpdateRequest> (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/CrudEntityControllerBase.cs:55) closes the set with the conditional PUT {id} (attributes at lines 87-89, the six documented response codes at :90-96, the token read at :102, and a fresh ETag on the way out at :111). The interfaces IEntityControllerBase<TEntityDTO, TIdentifierType> (IEntityControllerBase.cs:14) and IAggregateRootEntityControllerBase<TEntityDTO, TIdentifierType, TCreateRequest> (IAggregateRootEntityControllerBase.cs:15) describe those shapes for testing and documentation. The generic constraints tie the tower together: TEntity derives from AuditableBaseEntity<TIdentifierType> for reads and from AuditableAggregateRootEntity<TIdentifierType> for writes, TEntityDTO implements IBaseDTO<TIdentifierType>, and TCreateRequest implements ICreateRequest (IEntityControllerBase.cs:17-18, IAggregateRootEntityControllerBase.cs:20-22, AggregateRootEntityControllerBase.cs:42-45). Alongside the CRUD tower sit ten special-purpose bases: AuthControllerBase (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/AuthControllerBase.cs:49, anonymous login, register, and refresh over IAuthenticationService, lines 69-130, plus the [Authorize] revoke at lines 152-154 and the multi-device pair GET my-sessions (line 183) and POST revoke/{sessionId:guid} (line 216), whose current-device flag comes from the access token's own sid claim so no client state is involved, ADR-097); PasswordResetAuthControllerBase<TForgotPasswordCommand, TResetPasswordCommand> (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/PasswordResetAuthControllerBase.cs:43), a sibling of that base rather than an addition to it because each app's own AuthController already occupies the single-inheritance chain (it derives straight from ApiControllerBase, PasswordResetAuthControllerBase.cs:45), serving POST forgot-password (line 75) and POST reset-password (line 99); both are anonymous by necessity since the caller has lost the credential, forgot-password always answers 202 whether or not the address exists (line 92) so the response never reveals which addresses hold accounts, and each app supplies its own command record through a one-line factory (:61 and :69, ADR-091); EmailConfirmationControllerBase<TSendCommand, TConfirmCommand> (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/EmailConfirmationControllerBase.cs:43), a second sibling built the same way for the same single-inheritance reason (EmailConfirmationControllerBase.cs:16-19), serving POST send-email-confirmation (line 78) and POST confirm-email (line 106), both [Idempotent], both anonymous because the link is followed from a mail client with no session and an unconfirmed account may be unable to sign in (:23-27), and both behind auth-ip (lines 79-81 and 107-109); send answers 202 on every well-formed request so the response never reveals which addresses hold accounts (:30-32), and the two command records stay app-side behind one-line factories (CreateSendCommand at :61, CreateConfirmCommand at :69, ADR-116); UserAccountAuthControllerBase<TChangePasswordCommand, TChangePreferencesCommand> (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/UserAccountAuthControllerBase.cs:41), which subclasses AuthControllerBase purely additively (line 46) and adds the self-service account endpoints PUT password (line 86), PUT preferences (line 112), and GET preferences (line 138), taking the two mutation commands as type parameters because each app owns its own command record while the preferences query is shared (UserAccountAuthControllerBase.cs:48-49); OAuthControllerBase (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/OAuthControllerBase.cs:52, the Google, GitHub, and Apple external-provider challenges at lines 103, 113, and 126, the GET complete provider callback at line 145 and the POST exchange redemption at line 230, whose single-use exchange code, cached for two minutes at OAuthControllerBase.cs:104, keeps tokens out of the redirect URL; a multi-replica host passes an IDistributedLock to the four-argument constructor so the code is read and burned inside that lock (lease and wait at lines 80-81) and two replicas redeeming the same code at once cannot both mint a token pair, while the three-argument constructor (line 90) keeps an unlocked read-then-burn that is single-use only per replica (:35-40); ADR-036 and ADR-043); DataExportControllerBase<TQuery> (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Privacy/DataExportControllerBase.cs:61), the data-subject access and portability endpoint (ADR-076), which serves GET {userId}/export (line 79) as a real file download rather than an inline body (returned through File(...) at line 111, with an invariant user-data-{userId}-{yyyyMMdd}.json name derived from the package's own GeneratedOn, documented at lines 132-133 and built at line 141), gated by both an [Authorize] and a [FeatureGate] on PrivacyFeatures.DataExport (lines 59-60) while the handler independently enforces owner-or-privileged-role, and abstract only because each app owns its own query record (CreateQuery, line 126); LegalAcceptanceControllerBase (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Legal/LegalAcceptanceControllerBase.cs:45), the signed-in user's Terms of Service standing behind a class-level [Authorize] (line 44): a GET that reads the caller's standing against the configured current version (line 59) and an [Idempotent] POST that records an acceptance (lines 93-94), both on LegalAcceptanceRoutes.Action, with the current version resolved from options (CurrentTermsVersion, line 54) and the derived controller supplying only the route, the DataExportControllerBase precedent (:19-21); and ServiceInfoControllerBase (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/ServiceInfoControllerBase.cs:30), whose dual-version /ServiceInfo returns ServiceInfoResponse for the deprecated v1.0 (line 51) and ServiceInfoV2Response for v2.0 (line 54, a superset adding the supported and deprecated version lists held at lines 32-33), proving the versioning machinery works across versions ([MapToApiVersion] at lines 40 and 46). The last two are the administration surface, and both are gated on a capability rather than a role name, so the framework never has to know an app's role vocabulary. UsersAdminControllerBase<TUserDto> (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Administration/UsersAdminControllerBase.cs:43) carries a single class-level [HasPermission(AdministrationPermissions.ManageUsers)] (line 42) over GET {userId} (line 55), the view-only GET {userId}/sessions (line 76, served by the framework's IUserSessionsAdministrationService injected into that action at line 82), the POST {userId}/lock and POST {userId}/unlock pair (lines 103 and 123), and PUT {userId}/roles (line 144), the rest over the app's own IUserAdministrationService<TUserDto>. The user roster is not an action here: it is the app's own generic paged entity endpoint (UsersAdminControllerBase.cs:20-23). A host that grants the permission to nobody serves endpoints that deny everyone, which is the safe direction. A completed administrative action is counted on the mmca.auth.admin_action instrument of the MMCA.Common.Auth meter through the internal AdminActionMetrics (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Administration/AdminActionMetrics.cs:17, meter name at line 20), recorded only after the service reported success and tagged only with the low-cardinality action name, never a user id or an address (:13-15; recorded at UsersAdminControllerBase.cs:496 and MachineClientsControllerBase.cs:94). RolesAdminControllerBase (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Administration/RolesAdminControllerBase.cs:69, gated on AdministrationPermissions.ManageRoles at line 60) reports each role's compiled and stored permissions (GET at line 80, GET {role} at line 121), publishes the permission catalog (GET catalog at line 102), and writes a stored set through PUT {role}/permissions (line 143), recording the caller through an overridable ResolveChangedBy (line 162). Two refusals on that write are the ones to memorize, both 400: a set that names ManageRoles itself is rejected, because granting from here would make access to role administration a matter of data and deleting the row would lock every operator out of the screen that could restore it, and a set naming anything outside the catalog is rejected rather than stored as a row no endpoint will ever check. All of these carry the same note: class-level routing and versioning attributes are not reliably inherited, so the per-service sealed subclass supplies them. This is the clearest [Rubric §5, Vertical Slice] and [Rubric §15, Best Practices & Code Quality] payoff in the presentation layer: a module writes a DTO, a mapper, and a short sealed subclass, and inherits a fully paged, filterable, exportable, error-mapped REST resource, with [Rubric §30, Compliance & Data Governance] covered by the DSAR base.

Export is a route, not a content negotiation. EntityControllerBase.ExportAsync (EntityControllerBase.cs:261-272) streams the same filtered collection the paged endpoint serves as an RFC 4180 CSV download, page-looping the query service server-side (ADR-078). It is a distinct path rather than an Accept: text/csv variant for two reasons stated in the source: the public output-cache policy varies by query string but not by Accept, so a cached JSON body could be replayed to a CSV request, and AddAPI sets ReturnHttpNotAcceptable = false, so a negotiation miss would fall back to JSON silently instead of returning 406 (EntityControllerBase.cs:198-203). The work is split in two. The controller keeps the HTTP concerns (the action, the row scope, the file name, and the headers) and hands the format to EntityCsvExporter<TEntityDTO> (MMCA.Common/Source/Presentation/MMCA.Common.API/Export/EntityCsvExporter.cs:18, an internal static class whose own summary draws that line at :11-15), which owns which DTO properties can be exported, how a page of rows becomes CSV records, and the paging loop that streams every page under a row ceiling (WriteAsync, line 117, invoked from EntityControllerBase.cs:293). Its record-writing primitive is CsvWriter (MMCA.Common/Source/Core/MMCA.Common.Shared/Serialization/CsvWriter.cs:45), a deliberately hand-written public static helper in MMCA.Common.Shared: it quotes only when RFC 4180 requires it (WriteField, line 206, with the trigger set as a SearchValues<char> at line 74), terminates records with CRLF regardless of host OS (line 61), formats cells invariantly so the same row produces the same bytes on every machine (FormatCell, line 144, which writes a Money cell as its amount plus ISO 4217 code through FormatMoney at line 176), and writes a UTF-8 BOM explicitly (line 58, through WriteByteOrderMark at line 85, paired with the preamble-free encoding at line 68) because Excel reads a BOM-less UTF-8 CSV in the machine's ANSI code page. Two guards run before any byte is written. Columns a CSV cannot represent faithfully, binary concurrency tokens and every non-string collection property, are computed once per closed DTO type and dropped (UnexportablePropertyNames at EntityCsvExporter.cs:32, the type test IsExportableType at :239-242); value objects and other class-typed properties are deliberately kept, because CsvWriter renders each as a value (Money as amount and currency code, Currency as its code, any other record as compact JSON rather than its compiler-generated ToString, :27-30). And a caller who names one of those dropped properties in fields= gets an Error.InvalidEntityField validation failure rather than a quietly missing column (ValidateFields, EntityCsvExporter.cs:62, called at EntityControllerBase.cs:279-281, right after the AuthorizeExport caller gate at :275-277). Then the exporter renders into an in-memory buffer rather than the response body (a StreamWriter over a MemoryStream, EntityCsvExporter.cs:133-136) and copies each page to the body with awaited writes only (DrainAsync, :210-222), because the synchronous CSV writer would otherwise flush synchronously whenever its buffer filled, which Kestrel rejects (:105-109). Nothing reaches the body until the first page has succeeded: headers, BOM, and the header row go out only then (:158-165), and a first-page failure comes back as a plain failed Result (:145-146), which is what keeps the "a failure on page one still returns Problem Details" path honest (EntityControllerBase.cs:314-315). A failure on a later page can no longer change the status, so the exporter logs it through the controller (LogExportPageFailure, EntityControllerBase.cs:755) and ends the file with an explicit # export incomplete after N rows line (EntityCsvExporter.cs:148-152, text at :364) rather than letting it pass for a complete export of fewer rows. The row ceiling is announced up front through the X-Export-Row-Limit header (constant at EntityControllerBase.cs:535, default 100,000 at line 526, overridable per host through MaxExportRows at lines 78-86, written alongside the Content-Disposition attachment name in BeginExportResponse at lines 728-735, the name being a UTC {controller}-{yyyyMMddTHHmmssZ}.csv built at lines 744-747) with a # export truncated at N rows notice written as a final body line (EntityCsvExporter.cs:193-196, text at :358), because headers are frozen the moment the first byte flushes; when the ceiling lands exactly on a page boundary the exporter consults the page's TotalItemCount instead of issuing one more query just to find out (:182-188), and a short page ends the loop only when that total agrees, because the query pipeline can clamp a full page below the requested size and stopping there would truncate the file with no marker (IsLastPage, :230-231). Row scoping is a shared hook rather than an export-only one: GetReadSpecificationAsync (EntityControllerBase.cs:680-682) is what all seven read actions apply (both GetAllAsync overloads, the lookup, GetByIdAsync, the export, GetCursorPageAsync, and GetChangesAsync, :645-647), resolved once per request so one instance filters every page of an export loop (:676-677). It is asynchronous because row scoping is rarely a pure function of the principal (:656-661), it returns GetExportSpecification(), itself null by default (line 710), and the lookup, which takes a predicate rather than a specification, receives the same scope as its Criteria (:325-327, passed at line 342). So an export or a dropdown can no longer drift wider than the list it mirrors, and a scoped GetByIdAsync answers a filtered-out row with 404 rather than 403 so the read cannot become an existence oracle (:671-673). The default differs by surface on purpose. The JSON read endpoints stay unscoped until a controller overrides one of the two hooks, but the export is fail-closed: when no scope resolves it queries nothing and answers 403 carrying ExportRowScopeRequiredErrorCode (Export.RowScopeRequired, line 541; the check at lines 286-288, the error built by UnscopedExportRefused at :717-722), unless the controller deliberately overrides AllowUnscopedExport (false by default, line 602) for rows every caller who can reach the endpoint may see, such as reference data or an admin-only table. A controller that forgot to scope its export therefore serves no rows rather than every row (:239-246). That is a [Rubric §12, Performance & Scalability] and [Rubric §11, Security] pairing worth reading closely.

Idempotency for safe retries. Write endpoints are made replay-safe by IdempotentAttribute (MMCA.Common/Source/Presentation/MMCA.Common.API/Idempotency/IdempotentAttribute.cs:22), a one-line ServiceFilterAttribute that resolves the scoped IdempotencyFilter (MMCA.Common/Source/Presentation/MMCA.Common.API/Idempotency/IdempotencyFilter.cs:70) from DI (ADR-017). The filter runs at two MVC stages. As an IAsyncResourceFilter it runs before model binding, the last point at which the body can be made replayable, and calls EnableBuffering only when an Idempotency-Key header is actually present (lines 119-125), so ordinary traffic pays nothing. As an IAsyncActionFilter it does the real work (line 128): with no key the action simply runs (lines 132-136); with one, it derives the cache key from the caller's user id claim (or anon: plus the remote IP), the HTTP method, the route template, and the client-supplied key, joined on newlines and SHA-256 hashed so the key length stays bounded (BuildCacheKey, lines 485-498). Scoping to the caller stops one user's cached response from being replayed to another; scoping to method plus route stops one key from colliding across endpoints that share a cache instance. It also hashes the buffered request body (ComputeRequestBodyHashAsync, rewinding the stream on both sides so model binding still sees it) and the request target (path plus query string) into a RequestFingerprint (IdempotencyFilter.cs:589, built at line 142) and binds both hashes to the record, so a replay must match the body and the target. The flow is then a lock-free fast path (TryReplayAsync called at line 143), then the guarded section. The guard is an IDistributedLock resolved from RequestServices when the host registers one (lines 148-156), because a per-process lock only serializes duplicates that land on the same replica and both deployed apps run more than one; a host with no distributed lock falls back to the striped KeyedSemaphoreStripe (field at line 90, used from line 201) rather than a per-key semaphore table that would grow unbounded or race on removal. Under the distributed lock the filter waits LockWait (5 seconds, line 104) for a lease living LockTimeToLive (30 seconds, line 97), double-checks the cache, and runs the action. Four outcomes are worth memorizing. A hit replays the stored IdempotencyRecord (MMCA.Common/Source/Presentation/MMCA.Common.API/Idempotency/IdempotencyRecord.cs:14, a status code plus JSON body plus the request-body hash) with an X-Idempotent-Replay: true header (line 383, through IdempotencyHeaders), as a bare StatusCodeResult when the stored body is empty so a replayed 204 does not acquire a content type (lines 384-391). A key reused with a different payload is answered 422 Unprocessable Entity rather than replayed (line 376 and BodyMismatchResult at 322-333), because replaying would tell the client a genuinely new write succeeded when nothing ran. A duplicate that cannot take the lock within the wait and finds nothing cached gets 409 Conflict (lines 263-269 and InFlightDuplicateResult at 301-312), which is retryable and honest rather than a second execution. And a cache or lock that faults is swallowed: the request runs without the guarantee and the degradation is counted (lines 255, 364, and 439), because deduplication is an optimization over an at-least-once client retry and must not become an outage of every write endpoint. Only 2xx results are stored, and only the two shapes the record can represent: an ObjectResult or a body-less StatusCodeResult such as NoContent() (BuildRecord, line 448), for IdempotencySettings.CacheExpirationHours (default 24, constrained to the range 1 to 168, MMCA.Common/Source/Presentation/MMCA.Common.API/Idempotency/IdempotencySettings.cs:15-16) through ICacheService (line 430). Replaying a transient 500 for a whole retention window would defeat the retry the header exists to enable. All three behaviors are observable: IdempotencyMetrics (MMCA.Common/Source/Presentation/MMCA.Common.API/Idempotency/IdempotencyMetrics.cs:16) publishes idempotency.replayed (line 36), idempotency.conflict tagged kind=body_mismatch or in_flight (lines 24, 29, and 41), and idempotency.degraded (line 46) on the MMCA.Common.Idempotency meter (line 19), so a sustained degraded rate says out loud that deduplication is effectively off. The one thing the filter cannot do is notice an endpoint that forgot to opt in, which is what NonIdempotentAttribute (MMCA.Common/Source/Presentation/MMCA.Common.API/Idempotency/NonIdempotentAttribute.cs:23) exists for: it attaches no pipeline stage and changes no behavior, it only records a required Justification string (line 28), and its sole consumer is the PostActionsDeclareIdempotencyIntent fitness function (MMCA.Common/Source/Hosting/MMCA.Common.Testing.Architecture/Rules/Cqrs/ArchitectureRules.Idempotency.cs:44, matching at :72-73), which fails the build unless every POST action carries either [Idempotent] or this attribute. That is why AuthControllerBase reads the way it does: all five of its POST actions (login, register, refresh, revoke, and the per-session revoke) carry a written reason for staying outside the contract (AuthControllerBase.cs:76, :94, :125, :153, and :217), since replaying a stored token pair would hand a retrying client credentials minted for an earlier call or already invalidated by rotation (a retried register hits the email-exists 409 instead, which is the correct answer), and replaying a cached 204 would report success for a revoke that never ran. OAuthControllerBase's POST exchange opts out for the same reason, since it burns a single-use code (OAuthControllerBase.cs:314). This is a [Rubric §7, Microservices Readiness], [Rubric §13, Observability & Operability], [Rubric §34, Architecture Governance] and [Rubric §29, Resilience & Business Continuity] control: at-least-once retry from a gateway or a flaky client cannot create duplicate resources, and "no idempotency here" is always a recorded decision rather than an omission nobody noticed.

Conditional writes: the ETag round trip, and only the header. Idempotency keys make a retried write safe; the concurrency token makes a racing write safe, and the HTTP way to state that precondition is If-Match (ADR-035). The token travels in exactly one place. IConcurrencyAware (MMCA.Common/Source/Core/MMCA.Common.Shared/DTOs/IConcurrencyAware.cs:15) is the read-side contract: a byte[] RowVersion declared init (line 19), rendered as the response ETag and echoed back by the client in its next write, and its own doc states the rule (lines 9-14): update requests carry no token, a persisted aggregate always has one, and a write that states no precondition is refused rather than falling back to last-write-wins. ConcurrencyETag (MMCA.Common/Source/Core/MMCA.Common.Shared/Http/ConcurrencyETag.cs:24, taught with the auth and HTTP primitives in Group 08) is the pure translation layer between the EF Core rowversion byte array and the wire: Format renders it as the weak tag W/"<base64>" (line 44) and TryParse reads one back (line 62), with the header names and the * wildcard as constants (:27, :30, :33). Weak is the honest strength, because a strong tag promises byte-for-byte equality of the representation, which this cannot promise when the same row version renders differently under a fields= projection (ConcurrencyETag.cs:13). The read side emits it automatically: EntityControllerBase.GetByIdAsync calls SetConcurrencyETag (EntityControllerBase.cs:396), which resolves the DTO's RowVersion property once per closed controller type (line 391, so a DTO with no token costs no per-request reflection), reads the token off either the typed DTO or the camelCase dictionary a fields= projection produces (ReadRowVersion, lines 434-443), and writes the header at line 425; the method is protected rather than private (line 417) so a controller serving a row from a custom read emits the same header instead of re-implementing the format, which is where the two halves drift apart and a precondition quietly stops working. The write side is SupportsIfMatchAttribute (MMCA.Common/Source/Presentation/MMCA.Common.API/Concurrency/SupportsIfMatchAttribute.cs:49), which, unlike IdempotentAttribute, needs no scoped service and therefore implements IAsyncActionFilter directly and needs no DI registration (lines 44-48). Before the action it decodes the header into HttpContext.Items under a public key (TokenItemKey, line 57, written at line 122), which the action reads back through the static RequiredToken (line 68); after the action it rewrites a conflict outcome to 412 Precondition Failed, covering an ObjectResult 409 and a bare StatusCodeResult 409 (lines 143-160) as well as a DbUpdateConcurrencyException the action let escape, which it answers with its own 412 Problem Details and marks handled so the global DbUpdateExceptionHandler never turns it into a 409 (lines 132-140). A given concurrency exception therefore reaches exactly one of those two places, and each records it on ConcurrencyConflictMetrics (MMCA.Common/Source/Presentation/MMCA.Common.API/Concurrency/ConcurrencyConflictMetrics.cs:24), so every conflict is counted once (ConcurrencyConflictMetrics.cs:14-17). That internal static class publishes persistence.concurrency.conflict (lines 37-40) on the MMCA.Common.Persistence meter (line 27, duplicated as a literal in MMCA.Common.Aspire because that package has no reference to this one, :8-10), tagged entity_type with the CLR type of the first conflicting entry read from the EF model, so a lazy-loading proxy reports its entity rather than the generated subclass, or unknown when the exception carries no entry (EntityTypeName, lines 55-56). No alert ships on it: a sustained rate on one entity type points at contended rows, which is a design question rather than an incident (:20-21). Three responses make the contract unambiguous. A missing or wildcard If-Match is 428 Precondition Required and the action never runs (lines 109-114 and 164-173), so last-write-wins is not reachable by omission. A malformed tag is a 400 rather than being ignored (lines 116-120 and 176-185), because silently dropping a precondition the client believed it had set is the one outcome worse than rejecting it. And 412 is used rather than 409 because RFC 9110 reserves it for a precondition the client stated in a header (SupportsIfMatchAttribute.cs:36-41). CrudEntityControllerBase<TEntity, TEntityDTO, TIdentifierType, TCreateRequest, TUpdateRequest> is where all of it lands: [SupportsIfMatch] on the PUT (CrudEntityControllerBase.cs:91), the token read at :102, and the whole set of outcomes declared as ProducesResponseType at :90-96. [Rubric §9, API & Contract Design] and [Rubric §8, Data Architecture], with a [Rubric §13, Observability & Operability] counter on the conflicts.

Output caching at the edge, and evicting it across services. Read endpoints that are user-independent by contract can be cached at the HTTP edge even when the UI attaches a bearer token to every request, which the built-in ASP.NET policy refuses to do. PublicEndpointOutputCachePolicy (MMCA.Common/Source/Presentation/MMCA.Common.API/Caching/PublicEndpointOutputCachePolicy.cs:56), registered by name through OutputCacheOptionsExtensions (MMCA.Common/Source/Presentation/MMCA.Common.API/Caching/OutputCacheOptionsExtensions.cs:6, both overloads at lines 20 and 34), drops that identity bail-out and enables caching for the authenticated request anyway (lines 88-90), varies by every query-string key (QueryKeys = "*" at line 96) so search, paging, filtering and field projection each get their own entry, refuses to store responses that set cookies or are not plain 200s (lines 125-128), and offers a bypassRoles escape hatch so a privileged caller who receives an elevated payload always reads fresh, skipping both lookup and storage (the constructor parameter at line 69, the role test at line 142, applied at lines 88-90, ADR-040). The store behind it defaults to per-replica memory, so a tag eviction on one instance leaves every other instance serving stale bytes. OutputCacheEvictionHandler (MMCA.Common/Source/Presentation/MMCA.Common.API/Caching/OutputCacheEvictionHandler.cs:32) closes that gap by consuming the OutputCacheEvictionRequested integration event and calling EvictByTagAsync for each tag against this host's store (lines 38-64); no broker type appears in it (it implements only IIntegrationEventHandler<OutputCacheEvictionRequested>, lines 32-35), so the same handler is reachable from the in-process dispatcher and from the framework's own broker receive path, where a host subscribes with RegisterOutputCacheEvictionConsumer() inside its AddBrokerMessaging configuration (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Consumers/IntegrationEventConsumerExtensions.cs:28, shorthand for RegisterIntegrationEventConsumer<OutputCacheEvictionRequested>() at line 32) (ADR-026). Its two behaviors are both deliberate: eviction is per-tag best effort, so a store that throws on one tag is logged and counted rather than rethrown (lines 56-62), because rethrowing would redeliver the message, re-evict every tag that already succeeded, and eventually dead-letter a message whose only consequence is a cache entry that expires on its own TTL anyway; and an OperationCanceledException is explicitly not swallowed (line 56), so host shutdown looks like shutdown rather than an acked message. The failures are visible through OutputCacheMetrics (MMCA.Common/Source/Presentation/MMCA.Common.API/Caching/OutputCacheMetrics.cs:16), which publishes cache.eviction.failed tagged by cache tag on the MMCA.Common.OutputCache meter (lines 19 and 29-30), the alert target for cross-service cache coherence: a non-zero rate means this host is serving responses it was told to drop. OutputCacheEvictionExtensions (MMCA.Common/Source/Presentation/MMCA.Common.API/Caching/OutputCacheEvictionExtensions.cs:27) is the DI half plus the in-process shortcut: AddOutputCacheEvictionHandler (line 111) registers the handler as a singleton through TryAddEnumerable (lines 115-117) so a host and a module that both ask for the behavior get one handler rather than a double eviction, while EvictTagsAsync (line 49) and the log-and-continue TryEvictTagsAsync (line 78) let code already running in this host evict its own tags without publishing an event to itself. One more type exists only because of the cache: ApiVersionReportingResultFilter (MMCA.Common/Source/Presentation/MMCA.Common.API/Caching/ApiVersionReportingResultFilter.cs:21), an internal IResultFilter that AddCommonApiVersioning adds to every MVC action (WebApplicationBuilderExtensions.cs:60). The versioning library writes api-supported-versions and api-deprecated-versions from a Response.OnStarting callback, but the output cache snapshots the headers when the body starts, before those callbacks run, so a cached entry would otherwise be stored and replayed without the report (ApiVersionReportingResultFilter.cs:13-17). The filter reports ahead of the body through whatever IReportApiVersions the host registered (OnResultExecuting, lines 24-40, skipping a response that has already started or an endpoint with no version metadata), so the headers land in the snapshot, the library's own callback finds them present and adds nothing, and a host with ReportApiVersions off still reports nothing. [Rubric §12, Performance & Scalability] with a [Rubric §13, Observability & Operability] backstop.

The contract surface: mapping, JSON, and query filters. The framework maps between the wire and the domain by hand, not through a runtime reflection mapper (ADR-001). Two interfaces in the Application layer define the shape, both in MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/IEntityDTOMapper.cs: IEntityDTOMapper<TEntity, TEntityDTO, TIdentifierType> (line 14) turns an entity into its DTO and supplies a default interface implementation for the collection overload (line 27), and IEntityRequestMapper<TEntity, TCreateRequest, TIdentifierType> (line 42) turns an incoming request into a domain entity through its factory, returning a Result so mapping-time validation (a uniqueness check, for example) is a first-class failure rather than an exception (line 54). Their write-side twin, IEntityUpdateApplier<TEntity, TUpdateRequest, TIdentifierType> (same file, line 79), belongs to the CQRS group because it is what lets one generic update handler own loading, the concurrency token, and the save while the aggregate keeps owning its invariants (IEntityDTOMapper.cs:62-74). All three are auto-registered by module assembly scanning. The query string has one edge helper of its own, QueryFilterModelBinder (MMCA.Common/Source/Presentation/MMCA.Common.API/ModelBinders/QueryFilterModelBinder.cs:25) parses the filters[Prop].operator= and filters[Prop].value= query-string convention into the (operator, value) dictionary the paged read and export endpoints hand to the specification layer, capping one request at MaxFilters = 50 distinct properties (line 34, enforced at lines 61-62, bounding the per-request reflection work a caller can demand from QueryFilterService) and discarding entries missing an operator or a value (line 75). Request bodies that carry a file get the same treatment: FormFileUploadExtensions (MMCA.Common/Source/Presentation/MMCA.Common.API/Uploads/FormFileUploadExtensions.cs:31) puts the size check, the single exact read, and the refusal error behind one call (:27-28), answering an UploadedFileContent (FormFileUploadExtensions.cs:16, the bytes plus the file name and content type exactly as the client declared them) or, for a CSV import, a CsvUpload (:24) that keeps the raw upload beside the parsed table so a command can store or re-parse it while the edge runs its own validation and dry run (:19-20); the OversizeFormResourceFilter (MMCA.Common/Source/Presentation/MMCA.Common.API/Uploads/OversizeFormResourceFilter.cs:22) that AddAPI installs reads the form before model binding only for an action that binds one, so the server's "request body too large" refusal reaches the exception handlers as a 413 instead of becoming a model-state 400, and a streaming upload that reads the body itself is never buffered (:9-19). JSON bodies get a ceiling of their own: JsonRequestBodyLimitMiddleware (MMCA.Common/Source/Presentation/MMCA.Common.API/Middleware/JsonRequestBodyLimitMiddleware.cs:28), the JsonBodySizeLimit pipeline step placed after routing because it reads the selected endpoint's metadata (MiddlewarePipelineBuilder.cs:82-86), bounds a JSON request on any endpoint that states no size of its own to Api:MaxJsonBodyBytes (default 1 MiB, key at JsonRequestBodyLimitMiddleware.cs:31): a declared Content-Length over the limit answers 413 up front, otherwise the per-request body cap is lowered so a chunked body is cut off with the same 413, and a multipart upload, a form post, or an endpoint with its own limit keeps the server's limit (:13-21). The small shared DTO vocabulary those generics rely on lives in MMCA.Common.Shared: IBaseDTO<TIdentifierType> (MMCA.Common/Source/Core/MMCA.Common.Shared/DTOs/IBaseDTO.cs:9, an Id declared with an init accessor at line 13), BaseLookup<TIdentifierType> (MMCA.Common/Source/Core/MMCA.Common.Shared/DTOs/BaseLookup.cs:8, a required id at line 12 plus a required display name at line 15, for dropdowns and autocomplete), and the concurrency contract IConcurrencyAware described above. Manual mapping keeps the DTO contract explicit and reviewable: the [Rubric §9, API & Contract Design] and [Rubric §15, Best Practices] position this codebase takes deliberately.

Feature gating and per-module controller visibility. Three mechanisms let an operator turn surface area on and off without a code change. DisabledFeatureHandler (MMCA.Common/Source/Presentation/MMCA.Common.API/FeatureManagement/DisabledFeatureHandler.cs:14) renders a consistent Problem Details 404 when a FeatureGate-protected action is reached while its flag is off (lines 18-26), so a disabled feature looks like a nonexistent endpoint rather than an error (ADR-031). A percentage rollout needs to be sticky per user rather than random per request, which is what CurrentUserTargetingContextAccessor (MMCA.Common/Source/Presentation/MMCA.Common.API/FeatureManagement/CurrentUserTargetingContextAccessor.cs:68) supplies: registered by AddAPI through WithTargeting<...> (DependencyInjection.cs:108-109), it builds the targeting context from the current request's principal, taking the user id from the user_id claim that TokenService emits and falling back to the principal's name (line 86), and taking the groups from the caller's role claims under all three types the JWT middleware may produce (ClaimTypes.Role, role, roles, lines 76-82) because ICurrentUserService is scoped while this accessor is a singleton (DependencyInjection.cs:101-106). An anonymous request yields an empty context (lines 67-74), so a targeted feature is simply off for anonymous callers, and the accessor can never fail a request. A flag's value need not wait for a deployment either. A host that opts in to reloadable flags (AddReloadableFeatureFlags, which binds FeatureFlagOverrideSettings from the FeatureFlags section, MMCA.Common/Source/Core/MMCA.Common.Application/FeatureFlags/FeatureFlagOverrideSettings.cs:6-12) layers StoredOverrideFeatureDefinitionProvider (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/FeatureFlags/StoredOverrideFeatureDefinitionProvider.cs:31) over the configuration provider: a flag with a stored override answers with the override's definition and every other flag answers from configuration unchanged (:10-12, :43-50), so the FeatureGate decorators keep calling IFeatureManager and an override takes effect on the next evaluation with no restart (:16-18). It fails toward configuration, never toward an exception: an override set that cannot be loaded leaves every flag on its configured value and logs a warning (:24-25, :75-79). The overrides themselves are FeatureFlagOverride rows (MMCA.Common/Source/Core/MMCA.Common.Domain/FeatureFlags/FeatureFlagOverride.cs:24, created through a Result-returning Create at line 82 and cleared by soft delete at line 134) whose FeatureFlagOverrideMode is Off (the kill switch), On, Percentage, or Targeting (MMCA.Common/Source/Core/MMCA.Common.Shared/FeatureFlags/FeatureFlagOverrideMode.cs:12-28), translated into a FeatureDefinition by FeatureFlagDefinitions (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/FeatureFlags/FeatureFlagDefinitions.cs:33). They live in the owning service's own database behind IFeatureFlagOverrideStore, implemented by EFFeatureFlagOverrideStore (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/FeatureFlags/EFFeatureFlagOverrideStore.cs:33), in a FeatureFlagOverrides table (FeatureFlagOverrideModelBuilderExtensions, MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/FeatureFlags/FeatureFlagOverrideModelBuilderExtensions.cs:23) that enters the model only through FeatureFlagOverrideModelContributor (FeatureFlagOverrideModelBuilderExtensions.cs:86), the internal IModelContributor that AddReloadableFeatureFlags registers: it applies only to the one source FeatureFlags:DataSourceName names (AppliesTo, :92-93) and runs in the BeforeEntityPasses phase (:89), because an override is an auditable entity the soft-delete filter and concurrency token must see (:81-82). Its registration is the opt-in, so a host that never makes the call keeps a byte-identical model and sees no migration (:75-79, ADR-148). Reads go through IFeatureFlagOverrideSnapshot, whose FeatureFlagOverrideSnapshot (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/FeatureFlags/FeatureFlagOverrideSnapshot.cs:46) holds the whole override table as one entry in the host's ICacheService for OverrideCacheSeconds (default 30, FeatureFlagOverrideSettings.cs:24), keyed by both the application name and the data source so two services sharing one Redis never read each other's snapshot (FeatureFlagOverrideSnapshot.cs:27-32), and invalidated by prefix on a write so every replica of a two-level-cache host stops addressing the old snapshot (:18-24, :70-71). The administration half is IFeatureFlagAdministrationService, implemented by the internal FeatureFlagAdministrationService (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/FeatureFlags/FeatureFlagAdministrationService.cs:30, ListAsync, SetOverrideAsync, and ClearOverrideAsync at lines 45, 62, and 86), which validates a name against the FeatureFlagCatalog (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/FeatureFlags/FeatureFlagCatalog.cs:17, built from the registered FeatureFlagAssembly records at line 9 through FeatureFlagRegistry, which reads every public const string on a static *Features class into a FeatureFlagDescriptor, MMCA.Common/Source/Core/MMCA.Common.Shared/FeatureFlags/FeatureFlagRegistry.cs:17, :35, and :46, each declared with its FeatureFlagAttribute and FeatureFlagLifetime, MMCA.Common/Source/Core/MMCA.Common.Shared/FeatureFlags/FeatureFlagAttribute.cs:32). It is exposed over HTTP by FeatureFlagsControllerBase (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Administration/FeatureFlagsControllerBase.cs:38, gated on AdministrationPermissions.ManageFeatures at line 37: GET at line 49, PUT {name} at line 68, DELETE {name} at line 93). The wire vocabulary is the Shared records SetFeatureFlagOverrideRequest (MMCA.Common/Source/Core/MMCA.Common.Shared/FeatureFlags/SetFeatureFlagOverrideRequest.cs:18), FeatureFlagOverrideResponse (FeatureFlagOverrideResponse.cs:14), FeatureFlagStatusResponse (FeatureFlagStatusResponse.cs:15), and the FeatureFlagValueKind enum (FeatureFlagValueKind.cs:10) (ADR-031).

The newer edge surface: opt-in actions, declarative caching, view-as, and the composed host. Several smaller pieces extend the edge without changing a host that ignores them. Two marker attributes opt an entity controller in to extra list actions: SupportsCursorPagingAttribute (MMCA.Common/Source/Presentation/MMCA.Common.API/Pagination/SupportsCursorPagingAttribute.cs:14, the keyset list served by the query service's GetPageByCursorAsync, :4-11) and SupportsChangeFeedAttribute (MMCA.Common/Source/Presentation/MMCA.Common.API/Pagination/SupportsChangeFeedAttribute.cs:14, the change feed served by GetChangesSinceAsync, :4-11). Both are enforced by the internal OptInActionAttribute (MMCA.Common/Source/Presentation/MMCA.Common.API/Pagination/OptInActionAttribute.cs:17), an IActionModelConvention that removes the base action from any controller that did not opt in, so it has no route and no API description (:6-13). Output caching gains two declarative forms: PublicCachedReadsAttribute (MMCA.Common/Source/Presentation/MMCA.Common.API/Caching/PublicCachedReadsAttribute.cs:42, an IControllerModelConvention) marks the inherited base reads anonymous and output-cached under one named policy and names the by-id route, so a controller no longer overrides a read only to add attributes (:9-21), and EvictOutputCacheAttribute (MMCA.Common/Source/Presentation/MMCA.Common.API/Caching/EvictOutputCacheAttribute.cs:36, an IAsyncResultFilter) evicts its tags after a 2xx write and before the body is written, evicts nothing on a non-2xx, a GET or HEAD, or an unhandled exception, and logs rather than fails when eviction throws (:12-27). Rate limiting gains RateLimitPartitions (MMCA.Common/Source/Presentation/MMCA.Common.API/RateLimiting/RateLimitPartitions.cs:11), partition factories for a host's own policies built on the framework's limiters (:7-9), and the in-memory fixed window now runs through RemainingWindowFixedWindowRateLimiter (MMCA.Common/Source/Build/RateLimiting/RemainingWindowFixedWindowRateLimiter.cs:31), one internal source file linked into each package that runs such a window, which rewrites the 429's Retry-After hint from the whole window length to the time actually remaining (:6-22), handing back a RejectedLease that carries only that hint (:133-137). Read-only support access (ADR-137) has its HTTP half in ViewAsGuardMiddleware (MMCA.Common/Source/Presentation/MMCA.Common.API/Middleware/ViewAsGuardMiddleware.cs:42): for a principal carrying act_sub it refuses every method other than GET, HEAD, and OPTIONS with 403, except the action marked by ViewAsEndEndpointAttribute (:245) and an endpoint marked read-only, and it re-checks that the grant is still live on every request, answering 401 otherwise (:13-33). Unlike the soft-deleted-user gate it fails closed, because an outage then costs one support session rather than a write in someone else's name (:35-39). A service that does not hold the grant store checks the shared-cache ViewAsEndedMarker (MMCA.Common/Source/Presentation/MMCA.Common.API/Middleware/ViewAsEndedMarker.cs:32) instead, written only by the end endpoint (:16-26). The controller tower grows to match. Under Controllers/Administration, AuditHistoryControllerBase (AuditHistoryControllerBase.cs:48, GET {entity}/{key} at line 93 behind AdministrationPermissions.ViewAuditTrail at line 47) and ViewAsGrantsAdminControllerBase (ViewAsGrantsAdminControllerBase.cs:40, behind ManageUsers at line 39) join the users and roles bases; MachineClientsControllerBase (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/MachineClients/MachineClientsControllerBase.cs:42, behind ManageClients at line 38: list, create, and rotate, promote, and revoke at lines 48, 68, 93, 115, and 140) manages service credentials that MachineTokenControllerBase (MachineTokenControllerBase.cs:40) exchanges for a token through one anonymous POST behind auth-ip (lines 45-48). Three more self-service sign-in bases follow the same app-owns-the-command pattern as the recovery bases: SignInLinkControllerBase<TSendCommand, TRedeemCommand> (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/SignInLinks/SignInLinkControllerBase.cs:35, anonymous sign-in-link and sign-in-link/redeem behind auth-ip, lines 80-83 and 108-111), PasskeysControllerBase (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Passkeys/PasskeysControllerBase.cs:41, [Authorize] registration and management from line 62, anonymous signin/options and signin behind auth-ip at lines 229-232 and 254-257), and TwoFactorControllerBase<TBeginCommand, TConfirmCommand, TDisableCommand, TRegenerateCommand> (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/TwoFactor/TwoFactorControllerBase.cs:60, status, enrollment, confirmation, recovery codes, and disable at lines 92, 119, 150, 190, and 219, every action plain [Authorize] rather than a permission, :28). External sign-in now also accepts generic OIDC providers: each OidcProviderSettings (MMCA.Common/Source/Presentation/MMCA.Common.API/Authentication/OidcProviderSettings.cs:20) is read from OAuth:Oidc:<Name> (:8-10), the configured set is held by OidcProviderRegistry (OidcProviderRegistry.cs:10, registered only when at least one provider exists, :4-7), and OidcClaimNormalizer (OidcClaimNormalizer.cs:21) maps the validated ID token onto the app's claim shape, keyed by a stable oid or {iss}|{sub} and never by the mutable email (:6-18). On the outbound side, OutboundAddressPolicy (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Http/OutboundAddressPolicy.cs:11) holds an operator-supplied URL to public addresses, at validation time and again at connect time, so a stored webhook target cannot reach the host's own network (:7-9, the IPv6 allow-list at :35-38). Finally, the separate MMCA.Common.ServiceHost package composes all of this for an extracted service: ServiceHostBuilderExtensions's AddMmcaServiceHost (MMCA.Common/Source/Hosting/MMCA.Common.ServiceHost/ServiceHostBuilderExtensions.cs:65) runs the start-up list every extracted host repeated, in the one correct order, taking vendor calls only as callbacks so the package stays cloud-neutral (:21-24, ADR-059); what differs between hosts arrives through MmcaServiceHostOptions (MMCA.Common/Source/Hosting/MMCA.Common.ServiceHost/MmcaServiceHostOptions.cs:16, defaulting to an HTTP/2 cleartext endpoint at line 42 and ServiceHostAuthentication.ForwardedJwtBearer at line 52), and the returned MmcaServiceHost (MmcaServiceHost.cs:11) is what ServiceHostApplicationExtensions's UseMmcaServiceHostAsync (ServiceHostApplicationExtensions.cs:44) takes to apply the post-Build() pipeline, with the internal ServiceHostOpenApi (ServiceHostOpenApi.cs:10) and ServiceHostProfiling (ServiceHostProfiling.cs:11, the MiniProfiler step) as its helpers. [Rubric §7, Microservices Readiness], [Rubric §11, Security], and [Rubric §12, Performance & Scalability] again, each piece opt-in.

Per-module controller visibility. Back on the feature-gating thread, at a coarser grain, ModuleControllerFeatureProvider (MMCA.Common/Source/Presentation/MMCA.Common.API/ModuleControllerFeatureProvider.cs:28) removes a disabled module's controllers from MVC discovery entirely, snapshotting the disabled names once (lines 36-39), returning immediately when none are disabled (lines 41-44), and matching a .{ModuleName}. token against the controller's assembly name or namespace (lines 60-81, the dots on both sides preventing a Catalogue false positive on Catalog), so a module switched off in configuration cannot have its routes mapped (they would otherwise 500, since the module's DI services were never registered). Together these are the feature-flag story extended to the HTTP edge and part of the [Rubric §7, Microservices Readiness] "one codebase, many deployment shapes" design.

Well-known endpoints, database initialization, and the extraction edge. Several types here exist only so a module can be lifted out of the monolith into its own service (ADRs 004, 007, 008). JwksEndpointExtensions (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/Endpoints/JwksEndpointExtensions.cs:15) serves /.well-known/jwks.json (path constant at line 20, mapped at line 33) from IJwksProvider so extracted services validate tokens against the issuer's public keys instead of a shared secret, serializing the key set once per provider instance through the private SerializedKeySetCache (JwksEndpointExtensions.cs:65), whose Entry record (:84) pairs the key set with its JSON, so a provider that rebuilt its keys is serialized again and the same instance is not (:62-63), and OidcDiscoveryEndpointExtensions (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/Endpoints/OidcDiscoveryEndpointExtensions.cs:24) serves the minimal discovery document the JWT middleware fetches when AddForwardedJwtBearer sets an authority: it returns 404 when Jwt:Issuer is not configured (lines 62-66), derives jwks_uri from that configured issuer rather than from the inbound request (line 76) so issuer and JWKS URI stay origin-aligned, and disables the camelCase naming policy (line 45) because RFC 8414 field names are snake_case and jwksUri would not be recognized; the document is held by the private SerializedDocumentCache (OidcDiscoveryEndpointExtensions.cs:89) and rebuilt only if the configured issuer changes (:86-87). AddForwardedJwtBearer itself resolves RequireHttpsMetadata in three steps, explicit argument, then the Authentication:JwtBearer:RequireHttpsMetadata key (constant at WebApplicationBuilderExtensions.Authentication.cs:25), then "true outside Development" (WebApplicationBuilderExtensions.Authentication.cs:64-66); a resolved false outside Development is honored, because an internal-ingress h2c authority genuinely has no HTTPS metadata, but it is never silent: InsecureJwtMetadataWarningStartupFilter (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/Auth/InsecureJwtMetadataWarningStartupFilter.cs:15) is registered exactly then (WebApplicationBuilderExtensions.Authentication.cs:68-72) and logs one startup warning naming the key (InsecureJwtMetadataWarningStartupFilter.cs:21 with the message at :26-28). It is an IStartupFilter rather than a log line at registration time for a reason worth remembering: while the service collection is being built the logging providers are not configured yet, so a warning written there is dropped (InsecureJwtMetadataWarningStartupFilter.cs:7-13). The signing keys themselves are held to a strength floor at startup. JwtKeyStrengthValidator (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/Auth/JwtKeyStrengthValidator.cs:22) requires an RSA key of at least JwtSettings.MinimumRsaKeySizeBits bits (set through Jwt:MinimumRsaKeySizeBits, :27) and an EC key on P-384, checking only the keys the selected algorithm reads (:10-15), and JwksKeyStrengthValidator (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/Auth/JwksKeyStrengthValidator.cs:20) holds the current published key and every JwksSettings.AdditionalKeys entry to the same floor. Outside Development a shortfall fails options validation, so ValidateOnStart stops the host; in Development it logs one warning; and a missing environment is never treated as Development (JwtKeyStrengthValidator.cs:19-20). Both are registered as IValidateOptions singletons (WebApplicationBuilderExtensions.Authentication.cs:149 and :151). DatabaseInitializationExtensions (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/DatabaseInitializationExtensions.cs:28) initializes every physical data source the host owns: InitializeDatabaseAsync (line 51) validates the strategy before touching anything (EnsureKnownStrategy, called at line 63 and declared at line 290, which accepts only Migrate or None and otherwise throws naming the valid values through UnknownStrategy at line 302), warms the IEntityDataSourceRegistry so entity-to-database routing is deterministic before the first repository call (lines 70-72), runs EnsureCreated for the migration-less Cosmos, PostgreSQL, and SQLite sources up front (lines 76-106, skipping a PostgreSQL or SQLite source that does configure a migrations assembly, because creating its tables without an __EFMigrationsHistory row leaves every migration both pending and un-appliable), then, under a raised five-minute command timeout so a replica queued behind another's EF migrations lock does not die at the 30-second default (InitializationCommandTimeout, line 37, applied at line 112 through RaiseCommandTimeouts, line 257), applies the configured strategy per migrated source (lines 118-128), where None is the production guard that throws with a per-source breakdown of pending migrations (line 124 into ThrowIfPendingMigrationsAsync at line 359; ADR-030, ADR-006), repeats the same strategy per tenant that keeps its own copy of a source, each in a fresh scope with its tenant set (line 130 into InitializeTenantDatabasesAsync at line 196, ADR-073), and finishes by running the enabled modules' seeders on the default scope only (line 137). Five smaller startup helpers round out the host: OpenApiEndpointExtensions (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/Endpoints/OpenApiEndpointExtensions.cs:26) maps the per-version OpenAPI document (MapCommonOpenApi, lines 34-38) and the optional Scalar reference UI (MapCommonScalarUi, lines 52-56), both outside Production only, ApiParameterDescriptorBackfillProvider (MMCA.Common/Source/Presentation/MMCA.Common.API/OpenApi/ApiParameterDescriptorBackfillProvider.cs:43) fills in the placeholder descriptor MVC leaves null on an unbound route token (lines 65-71) so a URL-segment-versioned or {tenant}-templated route cannot turn document generation into a 500, running last by ordering itself at int.MinValue (line 46) and registered exactly once through TryAddEnumerable however many helpers a host calls (WebApplicationBuilderExtensions.cs:56 and :103, through the private helper at :124-126), the paired StronglyTypedIdSchemaTransformer (MMCA.Common/Source/Presentation/MMCA.Common.API/OpenApi/StronglyTypedIdSchemaTransformer.cs:24) and StronglyTypedIdParameterTransformer (same file, line 74), both registered by AddCommonOpenApi through a ConfigureAll that reaches every versioned document (WebApplicationBuilderExtensions.cs:116-120) and both inert in a host that declares no wrappers: the schema half clears the object schema the default generator produces for a one-property struct and rewrites it as the wrapped primitive's type and format (:38-41, mapped at :46 and :51) so the document matches the bare-primitive wire shape, and the operation half does the same for route and query parameters, which the API explorer describes as plain strings because they bind through a TypeConverter (:74-107, ADR-115), SignalRExtensions (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/SignalRExtensions.cs:12) maps NotificationHub at its configured path when push notifications are enabled (lines 22-27), MiniProfilerExtensions (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/MiniProfilerExtensions.cs:11) registers MiniProfiler with Entity Framework profiling when ApplicationSettings.UseMiniProfiler is set (lines 16-25), and AppAssociationEndpointExtensions (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/Endpoints/AppAssociationEndpointExtensions.cs:15) with AppAssociationOptions (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/Endpoints/AppAssociationOptions.cs:9) serve the Android Digital Asset Links and Apple App Site Association documents (paths at lines 18 and 24, mapped at lines 42 and 46) that let a mobile OS hand this host's https links to the installed native app (ADR-043). ExternalAuthExtensions (MMCA.Common/Source/Presentation/MMCA.Common.API/Authentication/ExternalAuthExtensions.cs:44) completes the OAuth half of authentication, staying entirely inert when no provider is configured (lines 47-52), each of Google, GitHub, and Apple gated on its OAuth:{Provider}:ClientId being present (lines 60-73) and throwing at startup when the matching client secret is missing (lines 98-100 and 110-112); Apple has no static secret, so its handler mints one (line 130) and startup throws instead on a missing TeamId, KeyId, or PrivateKeyPem (lines 131-139). Apple also never puts the user's name in its ID token: it posts it once, as the user form field of the first authorization's callback, and never again for that Apple ID, so the Apple scheme hooks OnCreatingTicket to AppleUserNameClaims (ExternalAuthExtensions.cs:239-241). That internal static helper (MMCA.Common/Source/Presentation/MMCA.Common.API/Authentication/AppleUserNameClaims.cs:18) reads the already buffered callback form (AddFromCallbackFormAsync, line 28, the field name held as UserFormField at line 21) and copies name.firstName and name.lastName into ClaimTypes.GivenName and ClaimTypes.Surname (AddFromUserField, line 47, the claims added at lines 75-76), leaving any claim the identity already carries untouched (line 86) and adding nothing for a missing or malformed field (lines 49-52 and 70-73), because the name is best effort and must never fail the sign-in. Without it the account is created with the "User User" placeholders and the real name cannot be recovered on a later sign-in (AppleUserNameClaims.cs:7-16). Taken together these are the [Rubric §7, Microservices Readiness], [Rubric §11, Security], and [Rubric §12, Performance & Scalability] concerns that let the same controller code run identically in a monolith and in a fleet of extracted services behind a YARP gateway.

Where this group sits. Everything above is the outermost ring. It depends downward on the CQRS pipeline and query services (Groups 03 and 05), the auth and caching infrastructure (Groups 08 and 09), the persistence factories (Group 07), the integration-event contracts it consumes (Group 04), and the module system that discovers controllers and drives health checks (Group 14 via ModuleLoader), and it rests on the Result and domain primitives (Groups 01 and 02). Nothing inside the framework depends on it: the app hosts and the gRPC transport group (Group 13) call into it. AssemblyReference and ClassReference (MMCA.Common/Source/Presentation/MMCA.Common.API/AssemblyReference.cs:8 and :20) are the scanning anchors that let those callers point at this assembly without naming an incidental type. Read the group as the framework's HTTP grammar: the reusable edge every downstream service inherits so its own code stays modules and domain logic, never plumbing.

AssemblyReference

MMCA.Common.API · MMCA.Common.API · MMCA.Common/Source/Presentation/MMCA.Common.API/AssemblyReference.cs:8 · Level 0 · class (static)

  • What it is: a tiny static class that exposes the MMCA.Common.API assembly handle and its simple name, so convention-based scanners have a stable, refactor-safe anchor into this layer.
  • Depends on: System.Reflection (BCL) only (AssemblyReference.cs:1).
  • Concept introduced (assembly-marker types for convention scanning). Scrutor-based DI registration and the architecture fitness rules both need a stable "anchor" type to say scan the assembly that contains this. Rather than reaching for typeof(SomeIncidentalClass).Assembly, a dedicated AssemblyReference makes the intent explicit and survives type moves. [Rubric §2, Design Patterns] assesses whether recurring structural problems are solved with named, reusable patterns; here the same two-type marker shape repeats in every layer and module assembly, which is exactly this pattern applied uniformly. [Rubric §33, Developer Experience] assesses how easy the framework is to build on; centralizing one assembly handle per package means every scan call references one obvious token.
  • Walkthrough: two public static readonly fields. Assembly (AssemblyReference.cs:11) is typeof(AssemblyReference).Assembly, resolved once at type initialization. AssemblyName (AssemblyReference.cs:14) is Assembly.GetName().Name with a ?? string.Empty fallback for logging and diagnostics.
  • Why it's built this way: a purpose-built anchor decouples scanning from any incidental type. The pattern is duplicated in every layer so each assembly is self-describing without a cross-layer reference back to a single "well-known" class.
  • Where it's used: module handler/validator/mapper scanning (see ModuleLoader) and the architecture tests' package-assembly pinning.

ClassReference

MMCA.Common.API · MMCA.Common.API · MMCA.Common/Source/Presentation/MMCA.Common.API/AssemblyReference.cs:20 · Level 0 · class

  • What it is: an empty, instantiable class in the MMCA.Common.API assembly, used where a generic constraint or a typeof(...) needs a concrete reference type from this layer rather than an Assembly instance.
  • Depends on: nothing. See AssemblyReference for the full concept; ClassReference is its type-shaped sibling.
  • Concept: covered under AssemblyReference. Where AssemblyReference.Assembly answers "which assembly", ClassReference answers "give me a class token from that assembly" for APIs whose generic parameter is constrained to a reference type (where T : class).
  • Walkthrough: the whole type is public class ClassReference; (AssemblyReference.cs:20), a body-less class declaration whose doc comment (:17-19) states the intent. It carries no members; its identity is the entire point.
  • Why it's built this way: some registration and scanning helpers take a marker type parameter instead of an Assembly; a dedicated empty class keeps those call sites from accidentally binding to a real domain or controller type.
  • Where it's used: generic registration helpers that need a per-assembly type anchor from the API layer.

AppleUserNameClaims

MMCA.Common.API · MMCA.Common.API.Authentication · MMCA.Common/Source/Presentation/MMCA.Common.API/Authentication/AppleUserNameClaims.cs:18 · Level 0 · class (internal static)

  • What it is: an internal static helper that recovers the user's given name and surname during a Sign in with Apple callback and adds them to the external identity as ClaimTypes.GivenName and ClaimTypes.Surname claims.
  • Depends on: the ASP.NET Core OAuth ticket context (OAuthCreatingTicketContext), System.Security.Claims, and System.Text.Json. No first-party dependencies. It is plugged into the Apple handler by ExternalAuthExtensions (ExternalAuthExtensions.cs:241).
  • Concept introduced (best-effort claim enrichment from a one-time payload). Apple's ID token never carries the user's name. Apple posts it once, as JSON in the callback form's user field, and only on the first authorization; every later sign-in sends an empty field (AppleUserNameClaims.cs:21, :45). [Rubric §11, Security] assesses how external identity input is trusted; here the payload is untrusted form data, parsed defensively, and a failure never blocks sign-in.
  • Walkthrough
    • UserFormField = "user" (:21) names the form field.
    • AddFromCallbackFormAsync(OAuthCreatingTicketContext) (:28) is the OnCreatingTicket handler. It returns early when there is no identity or the request is not form-encoded (:30-33), then reads the already buffered form (:35) and delegates to AddFromUserField with the scheme's ClaimsIssuer (:36).
    • AddFromUserField(ClaimsIdentity, string?, string?) (:47) returns on a blank value, parses the JSON, requires an object with a name object, and reads firstName and lastName (:54-68). A JsonException is swallowed (:70-73): the name is best effort and the controller's placeholders apply instead.
    • AddIfMissing (:84) adds a claim only when the value is non-blank and the identity does not already carry that claim type, so an existing claim is never overwritten (:84-91); ReadString (:79) trims string values and ignores non-strings.
  • Why it's built this way: the sign-in must never fail because a cosmetic field is missing or malformed, and the one-time nature of the payload means the only chance to capture it is inside the callback, which is why it hooks OnCreatingTicket rather than the controller.
  • Where it's used: only by the Apple branch of ExternalAuthExtensions (ExternalAuthExtensions.cs:241); covered by MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/Authentication/AppleUserNameClaimsTests.cs.

OidcClaimNormalizer

MMCA.Common.API · MMCA.Common.API.Authentication · MMCA.Common/Source/Presentation/MMCA.Common.API/Authentication/OidcClaimNormalizer.cs:21 · Level 0 · class (internal static)

  • What it is: an internal static helper that rebuilds the principal a generic OpenID Connect handler produces from a validated ID token into the claim shape the OAuth controller already reads, so a new OIDC provider needs no app change (OidcClaimNormalizer.cs:5-8).
  • Depends on: System.Security.Claims only (OidcClaimNormalizer.cs:1). It is called from the OnTokenValidated event that ExternalAuthExtensions wires for every OIDC scheme (ExternalAuthExtensions.cs:155-159).
  • Concept introduced (provider-neutral identity normalization). Each OIDC issuer names its claims a little differently, and the handler is configured to keep the raw names (ExternalAuthExtensions.cs:143-145). This class maps them onto one fixed shape and drops everything else. [Rubric §11, Security] assesses how external identity input is trusted; two choices here are trust decisions. The provider key is never the email, which a user or an administrator can change (OidcClaimNormalizer.cs:10-13), and email_verified passes through only when the operator configured the provider with TrustEmail and the token asserts it, so an app that links an external login to an existing account by email does so only for an issuer the operator vouched for (:14-16).
  • Walkthrough
    • EmailVerifiedClaimType = "email_verified" (OidcClaimNormalizer.cs:24) names the one non-standard claim the app reads.
    • Normalize(ClaimsPrincipal, string providerName, bool trustEmail) (:31) starts an empty claim list (:33), adds ClaimTypes.NameIdentifier from ProviderKey when one can be built (:35-39), then copies email, given name, surname, and name, each from the raw OIDC claim name with the mapped ClaimTypes name as a fallback (:41-44). It adds email_verified=true only when trustEmail is set and the token's value parses as true (:46-51). The result is a new principal whose authentication type is the provider name (:53), which the controller passes on as the login provider (:17-18).
    • ProviderKey (:56) returns {tid}|{oid} when both claims are present (:58-63); for Entra ID sub is pairwise per application while oid is the stable user id inside the tenant (:10-12). Otherwise it uses sub (or NameIdentifier) and returns null when there is none (:65-69), qualifies it with the iss claim, falling back to the subject claim's Issuer when iss was not kept and the issuer is not the default (:71-78), and returns {iss}|{sub}, or null when no issuer is known (:80).
    • First (:83-86) returns the first non-blank value across a list of claim types, and AddIfPresent (:88-94) adds a claim, issued by the provider name, only when the value is non-blank.
  • Why it's built this way: keying on {iss}|{sub} rather than the bare sub keeps two issuers from colliding on the same subject value, and building a fresh principal (rather than adding to the handler's) guarantees the controller sees only claims this class vouches for.
  • Where it's used: only by the OIDC branch of ExternalAuthExtensions (ExternalAuthExtensions.cs:157). See ADR-036 for the external-login decision.

OidcProviderSettings

MMCA.Common.API · MMCA.Common.API.Authentication · MMCA.Common/Source/Presentation/MMCA.Common.API/Authentication/OidcProviderSettings.cs:20 · Level 1 · record (internal sealed partial)

  • What it is: the validated configuration of one generic OIDC provider, a positional record of Name, Authority, ClientId, ClientSecret, Scopes, DisplayName, Domains, and TrustEmail (OidcProviderSettings.cs:20-28), plus the static reader that builds the list from configuration.
  • Depends on: IConfiguration and a source-generated Regex (OidcProviderSettings.cs:1-2, :140-141). First-party, it asks the Shared-layer OidcReservedProviderNames whether a section name is reserved (:3, :74).
  • Concept introduced (fail-fast, configuration-driven provider registration). Any OIDC provider joins by adding an OAuth:Oidc:<Name> section (SectionPath, OidcProviderSettings.cs:31); no code changes. [Rubric §11, Security] and [Rubric §9, API & Contract Design] both apply: a misconfigured section throws an InvalidOperationException that names the offending key at startup rather than producing a half-working scheme, and a section without ClientId stays inert, the same gate the built-in providers use (:35-44).
  • Walkthrough
    • ReadAll(IConfiguration) (:45) is null-tolerant about the section (:47-48) and reads each child whose ClientId is set (:52). It tracks which provider claimed each email domain and throws when a second provider lists a domain already claimed, because each domain may map to one provider only (:50, :55-61).
    • Read (:69) takes the section key as the name. It rejects a reserved name through OidcReservedProviderNames.IsReserved (:74-78): google, github, and apple (the built-in providers) and complete, exchange, and discover (the controller's own literal routes, which would shadow the challenge), compared ignoring case (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/ExternalProviders/OidcReservedProviderNames.cs:15-17, :22). It also rejects a name that fails ^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$, because the name becomes a URL path segment (OidcProviderSettings.cs:80-84, :140).
    • Authority and ClientSecret are required through Required (:86-87, :123-129). Scopes default to openid profile email when none are configured, and openid is inserted first when a configured list omits it (:33, :89-101). Domains are normalized, blanks dropped, and de-duplicated ignoring case (:103-107). DisplayName falls back to the name (:109, :118), and TrustEmail is true only when it parses as such (:110).
    • NormalizeDomain (:137-138) trims and drops a leading @; case is kept because every comparison is ordinal-ignore-case (:131-134).
  • Why it's built this way: validating eagerly at registration means an operator learns about a typo in a deployment, not at a user's first sign-in, and the reserved-name list keeps a configured provider from silently hijacking a built-in route. The list lives in Shared rather than here because it serves both halves: the API refuses a reserved section at startup, and the UI never lists one as a sign-in option (OidcReservedProviderNames.cs:9-10).
  • Where it's used: read by ExternalAuthExtensions (ExternalAuthExtensions.cs:72) and held by OidcProviderRegistry. See ADR-036.

OidcProviderRegistry

MMCA.Common.API · MMCA.Common.API.Authentication · MMCA.Common/Source/Presentation/MMCA.Common.API/Authentication/OidcProviderRegistry.cs:10 · Level 1 · class (internal sealed)

  • What it is: an internal lookup over the configured OidcProviderSettings list (primary-constructor parameter, OidcProviderRegistry.cs:10), registered as a singleton only when at least one OIDC provider is configured (ExternalAuthExtensions.cs:105-114).
  • Depends on: OidcProviderSettings for the provider list and its NormalizeDomain rule (OidcProviderRegistry.cs:34).
  • Concept introduced (home-realm discovery by email domain). A sign-in page can ask for an email address and route the user to the provider whose Domains claim that address's domain, rather than showing one button per provider. [Rubric §9, API & Contract Design] is relevant: both lookups return null instead of throwing, so the controller decides the response.
  • Walkthrough
    • Find(string? name) (OidcProviderRegistry.cs:15-18) returns the provider whose name equals the route segment, ignoring case, or null for a blank name or no match.
    • FindByEmail(string? email) (:26) takes the domain after the last @ and returns null for a missing @, an empty local part, or an empty domain (:28-32). It then normalizes the domain and returns the provider whose Domains contains it, exact match ignoring case (:34-37); a subdomain does not match its parent (:20-23).
  • Why it's built this way: the registry is absent in a host with no OIDC configuration, so the controller resolves it optionally and the generic routes stay inert.
  • Where it's used: OAuthControllerBase resolves it from the request services (OAuthControllerBase.cs:190) and calls Find for the generic challenge route (:160) and FindByEmail for discovery (:181).

ExternalAuthExtensions

MMCA.Common.API · MMCA.Common.API.Authentication · MMCA.Common/Source/Presentation/MMCA.Common.API/Authentication/ExternalAuthExtensions.cs:44 · Level 8 · class (static)

  • What it is: a static class that registers the external OAuth provider schemes (Google, GitHub, Apple), one OpenID Connect scheme per configured OAuth:Oidc:<Name> section, and the short-lived cookie scheme that carries the external principal from the provider callback to the app's OAuth controller. It is the counterpart wiring that AddCommonAuthentication (JWT-only) deliberately leaves out.
  • Depends on: the ASP.NET Core authentication, HTTP, configuration, DI, and OpenID Connect protocol surfaces (ExternalAuthExtensions.cs:1-5), plus the provider handlers reached through AddGoogle, AddGitHub, AddApple, and AddOpenIdConnect (:178, :195, :211, :127). First-party, it partners with the app's OAuth controller subclassing OAuthControllerBase, whose ExtractClaims consumes the schemes registered here (ExternalAuthExtensions.cs:10-12, :204-205), reads OidcProviderSettings, registers OidcProviderRegistry, hands each OIDC principal to OidcClaimNormalizer and maps the Google and Apple email-verified assertions onto its EmailVerifiedClaimType (:190-191, :237), routes every provider's remote failure through OAuthReturnUrls (:22-27), and names the same signal the UI's ConfigurationOAuthUISettings uses to decide which buttons to render (:16-18).
  • Concept introduced (config-gated, additive auth registration). The single public const string ExternalLoginScheme = "ExternalLogin" (ExternalAuthExtensions.cs:50) is shared with the OAuth controller so the sign-in scheme name can never drift between the two halves of the flow. The important property of this class is that it is additive and inert: AddCommonAuthentication registers only the JWT bearer scheme, so without this call the OAuth controller would Challenge and read schemes that are not in the authentication pipeline and the flow would fail at runtime (:14-16), yet a host with no OAuth configuration section keeps the JWT-only default completely untouched. [Rubric §11, Security] assesses how authentication, secrets, and trust boundaries are handled; each provider is gated on its ClientId being present, a missing companion secret throws at startup (:181-183, :198-200, :220-228), a misconfigured OIDC section fails startup naming its key (:59-61, :71-72) rather than silently half-configuring an auth scheme, and a round trip that fails at the provider lands on the login page with an error code instead of surfacing as a 500 (:22-27). The provider's email-verified assertion also reaches the app: Google and Apple map theirs onto one email_verified claim that the controller passes to ExternalLoginAsync, GitHub asserts nothing so its logins read as unverified, and an OIDC provider's assertion passes only under TrustEmail (:28-35). [Rubric §9, API & Contract Design] is relevant because the opt-in posture mirrors AddPermissions (ADR-020), and the class doc says so explicitly (:19-20).
  • Walkthrough
    • The public surface is one C# extension(IServiceCollection services) block (ExternalAuthExtensions.cs:52), matching the DI convention described in the primer.
    • AddExternalAuthProviders(IConfiguration configuration) (:64) reads the OAuth section (:66), pulls Google:ClientId, GitHub:ClientId, and Apple:ClientId (:67-69), and reads every OIDC provider eagerly through OidcProviderSettings.ReadAll (:71-72). When all three client ids are empty and no OIDC provider is configured it returns the collection untouched (:76-82), which is what keeps environments without OAuth secrets (most tests, local dev) exactly as AddCommonAuthentication left them (:74-75).
    • When at least one is configured it calls services.AddAuthentication() with no argument (:86). The comment above it is the load-bearing detail (:84-85): the parameterless overload does not reset the default scheme set by AddCommonAuthentication, it just yields a builder to append schemes onto.
    • It then adds the ExternalLogin cookie (:88) and each configured built-in provider in turn, each behind its own non-empty check (:90-103). When OIDC providers exist it adds one scheme per provider and registers a singleton OidcProviderRegistry, which the controller's generic challenge route and home-realm discovery read (:105-114), before returning services for chaining (:116).
    • AddOidcProvider (:126-160) registers an OpenID Connect scheme named after the provider, using its display name (:127): authorization code flow with PKCE (:132-133), signing into ExternalLoginScheme (:134) with callback /auth/callback/<Name> (:135) and OnRemoteFailure bound to OAuthReturnUrls.RedirectRemoteFailureAsync (:136). The sign-out callback and remote sign-out paths are per provider, because the handler defaults are shared and two OIDC providers would otherwise claim the same path (:138-141). MapInboundClaims = false, SaveTokens = false, and GetClaimsFromUserInfoEndpoint = false (:145-147) keep raw claim names (sub, iss, tid, oid, email_verified) for the event and keep the ID token out of the cookie, since nothing downstream reads it (:143-144). The scope list is replaced by the provider's (:149-153), and OnTokenValidated swaps the principal for OidcClaimNormalizer's output (:155-159).
    • AddExternalLoginCookie (:166-175) configures the bridge cookie: name mmca_external_login (:169), HttpOnly (:170), SameSite=Lax (:173, sufficient because the OAuth round trip returns as a top-level GET navigation, which avoids the Secure plus cross-site cost that SameSite=None imposes, :171-172), and a 10-minute expiry (:174).
    • AddGoogleProvider (:177-192) and AddGitHubProvider (:194-208) each set the client id, require the matching ClientSecret or throw (:181-183, :198-200), set SignInScheme = ExternalLoginScheme, pin a fixed CallbackPath (/auth/callback/google at :185, /auth/callback/github at :202), bind OnRemoteFailure to OAuthReturnUrls.RedirectRemoteFailureAsync (:186, :203), and set SaveTokens = true (:187, :207). Google also maps both the v3 userinfo key email_verified and the legacy v2 key verified_email onto OidcClaimNormalizer.EmailVerifiedClaimType through ClaimActions.MapJsonKey (:189-191). GitHub additionally requests the user:email scope (:206) because it does not return the email on the default scope and the controller's ClaimTypes.Email lookup would otherwise fail (:204-205); it maps no verified claim.
    • AddAppleProvider (:210-242) is the one that differs structurally among the built-in providers. Its ClientId is the Apple Services ID, not the app bundle id (:213-215), and Apple has no static client secret at all: the handler mints a short-lived ES256 JWT from the developer's private key, so GenerateClientSecret = true (:219) and TeamId (:220), KeyId (:223), and PrivateKeyPem (:226) are each required-or-throw. The PEM is handed over as a callback returning a ReadOnlyMemory<char> (:229). Scheme, callback path (/auth/callback/apple, :232), the OnRemoteFailure binding (:233), and SaveTokens (:234) match the other two. The ID token's email_verified (asserted for relay and real addresses alike) is mapped onto OidcClaimNormalizer.EmailVerifiedClaimType (:236-237). It also wires options.Events.OnCreatingTicket = AppleUserNameClaims.AddFromCallbackFormAsync (:241), because the handler reads only the ID token, which never carries the name; Apple posts the name once, in the callback's user form field, on the first authorization (:239-240). See AppleUserNameClaims.
  • Why it's built this way: the cookie is intentionally short-lived and single-purpose. It exists only to bridge the provider callback to the controller's CompleteAsync, which signs it out the moment the local JWT pair is minted (:163-164). Splitting the OAuth scheme registration from AddCommonAuthentication keeps the JWT-only default free of provider secrets, and gating each provider independently means one provider's configuration never disturbs another's. Every provider, built-in or OIDC, signs into the same cookie and shares the same remote-failure handler, so the controller's completion path and the failure destination are shared. See ADR-036 for the external-login decision.
  • Where it's used: called from the host composition of a service that exposes social login; pairs with the app's OAuthController (subclass of OAuthControllerBase). Covered by MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/Authentication/ExternalAuthExtensionsTests.cs, ExternalAuthOidcTests.cs, ExternalAuthRemoteFailureTests.cs, and ExternalLoginEmailVerifiedTests.cs.

OAuthReturnUrls

MMCA.Common.API · MMCA.Common.API.Authentication · MMCA.Common/Source/Presentation/MMCA.Common.API/Authentication/OAuthReturnUrls.cs:13 · Level 6 · class (internal static)

  • What it is: an internal static helper that decides where an external sign-in lands when it ends, shared by OAuthControllerBase (a completion that failed or succeeded) and the provider handlers' remote-failure event (a round trip that never reached the completion), so both choose the destination the same way (OAuthReturnUrls.cs:8-12).
  • Depends on: the ASP.NET Core authentication surface for RemoteFailureContext, configuration, and DI (OAuthReturnUrls.cs:1-3), plus OAuthControllerBase for its UIBaseUrlConfigKey (:4, :34).
  • Concept introduced (one destination rule for every way a sign-in ends). [Rubric §11, Security] applies twice. A failed provider round trip (the user cancelled at the provider, the correlation cookie expired during a long wait, or the state is forged or stale) redirects to the login page instead of letting the handler's exception surface as a 500 (:23-28). And the native-callback allowlist accepts only a custom scheme listed in OAuth:AllowedReturnUrlSchemes, never http or https, so web destinations always flow through the config-pinned OAuth:UIBaseUrl and the allowlist cannot become an open redirect (:58-63, :70-75); see ADR-043.
  • Walkthrough
    • Two constants: FailedErrorCode = "oauth_failed", the code the login page shows as a readable alert (:18), and ReturnUrlItemKey = "returnUrl", the authentication-properties key the challenge stashes the client's return URL under (:21).
    • RedirectRemoteFailureAsync(RemoteFailureContext context) (:31) is the handler every provider in ExternalAuthExtensions binds to OnRemoteFailure. It reads the trimmed UI base URL (:33-34) and the stashed return URL; a forged or stale state yields no properties, so only the web login page is possible then (:36-38). It redirects to ErrorRedirectUrl(..., FailedErrorCode) and calls HandleResponse() so the handler does not throw (:40-42).
    • ErrorRedirectUrl(string uiBaseUrl, Uri? mobileReturnUrl, string errorCode) (:53-56) returns {uiBaseUrl}/login?error=<code> normally, or the allow-listed native callback with error=<code> appended (so the WebAuthenticator window closes) when one is in play.
    • GetAllowedMobileReturnUrl(IConfiguration configuration, string returnUrl) (:68) returns null for anything that is not an absolute URI or is http/https (:70-75), then matches the scheme against OAuth:AllowedReturnUrlSchemes ignoring case (:80-81). The read is null-tolerant on purpose: a missing section, an empty one, or a test double whose GetSection returns null all mean "no allowlist", never a throw from the binder (:77-79).
    • AppendQuery(Uri target, string queryFragment) (:88) appends with ? or & onto OriginalString, not ToString(), because URI normalization adds a trailing slash to authority-only URIs and native authenticator callback matching can be exact (:90-94).
  • Why it's built this way: the controller's completion and the handlers' remote-failure event are two separate code paths that must agree on the destination; one internal class keeps the error-code shape, the allowlist, and the exact-echo rule in one place.
  • Where it's used: OAuthControllerBase calls ErrorRedirectUrl, GetAllowedMobileReturnUrl, AppendQuery, and both constants (OAuthControllerBase.cs:218, :203, :209, :217, :239, :254, :394); ExternalAuthExtensions binds RedirectRemoteFailureAsync for every provider (ExternalAuthExtensions.cs:136, :178, :191, :221). Covered by MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/Authentication/ExternalAuthRemoteFailureTests.cs.

ModuleControllerFeatureProvider

MMCA.Common.API · MMCA.Common.API · MMCA.Common/Source/Presentation/MMCA.Common.API/ModuleControllerFeatureProvider.cs:28 · Level 2 · class (sealed)

  • What it is: an IApplicationFeatureProvider<ControllerFeature> that removes controllers belonging to disabled modules from MVC's controller discovery, so a module turned off via configuration exposes no routes.
  • Depends on: ModulesSettings (the config-bound enabled/disabled map, ModuleControllerFeatureProvider.cs:4) and the MVC application-parts surface (IApplicationFeatureProvider<ControllerFeature>, ControllerFeature, ApplicationPart, :2-3), plus System.Reflection for the TypeInfo it inspects (:1).
  • Concept introduced (module-aware controller discovery). MVC discovers controllers by scanning referenced assemblies. When a host references a module's API assembly transitively but an operator has disabled that module (Modules:{Name}:Enabled=false), MVC would still map its controllers, and every request to them would 500 because the module's DI services were never registered (ModuleControllerFeatureProvider.cs:19-25). [Rubric §7, Microservices Readiness] assesses whether modules can be composed and decomposed cleanly; this provider is one boundary that lets a module be switched off without deleting code or breaking the host, complementing the disabled-module stub registrations in the module system. [Rubric §29, Resilience, Reliability & Business Continuity] is relevant: the enable/disable decision is enforced once at the edge rather than checked inside each controller.
  • Walkthrough: the primary-constructor parameter is ModulesSettings modulesSettings (ModuleControllerFeatureProvider.cs:28-29). PopulateFeature (:33) first snapshots the disabled module names once (:36-39) so it does not re-scan the settings dictionary per controller, returns early if none are disabled (:41-44), then materializes the matches and removes every controller matched by IsDisabledModuleController (:46-53). The private static matcher (:60) reads the controller's assembly simple name and namespace, each with a ?? string.Empty fallback (:64-65), and, for each disabled module, tests whether either contains the token .{ModuleName}. (:72). Wrapping the module name in dots is deliberate: it matches .Catalog. inside MMCA.Store.Catalog.API or its .Controllers namespace while avoiding false positives from substrings like "Catalogue" (:69-71). The comparison is OrdinalIgnoreCase on both the assembly name and the namespace (:74-75), and the loop falls through to false when nothing matches (:81).
  • Why it's built this way: matching on the dotted token handles both the MMCA.{Repo}.{Module}.API convention and the legacy {Prefix}.Modules.{Module}.* convention without maintaining a registry of controller types (:14-17). Removing controllers at feature-provider time is earlier than routing, so a disabled module is invisible rather than returning a runtime error.
  • Where it's used: registered by DependencyInjection's AddAPI(modulesSettings) via ConfigureApplicationPartManager (DependencyInjection.cs:72-73), but only when a non-null ModulesSettings is supplied (DependencyInjection.cs:70); pairs with the module system's disabled-stub registrations so cross-module interfaces stay resolvable.

DependencyInjection

MMCA.Common.API · MMCA.Common.API · MMCA.Common/Source/Presentation/MMCA.Common.API/DependencyInjection.cs:26 · Level 11 · class (static)

  • What it is: the primary DI entry point for the MMCA.Common.API layer. Using a C# extension(IServiceCollection services) block (DependencyInjection.cs:28) it adds six methods to IServiceCollection: AddAPI, AddErrorLocalization, AddErrorResources<TResource>, AddCommonExceptionHandlers, AddServerAuthSessionCookie, and AddModuleHealthChecks.
  • Depends on: a broad slice of the API layer plus feature management and localization (DependencyInjection.cs:1-19). Notable first-party types wired here: the Shared-layer EnumerationJsonConverterFactory (aliased, :19, because the Shared and API namespaces both surface converters), and StronglyTypedIdJsonConverterFactory (ADR-115 strongly typed identifiers, serializing wrapper types as their bare primitive), UnhandledResultFailureFilter, OversizeFormResourceFilter (from MMCA.Common.API.Uploads, :15), IdempotencyFilter and IdempotencySettings, OwnerOrAdminFilter and its OwnerOrAdminFilterOptions, ModuleControllerFeatureProvider, CurrentUserTargetingContextAccessor and DisabledFeatureHandler, IErrorLocalizer/ErrorLocalizer, ErrorResources/ErrorResourceSource, the exception handlers (OperationCanceledExceptionHandler, DbUpdateExceptionHandler, ValidationExceptionHandler, GlobalExceptionHandler), CookieTokenReader and ICookieSessionRefresher/CookieSessionRefresher, ICookieSessionEnder/CookieSessionEnder, the session-cookie options and store (SessionCookieSettings, ISessionCookieStore/SessionCookieStore, from MMCA.Common.API.SessionCookies, :14), and ModuleLoader/ModulesSettings. Externals: Microsoft.FeatureManagement (including its IDisabledFeaturesHandler contract), Microsoft.Extensions.Localization, ASP.NET Core MVC/ProblemDetails/HealthChecks/DataProtection.
  • Concept introduced (layered DI wiring at the API edge). [Rubric §3, Clean Architecture] assesses whether each layer registers only its own concerns; this class wires controllers, JSON/XML formatters, filters, feature management, exception handlers, and health checks, all API-layer edges, and reaches down to Application only for ModulesSettings/ModuleLoader (:16-17). [Rubric §13, Observability & Operability] and [Rubric §17, DevOps] both apply through AddModuleHealthChecks (:230), which projects module state into /health checks tagged module so /health?tag=module reports each module's status (:222-223). [Rubric §9, API & Contract Design] is relevant: every parameter is optional and defaulted so a host wires only what it needs.
  • Walkthrough
    • AddAPI(ModulesSettings? modulesSettings = null, IConfiguration? configuration = null) (DependencyInjection.cs:45) registers controllers with ReturnHttpNotAcceptable = false, the UnhandledResultFailureFilter global filter, and the OversizeFormResourceFilter at its own FilterOrder, so an oversize form body answers 413 rather than model binding's 400 (:47-54). It adds two JSON converters (:55-67) and the XML DataContract formatters (:68); Currency is not among them because it carries its own converter in Shared (:31-32). The first converter is the load-bearing one for enumerations: concrete enumerations do not inherit the base class's [JsonConverter] attribute because System.Text.Json resolves it with inherit: false, so the factory is registered once here and every Enumeration<T> serializes by Name across the whole API surface (:57-60). The second, StronglyTypedIdJsonConverterFactory (:62-66), does the same job for ADR-115 strongly typed identifiers, so wrapper types serialize as the bare primitive they wrap without the attribute being repeated on every wrapper a consumer declares; in a host that declares no wrappers the factory converts nothing. It then conditionally registers ModuleControllerFeatureProvider when modulesSettings is non-null (:70-74), conditionally binds IdempotencySettings from the config section with data-annotation validation on start (:76-82), and registers the scoped IdempotencyFilter and OwnerOrAdminFilter (:87-88). Scoped is driven by OwnerOrAdminFilter, which takes the scoped ICurrentUserService; IdempotencyFilter takes only a logger and reads the singleton ICacheService from the request's services (:84-86). Right after that it binds OwnerOrAdminFilterOptions with data-annotation validation but deliberately not ValidateOnStart (:90-95): BypassRole is required with no default, the framework knows no role names, so validating at startup would fail every host that never applies the filter; validating on first resolve puts the message in front of the host that actually uses it. Feature management comes next (:97-110) and is worth reading closely: AddHttpContextAccessor() is called first because it is TryAdd-based and therefore safe to repeat, then AddFeatureManagement().WithTargeting<CurrentUserTargetingContextAccessor>() registers the feature manager plus the built-in Percentage/TimeWindow/Targeting filters and supplies the targeting audience from the current request's principal, which is what makes a percentage rollout sticky per user instead of random per request; the accessor is a singleton, which is exactly why it reads IHttpContextAccessor rather than the scoped ICurrentUserService. Finally the singleton DisabledFeatureHandler is bound to IDisabledFeaturesHandler (:110) and AddErrorLocalization() is called (:113).
    • AddErrorLocalization() (:125) registers ASP.NET localization (:127), the singleton IErrorLocalizer via TryAddSingleton so a host can substitute its own (:128), and the framework's own ErrorResources source (:129-133). The framework source is registered inline as an ErrorResourceSource with IsFramework = true (:132) rather than through AddErrorResources<ErrorResources>(), so the localizer can consult it last: a module's entry for a code wins over the framework's (:121-122). AddErrorResources<TResource>() (:144) adds a module's resource anchor as another ErrorResourceSource built from an IStringLocalizerFactory (:146-147). This is the ADR-027 edge error-localization extension point, keyed by Error.Code, and modules add their translations additively (:119-122).
    • AddCommonExceptionHandlers() (:157) registers ProblemDetails (adding a requestId extension from TraceIdentifier, :159-161) then four IExceptionHandlers in specificity order (:162-165): OperationCanceled, DbUpdate, Validation, and GlobalExceptionHandler as the catch-all. ASP.NET Core invokes them in registration order and stops at the first that handles the exception, hence most-specific first and the 500 fallback last (:153-154).
    • AddServerAuthSessionCookie(string apiBaseAddress) (:182) wires the SSR-prerender auth path and the matching sign-out (:171-175): it guards the address (:184), then adds HttpContextAccessor, memory cache, the scoped CookieTokenReader (:186-188), a named HttpClient pointed at the internal API base address (:190-191), and the CookieSessionRefresher as a singleton (:194). The singleton is load-bearing: its in-flight map must be shared across requests for single-flight refresh to work (:193). The singleton ICookieSessionEnder/CookieSessionEnder follows via TryAddSingleton (:198): when the browser signs out (DELETE /auth/session-cookie) it ends the session behind the refresh cookie through the same named client, at the identity endpoint's anonymous auth/session/end (:196-197). It then registers the SessionCookieSettings options with no configuration binding, so SameSite and the cookie lifetime keep their default behavior unless the same-origin API proxy in MMCA.Common.UI.Web tightens SameSite on opt-in (ADR-131) (:200-202). Next it calls AddDataProtection() (:208): the access-token cookie is protected with DataProtection on write and unprotected on every read, so a multi-replica host must persist the key ring (AddAzureDataProtection and its peers), or a cookie another replica wrote reads as no access cookie and the refresh cookie re-issues one (:204-207). The singleton ISessionCookieStore/SessionCookieStore follows via TryAddSingleton (:209). Last it registers TimeProvider.System via TryAddSingleton (:211-214): the refresher judges access-token expiry against the injected clock, and a Blazor Web host that calls only this method has no AddServices registration to supply one, while TryAdd never displaces a clock the host registered itself. The doc comment is explicit that the address is the internal endpoint, not the browser-facing one (:178-179).
    • AddModuleHealthChecks(ModuleLoader moduleLoader) (:230) adds one health check per module, Healthy for each enabled module (:234-240) and Degraded for each disabled one (:242-249), named module-{Name} and tagged module. It must run after ModuleLoader's DiscoverAndRegister (:225-228).
  • Why it's built this way: bundling the API-edge concerns behind small, defaulted extension methods lets each host opt into exactly the surface it needs (a JWT-only test host skips AddServerAuthSessionCookie; a monolith with no disabled modules passes a null modulesSettings; a host with no idempotency configuration passes a null configuration and keeps the defaults). The exception-handler ordering, the oversize-form filter's 413, the enumeration and strongly-typed-id converter factories, the OwnerOrAdminFilterOptions validate-on-resolve (not on-start) choice, the targeting accessor's singleton lifetime, the refresher's singleton lifetime, the DataProtection registration that multi-replica hosts back with a persisted key ring, and the TryAdd fallback clock for hosts that call only AddServerAuthSessionCookie are the non-obvious, correctness-critical choices, and each carries an inline comment. Error localization is registered automatically by AddAPI so modules only add their own resources additively (ADR-027).
  • Where it's used: called from every service host's composition (Program.cs of the ADC/Store/Helpdesk API hosts and the integration-test hosts) to wire the shared API layer; AddApplicationDecorators() still runs last in the overall sequence (see MMCA.Common/CLAUDE.md DI ordering note).
  • Caveats / not-in-source: the relative ordering of AddAPI against AddInfrastructure/AddApplication in a given host is not fixed by this file; only AddApplicationDecorators() last is load-bearing.

ApiVersionReportingResultFilter

MMCA.Common.API · MMCA.Common.API.Caching · MMCA.Common/Source/Presentation/MMCA.Common.API/Caching/ApiVersionReportingResultFilter.cs:21 · Level 0 · class (internal sealed)

  • What it is: an MVC IResultFilter that writes the api-version report headers (api-supported-versions, api-deprecated-versions) before a result writes its body, so the output cache stores them with the entry (ApiVersionReportingResultFilter.cs:8-12).
  • Depends on: Asp.Versioning (IReportApiVersions, ApiVersionMetadata), Microsoft.AspNetCore.Http, and Microsoft.AspNetCore.Mvc.Filters (ApiVersionReportingResultFilter.cs:1-4). No first-party dependencies.
  • Concept introduced (report before the body so the cache snapshot sees it). The versioning library reports from a Response.OnStarting callback, but the output cache snapshots response headers when the body starts, before those callbacks run, so a cache hit replayed the stored headers without the version report (:14-17). [Rubric §9, API & Contract Design] assesses whether the contract a client observes is stable; this filter keeps the version headers present on cached and uncached responses alike. Versioning itself is the decision recorded in ADR-046, and the cache that makes the ordering matter is the one configured by OutputCacheOptionsExtensions.
  • Walkthrough: OnResultExecuting (:28-44) returns early if the response has already started (:31-34). Otherwise it reads ApiVersionMetadata from the matched endpoint (:36) and the host's IReportApiVersions from RequestServices (:37); if either is missing it returns (:38-41), else it calls reporter.Report(response, metadata.Map(reporter.Mapping)) (:43). OnResultExecuted is an empty body (:47-49).
  • Why it's built this way: reporting ahead of the body puts the headers in the cache snapshot, and the library's own OnStarting callback then finds them present and adds nothing (:17-18). Resolving IReportApiVersions from DI, rather than writing the headers directly, means a host with ReportApiVersions off still reports nothing (:18-19).
  • Where it's used: added to the global MVC filter collection by WebApplicationBuilderExtensions (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/WebApplicationBuilderExtensions.cs:60), right after AddApiParameterDescriptorBackfill() in the versioning setup. See WebApplicationBuilderExtensions.

ConcurrencyConflictMetrics

MMCA.Common.API · MMCA.Common.API.Concurrency · MMCA.Common/Source/Presentation/MMCA.Common.API/Concurrency/ConcurrencyConflictMetrics.cs:24 · Level 0 · class (internal static)

  • What it is: the OpenTelemetry counter for optimistic-concurrency conflicts: how often a save lost to a moved row version and the request was answered with a conflict, tagged by the entity type that conflicted (ConcurrencyConflictMetrics.cs:6-11).
  • Depends on: System.Diagnostics.Metrics (Meter, Counter<long>) and Microsoft.EntityFrameworkCore for DbUpdateConcurrencyException (ConcurrencyConflictMetrics.cs:1-2). No first-party dependencies. Its two recording sites are SupportsIfMatchAttribute and DbUpdateExceptionHandler.
  • Concept: the same "meter a mechanism an operator cannot otherwise see" idea introduced at IdempotencyMetrics and applied to cache eviction at OutputCacheMetrics, here applied to optimistic concurrency (ADR-035). A conflict is a correct outcome for the request that lost, so nothing fails visibly; the counter is what shows contention. [Rubric §13, Observability & Operability] assesses whether such a signal is exported. The type doc settles two points worth carrying (:12-23).
    • Counted once, at the two places a conflict becomes a response (:14-17): SupportsIfMatchAttribute answers 412 under an explicit If-Match and marks the exception handled, and DbUpdateExceptionHandler answers 409 for every other endpoint. A given exception reaches exactly one of the two, so each conflict is counted once.
    • No alert ships on it (:20-21): a sustained rate on one entity type points at contended rows (two editors, or a background writer racing user edits), which is a design question rather than an incident.
  • Walkthrough
    • MeterName = "MMCA.Common.Persistence" (:27) and a single static Meter built from it (:35). UnknownEntityType = "unknown" (:30) is the tag value when the exception names no entry; the tag name itself, entity_type, is private (:33).
    • ConflictCounter (:37-40) is a Counter<long> named persistence.concurrency.conflict with unit {conflict}.
    • RecordConflict(DbUpdateConcurrencyException) (:46-47) adds one, tagged with EntityTypeName(exception).
    • EntityTypeName (:55-56) returns UnknownEntityType when exception.Entries is empty, otherwise the CLR name of the first entry's type read from the EF model (Entries[0].Metadata.ClrType.Name), so a lazy-loading proxy reports its entity rather than the generated subclass (:49-52). The tag is bounded by the host's entity vocabulary.
  • Why it's built this way: internal static keeps the instrument out of the package's public surface while the filter and the handler in the same assembly record it. As with OutputCacheMetrics, the meter name is duplicated as a literal in MMCA.Common.Aspire because that package has no reference to MMCA.Common.API, and a host exports the counter by registering the meter, which the Aspire service defaults do (:8-10).
  • Where it's used: twice. SupportsIfMatchAttribute records before replacing the exception with a 412 (MMCA.Common/Source/Presentation/MMCA.Common.API/Concurrency/SupportsIfMatchAttribute.cs:186), and DbUpdateExceptionHandler records only for the DbUpdateConcurrencyException kind, leaving unique-key and foreign-key failures uncounted so they do not hide the contention signal (MMCA.Common/Source/Presentation/MMCA.Common.API/Middleware/DbUpdateExceptionHandler.cs:51-56).

EvictOutputCacheAttribute

MMCA.Common.API · MMCA.Common.API.Caching · MMCA.Common/Source/Presentation/MMCA.Common.API/Caching/EvictOutputCacheAttribute.cs:36 · Level 0 · class (sealed)

  • What it is: an attribute that is also an MVC result filter. Placed on a write action or on a whole controller, it evicts the output-cache tags it names after the write succeeds, instead of a hand-written eviction call before every return (EvictOutputCacheAttribute.cs:11-14).
  • Depends on: Microsoft.AspNetCore.Mvc.Filters.IAsyncResultFilter, IStatusCodeActionResult for the result's own status, IOutputCacheStore, and ILogger with a NullLogger fallback (EvictOutputCacheAttribute.cs:1-7). The eviction itself is the best-effort TryEvictTagsAsync verb of OutputCacheEvictionExtensions (:114).
  • Concept introduced (declarative, outcome-aware cache eviction). A public read cached by PublicEndpointOutputCachePolicy stays stale until a write drops its tag, so every successful mutation has to evict. Doing that by hand means one eviction call per success branch, and a branch that forgets it serves stale data for a full TTL. The class doc settles three decisions (:15-34).
    • When it evicts (:16-22): as a result filter it runs after the action filters, so it sees the final outcome, after SupportsIfMatchAttribute rewrote a conflict to 412 and after an idempotent replay was produced. A 2xx result evicts every tag BEFORE the response body is written; a non-2xx result, a GET or HEAD, and an unhandled action exception (which skips result filters) evict nothing.
    • Best effort (:23-28): the write has already committed, so a cache-store fault is a Warning, never a failed request, and a host with no IOutputCacheStore registered evicts nothing. [Rubric §29, Resilience & Business Continuity] assesses whether a post-commit follow-up degrades gracefully; this is the contract ADR-096 states.
    • Once per request (:29-33): tags already evicted are recorded in HttpContext.Items, so a class-level and a method-level instance naming the same tag evict it once. [Rubric §12, Performance & Scalability] assesses whether a hot path avoids redundant round trips; the dedupe keeps a stacked declaration from doubling store calls. The caching model this serves is ADR-040.
  • Walkthrough
    • [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)] (:35). EvictedTagsItemKey (:42) is the HttpContext.Items slot holding the per-request set of evicted tags.
    • The constructor takes params string[] tags (:52), throws ArgumentNullException on null (:54), ArgumentException when the array is empty (:56-57) or a tag is null, empty or whitespace (:59-60), and copies the array (:62). Tags (:66) exposes them read-only, in order.
    • OnResultExecutionAsync (:75) null-guards both arguments, evicts when ShouldEvict says so (:80-83), then always awaits next() (:85), so the eviction lands before the body is written.
    • ShouldEvict (:89) returns false for GET and HEAD (:92-93), then reads the status from the result's own IStatusCodeActionResult.StatusCode, falling back to the response status (:95), and accepts 200 through 299 (:96).
    • EvictAsync (:100) filters the tags through the request's evicted set, keeping only those HashSet.Add accepts (:102-103), returns when none are pending, returns when no IOutputCacheStore resolves (:107-109), resolves ILogger<EvictOutputCacheAttribute> or the null logger (:111-112), and calls store.TryEvictTagsAsync(logger, pending) (:114).
    • EvictedTagsOf (:118) returns the set already stored under EvictedTagsItemKey (:120-121) or creates an ordinal HashSet<string> and stores it (:123-125).
  • Why it's built this way: a result filter, not an action filter, is the one place that sees the status after every action-level rewrite and still runs before the body, which is what lets a 412 from the conditional-write filter evict nothing. Resolving the store and the logger from RequestServices instead of taking them by constructor keeps the attribute usable as a plain attribute with no DI registration.
  • Where it's used: the generic write base relies on it: CrudEntityControllerBase<TEntity, TEntityDTO, TIdentifierType, TCreateRequest, TUpdateRequest> documents that a derived controller declares its tags with this attribute (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/CrudEntityControllerBase.cs:42). ADC's Conference controllers carry it at class level, for example ActivitiesController (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.API/Controllers/Activities/ActivitiesController.cs:42) and SessionAssetsController (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.API/Controllers/SessionAssets/SessionAssetsController.cs:63), and at method level with several tags, for example EventsController (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.API/Controllers/Events/EventsController.cs:180) and the lifecycle transitions of EventLifecycleController (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.API/Controllers/Events/EventLifecycleController.cs:61). Framework coverage is EvictOutputCacheAttributeTests (MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/Caching/EvictOutputCacheAttributeTests.cs), and consumers assert their declarations through EvictOutputCacheAssertions in the testing package (MMCA.Common/Source/Hosting/MMCA.Common.Testing/Support/EvictOutputCacheAssertions.cs).

OutputCacheMetrics

MMCA.Common.API · MMCA.Common.API.Caching · MMCA.Common/Source/Presentation/MMCA.Common.API/Caching/OutputCacheMetrics.cs:16 · Level 0 · class (internal static)

  • What it is: the OpenTelemetry instrument set for the output-cache eviction consumer. Today it is exactly one counter, cache.eviction.failed, plus the helper that records it.
  • Depends on: System.Diagnostics.Metrics (Meter, Counter<long>, OutputCacheMetrics.cs:1) only. Its single recording site is OutputCacheEvictionHandler.
  • Concept: the same "meter a degradable mechanism" idea introduced at IdempotencyMetrics, applied to a different failure. Cross-service cache eviction (OutputCacheEvictionHandler) is deliberately best-effort: an eviction that throws is logged and swallowed rather than rethrown, because rethrowing would redeliver the message and eventually dead-letter it. The consequence is that a failing eviction is invisible from the outside, since every request still succeeds and the stale entry simply serves until its TTL. [Rubric §13, Observability & Operability] assesses whether an operator can see that: the counter doc names itself the alert target for cross-service cache coherence, because a non-zero rate means this host is serving output-cached responses it was told to drop (OutputCacheMetrics.cs:23-27). It also records the cardinality argument, which is the discipline that keeps a tagged counter affordable: the cache_tag tag is bounded by the host's own tag vocabulary, a small fixed set declared in its output-cache policies.
  • Walkthrough
    • MeterName = "MMCA.Common.OutputCache" (OutputCacheMetrics.cs:19) and a single static Meter built from it (:21). The type doc carries a warning worth reading once and remembering (:10-14): never create a second Meter with this name, because a duplicate instance publishes a parallel set of instruments under the same meter name and a listener enabling one of them silently misses measurements recorded on the other.
    • EvictionFailed (:29-32) is a Counter<long> named cache.eviction.failed with unit {tag}.
    • RecordEvictionFailure(string cacheTag) (:36-37) adds one with a cache_tag tag, so the instrument name and the tag name are spelled in exactly one place.
  • Why it's built this way: internal static keeps the instruments out of the package's public surface while the handler in the same assembly records them. As with IdempotencyMetrics, the meter name is duplicated as a literal in MMCA.Common.Aspire because that package has no reference to MMCA.Common.API (:8-9), and a host exports the instruments by registering the meter, which the Aspire service defaults (ConfigureOpenTelemetry) already do (:6-8).
  • Where it's used: exactly once, in OutputCacheEvictionHandler's catch block (OutputCacheEvictionHandler.cs:61), paired with a Warning log naming the same tag.

PublicEndpointOutputCachePolicy

MMCA.Common.API · MMCA.Common.API.Caching · MMCA.Common/Source/Presentation/MMCA.Common.API/Caching/PublicEndpointOutputCachePolicy.cs:56 · Level 2 · class (sealed)

  • What it is: a custom ASP.NET Core IOutputCachePolicy for public, user-independent GET/HEAD endpoints that must stay cacheable even when the request carries an Authorization header. It replaces the built-in default policy, which refuses to serve or store a cached response for any authenticated request.
  • Depends on: Microsoft.AspNetCore.OutputCaching (IOutputCachePolicy, OutputCacheContext) and Microsoft.Extensions.Primitives (StringValues), Asp.Versioning (IApiVersionReader, ApiVersion, ApiVersioningOptions, AmbiguousApiVersionException) for the version-vary key, and Microsoft.Extensions.Options (PublicEndpointOutputCachePolicy.cs:1-10), plus three first-party types resolved or called per request: ITenantContext for the tenant-vary key, and IPermissionRegistry with PermissionAuthorizationHandler for the permission bypass. It is registered by OutputCacheOptionsExtensions.
  • Concept introduced (auth-header-tolerant output caching). The framework UI attaches a Bearer token to every outgoing API request, including reads of [AllowAnonymous] endpoints whose payload is identical for every caller. Under the default policy those reads bypass the output cache for any signed-in user and land on the database each time (PublicEndpointOutputCachePolicy.cs:18-23). [Rubric §12, Performance & Scalability] assesses whether hot read paths avoid redundant work; this policy is a direct performance lever, letting public reads share one cached entry across authenticated and anonymous callers. [Rubric §11, Security] assesses trust boundaries; the class docs are explicit that a cached response is served verbatim to every subsequent caller, so it must be applied only to identity-independent payloads, and the bypassRoles mechanism exists precisely so a privileged role that receives an elevated payload (for example administrators seeing unpublished rows) is never served or stored from the shared cache, and bypassPermissions does the same when the elevated payload is gated by a permission rather than a fixed role, so any caller holding it by claim, by role or by stored grant skips the cache too (:31-40). A second SECURITY remark covers multi-tenancy (:42-47): the tenant-vary rule below is a backstop, not a license, an endpoint whose payload depends on the caller (rather than only on the tenant) still must not use this policy. A third remark covers API versioning (:48-54): on a host that versions its API by header (AddCommonApiVersioning), the key varies by the resolved version, so a v1 body is never replayed to a v2 request on the same path, while an absent header, 1 and 1.0 share one entry. This is the edge tier of the two-tier caching model (ADR-026); the authenticated-read decision itself is ADR-040.
  • Walkthrough: a TenantVaryByKey = "t" constant (:62) mirrors the t:{tenantId} prefix the caching CQRS decorators use, an ApiVersionVaryByKey = "v" constant (:65) names the version-vary slot, and four instance fields hold the rest of the config, _expiration, _bypassRoles, _bypassPermissions, _tags (:67-70). Three constructors chain to the last: the params string[] tags overload passes empty bypass-roles and bypass-permissions arrays (:75-76), the (expiration, bypassRoles, tags) overload passes an empty bypass-permissions array (:85-86), and the full (expiration, bypassRoles, bypassPermissions, tags) constructor (:104) guards its inputs (ThrowIfLessThanOrEqual(expiration, TimeSpan.Zero) and null checks on all three arrays, :106-109). All three interface methods are explicitly implemented, so they are reachable only through IOutputCachePolicy. CacheRequestAsync (:118) first resolves the version key (:124), then computes attemptOutputCaching as "is a GET/HEAD request" AND "the version is readable" AND "is not a bypassed caller" (:125-127), enables output caching, sets AllowCacheLookup/AllowCacheStorage to that flag, deliberately turns request coalescing off with AllowLocking = false (:136), sets the expiration (:137), and (matching the built-in default) varies the cache key by every query-string parameter via CacheVaryByRules.QueryKeys = "*" (:141). Locking is off because with it on, concurrent misses for one key wait on the first request's execution, which runs under that request's RequestAborted token: one client disconnecting would cancel the shared query and every waiter would answer 500 with a TaskCanceledException; the cost is that simultaneous misses each run the query once (:132-135). It then resolves the tenant from context.HttpContext.RequestServices and, when one is present, stamps it into CacheVaryByRules.VaryByValues[TenantVaryByKey] (:147-151), an unresolved tenant, single-tenant host or background call, adds nothing; stamps a non-null version key into VaryByValues[ApiVersionVaryByKey] (:155-158), because versioning is header-based and the key is otherwise path plus query (:153-154); then copies the eviction tags in (:160-161). ServeFromCacheAsync (:167) is a no-op returning ValueTask.CompletedTask. ServeResponseAsync (:171) refuses to store any response that set a cookie or returned a non-200 status (:177-181), the same guard the built-in default applies. Four private helpers close it out. TryResolveApiVersionKey(HttpContext, out string?) (:195) returns true with a null key when no IApiVersionReader is registered, so a host that does not version keeps its key unchanged (:199-202); otherwise it reads httpContext.ApiVersioningFeature (:204), returns false when a version was named but did not parse (RequestedApiVersion null while RawRequestedApiVersion is not, :208-213) or when versioning throws AmbiguousApiVersionException (:215-218), falls back to the configured ApiVersioningOptions.DefaultApiVersion (or ApiVersion.Default) for an absent version (:220), and normalizes it (:221). NormalizeApiVersion (:229-232) formats one invariant-culture spelling, group date, major.minor with a missing part read as 0 (so 1 and 1.0 agree) and status. IsCacheableRequest (:234-235) accepts GET or HEAD. IsBypassedCaller(HttpContext) (:241) first returns true when Array.Exists(_bypassRoles, user.HasRole) (:244), returns false when no bypass permissions are configured (:249-252), and otherwise resolves the optional IPermissionRegistry from RequestServices (:256) and asks PermissionAuthorizationHandler.Holds(user, registry, permission) for each bypass permission (:257), the same evaluation the permission handler grants the elevated payload by (:254-255). HasRole is deliberate, not ClaimsPrincipal.IsInRole: IsInRole only matches the identity's own role claim type, so against a provider that emits bare role/roles claims the permission handler would grant the elevated payload while this bypass check missed it, and that response would be stored under the shared public key (:237-240).
  • Why it's built this way: it mirrors the built-in default policy minus one behavior, the authenticated-request bail-out, so its caching, query-key variance, and cookie/status guards stay identical to what developers already expect; its additions are the tenant and API-version vary keys. Bypass roles and bypass permissions get the default behavior back (no lookup, no storage), which keeps elevated payloads out of the shared cache without disabling caching for everyone. Evaluating a bypass permission through the permission handler's own Holds, rather than a second claim check, means a role granted the permission later (including a stored grant) is bypassed too, so the cache can never answer a caller the endpoint would have given the elevated payload. Stamping the resolved tenant into the vary key means a multi-tenant host's shared cache entry per path+query never crosses tenants, since the same path and query mean different rows per tenant (:143-146). Keying on the resolved version rather than the raw header keeps one entry per version instead of one per spelling, and refusing an unreadable version leaves that request to versioning's own error response instead of the cache (:211-212). A raw IOutputCachePolicy implementation inherits none of the default policy's behavior, so every guard is re-implemented here.
  • Where it's used: registered as a named policy by OutputCacheOptionsExtensions and referenced from controller actions via [OutputCache(PolicyName = ...)] or, for the base reads of an entity controller, through PublicCachedReadsAttribute. Store's Catalog service registers three such policies with no bypass roles, the products one at 60 seconds because an effective price moves on the clock (MMCA.Store/Source/Services/MMCA.Store.Catalog.Service/Program.cs:59-69); ADC's Conference service registers eleven, most of them with an admin bypass-roles array (MMCA.ADC/Source/Services/MMCA.ADC.Conference.Service/Program.cs:172-214), including two short 60-second policies, NowNextPolicy (:200) and BookmarkCountsPolicy (:214). Its sessions policy is the one that constructs the policy directly with a bypass permission, ConferencePermissions.SessionAssetsManage, because SessionAssetsController's read answers a holder of that permission with materials the public cannot see (:179-190). Framework coverage is PublicEndpointOutputCachePolicyTests and PublicEndpointOutputCachePermissionBypassTests (MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/Caching/). The tags passed here are the same strings OutputCacheEvictionHandler evicts by.

OutputCacheOptionsExtensions

MMCA.Common.API · MMCA.Common.API.Caching · MMCA.Common/Source/Presentation/MMCA.Common.API/Caching/OutputCacheOptionsExtensions.cs:6 · Level 2 · class (static)

  • What it is: registration helpers that add named output-cache policies backed by PublicEndpointOutputCachePolicy onto ASP.NET Core's OutputCacheOptions.
  • Depends on: Microsoft.AspNetCore.OutputCaching (OutputCacheOptions, OutputCacheOptionsExtensions.cs:1) and PublicEndpointOutputCachePolicy.
  • Concept: this is a thin fluent facade over OutputCacheOptions.AddPolicy, using a C# extension(OutputCacheOptions options) block (OutputCacheOptionsExtensions.cs:8) so the policy registration reads as a first-class option on the options object. See the DI registration extension(T) convention. [Rubric §9, API & Contract Design] is relevant: the helper gives callers a self-documenting, named entry point instead of hand-constructing the policy at each call site.
  • Walkthrough: two overloads of AddPublicEndpointPolicy. The first (OutputCacheOptionsExtensions.cs:20-21) takes name, expiration, and params string[] tags and registers new PublicEndpointOutputCachePolicy(expiration, tags). The second (:34-35) adds a string[] bypassRoles parameter before the params string[] tags and forwards to the three-argument policy constructor, for endpoints whose payload is identical for every caller except one privileged role. Both are expression-bodied and return void, mutating the options in place.
  • Why it's built this way: keeping the policy construction behind a named helper means the "apply only to [AllowAnonymous], identity-independent endpoints" guidance travels with the API surface (see the doc comments at :10-16 and :23-29) instead of being re-derived at each registration.
  • Where it's used: called during host composition where the app configures AddOutputCache(...); the registered name is then referenced by [OutputCache(PolicyName = ...)] on controller actions. Store's Catalog service uses the two-argument form (MMCA.Store/Source/Services/MMCA.Store.Catalog.Service/Program.cs:59-69); ADC's Conference service mostly uses the bypass-roles form (MMCA.ADC/Source/Services/MMCA.ADC.Conference.Service/Program.cs:172-214).

OutputCacheEvictionHandler

MMCA.Common.API · MMCA.Common.API.Caching · MMCA.Common/Source/Presentation/MMCA.Common.API/Caching/OutputCacheEvictionHandler.cs:32 · Level 4 · class (sealed, partial)

  • What it is: the integration-event handler that drops named tags from this host's output cache when another service says the underlying data changed. It is the consumer half of cross-service output-cache coherence.
  • Depends on: IIntegrationEventHandler<in TIntegrationEvent> closed over OutputCacheEvictionRequested (OutputCacheEvictionHandler.cs:35), ASP.NET Core's IOutputCacheStore, ILogger, and OutputCacheMetrics for the failure counter (:1-4).
  • Concept introduced (cache coherence across a service boundary, as a best-effort hint). PublicEndpointOutputCachePolicy makes a public read cheap by caching it for minutes at a time. The cost of that is staleness when the data changes, and in a multi-service topology the change usually happens somewhere else: a write in one service invalidates a cached read in another. The framework's answer is an ordinary integration event, so nothing about this handler is broker-specific. [Rubric §6, CQRS & Event-Driven] assesses whether cross-service reactions travel as events rather than as direct calls; the class doc is explicit that no broker type appears here, so the handler is equally reachable from the in-process dispatcher (:8-16). Two failure decisions carry the design.
    • Per-tag best effort (:18-24): each tag is evicted independently and a failure is logged and counted rather than rethrown. Rethrowing would hand the message back to the retry policy and redeliver it, re-evicting every tag that already succeeded, and would eventually dead-letter a message whose only consequence is a cache entry that expires on its own TTL anyway. The doc gives the one-line principle worth remembering: a failed eviction is a staleness window, not a lost fact. [Rubric §29, Resilience & Business Continuity] assesses whether degraded dependencies degrade the system gracefully instead of failing it; this is the contract ADR-096 generalizes.
    • Cancellation is not swallowed (:25-28): an OperationCanceledException from host shutdown propagates, so the broker receive pipeline sees the shutdown rather than a completed message. This is the same when (ex is not OperationCanceledException) discipline used across the framework's cache-touching code.
  • Walkthrough: the primary constructor takes IOutputCacheStore outputCacheStore and ILogger<OutputCacheEvictionHandler> logger (:32-34). HandleAsync(OutputCacheEvictionRequested integrationEvent, CancellationToken) (:38) null-guards the event (:42), then loops the tags (:44), skipping blank entries (:46-49). Each tag goes through outputCacheStore.EvictByTagAsync(tag, cancellationToken) inside its own try (:51-53) followed by a Debug log (:54). The catch (:56-63) is deliberately broad, filtered only by when (ex is not OperationCanceledException); its comment notes that CA1031 stays at error but does not flag a filtered catch, and S2221 is a suggestion, because an eviction store that throws must not turn a coherence hint into a dead-lettered message (:58-60). It records the failure on OutputCacheMetrics (:61) and logs a Warning naming the tag and stating that responses carrying it stay cached until their own TTL expires (:62, template at :72-75).
  • Why it's built this way: partial plus two [LoggerMessage] declarations (:67-75) gives source-generated, allocation-free logging at Debug for the success path and Warning for the failure path. Keeping the handler free of any broker type is what lets the same class serve both the in-process dispatcher and the broker consumer, which is the extraction property the module system is built around (ADR-007, ADR-008).
  • Where it's used: registered by OutputCacheEvictionExtensions.AddOutputCacheEvictionHandler(). The broker half is RegisterOutputCacheEvictionConsumer() inside the host's AddBrokerMessaging configuration, which wires the generic IntegrationEventConsumer<OutputCacheEvictionRequested> onto this handler; ADC's Conference service calls both (MMCA.ADC/Source/Services/MMCA.ADC.Conference.Service/Program.cs:259 and MMCA.ADC/Source/Services/MMCA.ADC.Conference.Service/ConferenceBrokerConsumers.cs:36); on the far side, ADC's Engagement bookmark path names this handler as the receiver of the OutputCacheEvictionRequested it causes to be published (MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.Application/UserSessionBookmarks/DomainEventHandlers/UserSessionBookmarkCacheEvictionHandler.cs). The tags it evicts are the ones passed to OutputCacheOptionsExtensions.AddPublicEndpointPolicy. Framework coverage is OutputCacheEvictionHandlerTests (MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/Caching/OutputCacheEvictionHandlerTests.cs).

SupportsIfMatchAttribute

MMCA.Common.API · MMCA.Common.API.Concurrency · MMCA.Common/Source/Presentation/MMCA.Common.API/Concurrency/SupportsIfMatchAttribute.cs:58 · Level 4 · class (sealed)

  • What it is: an attribute that is also an action filter and an application-model convention. It makes a write action conditional: the optimistic-concurrency token comes from the HTTP If-Match header, the header is mandatory, and a conflict outcome is answered with 412 Precondition Failed rather than 409 Conflict. As a convention it also documents those answers in the API description.
  • Depends on: ConcurrencyETag (the header name, the wildcard, and the tag decoder), Error, ErrorHttpMapping and IErrorLocalizer for the problem body, ConcurrencyConflictMetrics for the conflict counter, plus Microsoft.AspNetCore.Mvc.Filters.IAsyncActionFilter, Microsoft.AspNetCore.Mvc.ApplicationModels (IActionModelConvention, IControllerModelConvention), IApiResponseMetadataProvider, ProblemDetailsFactory, and Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException (SupportsIfMatchAttribute.cs:1-12).
  • Concept introduced (conditional writes, and why two conflict statuses are not one). The type doc (:16-56) is the whole design, in five decisions.
    • The token never touches the request model (:22-27, :60-65): the filter decodes the header and puts the bytes in HttpContext.Items under TokenItemKey, and the action reads them from there. A request body therefore never carries a concurrency token, and no request record has to loosen its immutability to receive one.
    • The header is required (:28-34). A guarded mutation without a usable token would be a last-write-wins write, so a request that states no precondition is refused with 428 Precondition Required and the action never runs. A malformed tag is a 400 Bad Request, because the server cannot tell what the caller meant. * counts as no precondition, since it names no particular version.
    • Why 412 and not 409 (:33-41): RFC 9110 reserves 412 for a precondition the client stated in a conditional request header, which is precisely what If-Match is, while 409 stays the answer for a conflict the client did not condition on. [Rubric §9, API & Contract Design] assesses whether status codes carry their standard meaning rather than a local one. The doc also names the consequence worth carrying, because the rewrite keys on the outcome rather than on an error code: an endpoint whose 409 means something else (a duplicate key, say) reports that conflict as 412, with the original problem details, error codes included, intact.
    • The attribute IS the filter (:44-48): unlike IdempotentAttribute this needs no scoped service, so it implements IAsyncActionFilter directly and requires no DI registration by the host.
    • The attribute owns its response metadata (:49-55): as an action or controller model convention it appends Problem Details 412 and 428 response types after the action's own, each only when neither the action nor its controller already declares that status. Apply(ActionModel) (:96) collects the declared statuses from every IApiResponseMetadataProvider filter on the action and its controller (:100-104) and adds a ProducesResponseTypeAttribute(typeof(ProblemDetails), status) for each missing one of PreconditionStatusCodes (:69-70, :106-109); Apply(ControllerModel) (:117) runs that for every action of a controller carrying the attribute at class level (:121-124). [Rubric §9, API & Contract Design] again: the published contract states the answers the filter can produce without each action repeating them.
  • Walkthrough
    • [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)] (:48); TokenItemKey (:57) is the HttpContext.Items slot. RequiredToken(HttpContext) (:68-76) is the action-side accessor: it returns the decoded byte[], or throws InvalidOperationException naming the attribute when the slot is empty. That is deliberate (:64-67): reaching the action with no token means the attribute is missing, which is a wiring mistake rather than a client error.
    • OnActionExecutionAsync (:79) guards its arguments (:81-82), calls TryApplyIfMatch (:84), and returns without running the action when it is false (:84-88), because the 428 or the 400 is already on the context. Otherwise it awaits next() (:90) and passes the outcome to the rewrite (:92).
    • TryApplyIfMatch (:104) reads the header (:106-107), then refuses with PreconditionRequiredResult when the value is blank or is the wildcard (:109-114), refuses with MalformedIfMatchResult when ConcurrencyETag.TryParse cannot decode it (:116-120), and otherwise stores the bytes in HttpContext.Items and returns true (:122-123).
    • RewriteConflictToPreconditionFailed (:130) handles two shapes. A DbUpdateConcurrencyException is first recorded on ConcurrencyConflictMetrics (:137), then replaced with the 412 result and marked ExceptionHandled = true (:132-141). Marking it handled is what stops DbUpdateExceptionHandler from mapping it to a 409 like any other DbUpdateException, and it is also why the conflict is counted here: the global handler never sees it (:134-136). An ObjectResult already carrying 409 has both its own StatusCode and its ProblemDetails.Status moved to 412, leaving the body otherwise intact (:145-152); a bare StatusCodeResult 409 is swapped for a 412 (:154-156); anything else falls through untouched (:158-159).
    • The three responses are built by one private helper, Problem (:206-222), which asks the registered ProblemDetailsFactory for the body so the response carries the same diagnostic extensions (traceId) as the rest of the API, falls back to a hand-built ProblemDetails when no factory is registered, and attaches the framework's standard errors extension through ErrorHttpMapping.BuildErrorsExtension with the optional IErrorLocalizer (:218-219). The three call sites differ only in status, title, detail and error: 428 Concurrency.PreconditionRequired (:164-173), 400 Concurrency.MalformedIfMatch (:176-185), and 412 Concurrency.PreconditionFailed (:188-197), each detail line showing a sample tag or telling the caller to re-read and retry.
  • Why it's built this way: making the attribute its own filter keeps adoption to a single line on an action with no host wiring, which matters for a framework whose consumers upgrade in lockstep (ADR-035). Routing the token through HttpContext.Items instead of through the bound model is what removed reflection from the request path entirely: there is no per-type property lookup, and request records stay init-only as the immutability fitness rules require.
  • Where it's used: applied across all three consumer apps on writes whose stale-view risk is real, each action reading the token with SupportsIfMatchAttribute.RequiredToken(HttpContext) a few lines below the attribute. In ADC: the event lifecycle transitions (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.API/Controllers/Events/EventLifecycleController.cs:59, :86), the hand-written PUT actions of EventsController (.../Controllers/Events/EventsController.cs:228), SessionsController (.../Controllers/Sessions/SessionsController.cs:310), SpeakersController (.../Controllers/Speakers/SpeakersController.cs:372) and the other Conference controllers (activities, sponsors, categories, session assets, partners, questions), plus Engagement's SessionQuestionsController (MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.API/Controllers/SessionQuestionsController.cs:137, :160, :186) and LivePollsController (.../Controllers/LivePollsController.cs:86, :120). In Store: OrdersController (MMCA.Store/Source/Modules/Sales/MMCA.Store.Sales.API/Controllers/OrdersController.cs:299, :359), OrderFulfillmentController (.../OrderFulfillmentController.cs:55, :88, :134), GuestOrdersController (.../GuestOrdersController.cs:165) and InventoryItemsController (.../InventoryItemsController.cs:96, :129) in Sales, the Catalog controllers (for example MMCA.Store/Source/Modules/Catalog/MMCA.Store.Catalog.API/Controllers/ProductVariantsController.cs:100), and Identity's CustomersController (MMCA.Store/Source/Modules/Identity/MMCA.Store.Identity.API/Controllers/CustomersController.cs:178, :204, :230). In Helpdesk: TicketsController (MMCA.Helpdesk/Source/Modules/Tickets/MMCA.Helpdesk.Tickets.API/Controllers/TicketsController.cs:116, :144, :212). ADC pins the convention with ConditionalWriteConventionTests fitness tests that assert the attribute is present on the endpoints that need it (MMCA.ADC/Tests/Modules/Conference/MMCA.ADC.Conference.API.Tests/Conventions/ConditionalWriteConventionTests.cs:43, and an Engagement twin at MMCA.ADC/Tests/Modules/Engagement/MMCA.ADC.Engagement.API.Tests/Controllers/ConditionalWriteConventionTests.cs:13). The read half of the round trip is EntityControllerBase<TEntity, TEntityDTO, TIdentifierType>.SetConcurrencyETag (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/EntityControllerBase.cs:417-425), which gives the client the tag to send back.

OutputCacheEvictionExtensions

MMCA.Common.API · MMCA.Common.API.Caching · MMCA.Common/Source/Presentation/MMCA.Common.API/Caching/OutputCacheEvictionExtensions.cs:27 · Level 5 · class (static, two extension blocks)

  • What it is: two things that travel together. It is the one-method DI registration for OutputCacheEvictionHandler (the container half of the cross-service eviction path), and it is the multi-tag eviction helper pair a mutating controller reaches for right after a write.
  • Depends on: OutputCacheEvictionHandler, IIntegrationEventHandler<in TIntegrationEvent>, OutputCacheEvictionRequested, BestEffort, and ServiceCollectionDescriptorExtensions.TryAddEnumerable (OutputCacheEvictionExtensions.cs:1-8).
  • Concept introduced (two eviction verbs for two call sites). ASP.NET Core's IOutputCacheStore evicts one tag per call, but a single write usually invalidates several (a speaker edit drops both conference:speakers and conference). Rather than a private per-controller helper wrapping a run of EvictByTagAsync calls (:17-21), the framework offers one call that names every tag, in two flavors that differ only in what they do when the cache store is unreachable.
    • EvictTagsAsync propagates the failure. A caller that considers a failed eviction part of its own success uses this one.
    • TryEvictTagsAsync is the best-effort sibling: a Redis outage or a transient network fault becomes one Warning plus one BestEffort metric increment instead of an exception (:60-66). The reasoning is worth internalizing: the mutation this follows has already committed, so surfacing the failure would turn a successful write into a client-visible error while leaving the write in place, and an entry that could not be evicted expires on its own TTL anyway. [Rubric §29, Resilience & Business Continuity] covers exactly this post-commit-follow-up contract (ADR-096).
    • A second detail in TryEvictTagsAsync is easy to miss and load-bearing: eviction runs under CancellationToken.None, not the request token (:67-70, :90). The write has committed, so a client that disconnected mid-response must not abandon the cleanup.
  • Concept (an idempotent registration for a handler that must not run twice). Two lifetime decisions are documented on AddOutputCacheEvictionHandler and both matter. The handler is registered as a singleton, matching the lifetime the module scanner gives every other integration-event handler, so a host that wires it by hand and a module that wires it through the scan agree. And it goes in through TryAddEnumerable rather than AddSingleton, so calling it twice (a host plus a module that both want the behavior) registers one handler rather than evicting every tag twice (:102-108). [Rubric §12, Performance & Scalability] assesses whether a shared concern can be opted into safely from more than one place; a plain Add here would double every eviction, harmless in effect but doubling the store round trips and the failure counter.
  • Walkthrough
    • A class-level [SuppressMessage] for CA1708 (:23-26) records a known analyzer trap: with multiple extension(T) blocks in one static class, CA1708 flags the compiler-generated grouping members as case-colliding, and no user-visible identifier differs only by case.
    • EvictOperationPrefix = "output-cache-evict:" (:34) is the prefix of the best-effort operation name. The tag is appended so a failure is attributable to the cache it could not clear, which is also why the doc insists call-site tags stay low-cardinality literals: the name becomes a metric tag (:29-33).
    • extension(IOutputCacheStore store) (:36) holds the two verbs. EvictTagsAsync(CancellationToken cancellationToken, params string[] tags) (:49) null-guards store and tags (:51-52) and awaits EvictByTagAsync for each tag in the order given (:54-57). TryEvictTagsAsync(ILogger logger, params string[] tags) (:78) adds a logger guard (:80-82) and routes each eviction through BestEffort.ExecuteAsync with the prefixed operation name, the caller's logger, the eviction as the action, and CancellationToken.None (:86-90).
    • extension(IServiceCollection services) (:95) holds AddOutputCacheEvictionHandler() (:111). It null-guards services (:113), calls services.TryAddEnumerable(ServiceDescriptor.Singleton<IIntegrationEventHandler<OutputCacheEvictionRequested>, OutputCacheEvictionHandler>()) (:115-117), and returns the collection for chaining (:119). The doc records the one prerequisite (:100-101): AddOutputCache() must have been called, since it supplies the singleton IOutputCacheStore the handler evicts through.
  • Why it's built this way: the class doc states the pairing rule plainly (:12-16): this is the DI half, RegisterOutputCacheEvictionConsumer() on the framework's IBrokerConsumerBuilder is the broker half (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Consumers/IntegrationEventConsumerExtensions.cs:28, shorthand for RegisterIntegrationEventConsumer<OutputCacheEvictionRequested>() at :32), and a host that wants the behavior calls both. Splitting them is what keeps the handler broker-agnostic, since the DI registration has no messaging dependency at all. Housing the eviction verbs in the same class keeps the write-side helper and the read-side coherence path in one file.
  • Where it's used: ADC's Conference service calls services.AddOutputCacheEvictionHandler() (MMCA.ADC/Source/Services/MMCA.ADC.Conference.Service/Program.cs:292) alongside the broker registration (:352). No consumer controller calls either verb directly: the one caller is EvictOutputCacheAttribute, which runs the best-effort form after a 2xx write (MMCA.Common/Source/Presentation/MMCA.Common.API/Caching/EvictOutputCacheAttribute.cs:114), so ADC's Conference controllers and Store's Catalog controllers name their tags declaratively instead, for example SpeakerCategoryItemsController (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.API/Controllers/Speakers/SpeakerCategoryItemsController.cs:50), ProductsController (MMCA.Store/Source/Modules/Catalog/MMCA.Store.Catalog.API/Controllers/ProductsController.cs:46) and CategoriesController (MMCA.Store/Source/Modules/Catalog/MMCA.Store.Catalog.API/Controllers/CategoriesController.cs:33). Framework coverage: OutputCacheEvictTagsTests pins both verbs, including the CancellationToken.None rule and the swallow-versus-throw split (MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/Caching/OutputCacheEvictTagsTests.cs:59-113), and OutputCacheEvictionHandlerTests pins the double-registration behavior (MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/Caching/OutputCacheEvictionHandlerTests.cs:107-114).

PublicCachedReadsAttribute

MMCA.Common.API · MMCA.Common.API.Caching · MMCA.Common/Source/Presentation/MMCA.Common.API/Caching/PublicCachedReadsAttribute.cs:42 · Level 8 · class (sealed)

  • What it is: a class-level attribute that is also an MVC controller-model convention. On an entity controller it marks the inherited base reads (both GetAllAsync overloads, GetAllForLookupAsync and GetByIdAsync) as anonymous and output-cached under one named policy, and names the by-id route, so a controller no longer overrides a base read only to add attributes (PublicCachedReadsAttribute.cs:8-13).
  • Depends on: Microsoft.AspNetCore.Authorization (AllowAnonymousAttribute, IAllowAnonymous, IAuthorizeData), Microsoft.AspNetCore.Mvc.ApplicationModels (IControllerModelConvention, ControllerModel, ActionModel, SelectorModel) and Microsoft.AspNetCore.OutputCaching.OutputCacheAttribute (PublicCachedReadsAttribute.cs:1-3), plus EntityControllerBase<TEntity, TEntityDTO, TIdentifierType>, whose read actions it recognizes (:4, :45-50). The named policy it points at is normally a PublicEndpointOutputCachePolicy registered through OutputCacheOptionsExtensions (:36-38).
  • Concept introduced (declaring a public cached read surface once, at the controller). A public read cached under PublicEndpointOutputCachePolicy needs two markers on every read action, [AllowAnonymous] and [OutputCache(PolicyName = ...)], and the base reads live in the framework's generic controller, so without this attribute a consumer overrides each inherited read just to decorate it. The class doc settles three decisions (:14-39).
    • What it adds (:15-22): on every selector of a base read it appends the anonymous marker and the output-cache marker, each only when the selector does not already carry one, so an override's own [OutputCache] wins whatever its policy. The by-id read gets a route name unless one is already declared. Nothing is added to the action filters, so the API description changes only by the operationId a new route name produces. [Rubric §12, Performance & Scalability] assesses whether hot read paths avoid redundant work; this makes the cached shape the one-line default for an entity's public reads, the authenticated-read caching model of ADR-040.
    • What it leaves alone (:23-27): the export, every write, the opt-in cursor and change-feed reads, and every action the application declares itself keep exactly the authorization and caching the controller gives them.
    • What it refuses (:28-34): an override of a base read is still a base read and is marked like an inherited one, so an override that declares its own [Authorize] or permission attribute without [AllowAnonymous] makes the convention throw when the application model is built, because the anonymous marker would silently replace the requirement. [Rubric §11, Security] assesses whether access-control changes are explicit; this turns an accidental widening of a gated read into a startup failure rather than a public endpoint. A read that needs a gate belongs on a controller without the attribute.
  • Walkthrough
    • [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)] (:41). ReadActionNames (:45-50) holds the three base read names via nameof on the open EntityControllerBase<,,>; both GetAllAsync overloads share one name.
    • The constructor takes policyName (:57) and rejects null, empty or whitespace with ArgumentException.ThrowIfNullOrWhiteSpace (:59). PolicyName (:64) exposes it. ByIdRouteName (:71) is an optional init property: null derives Get{EntityName}ById, and empty or whitespace is rejected when the convention runs.
    • Apply(ControllerModel) (:83) null-guards the model, finds the closed EntityControllerBase<,,> in the controller's base chain or throws InvalidOperationException naming the controller (:87-89), throws when ByIdRouteName is set but blank (:91-95), and derives the route name from the first generic argument, the entity type (:97). For every action IsBaseRead accepts (:99) it runs EnsureNoDeclaredAuthorization (:101), notes whether the action is GetByIdAsync (:103), and marks each selector, passing the route name only for the by-id read (:105-108).
    • MarkSelector (:118) adds AllowAnonymousAttribute when no IAllowAnonymous is present (:120-123), adds OutputCacheAttribute { PolicyName = PolicyName } when no OutputCacheAttribute is present (:125-128), and sets the attribute route's name only when a name is wanted and the route model has none (:130-133).
    • EnsureNoDeclaredAuthorization (:146) throws when the action's own attributes carry an IAuthorizeData and no IAllowAnonymous (:148); authorization declared on the controller class is deliberately left alone, the usual shape of gated writes beside public reads (:136-141).
    • FindEntityControllerBase (:156) walks BaseType until it meets a generic type whose definition is EntityControllerBase<,,> (:158-161). IsBaseRead (:171) takes the method's GetBaseDefinition().DeclaringType (:173), so an override still counts as a base read, and requires that declaring type to be a closed EntityControllerBase<,,> and the method name to be one of ReadActionNames (:175-177).
  • Why it's built this way: a controller-model convention runs once when the application model is built, so the markers become ordinary endpoint metadata with no per-request cost, and a misuse (a non-entity controller, a blank route name, a gated override) fails at startup rather than at the first request. Writing to EndpointMetadata rather than to the action filters keeps the published API description unchanged. Adding a marker only when absent lets an individual override opt out of the shared policy by declaring its own [OutputCache]. An unknown policy name is not checked here; it fails at request time exactly as a hand-written [OutputCache(PolicyName = ...)] does (:36-38).
  • Where it's used: fourteen ADC Conference controllers carry it at class level, each beside a class-level EvictOutputCacheAttribute for the write side, for example SessionsController (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.API/Controllers/Sessions/SessionsController.cs:42), EventsController (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.API/Controllers/Events/EventsController.cs:47), SpeakerCategoryItemsController (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.API/Controllers/Speakers/SpeakerCategoryItemsController.cs:47) and SponsorsController (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.API/Controllers/Sponsors/SponsorsController.cs:39). Framework coverage is PublicCachedReadsAttributeTests (MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/Caching/PublicCachedReadsAttributeTests.cs), and ADC asserts its declarations through PublicCachedReadAssertions (MMCA.ADC/Tests/Modules/Conference/MMCA.ADC.Conference.API.Tests/Helpers/PublicCachedReadAssertions.cs). The generic entity-controller decision it builds on is ADR-099.

ServiceInfoResponse

MMCA.Common.API · MMCA.Common.API.Controllers · MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/ServiceInfoControllerBase.cs:51 · Level 0 · record (sealed, nested)

  • What it is: the v1.0 (minimal) payload returned by the service-info discovery endpoint: just the service name and the API version.
  • Depends on: nothing beyond the BCL; a nested positional record inside ServiceInfoControllerBase.
  • Concept: the deprecated shape in a versioned-contract pair. [Rubric §9, API & Contract Design] assesses whether an API can evolve without breaking callers; this record is the "before" shape that v1.0 clients keep receiving unchanged while v2.0 clients get the superset (ADR-046).
  • Walkthrough: ServiceInfoResponse(string Service, string ApiVersion) (ServiceInfoControllerBase.cs:51), returned by GetV1() populated with the concrete service name and the literal "1.0" (ServiceInfoControllerBase.cs:42).
  • Where it's used: produced by ServiceInfoControllerBase.GetV1(); superseded by ServiceInfoV2Response.

ServiceInfoV2Response

MMCA.Common.API · MMCA.Common.API.Controllers · MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/ServiceInfoControllerBase.cs:54 · Level 0 · record (sealed, nested)

  • What it is: the v2.0 (evolved) service-info payload, a strict superset of ServiceInfoResponse that additionally advertises the supported and deprecated version lists.
  • Depends on: nothing beyond the BCL; a nested positional record inside ServiceInfoControllerBase.
  • Concept: the additive-evolution half of the versioned pair. [Rubric §9, API & Contract Design]: adding fields (not renaming or removing them) is the backward-compatible way to grow a contract, so a v1.0 caller who never sees the new fields is unaffected.
  • Walkthrough: ServiceInfoV2Response(string Service, string ApiVersion, IReadOnlyList<string> SupportedVersions, IReadOnlyList<string> DeprecatedVersions) (ServiceInfoControllerBase.cs:54-58). The two extra members surface the Supported/Deprecated arrays the controller holds (ServiceInfoControllerBase.cs:32-33), so the body itself documents the version landscape, the same facts the api-supported-versions / api-deprecated-versions headers carry.
  • Where it's used: produced by ServiceInfoControllerBase.GetV2() (ServiceInfoControllerBase.cs:47-48).

ServiceInfoControllerBase

MMCA.Common.API · MMCA.Common.API.Controllers · MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/ServiceInfoControllerBase.cs:30 · Level 1 · class (abstract)

  • What it is: an anonymous, read-only discovery controller that proves the API-versioning machinery works across more than one version. The same /ServiceInfo route is served by v1.0 (deprecated) and v2.0, selected via the api-version header.
  • Depends on: Asp.Versioning (MapToApiVersion) and ASP.NET Core MVC (ControllerBase); returns ServiceInfoResponse and ServiceInfoV2Response, both nested in this file.
  • Concept introduced: header-based API versioning as a first-class contract. [Rubric §9, API & Contract Design] assesses whether an API can carry multiple versions concurrently and signal deprecation; this controller demonstrates the whole loop: two versions on one route, one marked deprecated, and ReportApiVersions = true (set in AddCommonApiVersioning on WebApplicationBuilderExtensions, WebApplicationBuilderExtensions.cs:47, inside the extension member declared at WebApplicationBuilderExtensions.cs:39) so responses carry api-supported-versions / api-deprecated-versions headers (class doc, ServiceInfoControllerBase.cs:6-14). ADR-046 makes the point that a versioning claim which only ever ships v1.0 is untestable; this endpoint is what makes it testable.
  • Walkthrough
    • Supported = ["1.0", "2.0"] and Deprecated = ["1.0"] (ServiceInfoControllerBase.cs:32-33) are the static version lists the v2 payload echoes.
    • ServiceName (ServiceInfoControllerBase.cs:36) is an abstract property the sealed per-service subclass supplies, because class-level routing/versioning attributes are not reliably inherited (remarks, ServiceInfoControllerBase.cs:15-29): the subclass carries [ApiController], [Route("[controller]")], [AllowAnonymous], and the two [ApiVersion] attributes.
    • GetV1() (ServiceInfoControllerBase.cs:41) is [HttpGet] plus [MapToApiVersion("1.0")] (ServiceInfoControllerBase.cs:39-40) and returns the minimal ServiceInfoResponse.
    • GetV2() (ServiceInfoControllerBase.cs:47) is [MapToApiVersion("2.0")] (ServiceInfoControllerBase.cs:46) and returns the superset ServiceInfoV2Response with the supported/deprecated lists.
  • Why it's built this way: the type is abstract with an abstract ServiceName so each extracted service reuses the identical versioning surface while stamping its own identity, keeping the "build the monolith now, extract a service later" path uniform ([Rubric §7, Microservices Readiness]). The endpoint is anonymous and reached on the service host directly; gateways do not route it (class doc, ServiceInfoControllerBase.cs:12-13).
  • Where it's used: subclassed by each service's sealed ServiceInfoController, for example ADC's Conference service (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.API/Controllers/ServiceInfoController.cs:20) and Store's Catalog service (MMCA.Store/Source/Modules/Catalog/MMCA.Store.Catalog.API/Controllers/ServiceInfoController.cs:20). Because the controller ships in the framework, the fitness contract that exercises it is shared too: ServiceInfoVersioningContractTestsBase<TFixture> (MMCA.Common/Source/Hosting/MMCA.Common.Testing/Conformance/ServiceInfoVersioningContractTestsBase.cs:20), and a repo subclasses it supplying only its fixture.

IEntityControllerBase<TEntityDTO, TIdentifierType>

MMCA.Common.API · MMCA.Common.API.Controllers · MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/IEntityControllerBase.cs:14 · Level 2 · interface

  • What it is: the contract every read-only entity controller implements, four GET-shaped methods for all-entities, paged, lookup, and by-id retrieval.
  • Depends on: IBaseDTO<TIdentifierType> (constraint), CollectionResult<T>, PagedCollectionResult<T>, BaseLookup<TIdentifierType>, and QueryFilterModelBinder for the filter parameter.
  • Concept introduced: the generic entity-controller contract. [Rubric §9, API & Contract Design] assesses uniform endpoint conventions across every entity, and this interface is the guarantee that all read controllers expose the same four GET shapes. [Rubric §1, SOLID]: it is deliberately the read-only slice, kept separate from the create/delete slice (IAggregateRootEntityControllerBase<TEntityDTO, TIdentifierType, TCreateRequest>) so a child-collection controller can implement reads without inheriting mutation endpoints (Interface Segregation).
  • Walkthrough: the type constrains TEntityDTO : IBaseDTO<TIdentifierType> and TIdentifierType : notnull (IEntityControllerBase.cs:17-18). The members:
    • GetAllAsync unpaged (IEntityControllerBase.cs:26), with fields projection ([FromQuery]) and the two eager-load flags (IEntityControllerBase.cs:27-30).
    • the paged GetAllAsync overload (IEntityControllerBase.cs:43), adding sortColumn/sortDirection, [Range(1, int.MaxValue)]-guarded pageNumber/pageSize (IEntityControllerBase.cs:49-50), and a Dictionary<string, (string Operator, string Value)> of filters bound by QueryFilterModelBinder (IEntityControllerBase.cs:51).
    • GetAllForLookupAsync for id/label dropdown data (IEntityControllerBase.cs:58).
    • GetByIdAsync (IEntityControllerBase.cs:69), whose includeFKs defaults to true for the single-entity case (IEntityControllerBase.cs:71) while the collection endpoints default it to false (IEntityControllerBase.cs:28 and IEntityControllerBase.cs:44).
  • Why it's built this way: expressing the surface as an interface lets architecture tests and OpenAPI tooling reason about the contract independently of the concrete generic base, and lets the two-level controller hierarchy layer capabilities without collapsing reads and writes into one type. Note what is deliberately absent: the CSV ExportAsync action added to the generic base is a base-class method only, and this interface still declares exactly four members (IEntityControllerBase.cs:26, :43, :58, :69). Adding a fifth would be a breaking change for any consumer implementing the interface explicitly instead of inheriting the base, and a default interface member would hide that break behind a runtime surprise (ADR-078).
  • Where it's used: implemented by EntityControllerBase<TEntity, TEntityDTO, TIdentifierType> and extended by IAggregateRootEntityControllerBase<TEntityDTO, TIdentifierType, TCreateRequest>.

IAggregateRootEntityControllerBase<TEntityDTO, TIdentifierType, TCreateRequest>

MMCA.Common.API · MMCA.Common.API.Controllers · MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/IAggregateRootEntityControllerBase.cs:15 · Level 3 · interface

ApiControllerBase

MMCA.Common.API · MMCA.Common.API.Controllers · MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/ApiControllerBase.cs:23 · Level 5 · class (abstract)

  • What it is: the base class of the entity and use-case API controllers (the OAuth and service-info bases derive ControllerBase directly, as the class doc at ApiControllerBase.cs:16-21 states). It carries the [ApiController] behavior, the shared HandleFailure that turns domain errors into RFC 9457 Problem Details responses (adding a Retry-After header to a 429 or 503 that knows its wait), and the concurrency-token plumbing every controller that serves or conditionally writes a row reuses: SetConcurrencyETag and the two HandleConditionalCommand*Async helpers.
  • Depends on: Error, ErrorType, Result, ErrorHttpMapping (and through it ErrorTypeSeverity), IErrorLocalizer (resolved optionally from RequestServices), RetryAfterHeader (Format), ConcurrencyETag, SupportsIfMatchAttribute (RequiredToken), and ICommandHandler<in TCommand, TResult>; System.Reflection plus a ConcurrentDictionary for the per-type token-property cache.
  • Concept introduced: centralized error-to-HTTP mapping. [Rubric §9, API & Contract Design] assesses whether every endpoint fails the same way; [Rubric §3, Clean Architecture] covers keeping the HTTP-translation concern in the presentation layer rather than the domain. This is the boundary where a Result failure from the Application/Domain layers becomes an HTTP status: the domain never knows about status codes, this base owns that mapping. The [ApiController] attribute (ApiControllerBase.cs:22) enables automatic model-state validation, binding-source inference, and ProblemDetails serialization.
  • Concept introduced: the status code is ranked, not positional. [Rubric §11, Security] and [Rubric §9, API & Contract Design] both bear on this. An aggregate failure built by Result.Combine carries several errors at once, and if the response status came from errors[0] then the order in which handlers appended errors would decide whether a caller saw 403 or 400. HandleFailure therefore hands the whole list to ErrorHttpMapping.GetStatusCode(IReadOnlyList<Error>) (ApiControllerBase.cs:63, mapping at MMCA.Common/Source/Presentation/MMCA.Common.API/Middleware/ErrorHttpMapping.cs:54-55), which resolves the most severe ErrorType present through ErrorTypeSeverity. The ranking is spelled out on the method doc (ApiControllerBase.cs:36-45): Unexpected (500), then Unavailable (503), Unauthorized (401), Forbidden (403), TooManyRequests (429), Conflict (409), NotFound (404), UnprocessableEntity (422), and finally Invariant/Validation (400). The 503 comes from the [ErrorType.Unavailable] = StatusCodes.Status503ServiceUnavailable entry of the mapping table (ErrorHttpMapping.cs:34); any type the table does not list falls back to 400 (ErrorHttpMapping.cs:41-42). Equal ranks keep the earliest error, so a same-rank list behaves exactly as a positional selection would. The ranking itself lives in MMCA.Common.Shared on purpose (ErrorHttpMapping.cs:49-50), so the gRPC edge classifies the same aggregate identically. Every error still travels in the response; only the status is ranked.
  • Concept introduced: a 429 or 503 that says how long to wait. [Rubric §11, Security] and [Rubric §9, API & Contract Design]. A refusal such as a sign-in lockout (ADR-029) or a dependency outage knows its own duration, carried on Error.RetryAfter. SetRetryAfter (ApiControllerBase.cs:89) picks the error type whose hint it honours from the ranked status: TooManyRequests for a 429 (:92-95), Unavailable for a 503 (:96-99), and for any other status it returns without a header (:100-103). It then takes the longest RetryAfter among the errors of that type (:105-107, because retrying before the longest would only be refused again), and writes Response.Headers.RetryAfter through RetryAfterHeader.Format (:108-111) when that delay is positive, so the header uses the same whole, rounded-up seconds the rate limiters send (:80-88). Any other status, or a 429 or 503 with no hint, sends no header.
  • Concept introduced: one place that turns a row version into a precondition. [Rubric §8, Data Architecture] and [Rubric §9, API & Contract Design] (ADR-035). A client gets the concurrency token as a weak ETag on a read and hands it back as If-Match on the next write (see SupportsIfMatchAttribute); this base owns both halves so they cannot drift apart.
    • SetConcurrencyETag(object? dto) (:136) is protected, so a custom read action, a hand-built projection, or a conditional write answering with the refreshed value emits the identical header instead of re-implementing the reflection and the base64 format (:129-134). A null row returns at once (:138-139), a row with no or an empty token gets no header (:141-142, because a fabricated tag would invite preconditions the write side cannot honour, :123-128), and otherwise it writes ConcurrencyETag.Format(rowVersion) under ConcurrencyETag.ETagHeaderName (:144).
    • ReadRowVersion (:250) reads the token off the row's RUNTIME shape: a shaped dictionary (a fields= projection) is probed under rowVersion, then RowVersion (:252-257); a typed value goes through RowVersionProperties.GetOrAdd(dto.GetType(), FindRowVersionProperty) (:259). That static ConcurrentDictionary<Type, PropertyInfo?> (:30) resolves each runtime type once, since a type's shape cannot change at runtime (:25-29), and FindRowVersionProperty (:266-271) accepts only a public instance, readable, non-indexer byte[] property named exactly RowVersion. Keying on the runtime type is what lets the helper live on this non-generic base rather than on a DTO-typed one.
    • HandleConditionalCommandAsync<TCommand, TResult> (:164, TResult : Result at :169) and HandleConditionalCommandWithResponseAsync<TCommand, TResponse> (:195) run a conditional write end to end. Each null-guards its handler and command builder eagerly (:171-172, :201-202), reads the token SupportsIfMatchAttribute.RequiredToken(HttpContext) decoded (:174, :204; an action without [SupportsIfMatch] throws InvalidOperationException and the handler never runs, :162-163, :193-194), builds the command from it, and hands off to a private awaited half (:175, :205; the split keeps the argument checks eager, :208, :226). RunConditionalCommandAsync (:209) dispatches (:216), maps a failure through HandleFailure (:217-218), awaits the optional onSuccess follow-up such as a cache eviction (:220-221), and answers 204 (:223). RunConditionalCommandWithResponseAsync (:227) unwraps the value with TryGetValue (:234-235), awaits onSuccess with it (:237-238), emits the refreshed token through SetConcurrencyETag(value) (:240), and answers 200 with the value (:241), so the client already holds the precondition for its next write (ADR-144 relies on that round trip).
  • Walkthrough: HandleFailure(IEnumerable<Error> errors) (ApiControllerBase.cs:50) is protected virtual:
    • Null/empty guard (ApiControllerBase.cs:52-60): with no errors it returns a 500 "Unknown error", treating an empty failure as a programming mistake rather than a domain outcome.
    • Ranked status (ApiControllerBase.cs:63, with the intent stated in the comment just above it at ApiControllerBase.cs:62).
    • Builds a ProblemDetails with that status and a fixed title/detail (ApiControllerBase.cs:65-70), attaches Extensions["errors"] via ErrorHttpMapping.BuildErrorsExtension (ApiControllerBase.cs:73), optionally localized through an IErrorLocalizer resolved with GetService (ApiControllerBase.cs:72, so a host without localization simply passes null), sets the Retry-After header when it applies (ApiControllerBase.cs:75), then returns StatusCode(statusCode, problemDetails) (ApiControllerBase.cs:77).
  • Why it's built this way: one virtual method instead of a switch in every action removes duplication and makes the response shape uniform (ADR-013 for why failures are values rather than exceptions in the first place); keeping it virtual lets a subclass (EntityControllerBase<TEntity, TEntityDTO, TIdentifierType>) wrap it with logging without reimplementing the mapping. The ErrorHttpMapping members are internal static (ErrorHttpMapping.cs:41, :54, :65), which is what lets UnhandledResultFailureFilter reuse the same ranked status mapping and the same errors extension array for a failed Result that an action returned without calling HandleFailure (UnhandledResultFailureFilter.cs:36 and :47). The two bodies are deliberately not identical: the filter labels its ProblemDetails Title/Detail "Unhandled result failure" / "The action returned a Result.Failure that was not mapped to an HTTP error response." (UnhandledResultFailureFilter.cs:42-43) against the base's "Operation failed" / "One or more errors occurred." (ApiControllerBase.cs:68-69), so a response that fell through the filter is distinguishable from one the controller mapped on purpose. Localization is the ADR-027 extension point, keyed by Error.Code and leaving Code/Type/Source/Target verbatim so clients can still branch on them (ErrorHttpMapping.cs:60-63 for the contract, ErrorHttpMapping.cs:65-74 for the projection that honours it).
  • Where it's used: the root of the entity and use-case controller hierarchy. EntityControllerBase<TEntity, TEntityDTO, TIdentifierType>, AuthControllerBase, PasswordResetAuthControllerBase<TForgotPasswordCommand, TResetPasswordCommand>, DataExportControllerBase<TQuery>, and every module controller derive from it directly or transitively; OAuthControllerBase and ServiceInfoControllerBase do not. The architecture rule ControllersInheritApiControllerBase (MMCA.Common/Source/Hosting/MMCA.Common.Testing.Architecture/Rules/Api/ArchitectureRules.Controllers.cs:66) fails a module controller that derives raw ControllerBase unless it is listed as exempt. The conditional-write helpers are used by ADC's EventLifecycleController (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.API/Controllers/Events/EventLifecycleController.cs:72, HandleConditionalCommandAsync) and QuestionsController (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.API/Controllers/Questions/QuestionsController.cs:67, HandleConditionalCommandWithResponseAsync) among others, and SetConcurrencyETag directly by ADC's SpeakersController (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.API/Controllers/Speakers/SpeakersController.cs:301). Framework coverage is ApiControllerBaseTests (MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/Controllers/ApiControllerBaseTests.cs) and ApiControllerBaseConditionalCommandTests (MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/Controllers/ApiControllerBaseConditionalCommandTests.cs).

EmailConfirmationControllerBase<TSendCommand, TConfirmCommand>

MMCA.Common.API · MMCA.Common.API.Controllers · MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/EmailConfirmationControllerBase.cs:43 · Level 6 · class (abstract)

  • What it is: the abstract base for the two anonymous email-confirmation endpoints, POST send-email-confirmation and POST confirm-email (ADR-116 is the identity-completions decision it implements; the route names are at EmailConfirmationControllerBase.cs:78 and :106). The app subclass supplies the route prefix, the API version and two one-line command factories; the base owns the HTTP shape.
  • Depends on: ApiControllerBase (base, for HandleFailure), ICommandHandler<in TCommand, TResult> (one handler per action, both returning Result), ICommandWithRequest<out TRequest> (the generic constraints, :46-47), SendEmailConfirmationRequest and ConfirmEmailRequest (the bodies), IdempotentAttribute, and the RateLimitPolicyAuthIp constant on WebApplicationBuilderExtensions.
  • Concept introduced: a sibling controller instead of a longer inheritance chain. [Rubric §9, API & Contract Design] assesses uniform endpoint conventions; [Rubric §1, SOLID] covers keeping the base closed and the variation in small abstract members. The app's own AuthController already occupies the single-inheritance chain (AuthControllerBase to UserAccountAuthControllerBase<TChangePasswordCommand, TChangePreferencesCommand>), so confirmation ships as a separate controller routed to the same Auth prefix, which reaches the gateway through the existing /Auth route (:13-20). The commands stay app-side, the same split PasswordResetAuthControllerBase<TForgotPasswordCommand, TResetPasswordCommand> uses: the derived controller supplies each through CreateSendCommand (:61) and CreateConfirmCommand (:69), and the base reads the request back only through ICommandWithRequest<TRequest> (:35-38).
  • Concept introduced: anonymous by necessity, and non-enumerating. [Rubric §11, Security] is the angle. Both actions are [AllowAnonymous] because the link is followed from a mail client with no session, and an unconfirmed account may be unable to sign in at all (:23-27). Send answers 202 on every well-formed request: the handler treats an unknown address and an already-confirmed one as success, so the response never reveals which addresses hold accounts, and only a malformed payload reaches 400 through the request validator (:30-33, :78-84). Both carry [EnableRateLimiting(RateLimitPolicyAuthIp)] (:81, :109) and declare the 429 (:84, :113), for the same reason login and recovery do (ADR-019, ADR-029).
  • Walkthrough
    • Primary constructor (:43-45) exposes the two handlers as protected SendHandler (:50) and ConfirmHandler (:53).
    • SendEmailConfirmationAsync (:85): [HttpPost("send-email-confirmation")], [Idempotent], [AllowAnonymous] (:78-80); dispatches CreateSendCommand(request) (:89-91) and returns Accepted() on success, HandleFailure(result.Errors) otherwise (:93-95).
    • ConfirmEmailAsync (:114): [HttpPost("confirm-email")], [Idempotent], [AllowAnonymous] (:106-108); the link carries the address and token in the URI fragment, so the page reads them client-side and posts them here and neither reaches a server log or a Referer header (:98-101). It returns NoContent() on success (:122-124) and declares 400, 401 and 429 (:111-113).
  • Why it's built this way: unlike the credential-issuing endpoints in AuthControllerBase, neither action mints a token pair, so both opt in with [Idempotent] (ADR-017): a retried send or confirm replays the stored answer instead of re-running the handler. Both methods are virtual so an app can wrap them. Errors go through the shared HandleFailure, so a failed confirm is the same RFC 9457 shape as every other endpoint.
  • Where it's used: subclassed by ADC's EmailConfirmationController (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/Controllers/EmailConfirmationController.cs:29). Both actions are listed by name in the framework's anonymous-endpoint architecture gate (MMCA.Common/Tests/Architecture/MMCA.Common.Architecture.Tests/Api/AnonymousEndpointTests.cs:47-48), so their [AllowAnonymous] is an approved exception. Framework coverage is EmailConfirmationControllerBaseTests (MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/Controllers/Auth/EmailConfirmationControllerBaseTests.cs).

OAuthControllerBase

MMCA.Common.API · MMCA.Common.API.Controllers · MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/OAuthControllerBase.cs:52 · Level 8 · class (abstract)

  • What it is: the base controller for external sign-in (Google, GitHub, Apple, and any configured generic OIDC provider). It runs the challenge/callback/complete/exchange dance so a browser or native head can log in through a provider and receive a local JWT pair without ever exposing tokens in a redirect URL, can bind that exchange to a client-held proof key (RFC 7636, S256) so a captured completion code redeems nothing, and answers the home-realm discovery question "which organization provider owns this email domain".
  • Depends on: IAuthenticationService (ExternalLoginAsync), ICacheService (SetAsync, GetFromSharedStoreAsync, RemoveAsync), IConfiguration, a required IDistributedLock (TryAcquireAsync), ExternalAuthExtensions (the scheme constant, OAuthControllerBase.cs:64), OAuthReturnUrls (ErrorRedirectUrl, GetAllowedMobileReturnUrl, AppendQuery, ReturnUrlItemKey, FailedErrorCode), OidcProviderRegistry (Find, FindByEmail, resolved optionally from RequestServices), OidcClaimNormalizer (EmailVerifiedClaimType), OidcDiscoveryResponse, WebApplicationBuilderExtensions (RateLimitPolicyAuthIp), NonIdempotentAttribute, AuthenticationResponse, OAuthCodeExchangeRequest (Code, CodeVerifier), and Error; the Google, GitHub, and Apple OAuth packages, System.Security.Cryptography (RandomNumberGenerator, SHA256), and Base64Url.
  • Concept introduced: the code-exchange OAuth completion pattern. [Rubric §11, Security] assesses how credentials move through the system; the design's whole point is that the redirect after a successful provider login carries only a single-use opaque code, never the access/refresh tokens, so tokens never land in the address bar, browser history, the Referer header, or upstream access logs (OAuthControllerBase.cs:255-259). [Rubric §7, Microservices Readiness]: the base is hoisted from the app hosts so every service reuses the identical flow, with the sealed subclass supplying only [Route("auth/oauth")] and versioning, and the burn check reads the shared cache store so the single-use guarantee holds across replicas. The subclass must also pass an IDistributedLock to the primary constructor (:52-56); there is no lock-free overload, so the read-then-burn is always one critical section across replicas (:340-354). AddCaching always registers a lock, Redis-backed when an IConnectionMultiplexer is present (class doc :42-45). See ADR-036.
  • Concept introduced: a proof key that binds the exchange to the client that started the flow. [Rubric §11, Security]. A single-use code is still a bearer credential for its two-minute life, and a custom-scheme redirect can be captured by another app on the device (:257-259). Every challenge route therefore reads an optional code_challenge and code_challenge_method from the query through ReadCodeChallenge (:496-514), so no action declares them as parameters, and ChallengeProvider stashes the result under CodeChallengeItemKey = "codeChallenge" (:78, set at :485). Only S256 with a well-formed challenge is kept: 43 base64url characters (CodeChallengeLength, :90; IsWellFormedCodeChallenge, :393-395). Any other challenge that was sent becomes InvalidCodeChallengeMarker = "!" (:87), which can never equal a computed challenge (:85-86), and CompleteAsync refuses such a flow before minting anything, redirecting with invalid_code_challenge (InvalidCodeChallengeErrorCode, :83; check at :228-233). A bound flow's token pair waits under ExchangeCacheKey (:380-383): oauth-exchange-pkce:{challenge}:{code} (ProofKeyExchangeCodePrefix, :82) instead of oauth-exchange:{code}, with the fixed-length, separator-free challenge before the code, so no caller-chosen code can spell the key of a bound flow (:375-379). At exchange time a sent CodeVerifier must be 43 to 128 characters of the RFC 7636 unreserved set (IsWellFormedCodeVerifier, :389-391; bounds :93-94) or the request is an invalid code (:327-336); otherwise it is hashed by ComputeCodeChallenge, the unpadded base64url SHA-256 of its ASCII bytes (:386-387), and the key is rebuilt from it (:338). A missing or wrong verifier simply misses the key, is answered as an invalid code, and leaves the code redeemable by its owner until it expires; a flow started without a challenge (the web sign-in) redeems with the code alone, and a verifier sent for it is refused the same way (:298-304).
  • Concept introduced: generic OIDC providers and home-realm discovery. [Rubric §11, Security] and [Rubric §9, API & Contract Design]. Beyond the three named providers, any provider configured under OAuth:Oidc:<Name> (registered by ExternalAuthExtensions.AddExternalAuthProviders, :146-147) is reachable through one parameterized route. OidcLogin (:160, [HttpGet("{provider}")] and [AllowAnonymous] at :156-157) looks the name up ignoring case through OidcProviders?.Find(provider) and either challenges with the provider's registered name or answers 404 (:162-163). The literal google, github, and apple routes take precedence and those names are reserved, so an OIDC provider can never shadow them, and MAUI heads reach it through the same auth/oauth/{provider} URL the external auth broker already builds (:148-150). DiscoverOidcProvider (:181; [HttpGet("discover")], [AllowAnonymous], and [EnableRateLimiting(WebApplicationBuilderExtensions.RateLimitPolicyAuthIp)] at :176-178) maps the domain of an email to the provider whose Domains list claims it through FindByEmail (:183) and answers an OidcDiscoveryResponse(Name, DisplayName) or 404 (:184-186), so a sign-in page can offer one "Sign in with your organization" step instead of a button per identity provider. The answer reveals only which configured provider owns a domain, never whether an account exists, and it is throttled per client IP like the other anonymous auth endpoints (:166-172). The registry comes from OidcProviders (:190), an optional GetService lookup, because AddExternalAuthProviders registers it only when at least one OIDC provider is configured (:189); a host with none answers 404 on both actions.
  • Walkthrough
    • OAuthExchangeCodePrefix (OAuthControllerBase.cs:69) and a 2-minute OAuthExchangeCodeLifetime (:104) namespace and time-box the server-side token stash; the short TTL matches the single redirect-then-POST round trip. A second constant, ClientStateItemKey = "clientState" (:73), names a separate AuthenticationProperties.Items slot for the client's own opaque per-attempt value, deliberately not called "state" because that name belongs to the OAuth handler's own protocol value (:71-72); the return URL's slot is OAuthReturnUrls.ReturnUrlItemKey = "returnUrl" (MMCA.Common/Source/Presentation/MMCA.Common.API/Authentication/OAuthReturnUrls.cs:21), shared with the provider handlers' remote-failure path. The proof-key constants (item key, query keys, S256, the bound prefix, the error code, the invalid marker, and the challenge and verifier lengths) sit together at :75-94. The redeem lock uses a 10-second lease and a 5-second wait (RedeemLockTimeToLive, RedeemLockWait, :109-110), matching the password-reset token service: the critical section is one cache read and one remove (:106-108). UIBaseUrlConfigKey = "OAuth:UIBaseUrl" (:62) is public so the AppHost can set the same key through WithUiLinks as OAuth__UIBaseUrl (:58-61).
    • GoogleLogin (:119), GitHubLogin (:129), and AppleLogin (:142) each take an optional state query parameter alongside returnUrl and carry [AllowAnonymous] directly (:118, :128, :141); all three, like OidcLogin, call ChallengeProvider (:469), which stashes returnUrl under OAuthReturnUrls.ReturnUrlItemKey (:476), the client's state under ClientStateItemKey (:481), and the proof-key challenge (:485) in AuthenticationProperties.Items and sets RedirectUri = "/auth/oauth/complete" (:471-488). Apple needs no special action here: its callback arrives as a cross-site form POST (response_mode=form_post is forced by the name/email scopes) that the middleware handles at /auth/callback/apple like any other provider (:133-136).
    • CompleteAsync (:209) carries [AllowAnonymous] (:207). It reads the UI base URL through UIBaseUrlConfigKey (:211), and after the middleware handles the provider callback it reads the external cookie (:212), redirects to /login?error=oauth_failed when the ticket did not survive (:214-219, through OAuthReturnUrls.ErrorRedirectUrl with no native callback and FailedErrorCode = "oauth_failed", OAuthReturnUrls.cs:18), reads both the stashed returnUrl and clientState via ReadChallengeState (:224, :270-271), resolves an allow-listed native callback (:225), reads the stashed proof-key challenge (:226) and refuses a flow carrying the invalid marker (:228-233), extracts provider claims (ExtractClaims, :235), redirects with missing_claims when the provider key or email is absent (:237-240), calls ExternalLoginAsync with the email-verified flag to find or create the local user and mint tokens (:242-243), redirects with the first error's code on failure (:245-248), signs out the temporary external cookie (:253), then mints a 32-byte hex exchangeCode (:260), stashes the token pair in the cache under ExchangeCacheKey(exchangeCode, codeChallenge) (:261-262), and redirects with the code and, when the client sent one, the echoed state (:264, URL built by BuildSuccessRedirectUrl at :273-287).
    • ExtractClaims (:405-417) returns the provider name, key, email, both name parts, and an EmailVerified flag read from OidcClaimNormalizer.EmailVerifiedClaimType. The flag fails closed: an absent or unparseable assertion reads as unverified (:413-415).
    • ReadChallengeState (:270-271) is a safe-lookup helper (GetString is TryGetValue under the hood): the challenge normally stashes both returnUrl and clientState, but a ticket minted without them (custom challenge, provider round-trip edge) falls back to "/" and null instead of throwing on the Items indexer.
    • BuildSuccessRedirectUrl (:273-287) appends &state= (URL-escaped) only when clientState is non-empty (:280-282), for both the web redirect and the native OAuthReturnUrls.AppendQuery branch (:284-286), so callers that never sent a state see no change to the redirect shape.
    • Name handling is defensive and never yields an empty name, because user invariants reject an empty first or last name and an empty value would fail the first external sign-up outright (:99-100). ExtractName (:419) uses GivenName/Surname only when both are non-blank (:424-427); otherwise it takes the full name from the GitHub display-name claim urn:github:name (GitHubDisplayNameClaimType, :97), because the GitHub handler maps ClaimTypes.Name to the login handle, and falls back to ClaimTypes.Name when that claim is blank (:429-435). It then splits through SplitFullName (:448), which breaks at the first space, trims, and returns the "User" / "User" placeholders (:101-102) for a blank or single-token name or an empty remainder (:450-463). A blank given or family name is replaced individually by its fallback (:438-439), so a provider that returns only a display name still yields a creatable local account. That fallback matters most for Apple, which returns name claims on the first authorization only.
    • Native heads (ADR-043): CompleteAsync asks OAuthReturnUrls.GetAllowedMobileReturnUrl(configuration, returnUrl) (:225; defined at OAuthReturnUrls.cs:68), which returns the stashed returnUrl as the redirect target only when it is an absolute URI whose custom scheme is listed in OAuth:AllowedReturnUrlSchemes; http/https never match (OAuthReturnUrls.cs:70-75), so the allowlist cannot become an open redirect, and a missing or empty section (or a test double returning null from GetSection) means "no allowlist", the exact pre-ADR-043 behavior (OAuthReturnUrls.cs:77-81). Failures route to the same surface through OAuthReturnUrls.ErrorRedirectUrl (OAuthReturnUrls.cs:53-56, called at :228-233, :237-240, and :245-248), so a native window closes on an error instead of stranding on a web login page. The provider handlers' remote-failure event uses the same helper class (OAuthReturnUrls.cs:8-12, RedirectRemoteFailureAsync at :31-43), so a round trip that fails before reaching CompleteAsync lands in the same place.
    • ExchangeAsync (:318): [HttpPost("exchange")] with [NonIdempotent(...)], [AllowAnonymous], and [EnableRateLimiting(WebApplicationBuilderExtensions.RateLimitPolicyAuthIp)] (:313-316); the UI swaps the code for the real AuthenticationResponse out-of-band. It is throttled per client IP like login because each request reads the shared store and takes a lock keyed by the caller-chosen code, so junk codes would otherwise be an amplification path; the UI host calls it on the same path as login, so it shares login's UI-host-IP bucket trade-off (:305-309). A blank code is answered as an invalid code (:322-325), a sent verifier is validated and hashed (:327-336), and the cache key is built (:338). It then takes lock:{cacheKey} through TryAcquireAsync (:343-345), answers an invalid code if the lock cannot be taken within the wait (:346-349), and redeems inside await using on the handle (:351-354). Two replicas that both read before either removes would otherwise both hand out the token pair (:340-342). RedeemExchangeCodeAsync (:357) does the read and the burn: the lookup goes through ICacheService.GetFromSharedStoreAsync (:363) rather than the ordinary read, because a code already burned on another replica must be a miss here, not a stale local copy that would mint a second token pair (:361-362). Because the response is a struct, a cache miss yields a default value rather than null, so the miss is detected via an empty AccessToken (:364-367). The code is then removed (:370), making it single-use so a leaked or replayed code cannot mint a second token pair. Every failure path returns the same opaque 400 "Invalid sign-in code" (InvalidCode, :397-403).
  • Why it's built this way: carrying tokens in a redirect is the classic OAuth token-leak vector; the single-use code plus a short-lived server-side stash closes it while keeping the client flow a plain redirect and one POST. Reading the stash from the shared store keeps "single-use" true when the API runs on more than one replica, where a per-node copy could otherwise outlive the burn. The [NonIdempotent] justification on ExchangeAsync (:314) records why this one endpoint must stay outside the replay contract: replaying the stored response would defeat the burn, letting a leaked code mint the same tokens again for the whole retention window. The lock is a required constructor argument rather than an opt-in, so no host can redeem a code unlocked; a caller that loses the lock race is answered as an invalid code, never as a second success (:340-342). Folding the proof-key challenge into the cache key, rather than storing it beside the pair and comparing, means a wrong verifier never even finds the pair, and an attacker's miss leaves the owner's code intact. Hoisting the redirect helpers into OAuthReturnUrls lets the completion and the handlers' remote-failure event choose the destination the same way. Its AppendQuery (OAuthReturnUrls.cs:88) deliberately uses OriginalString rather than ToString(), because Uri normalization appends a trailing slash to authority-only URIs (e.g. myapp://oauth-complete) and native authenticator callback matching can be exact (OAuthReturnUrls.cs:90-92). The client-supplied state is carried opaquely: the server never interprets or trusts it, only stores and echoes it back so the client can bind the completion to the flow it started (:478-480). Generic OIDC providers ride the same challenge and completion path rather than a parallel one, so every guarantee above applies to them unchanged.
  • Caveats / not-in-source: the provider scheme registration, the OIDC provider registry, and the concrete ExternalLoginAsync implementation live outside this base (ExternalAuthExtensions, OidcProviderRegistry, and the app's IAuthenticationService); this file assumes they are wired, and what the service does with the emailVerified flag is decided there, not here. How GetFromSharedStoreAsync bypasses a local tier is the cache implementation's concern (ICacheService), not this file's. The proof key is optional: a client that sends no code_challenge gets the unbound flow, so the binding protects only the clients that opt in. The complete and exchange actions are hidden from OpenAPI with [ApiExplorerSettings(IgnoreApi = true)] (:208, :317) because they are browser redirects, not a documented client contract; OidcLogin and DiscoverOidcProvider carry no such attribute and declare their responses (:158-159, :179-180). The ExchangeAsync doc paragraph says the lock comes from "the four-argument constructor" (:294-296); the four-argument primary constructor is the only one, so the lock always applies. This base derives ControllerBase directly (:56), not ApiControllerBase.
  • Where it's used: subclassed by each app's sealed OAuth controller, today ADC's OAuthController (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/Controllers/OAuthController.cs:21), which adds only the class-level routing and versioning attributes and forwards its injected IDistributedLock to the base (OAuthController.cs:25). ExchangeAsync is one of the endpoints the framework's anonymous-endpoint architecture gate lists by name (MMCA.Common/Tests/Architecture/MMCA.Common.Architecture.Tests/Api/AnonymousEndpointTests.cs:36), and the challenge, completion, OidcLogin, and DiscoverOidcProvider actions are listed there too (AnonymousEndpointTests.cs:62-69), so each [AllowAnonymous] is an approved exception rather than an oversight. The Aspire hosting side writes UIBaseUrlConfigKey through IdentityLinkExtensions (MMCA.Common/Source/Hosting/MMCA.Common.Aspire.Hosting/IdentityLinkExtensions.cs). Framework coverage is OAuthControllerBaseTests and OAuthControllerBaseOidcTests (MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/Controllers/Auth/), and ADC exercises the exchange end to end in OAuthExchangeTests (MMCA.ADC/Tests/Integration/MMCA.ADC.Identity.IntegrationTests/Auth/OAuthExchangeTests.cs).

EntityControllerBase<TEntity, TEntityDTO, TIdentifierType>

MMCA.Common.API · MMCA.Common.API.Controllers · MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/EntityControllerBase.cs:33 · Level 9 · class (abstract)

  • What it is: the generic read-only controller that gives any entity five working REST endpoints (GET /, GET /paged, GET /export, GET /lookup, GET /{id}) plus two opt-in ones (GET /cursor for keyset paging, GET /changes for a change feed), with filtering, sorting, pagination, field projection, one shared row-scoping hook, a fail-closed export behind an overridable caller gate, and an ETag on the by-id read, by delegating to the IEntityQueryService<TEntity, TEntityDTO, TIdentifierType> pipeline.
  • Depends on: ApiControllerBase (base, which also supplies SetConcurrencyETag), IEntityControllerBase<TEntityDTO, TIdentifierType> (implements), IEntityQueryService<TEntity, TEntityDTO, TIdentifierType>, AuditableBaseEntity<TIdentifierType> (constraint), ApplicationSettings (through IOptions<T>), CollectionResult<T>, PagedCollectionResult<T>, KeysetCollectionResult<T>, KeysetPageRequest, EntityChange<TEntityDTO, TIdentifierType>, BaseLookup<TIdentifierType>, QueryFilterModelBinder, OptInActionAttribute, SupportsCursorPagingAttribute, SupportsChangeFeedAttribute, Error and Result (the export caller gate), EntityCsvExporter<TEntityDTO>, QueryFieldService, and Specification<TEntity, TIdentifierType>; EntityQueryPipeline.MaxUnboundedResultLimit for the page-size clamp; ASP.NET Core MVC, Asp.Versioning, TimeProvider, and ILogger.
  • Concept introduced: generic controller bases that eliminate CRUD boilerplate. [Rubric §9, API & Contract Design] covers uniform endpoint conventions; [Rubric §1, SOLID] covers the Open/Closed side, since a new entity controller extends this base rather than re-writing the endpoints. The class-level [ApiController], [Route("[controller]")], [ApiVersion("1.0")] (EntityControllerBase.cs:30-32) plus the three generic constraints (EntityControllerBase.cs:40-42) turn the type parameters into the contract: name the entity, the DTO, and the identifier alias, and the routes, the versioning, and the query behavior follow (ADR-034).
  • Walkthrough
    • Primary constructor (EntityControllerBase.cs:33-38) takes the query service and an ILogger, both null-guarded into the QueryService (:44) and Logger (:49) protected properties.
    • MaxPageSize (:58-65) resolves IOptions<ApplicationSettings> per-request from HttpContext.RequestServices, falling back to 500, and clamps the result to the range 1 to EntityQueryPipeline.MaxUnboundedResultLimit (:63; the ceiling is defined as KeysetPageRequest.MaxPageSize at MMCA.Common/Source/Core/MMCA.Common.Application/Services/Query/EntityQueryPipeline.cs:25, which is 1000 at MMCA.Common/Source/Core/MMCA.Common.Shared/Abstractions/KeysetPagination.cs:27). The pipeline caps every page at that ceiling anyway, so the clamp keeps the pagination metadata and the export loop from assuming a page size the pipeline does not serve (:52-56). Per-request resolution means a settings change takes effect without a restart. MaxExportRows (:78-86) does the same for the export ceiling, with the extra rule that a configured value of zero or less is treated as unconfigured (:83-84), because a cap of zero would silently serve every caller a header-only file (:74-76). EntityName (:91) is typeof(TEntity).Name, used in log messages and in the export refusals.
    • GetAllAsync unpaged (:109, [HttpGet] at :106): resolves the read specification (:115), then delegates to the query service with pageNumber: 1 and pageSize: MaxPageSize (:122-123), so even the "all" endpoint is capped, then either HandleFailure or Ok.
    • GetAllAsync paged (:157, [HttpGet("paged")] at :153): clamps with Math.Min(pageSize, MaxPageSize) (:168), unwraps the page with result.TryGetValue(out var page) (:184, the miss routes to HandleFailure at :185) so the success branch reads a non-null page with no ! suppression, and on success writes PaginationMetadata into the X-Pagination response header through the shared PaginationHeaderExtensions helper, Response.AppendPaginationHeader(...) (:187), rather than mixing it into the body, [Rubric §9] again, and [Rubric §12, Performance & Scalability] for the clamp.
    • ExportAsync (:266, [HttpGet("export")] at :261) is covered as its own concept below.
    • GetAllForLookupAsync (:334, [HttpGet("lookup")] at :331): returns CollectionResult<BaseLookup<TIdentifierType>>, a lightweight id/label pair, with a [Required] nameProperty (:335) choosing the label. The same TryGetValue unwrap (:346) feeds the lookups into the CollectionResult items (:348-352).
    • GetByIdAsync (:375, [HttpGet("{id}")] at :370): includeFKs defaults to true for the single-entity case (:377), and on success it calls the inherited SetConcurrencyETag(result.Value) before returning (:396-397).
    • GetCursorPageAsync (:421) and GetChangesAsync (:474) are covered as their own concept below.
    • HandleFailure override (:498-512): logs the first error at Warning, guarded by Logger.IsEnabled (:501), before delegating to ApiControllerBase.HandleFailure, so the read path gets observability ([Rubric §13, Observability & Operability]) without changing the response mapping. The logged message goes through SingleLine (:508, defined at :518-519), which strips every carriage return and line feed so a logged message is always one line whatever the sink. Note it logs the first error while the base ranks the status by the most severe one: the log line is a breadcrumb, not the status decision.
    • Every read action that takes the option passes asTracking: false to the query service (for example :124), because a read endpoint never mutates what it loaded.
  • Concept introduced: one row-scoping hook for every read the controller serves. [Rubric §11, Security] assesses whether an authorization decision can be reproduced consistently across every path that returns the same rows; [Rubric §15, Best Practices & Code Quality] assesses whether that decision lives in one place. GetReadSpecificationAsync(cancellationToken) (:680-682) returns the Specification<TEntity, TIdentifierType> applied by all seven read actions: both GetAllAsync overloads, GetAllForLookupAsync, GetByIdAsync, ExportAsync, GetCursorPageAsync, and GetChangesAsync (each resolves it at :115, :170, :338, :382, :284, :435, and :482; the list is on the hook's doc at :645-647). Four properties are worth internalizing, all stated on the hook's own doc (:644-679).
    • It is asynchronous because row scoping usually is (:656-661). Scope is rarely a pure function of the current principal: it comes from a query handler, a claim lookup that hits a store, a tenancy read. A synchronous hook forced such a controller to override every read action by hand purely to get an await in before the query. An override with nothing to await returns ValueTask.FromResult(...) and allocates nothing.
    • It narrows, it never replaces (:664-668). The query service ANDs the specification with the caller's filters dictionary and fields projection, so a caller can only narrow what the specification already allows; a filter naming excluded rows yields an empty page rather than leaking them (:138-141).
    • A rejected row is a 404, not a 403 (:671-673, restated on GetByIdAsync at :364-369). The specification narrows the query, so the row is simply absent. Answering "forbidden" would confirm the id exists and turn a scoped read into an existence oracle a caller could walk.
    • The lookup endpoint carries the scope as a predicate (:324-330). GetAllForLookupAsync has no specification parameter, so the scope travels as specification?.Criteria (:342); a null specification passes a null predicate, the unscoped query this endpoint always issued. A dropdown that lists what the list endpoint hides would be an oracle of its own. GetExportSpecification() (:710) is the synchronous half: it returns null by default and is what GetReadSpecificationAsync returns by default (:682). A controller that can build its scope without awaiting overrides this one and gets all seven actions scoped; a controller that needs an await overrides the async hook instead, and then this one is no longer consulted (:692-696). For the JSON reads a null specification still means unscoped; for the export it means refused (next concept), so a row-scoped controller that overrides neither hook gets a 403 on /export rather than handing every caller the whole table (:699-702). See ADR-033 for the ownership model this hook reproduces in the query.
  • Concept introduced: a bulk read that fails closed when no scope was declared. [Rubric §11, Security] assesses whether the default on a sensitive path is the safe one. ExportAsync is the one read that can hand a caller a whole table in one request, so it does not treat a null specification as "unscoped": when the hook resolves to null and AllowUnscopedExport is false, it returns before any query runs (:287-288) with the Error.Forbidden built by UnscopedExportRefused (:717-722), which HandleFailure turns into a 403 Problem Details carrying the code ExportRowScopeRequiredErrorCode = "Export.RowScopeRequired" (:541; the 403 is declared on the action at :264). The error message names the three ways out: override GetReadSpecificationAsync, override GetExportSpecification, or opt in.
    • A caller gate runs before the scope. AuthorizeExport() (protected virtual Result, default Result.Success(), :569) is checked first, ahead of field validation and the row-scope hook, so a refused caller learns nothing about the column set or the row scope (:274-277). Its doc (:549-567) aims it at a controller whose download is narrower than its list (a public list with a staff-only export), typically IsPrivileged ? Result.Success() : ExportNotPermitted(), or returning an existing gate's own Result so that gate's error code survives. ExportNotPermitted() (:576-581) builds the standard Error.Forbidden with ExportNotPermittedErrorCode = "Export.NotPermitted" (:547), and a refusal answers a 403 Problem Details with nothing validated, queried or written (:213-218). It is read per request and decides only WHO may export; which rows they get stays with the read hook and AllowUnscopedExport (:563-565).
    • AllowUnscopedExport (protected virtual bool, default false, :602) is the deliberate opt-in. Its doc (:583-601) limits it to controllers whose rows every caller allowed to reach the endpoint may see (reference data, a catalog, an admin-only table already behind a role gate), and notes it is read per request, so it may depend on the principal: return null from the read hook for an administrator and a specification for everyone else, and opt in only for the administrator.
    • A non-null specification never consults the property (:598-599): a scoped export needs no opt-in. The effect is that a controller which forgot to scope its export serves no rows rather than every row (:239-246).
  • Concept introduced: opt-in keyset paging and a change feed. [Rubric §12, Performance & Scalability] and [Rubric §9, API & Contract Design] (ADR-144). Both actions carry [OptInAction(...)], so they exist only on a controller that declares the matching attribute: GetCursorPageAsync needs SupportsCursorPagingAttribute (:416-417) and GetChangesAsync needs SupportsChangeFeedAttribute (:469-470). Both clamp the page size to MaxPageSize (:432, :480), read the same row-scoping hook, and unwrap with TryGetValue into Ok or HandleFailure (:442-444, :487-489).
    • GET /cursor ([HttpGet("cursor")], :416) returns one seek page after an opaque cursor, ordered by sortColumn with Id as the tie-break, plus the next page's cursor (null on the last page). It validates the sort direction first (:428-430) and calls QueryService.GetPageByCursorAsync with a KeysetPageRequest (:437-440). Unlike the paged endpoint it has no total, no pagination header, no field projection, no includes, and no filter dictionary: the keyset read takes a specification only, and a malformed cursor or an unknown sort column is a 400 (:411-415).
    • GET /changes ([HttpGet("changes")], :469, default page size 100 at :477) returns one page of EntityChange<TEntityDTO, TIdentifierType> rows changed at or after since, ordered by (LastModifiedOn, Id), each an upsert carrying the DTO or a tombstone for a soft-deleted row (:448-451), through QueryService.GetChangesSinceAsync (:484-485). The bound is inclusive, so a client pages with the same since until the cursor is null, then keeps the largest changedOn as its next since, and applies the repeated boundary rows idempotently by id and row version; a row that left the read scope without being deleted yields no tombstone (:460-466).
  • Concept introduced: streaming a bulk extract from a paged read. [Rubric §12, Performance & Scalability] assesses whether a large response is bounded and whether memory grows with the result set; [Rubric §11, Security] covers who may pull a whole table in one request. ExportAsync answers the "export what you filtered" request without any new query path (ADR-078). The action itself is a thin adapter over EntityCsvExporter<TEntityDTO>, which owns the page loop, the column resolution, and the CSV format; this controller keeps only the HTTP concerns.
    • A dedicated route, not content negotiation ([HttpGet("export")], :261). The remarks name the two behaviors that make an Accept: text/csv formatter wrong here (:198-203): the public output-cache policy varies by query string but not by Accept, so a cached JSON body could be replayed to a CSV request, and AddAPI sets ReturnHttpNotAcceptable = false (MMCA.Common/Source/Presentation/MMCA.Common.API/DependencyInjection.cs:49), so a negotiation miss falls back to JSON silently instead of returning 406. A distinct path has neither failure mode.
    • Field validation before a byte moves (:279-281, after the caller gate): EntityCsvExporter<TEntityDTO>.ValidateFields rejects a fields= request naming a property the CSV cannot render, as an Error.InvalidEntityField failure, rather than quietly dropping the column.
    • Row scoping through the shared hook, fail-closed: the specification is resolved once, before the first page (:284), and refused when null without the opt-in (:287-288, previous concept), so the same closed-over instance filters every page the fetch delegate reads, and it is the same hook the list endpoints read, so an export cannot drift wider than the list it mirrors.
    • The page loop lives in the exporter: ExportAsync builds a fetch delegate that calls QueryService.GetAllAsync (:295-306) at pageSize = Math.Max(1, MaxPageSize) (:291) and hands it, beginResponse, and onFailureAfterStart to EntityCsvExporter<TEntityDTO>.WriteAsync (:293); the loop, its termination conditions, and the truncation bookkeeping are documented on that type.
    • Navigations for computed columns, never child columns: the export takes no includeChildren parameter, but the fetch delegate loads children when ExportIncludeChildren is overridden to true and foreign keys when either the request's includeFKs or ExportIncludeFKs is set (:296-297). Both are protected virtual bool defaulting to false (:610, :617), for a DTO that computes a scalar from a loaded navigation (a count of children, a parent's name); the collections themselves still earn no CSV column (:604-609, :229-236).
    • Headers first, then body (BeginExportResponse, :728): content type text/csv; charset=utf-8 (CsvContentType, :529, set at :732), a Content-Disposition attachment whose file name is {controller}-{yyyyMMdd'T'HHmmss'Z'}.csv built invariantly from an injected TimeProvider (:730, :733, BuildExportFileName at :744-747, prefix ExportFileNamePrefix at :619-642), and X-Export-Row-Limit (ExportRowLimitHeaderName, :535, appended at :734) so a client can tell "exactly at the limit" from "coincidentally that many rows".
    • Truncation rides in the body. Headers freeze the moment the first body byte flushes, so a truncated export ends with a # export truncated at N rows record (marker built by EntityCsvExporter<TEntityDTO>.TruncationMarker; the remarks at :220-226 name the same line) and a mid-stream query failure ends with an incomplete marker plus a Warning log (LogExportPageFailure, :755-767, wired as onFailureAfterStart at :311), whose error code and message pass through the same SingleLine as HandleFailure's (:765-766). A failure on the FIRST page, before anything was written, still returns Problem Details through HandleFailure (:315), which is exactly what "constructing the writer sends nothing" protects on the exporter side.
    • Column resolution is derived, not invented: EntityCsvExporter<TEntityDTO>.ResolveColumns takes the shaped keys of the first row, so the CSV columns for a given fields= request are the same camelCase JSON names the JSON endpoints emit; an empty result still gets a header row built from the DTO's own properties in declaration order. UnexportablePropertyNames on that type drops the properties that cannot render a faithful scalar cell, byte[]/ReadOnlyMemory<byte> concurrency tokens and every collection type except string, computed once per closed DTO type. Value objects and other class-typed properties are deliberately NOT dropped, because a record or value object has a meaningful invariant ToString. See EntityCsvExporter<TEntityDTO> for the full walkthrough.
  • Why it's built this way: the controller stays thin. All filtering/sorting/paging lives in IEntityQueryService<TEntity, TEntityDTO, TIdentifierType>, and manual DTO mapping (ADR-001) keeps entities off the wire. The controller only translates HTTP concerns: query strings, headers, status codes. The ETag emission and its per-type reflection live on ApiControllerBase, so a conditional write answering from a non-entity controller emits the same header the by-id read does. The export reuses the paged read wholesale precisely so it cannot disagree with the grid it was launched from, and the row ceiling (DefaultMaxExportRows = 100_000, :526, matching ApplicationSettings.MaxExportRows's own default) is a number an operator can reason about rather than an unbounded connection hold. The fail-closed default puts the cost of a forgotten scope on the controller author (a 403 in their own tests) instead of on the data. Splitting the caller gate (AuthorizeExport, who) from the row scope (the read hook, which rows) lets a controller narrow the export audience with one override instead of overriding the action itself. The cursor and change-feed actions are opt-in so an existing controller's route surface does not grow until its author asks for it.
  • Caveats / not-in-source: the export carries no authorization attributes of its own. It inherits whatever [Authorize] or [FeatureGate] the derived controller declares, so a controller that exposes paged anonymously exposes export anonymously once it scopes the rows or opts in, unless it narrows the audience through AuthorizeExport; the symmetry is deliberate and documented (:206-210). The fail-closed rule applies to ExportAsync only: the JSON reads, including the cursor and change-feed actions, still run unscoped on a null specification. The export is also not output-cached.
  • Where it's used: the base for every read-only module controller, for example ADC's child-collection controllers SessionSpeakersController (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.API/Controllers/Sessions/SessionSpeakersController.cs:60) and CategoryItemsController (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.API/Controllers/Categories/CategoryItemsController.cs:71). Extended by AggregateRootEntityControllerBase<TEntity, TEntityDTO, TIdentifierType, TCreateRequest> for entities that also create and delete. The scoping hooks are widely overridden: the async GetReadSpecificationAsync by ADC's SpeakersController (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.API/Controllers/Speakers/SpeakersController.cs:116), SessionsController (SessionsController.cs:78), RoomsController (RoomsController.cs:131) and their child controllers, and by Store's owner-scoped ShoppingCartsController (MMCA.Store/Source/Modules/Sales/MMCA.Store.Sales.API/Controllers/ShoppingCartsController.cs:200); the synchronous GetExportSpecification by ADC's EventsController (EventsController.cs:72) and SessionQuestionAnswersController (SessionQuestionAnswersController.cs:111) and by Store's OrdersController (MMCA.Store/Source/Modules/Sales/MMCA.Store.Sales.API/Controllers/OrdersController.cs:241). AllowUnscopedExport is overridden two ways. Unconditional true on reference and catalog data: ADC's ConferenceCategoriesController (ConferenceCategoriesController.cs:44), QuestionsController (QuestionsController.cs:43) and CategoryItemsController (CategoryItemsController.cs:74), and Store's ProductsController (MMCA.Store/Source/Modules/Catalog/MMCA.Store.Catalog.API/Controllers/ProductsController.cs:51), CategoriesController (CategoriesController.cs:48), InventoryItemsController (InventoryItemsController.cs:43) and CustomersController (MMCA.Store/Source/Modules/Identity/MMCA.Store.Identity.API/Controllers/CustomersController.cs:48), whose export sits behind CustomersManage and whose list endpoints are Admin-only rather than row-scoped (:90-104). Per principal, where the read hook returns null to a privileged caller: ADC's SpeakersController (SpeakersController.cs:126), SessionsController (SessionsController.cs:96), RoomsController (RoomsController.cs:149), EventsController (EventsController.cs:80), SessionQuestionAnswersController (SessionQuestionAnswersController.cs:123) and their siblings, and Store's OrdersController (OrdersController.cs:249) and ShoppingCartsController (ShoppingCartsController.cs:209). No ADC or Store controller overrides AuthorizeExport today. Framework coverage lives in EntityControllerBaseTests, EntityControllerBaseExportTests (opt-in doubles at EntityControllerBaseExportTests.cs:692 and :672), EntityControllerBaseETagTests, and EntityControllerBaseReadSpecificationTests (MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/Controllers/), the last of which drives both hooks through purpose-built doubles (EntityControllerBaseReadSpecificationTests.cs:358 and :377).

AggregateRootEntityControllerBase<TEntity, TEntityDTO, TIdentifierType, TCreateRequest>

MMCA.Common.API · MMCA.Common.API.Controllers · MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/AggregateRootEntityControllerBase.cs:29 · Level 8 · class (abstract)

  • What it is: the read-plus-create-plus-delete tier of the controller hierarchy. It extends EntityControllerBase<TEntity, TEntityDTO, TIdentifierType> (the read endpoints) by adding a CreateAsync (POST) and a DeleteAsync (DELETE) for aggregate-root entities.
  • Depends on: EntityControllerBase<TEntity, TEntityDTO, TIdentifierType> (base), IAggregateRootEntityControllerBase<TEntityDTO, TIdentifierType, TCreateRequest> (implements), ICommandHandler<in TCommand, TResult> (create and delete handlers), DeleteEntityCommand<TEntity, TIdentifierType>, AuditableAggregateRootEntity<TIdentifierType> (constraint), ICreateRequest (constraint), IdempotentAttribute; ASP.NET Core MVC and Asp.Versioning.
  • Concept introduced: idempotent creation guarded at the endpoint. [Rubric §9, API & Contract Design] assesses safe mutation; CreateAsync carries [Idempotent] (AggregateRootEntityControllerBase.cs:76, beside [HttpPost] at :75), which wires IdempotencyFilter so a retried POST carrying the same Idempotency-Key replays the original 201 (flagged X-Idempotent-Replay: true, IdempotencyFilter.cs:41) instead of creating a duplicate aggregate, exactly what mobile and flaky-network clients need. A duplicate that arrives while the first request is still running and cannot take the lock within the 5-second LockWait (IdempotencyFilter.cs:107, awaited at IdempotencyFilter.cs:269) is answered with 409 Conflict rather than a replay (IdempotencyFilter.cs:323-328). Because the fitness rule reads attributes with inherit: true, every concrete controller that inherits this action satisfies its POST idempotency-intent obligation through this base (see NonIdempotentAttribute). [Rubric §1, SOLID]: the four constraints (AggregateRootEntityControllerBase.cs:42-45, notably TEntity : AuditableAggregateRootEntity<TIdentifierType>) enforce at compile time that only aggregate roots reach this create/delete surface.
  • Walkthrough
    • Primary constructor (AggregateRootEntityControllerBase.cs:29-40): four parameters, where queryService and logger are forwarded to the EntityControllerBase<TEntity, TEntityDTO, TIdentifierType> base (:40), plus createHandler and deleteHandler. The logger is typed ILogger<EntityControllerBase<...>>, not of this class, because ILogger<T> is not covariant and the base ctor requires that exact type; the #pragma warning disable S6672 (:37-39) is a justified, narrowly-scoped suppression documenting exactly that ([Rubric §15, Best Practices]).
    • CreateHandler property (:50): protected, so a derived controller that overrides CreateAsync to build a more specific command can still reach the handler. deleteHandler stays a captured constructor parameter, used directly at :115, because nothing overrides delete today.
    • GetByIdRouteName (:57): a protected virtual string defaulting to $"Get{EntityName}ById", the route name CreateAsync links the new resource to. A derived controller that names its by-id route differently overrides it.
    • CreateAsync (:80-98): [HttpPost] plus [Idempotent] (:75-76), body bound [FromBody, Required] (:81); it dispatches the create command (:84) and unwraps the DTO with result.TryGetValue(out var created) (:86), returning HandleFailure on a miss (:86-89), so the success path reads a non-null created with no ! suppression. On success it resolves the Location itself, before returning (:93-95), and returns Created(location, created) (:97). The remarks (:67-74) give the reason: a CreatedAtRoute naming a route the derived controller does not declare throws only when the result executes, after the entity was saved, so the client would get a 500 for a create that succeeded. Url.Link(GetByIdRouteName, ...) supplies an absolute URL when the route resolves (:93-94); otherwise CollectionMemberPath (:126-131) appends the escaped id to the request's own path (PathBase + Path, trailing slash trimmed), a host-relative Location that RFC 9110 permits and where the inherited GET {id} answers. Each branch is parsed with its own UriKind, because RelativeOrAbsolute reads /x/1 as a file URI on Unix (:91-92).
    • DeleteAsync (:111-120): [HttpDelete("{id}")] (:106); builds a DeleteEntityCommand<TEntity, TIdentifierType>, dispatches it, and returns NoContent() on success. Delete here means soft-delete: the handler loads the aggregate and calls its Delete() method, so the domain, not the controller, decides whether the removal is allowed.
  • Why it's built this way: splitting the read-only base from the aggregate-root base means a child-collection controller (add/remove associations, not create whole aggregates) can extend the read base without inheriting create/delete it should not expose ([Rubric §1, SOLID], Interface Segregation), while the actual work stays in injected Application-layer handlers ([Rubric §3, Clean Architecture]) that the CQRS decorator pipeline already wraps with validation, transactions, and cache invalidation (ADR-014). Update is deliberately NOT here: it needs a fifth type parameter, so it lives on CrudEntityControllerBase<TEntity, TEntityDTO, TIdentifierType, TCreateRequest, TUpdateRequest> instead of changing this type's generic arity.
  • Where it's used: concrete aggregate controllers in the modules extend this, for example ADC's EventsController (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.API/Controllers/Events/EventsController.cs:57) and SessionsController (SessionsController.cs:58), and Store's CustomersController (MMCA.Store/Source/Modules/Identity/MMCA.Store.Identity.API/Controllers/CustomersController.cs:43); child-only controllers deliberately extend the read-only base instead. Framework coverage lives in AggregateRootEntityControllerBaseTests (MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/Controllers/AggregateRootEntityControllerBaseTests.cs).

CrudEntityControllerBase<TEntity, TEntityDTO, TIdentifierType, TCreateRequest, TUpdateRequest>

MMCA.Common.API · MMCA.Common.API.Controllers · MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/CrudEntityControllerBase.cs:55 · Level 8 · class (abstract)

  • What it is: the top rung of the generic controller chain. It adds the one endpoint AggregateRootEntityControllerBase<TEntity, TEntityDTO, TIdentifierType, TCreateRequest> leaves out, a conditional PUT /{id}, completing read, create, update, and delete with no per-entity action bodies at all.
  • Depends on: AggregateRootEntityControllerBase<TEntity, TEntityDTO, TIdentifierType, TCreateRequest> (base), ICommandHandler<in TCommand, TResult> with UpdateEntityCommand<TEntity, TUpdateRequest, TIdentifierType>, SupportsIfMatchAttribute, IdempotentAttribute, AuditableAggregateRootEntity<TIdentifierType> and ICreateRequest (constraints, CrudEntityControllerBase.cs:70-73); ASP.NET Core MVC and Asp.Versioning.
  • Concept introduced: adding an endpoint without changing a shipped generic arity. [Rubric §15, Best Practices & Code Quality] assesses whether a capability can be added without disturbing what already works, and [Rubric §32, Dependency & Supply-Chain] covers what a version bump costs a consumer. The update endpoint needs a fifth type, the update request. Adding that parameter to the shipped four-parameter base would change that type's arity, and every controller in every consuming app would stop compiling on the next version bump (CrudEntityControllerBase.cs:23-30). So this base is purely additive: a controller offering only create and delete keeps inheriting the four-parameter base; one that also offers update inherits this and gains the action. Note also what did not change: IAggregateRootEntityControllerBase<TEntityDTO, TIdentifierType, TCreateRequest> gained no UpdateAsync member, for the same reason.
  • Concept introduced: a write that requires the client to state a precondition. [Rubric §8, Data Architecture]. The PUT is conditional (ADR-035): [SupportsIfMatch] (:89) decodes the caller's If-Match header into the command's RowVersion, refuses a request that states no precondition with 428 Precondition Required, and answers a failed one with 412 Precondition Failed (:30-37, and the full status contract declared for OpenAPI at :90-96). The request body carries no token at all, so there is exactly one route a concurrency token travels: out as an ETag on the read, back as If-Match on the write. On success the refreshed token is emitted through the inherited SetConcurrencyETag (:111), so the client can condition its next write without re-reading the resource.
  • Walkthrough
    • Class attributes (:50-52) repeat [ApiController], [Route("[controller]")], [ApiVersion("1.0")], since class-level routing attributes are not reliably inherited.
    • Primary constructor (:53-67): five handlers and services, of which queryService, createHandler, deleteHandler, and logger are forwarded straight to the aggregate-root base (:66-67); only updateHandler is new. The same narrowly-scoped #pragma warning disable S6672 covers the non-covariant ILogger<T> category (:63-65).
    • UpdateHandler property (:77): protected, for a derived controller that overrides UpdateAsync entirely rather than wrapping it.
    • UpdateAsync (:97-113): [HttpPut("{id}")], [Idempotent], [SupportsIfMatch] (:87-89), body bound [FromBody, Required] (:99). It reads the decoded token with SupportsIfMatchAttribute.RequiredToken(HttpContext) (:102), dispatches an UpdateEntityCommand<TEntity, TUpdateRequest, TIdentifierType> carrying id, request, and row version (:104-106), and on success sets the fresh ETag and returns Ok(result.Value) (:111-112). Returning 200 with the refreshed DTO rather than 204 is deliberate (:80-81): the caller re-renders from the response instead of issuing a follow-up read.
  • Why it's built this way: the same Clean Architecture split as the rungs below it. No loading, no mapping, no concurrency comparison happens in this file; the command handler behind the CQRS decorator pipeline does all of it (ADR-014), and cache eviction rides on the command's default CachePrefix through the caching decorator (:38-43). An app that also uses ASP.NET output caching overrides UpdateAsync, awaits base.UpdateAsync, and evicts its own output-cache tags on success, exactly the pattern it already follows for the inherited create and delete actions.
  • Where it's used: today the framework's own coverage is the only consumer: CrudEntityControllerBaseTests (MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/Controllers/CrudEntityControllerBaseTests.cs:20) drives it through a TestCrudController double (:145, closing the five type parameters at :151). No ADC or Store controller extends it yet; they inherit the four-parameter base and write their own PUT actions, which is exactly the case this base exists to absorb.

AuthControllerBase

MMCA.Common.API · MMCA.Common.API.Controllers · MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/AuthControllerBase.cs:49 · Level 12 · class (abstract)

  • What it is: the abstract base for password-based authentication and session management: login, register, refresh, end one session by its refresh token, sign out everywhere, sign out this device, list my devices, record this device's metadata, list my sign-in history, end a view-as session, and revoke one named device. A downstream module (Identity) inherits it and adds the route prefix, version attribute, and any module-specific endpoints.
  • Depends on: ApiControllerBase (base), IAuthenticationService and ICurrentUserService (injected), IAuthSessionIssuer, IViewAsService and ViewAsSettings (resolved per action with [FromServices]), LoginRequest, RegisterRequest, RefreshTokenRequest, EndSessionRequest, AuthenticationResponse, RegistrationPendingResponse, RegistrationOutcome (IsConfirmationPending), RefreshSessionSummaryResponse, SignInSummaryResponse, DeviceMetadata, AuthClaimTypes, ClaimsPrincipalExtensions (FindSessionId), NonIdempotentAttribute, ViewAsEndEndpointAttribute, ViewAsEndedMarker, Error, and the RateLimitPolicyAuthIp constant on WebApplicationBuilderExtensions; Microsoft.AspNetCore.RateLimiting for [EnableRateLimiting].
  • Concept introduced: a secure-by-default base, not just a shared one. [Rubric §9, API & Contract Design] assesses uniform endpoint conventions and [Rubric §1, SOLID] the Open/Closed angle (the base provides virtual endpoints, a derived controller overrides only what differs), but the load-bearing idea here is [Rubric §11, Security]: anti-spray throttling is on by default. LoginAsync and RegisterAsync carry [EnableRateLimiting(WebApplicationBuilderExtensions.RateLimitPolicyAuthIp)] (AuthControllerBase.cs:78 and :103), so any consumer inheriting this base gets per-IP protection without opting in. The class doc (AuthControllerBase.cs:27-34) records why: the earlier arrangement shipped the policy in the framework and left each app to attach it, and an app that simply inherited these actions silently had no spray protection at all, because the global limiter deliberately no-ops for anonymous traffic and account lockout is per-email (ADR-019, ADR-029). Every action otherwise shares the same Result-to-ActionResult shape: call the service, check result.IsFailure, return HandleFailure(result.Errors) or the success result. None carries business logic; they are thin HTTP adapters over IAuthenticationService and the per-action services.
  • Concept introduced: every POST states its idempotency intent, and here every one opts out. This base is the framework's worked example of the NonIdempotentAttribute rule: all eight POSTs carry [NonIdempotent("...")] with a written harm, because each one either mints credentials or must reach the store. Login issues a token pair, so a replayed response would hand a retrying client the tokens minted for an earlier call and extend the lifetime of credentials the caller may already have discarded (:76). Register issues a token pair too, so a replay would hand back tokens minted for an earlier call and keep serving them after the session was revoked; a retried registration instead hits the email-exists 409, which the justification names as the correct answer (:101, the 409 declared at :108). Refresh rotates the refresh token, so a replay would return a token the rotation has already invalidated and hand the client dead credentials (:165). Revocation must reach the store on every call, since a replayed 204 would report a session ended when the store was never touched (:202), report success for a revoke that never ran and leave a refresh token live (:224, :254), or leave a device signed in (:458) after the user asked otherwise, and ending a view-as grant must reach the store for the same reason (:406). The one PUT, RecordCurrentSessionDeviceAsync, carries no such attribute: a retried call simply records the same values again (:312).
  • Walkthrough
    • Primary constructor (:49-51) exposes AuthenticationService and CurrentUserService as protected properties (:54 and :57) so derived controllers can reach them for extra endpoints.
    • ClientIpAddress (:64) and ClientUserAgent (:70) are the two request facts the login, register, and refresh actions forward to the service. The IP is recorded on the refresh session and drives the registration rate limit, and behind a proxy it is the forwarded value only when the host configured UseForwardedHeaders (:60-62). The user agent is purely informational, so a device list can name the session a user is looking at; nothing validates against it (:67-68).
    • LoginAsync (:82): [HttpPost("login")], [NonIdempotent], [AllowAnonymous], throttled per IP (:75-78); calls LoginAsync(request, ClientIpAddress, ClientUserAgent, ...) (:86-88) and returns Ok or HandleFailure. The [ProducesResponseType] attributes (:79-81) feed the OpenAPI contract and include the 429 the limiter can produce.
    • RegisterAsync (:109): [HttpPost("register")], [NonIdempotent], anonymous and throttled (:100-103); passes the caller's IP and user agent to the service (:113-115) and returns RegistrationResult(result, request.Email) (:117). It is virtual so a module can override it to pass further context (:96-98). Its declared responses are 201 with the token pair, 202 with a RegistrationPendingResponse (:105), 429, 400 and 409 (:104-108), matching every status RegistrationResult can answer.
    • RegistrationResult (:132) is the protected mapping a derived RegisterAsync override returns instead of writing the 201 itself, so the pending case never answers a token-less 201 (:121-127). After argument guards (:134-135) a failure goes to HandleFailure (:137-140); a value for which IsConfirmationPending() holds (the account exists but the host requires a confirmed address first) sets Cache-Control: no-store (:142-147) and answers 202 Accepted with a RegistrationPendingResponse carrying the trimmed email (:149); otherwise it answers 201 Created with the token pair (:152).
    • RefreshAsync (:170): [AllowAnonymous] (:166), since exchanging an expired token pair is pre-authentication, and deliberately not throttled (:37-41): refresh is automatic and periodic rather than user-initiated, Blazor Server circuits issue it server-side so every Server-circuit user shares the UI host's IP, and refresh tokens are high-entropy, so brute force is not the threat password spraying is. It declares a 409 (:169): a refresh token that a concurrent request rotated less than RefreshSessions:ReuseGraceSeconds ago is answered 409 Conflict (Auth.RefreshSuperseded) with nothing revoked, because the session is still live and the client should retry with the winner's token rather than sign out (:158-161).
    • EndSessionAsync (:205): [HttpPost("session/end")], [NonIdempotent], [AllowAnonymous] (:201-203) ends the one session behind a refresh token, with the token as the only proof. The Blazor web head calls it server-to-server when the browser deletes its session cookies at sign-out (DELETE /auth/session-cookie), because that host holds the HttpOnly refresh cookie but not the session store, and a Server circuit signing out during a view-as session never holds the staff user's own access token (:184-188). It takes an EndSessionRequest and an IAuthSessionIssuer injected with [FromServices] (:206-208), guards both (:210-211), calls SignOutByRefreshTokenAsync(request.RefreshToken, ...) (:213), and always answers 204 (:214, the only declared response at :204): a live matching session is revoked, and an empty, unknown, expired or already-revoked token changes nothing, so the answer reveals nothing about the token. It is not throttled, for the same reason refresh is not (:191-195).
    • RevokeAsync (:228): [HttpPost("revoke")] with [Authorize] (:223-225); reads CurrentUserService.UserId, returns Unauthorized() if null (:230-232) as a defensive guard even though [Authorize] should already prevent a null id, then calls RevokeAllSessionsAsync and returns NoContent() (:234-240). It is the explicit "sign out of all devices" action (:218-221).
    • RevokeCurrentSessionAsync (:258): [HttpPost("revoke/current")] with [Authorize] (:253-255), the everyday sign-out. It revokes only the session named by the access token's own sid claim through RevokeSessionByIdAsync, so the account stays signed in on its other devices, and falls back to RevokeAllSessionsAsync for a token minted before sid shipped (:264-266). A failure made only of NotFound errors still answers 204 (:268-270): an already-revoked or vanished session means the device is signed out either way, and a sign-out is never a failure to show the user (:249-250).
    • GetMySessionsAsync (:288): [HttpGet("my-sessions")] plus [Authorize] (:284-285), one row per live refresh session, newest first. The "this is the device you are on" flag comes from the access token's own sid claim, read with User.FindSessionId() (:296), so no client state is involved and nothing has to send a refresh token to a read endpoint; a token minted before sid shipped simply flags no row (:278-280).
    • RecordCurrentSessionDeviceAsync (:325): [HttpPut("sessions/current/device")] plus [Authorize] (:320-321) records the DeviceMetadata a native client reports for the calling device, through an IAuthSessionIssuer injected with [FromServices] (:327). A native app sends it once after each sign-in and rotation carries it to every successor session, so the device list and the sign-in history name the device instead of describing its user agent (:305-309). A token with no sid answers 404 Auth.SessionNotFound (:337-344); otherwise it calls RecordDeviceAsync (:346-348), which also answers 404 for a session that is not this user's live one (:312-314).
    • GetMySignInsAsync (:371): [HttpGet("my-sign-ins")] plus [Authorize] (:367-368) lists the caller's sign-in history through GetSignInsAsync with the current sid (:378-380): one row per sign-in however often its refresh token rotated, ended sign-ins included with how they ended, newest first, capped at the newest 50 (:356-358). It takes no user id, so another account's history cannot be requested here; an administrator reads it through the user-administration endpoints under users:manage (:361-363).
    • EndViewAsAsync (:412): [HttpPost("view-as/end")], [ViewAsEndEndpoint], [NonIdempotent], [Authorize] (:404-407) ends the caller's read-only view-as session (ADR-137), the one non-safe call a view-as token may make. It answers 404 while ViewAs:Enabled is false or this host does not hold the grant store (:420-423), 400 ViewAs.NotViewing when the token carries no parsable grant and actor claim (:425-429), maps an EndAsync failure through HandleFailure (:431-435), and on success writes the grant-ended marker to the shared cache through ViewAsEndedMarker.WriteAsync (:439) so the other services of a multi-service host refuse the token on their next request too (:393-398), then answers 204 (:441).
    • RevokeSessionAsync (:463): [HttpPost("revoke/{sessionId:guid}")] (:457), the per-device counterpart. The session is named in the route rather than by its refresh token, so a client can sign out a device it does not hold the token for, which is the whole point of a device list. Ownership is enforced in the store query, so another account's session id answers 404 exactly as a nonexistent one does, and revoking an already-revoked session also answers 404 (code Auth.SessionAlreadyRevoked) and writes nothing, so the device list can say the device was already signed out rather than claim this click signed it out (:448-453).
  • Why it's built this way: [Rubric §15, Best Practices & Code Quality]: adding a new token flow means changing one base, not N module controllers; keeping the methods virtual (rather than the class open-ended) keeps the override surface intentional. The rate-limit default is deliberately a loud dependency: a consumer that inherits this base without calling AddCommonRateLimiting() (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/WebApplicationBuilderExtensions.RateLimiting.cs:403, whose authIpPermitLimit defaults to 30 requests per minute per IP on the same line, and whose settings overload registers the "auth-ip" policy at :468-470, constant defined at :28) fails at startup on an unregistered policy rather than silently serving unthrottled logins (AuthControllerBase.cs:44-46). Splitting "sign out this device" from "sign out everywhere" keeps the everyday action from ending a user's other sessions, and EndSessionAsync gives a host that holds only the refresh cookie the same per-session sign-out. The per-action [FromServices] dependencies keep the constructor at two arguments, so a derived controller does not change when an optional capability (device metadata, session end, view-as) is added.
  • Caveats / not-in-source: the per-IP policy partitions on ClientAddressKey.For(httpContext.Connection.RemoteIpAddress) (WebApplicationBuilderExtensions.RateLimiting.cs:336), the shared key that treats an IPv6 /64 as one client and unmaps IPv4-mapped addresses (WebApplicationBuilderExtensions.RateLimiting.cs:335), and deliberately does not limit when that key is null (in-process TestServer, integration tests): AuthIpRateLimitPartition returns RateLimitPartition.GetNoLimiter("__unknown-ip") in that case (WebApplicationBuilderExtensions.RateLimiting.cs:338-339), a fail-open posture matching the global limiter and documented at WebApplicationBuilderExtensions.RateLimiting.cs:460-467. With RateLimitingSettings.Distributed and a registered Redis client the allowance is shared across replicas, falling back to a per-instance count on a Redis fault (WebApplicationBuilderExtensions.RateLimiting.cs:325-330). EndSessionAsync is anonymous and unthrottled by design, so it relies on the refresh token's entropy alone.
  • Where it's used: the base of every app's Identity AuthController, reached today through UserAccountAuthControllerBase<TChangePasswordCommand, TChangePreferencesCommand>, which both ADC (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/Controllers/AuthController.cs:42) and Store (MMCA.Store/Source/Modules/Identity/MMCA.Store.Identity.API/Controllers/AuthController.cs:34) extend. Password recovery is deliberately NOT on this chain: it ships as the sibling PasswordResetAuthControllerBase<TForgotPasswordCommand, TResetPasswordCommand>. RegisterAsync and EndSessionAsync are among the anonymous endpoints the framework's architecture gate lists by name (MMCA.Common/Tests/Architecture/MMCA.Common.Architecture.Tests/Api/AnonymousEndpointTests.cs:27 and :33). The framework's own coverage drives the base through a minimal test double, TestAuthController (MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/Controllers/Auth/AuthControllerBaseTests.cs:548), with the throttling asserted separately in AuthControllerBaseRateLimitTests.

PasswordResetAuthControllerBase<TForgotPasswordCommand, TResetPasswordCommand>

MMCA.Common.API · MMCA.Common.API.Controllers · MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/PasswordResetAuthControllerBase.cs:43 · Level 15 · class (abstract)

  • What it is: the two anonymous password-recovery endpoints, POST forgot-password and POST reset-password, for a user who cannot sign in at all. It is a sibling of AuthControllerBase, not an addition to it.
  • Depends on: ApiControllerBase (base), two ICommandHandler<in TCommand, TResult> instances returning Result (PasswordResetAuthControllerBase.cs:44-45), ICommandWithRequest<out TRequest> as the constraint on both type parameters (:46-47), ForgotPasswordRequest and ResetPasswordRequest, IdempotentAttribute, and the RateLimitPolicyAuthIp constant on WebApplicationBuilderExtensions; ASP.NET Core MVC, Microsoft.AspNetCore.Authorization, and Microsoft.AspNetCore.RateLimiting.
  • Concept introduced: a recovery surface that leaks nothing, on a chain single inheritance already owns. Two separate ideas meet in this one type.
    • Why a sibling controller and not two more actions on the auth base. C# gives a class one base, and each app's AuthController already spends it on UserAccountAuthControllerBase<TChangePasswordCommand, TChangePreferencesCommand>. Recovery therefore ships as its own base that the app routes to the same Auth prefix ([Route("Auth")] on the concrete controller), so POST /Auth/forgot-password rides the gateway's existing /Auth route with no gateway change (class doc, PasswordResetAuthControllerBase.cs:13-18; the ADC subclass records the same reasoning at MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/Controllers/PasswordResetController.cs:19-24). [Rubric §15, Best Practices & Code Quality] assesses whether a capability can be added without disturbing what already works: nothing on the authentication chain changed to make room for this.
    • Response shapes chosen so the endpoint is not an account oracle. [Rubric §11, Security] assesses what an unauthenticated caller can learn by probing. Forgot-password always answers 202 on a well-formed request: an unknown address, a throttled request and a failed send are all treated as success by the handler, so the response never reveals which addresses hold accounts, and only a malformed payload reaches 400 through the request validator (remarks, :27-31). Reset-password collapses every rejection to one 401 for the same reason (:95-98). Both actions must be anonymous by necessity, because the caller has lost the credential that authentication would demand, so requiring one would be circular (:20-26); the framework's anonymous-endpoint architecture gate therefore lists both by name rather than letting them pass silently (MMCA.Common/Tests/Architecture/MMCA.Common.Architecture.Tests/Api/AnonymousEndpointTests.cs:42-43). See ADR-091, which chose a cache-backed single-use token over user-row columns or a self-contained signed payload.
  • Walkthrough
    • Type parameters and constraints (:43-47): TForgotPasswordCommand : ICommandWithRequest<ForgotPasswordRequest> and TResetPasswordCommand : ICommandWithRequest<ResetPasswordRequest>. That is the entire contract the base needs, a command that carries a request payload. Note the difference from the account base next door, whose commands are IUserScopedCommand<TRequest>: recovery has no authenticated user to scope to.
    • The two handlers become protected properties (:50 and :53), the same convention the other auth bases follow, so a derived controller can dispatch them itself for an extra endpoint.
    • CreateForgotPasswordCommand(request) (:61) and CreateResetPasswordCommand(request) (:69) are the two abstract factories. The doc comments state the expected implementation verbatim, => new(request);, and both consumers do exactly that (MMCA.ADC/.../PasswordResetController.cs:36 and :39).
    • ForgotPasswordAsync (:82): [HttpPost("forgot-password")], [Idempotent], [AllowAnonymous], [EnableRateLimiting(RateLimitPolicyAuthIp)] (:75-78), with the 202/400/429 contract declared for OpenAPI (:79-81). The body dispatches the app command and returns Accepted() on success or HandleFailure (:86-92).
    • ResetPasswordAsync (:107) mirrors it at [HttpPost("reset-password")] (:99-102), declaring 204/400/401/429 (:103-106) and returning NoContent() on success (:111-117).
  • Why it's built this way: the commands stay app-side, as they do on the account base (remarks, :32-39). That remark gives ADC marking its commands ICacheInvalidating as the reason, but today ADC's ResetPasswordCommand implements only ICommandWithRequest<ResetPasswordRequest> (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/ResetPassword/ResetPasswordCommand.cs:10-11), the same shape as Store's (MMCA.Store/Source/Modules/Identity/MMCA.Store.Identity.Application/Users/UseCases/ResetPassword/ResetPasswordCommand.cs:13), so for this command the two records differ only in namespace and the stated reason no longer applies. [Rubric §2, Design Patterns]: this is Template Method again, the base owning the HTTP shape and deferring construction to two primitive operations. Both actions carry [Idempotent] rather than a [NonIdempotent] justification, which fits their contract: a retried forgot-password should replay the same 202 instead of mailing a second token, and a retried reset should replay the same 204 rather than fail against a token the first call already burned. [Rubric §3, Clean Architecture]: no token generation, hashing, or mail send appears here at all; the controller dispatches and maps, and everything else lives behind the CQRS decorator pipeline (ADR-014).
  • Where it's used: subclassed by each app's sealed PasswordResetController: ADC's (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/Controllers/PasswordResetController.cs:28) and Store's (MMCA.Store/Source/Modules/Identity/MMCA.Store.Identity.API/Controllers/PasswordResetController.cs:25), each supplying only the two one-line factory overrides plus [ApiController], [Route("Auth")], and [ApiVersion("1.0")]. Framework coverage is PasswordResetAuthControllerBaseTests (MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/Controllers/Auth/PasswordResetAuthControllerBaseTests.cs:23), which drives a TestPasswordResetController double (:165) and additionally asserts, action by action, that the anonymous, rate-limited and idempotent attributes are still attached (:115-141), so the security posture cannot be removed silently.
  • Caveats / not-in-source: the "always 202" and "every rejection collapses to one 401" guarantees are properties of the app's command handlers, stated in this base's remarks (:27-31, :95-98) but enforced one layer down; nothing in this file forces them.

UserAccountAuthControllerBase<TChangePasswordCommand, TChangePreferencesCommand>

MMCA.Common.API · MMCA.Common.API.Controllers · MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/UserAccountAuthControllerBase.cs:41 · Level 16 · class (abstract)

  • What it is: AuthControllerBase plus the three self-service account endpoints every app needs once a user is signed in: PUT password, PUT preferences, and GET preferences. The app Identity modules previously carried line-identical copies of all three actions, and the only real difference between them was the command record each one constructed (class doc, UserAccountAuthControllerBase.cs:15-20).
  • Depends on: AuthControllerBase (base, constructed with the same IAuthenticationService and ICurrentUserService it forwards, UserAccountAuthControllerBase.cs:47), two ICommandHandler<in TCommand, TResult> instances and one IQueryHandler<in TQuery, TResult> (:44-46), IUserScopedCommand<out TRequest> as the constraint on both command type parameters (:48-49), ChangePasswordRequest, ChangePreferencesRequest, GetUserPreferencesQuery, UserPreferencesResponse, and Result; ASP.NET Core MVC and Microsoft.AspNetCore.Authorization.
  • Concept introduced: generic-over-the-command deduplication. Two apps wanted the same HTTP surface while each keeps its own command record. The base's remarks justify that by ADC marking its records ICacheInvalidating with a cache prefix built from its own User type while Store's do not (remarks, UserAccountAuthControllerBase.cs:22-31), but today ADC's ChangePasswordCommand implements only ICommandWithRequest<ChangePasswordRequest> and IUserScopedCommand<ChangePasswordRequest> (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/ChangePassword/ChangePasswordCommand.cs:12-13), the same shape as Store's (MMCA.Store/Source/Modules/Identity/MMCA.Store.Identity.Application/Users/UseCases/ChangePassword/ChangePasswordCommand.cs:12-13), and no ADC Identity user use case implements ICacheInvalidating, so the remark's reason no longer holds and the records stay app-side by that earlier design. The resolution is the classic Template Method: the base owns the HTTP shape and the dispatch, and defers construction of the app command to two abstract factory methods. [Rubric §15, Best Practices & Code Quality] assesses whether a change lands in one place; [Rubric §1, SOLID] covers both the Open/Closed extension point and the Dependency Inversion angle, since the base depends only on the IUserScopedCommand<TRequest> abstraction and never on either app's concrete record. [Rubric §2, Design Patterns]: the two Create*Command overrides are the pattern's primitive operations, and their implementations really are one line each.
  • Walkthrough
    • Type parameters and constraints (:41-49): TChangePasswordCommand : IUserScopedCommand<ChangePasswordRequest> and TChangePreferencesCommand : IUserScopedCommand<ChangePreferencesRequest>. That constraint is the whole contract the base needs: a command that carries a user id and a request payload.
    • The three handlers become protected properties (:52, :55, :58), matching the base's convention so a derived controller can dispatch them itself for an extra endpoint.
    • CreateChangePasswordCommand(userId, request) (:67-69) and CreateChangePreferencesCommand(userId, request) (:78-80) are the two abstract factories. Both take a UserIdentifierType, the solution-wide identifier alias, so the base never has to know whether an app's user key is an int or a Guid.
    • ChangePasswordAsync (:92): [HttpPut("password")] plus [Authorize] (:87-88). It reads CurrentUserService.UserId, returns Unauthorized() when null (:96-98), then dispatches CreateChangePasswordCommand(userId.Value, request) through the handler (:100-102) and returns NoContent() or HandleFailure. Note what is absent: no password verification, no hashing, no user lookup. Those live in the app's command handler, behind the CQRS decorator pipeline, so validation and the transaction wrap them (ADR-014). The doc comment is explicit that this dispatches the handler directly rather than brokering through the authentication service (:83-85).
    • ChangePreferencesAsync (:118) mirrors it at [HttpPut("preferences")] (:113): the stored UI culture and theme (ADR-027, ADR-028) follow the user across devices, and a null field leaves that preference unchanged (:110-111).
    • GetPreferencesAsync (:143): [HttpGet("preferences")] (:139). This one constructs its query inline, new GetUserPreferencesQuery(userId.Value) (:151), because the read side has no per-app detail to preserve; the remarks call that asymmetry out deliberately (:29-30).
    • All three actions repeat the same "UserId is null yields Unauthorized()" guard rather than trusting [Authorize] alone, the same defensive posture AuthControllerBase.RevokeAsync takes.
  • Why it's built this way: inheriting this base instead of AuthControllerBase is purely additive (remarks, :33-36): every inherited login/register/refresh/revoke action, including the default per-IP throttling, the idempotency attributes, and the ability to override RegisterAsync or attach another [EnableRateLimiting] policy app-side, behaves exactly as before. That is what made the consolidation safe to do at all. The alternative (pushing the command records into the framework) would have forced ADC's cache-invalidation behavior onto Store or dropped it from ADC. [Rubric §14, Testability]: because the extension point is two abstract methods rather than a service lookup, the framework can exercise the whole base with a test double supplying trivial commands.
  • Where it's used: extended by each app's Identity AuthController: ADC's (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/Controllers/AuthController.cs:34) and Store's (MMCA.Store/Source/Modules/Identity/MMCA.Store.Identity.API/Controllers/AuthController.cs:28), each supplying the two one-line factory overrides. Covered in the framework by UserAccountAuthControllerBaseTests (MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/Controllers/Auth/UserAccountAuthControllerBaseTests.cs:17), which drives the base through a TestUserAccountAuthController double (:235).

AdminActionMetrics

MMCA.Common.API · MMCA.Common.API.Controllers.Administration · MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Administration/AdminActionMetrics.cs:17 · Level 0 · class (internal static)

  • What it is: the single OpenTelemetry counter, mmca.auth.admin_action, that counts completed administrative actions (a role change, a lock, an unlock, a machine-client create or secret rotation, the start of a view-as session), tagged by which action ran.
  • Depends on: System.Diagnostics.Metrics (Meter, Counter<long>) from the BCL only. Consumed by UsersAdminControllerBase<TUserDto> and MachineClientsControllerBase; exported by the Aspire service defaults under the shared meter name.
  • Concept: metering a cross-cutting mechanism is introduced by IdempotencyMetrics; this type applies the same pattern to the admin surface with one difference: it does not own a meter. MeterName = "MMCA.Common.Auth" (AdminActionMetrics.cs:20) is the meter that already carries the sign-in, refresh-reuse and lockout counters, so the admin counter sits beside them under one export registration; the name is duplicated as a literal in the Aspire service defaults and in MMCA.Common.Application, which declare the other instruments, because neither references this package (type doc, AdminActionMetrics.cs:5-11). [Rubric §13, Observability & Operability]: a burst of locks or role changes shows up as a number an operator can alert on, rather than something reconstructed from log lines. [Rubric §11, Security]: the only tag is the low-cardinality action, never a user id, an address or a client IP (remarks, AdminActionMetrics.cs:12-16), so the metric pipeline carries no personal data.
  • Walkthrough
    • ActionTag = "action" (AdminActionMetrics.cs:23) names the one tag, and six string constants are its closed value set: RoleChange = "role_change" (AdminActionMetrics.cs:26), Lock = "lock" (:29), Unlock = "unlock" (:32), MachineClientCreate = "machine_client_create" (:35), MachineClientRotate = "machine_client_rotate" (:38) and ViewAsStart = "view_as_start" (:41).
    • One static Meter built from the name (AdminActionMetrics.cs:43) and one Counter<long> named mmca.auth.admin_action with unit {action} (AdminActionMetrics.cs:45-48).
    • Record(string action) (AdminActionMetrics.cs:52-53) is the only recording surface: it adds 1 with the action attached as a KeyValuePair tag.
  • Why it's built this way: the counter is recorded once per COMPLETED action, after the service reported success, so a refused or failed request is never counted (remarks, AdminActionMetrics.cs:13-14); that is why every call site sits after the failure check rather than at the top of the action. internal static keeps the instrument off the package's public API while letting every controller in the assembly record it, and named constants instead of free strings keep the tag's value set closed.
  • Where it's used: UsersAdminControllerBase<TUserDto> records ViewAsStart after a successful StartViewAsAsync (UsersAdminControllerBase.cs:196) and passes Lock, Unlock and RoleChange into its Completed helper, which records on success (UsersAdminControllerBase.cs:496); MachineClientsControllerBase records MachineClientCreate (MachineClientsControllerBase.cs:94) and MachineClientRotate (MachineClientsControllerBase.cs:122). Promote and revoke on the machine-client surface, and the permission set on RolesAdminControllerBase, record nothing.

IdempotencyMetrics

MMCA.Common.API · MMCA.Common.API.Idempotency · MMCA.Common/Source/Presentation/MMCA.Common.API/Idempotency/IdempotencyMetrics.cs:16 · Level 0 · class (internal static)

  • What it is: the three OpenTelemetry counters that make the idempotency filter observable: how often a stored response was replayed, how often a duplicate was refused, and how often the filter ran without its guarantee because the cache or the lock was unhealthy.
  • Depends on: System.Diagnostics.Metrics (Meter, Counter<long>) from the BCL only. Consumed by IdempotencyFilter; the meter is exported by the Aspire service defaults.
  • Concept introduced: metering a degradable cross-cutting filter. [Rubric §13, Observability & Operability] assesses whether an operator can tell that a mechanism is still doing its job. That matters here more than for most filters because IdempotencyFilter is deliberately best-effort: when its cache or its lock faults, it swallows the fault and lets the request run unguarded rather than failing the write. Without a counter that failure mode is invisible, since every request still succeeds, so a Redis outage would silently turn deduplication off across the fleet. idempotency.degraded is the signal that turns that silence into an alertable number, and the doc says so directly: a sustained non-zero rate means deduplication is effectively off (IdempotencyMetrics.cs:70-73). [Rubric §12, Performance & Scalability] applies because instrument names and tag names are centralized in one type rather than restated at each call site (remarks, IdempotencyMetrics.cs:12-15).
  • Walkthrough
    • MeterName = "MMCA.Common.Idempotency" (IdempotencyMetrics.cs:19) names the meter; Meter is a single static instance built from it (IdempotencyMetrics.cs:39).
    • Three counters, all Counter<long> with unit {request}: idempotency.replayed (IdempotencyMetrics.cs:41-44), idempotency.conflict (IdempotencyMetrics.cs:46-49), and idempotency.degraded (IdempotencyMetrics.cs:51-54).
    • The three conflict shapes are separated by a tag rather than by separate counters: ConflictKindTag = "kind" (IdempotencyMetrics.cs:37) carries ConflictKindBodyMismatch = "body_mismatch" (IdempotencyMetrics.cs:24), ConflictKindTargetMismatch = "target_mismatch" for a key reused against a different concrete path or query (IdempotencyMetrics.cs:29), or ConflictKindInFlight = "in_flight" (IdempotencyMetrics.cs:34), so one time series can be split or summed.
    • The three helpers are the only recording surface: RecordReplayed() (IdempotencyMetrics.cs:57), RecordConflict(string kind), which attaches the tag as a KeyValuePair (IdempotencyMetrics.cs:67-68), and RecordDegraded() (IdempotencyMetrics.cs:74).
  • Why it's built this way: internal static keeps the instruments off the package's public API while still letting the filter in the same assembly record them. A host exports these by registering the meter, which the Aspire service defaults do with the name as a literal, because MMCA.Common.Aspire has no reference to MMCA.Common.API; the duplication is called out in the type doc (IdempotencyMetrics.cs:8-10). OutputCacheMetrics and AdminActionMetrics use the identical pattern.
  • Where it's used: every recording site is in IdempotencyFilter: RecordDegraded on a faulted lock acquisition (IdempotencyFilter.cs:274), a failed cache read (IdempotencyFilter.cs:403) and a failed cache write (IdempotencyFilter.cs:503); RecordConflict for an in-flight duplicate (IdempotencyFilter.cs:286), a body mismatch (IdempotencyFilter.cs:413) and a target mismatch (IdempotencyFilter.cs:424); RecordReplayed on every served replay (IdempotencyFilter.cs:430).

IdempotencyRecord

MMCA.Common.API · MMCA.Common.API.Idempotency · MMCA.Common/Source/Presentation/MMCA.Common.API/Idempotency/IdempotencyRecord.cs:27 · Level 0 · record (sealed, positional)

  • What it is: the cached snapshot of an idempotent action's response: the HTTP status code, the JSON-serialized body, the hash of the request body that produced it, the two response headers a client may act on (Location and ETag), and the hash of the concrete request target (path plus query string). It is what IdempotencyFilter writes after the first successful execution and replays for every duplicate carrying the same key, the same payload and the same target.
  • Depends on: nothing beyond the BCL; a six-parameter positional record whose first three parameters are required and whose last three are optional and nullable.
  • Concept: introduced fully by IdempotencyFilter; this is the value it persists. Three properties of the shape are load-bearing. First, the record captures the status, the body and exactly two headers, not the whole header collection: Location so a replayed 201 Created still says where the resource is, and ETag so a replayed response still carries its concurrency token (parameter docs, IdempotencyRecord.cs:14-20; replay at IdempotencyFilter.cs:435-441). The replay path adds X-Idempotent-Replay itself (IdempotencyFilter.cs:433). Second, RequestBodyHash is non-nullable, so there is no "no hash stored" state to fall through: every record carries one and a key replayed with a different payload is always rejected rather than served someone else's response (parameter doc, IdempotencyRecord.cs:9-13). A body-less request hashes the empty payload rather than storing nothing. Third, RequestTargetHash binds the record to the concrete resource: the cache key holds only the route template, so PUT /orders/1 and PUT /orders/2 share a key, and the target hash is what refuses the second with a 422 instead of serving it the first one's response (parameter doc, IdempotencyRecord.cs:21-26). [Rubric §9, API & Contract Design] assesses whether a persisted contract states its invariants in its shape rather than in a comment; making the body hash required is what removes the unchecked path.
  • Walkthrough: IdempotencyRecord(int StatusCode, string ResponseBody, string RequestBodyHash, string? Location = null, string? ETag = null, string? RequestTargetHash = null) (IdempotencyRecord.cs:27-33). StatusCode is the original response's code, defaulting to 200 when an ObjectResult carried none (IdempotencyFilter.cs:525). ResponseBody is non-nullable: an ObjectResult stores objectResult.Value serialized with the host's MVC JSON options (falling back to JsonSerializerOptions.Web), and stores string.Empty when the value is null (IdempotencyFilter.cs:484-485 and :530), while a body-less 2xx such as the 204 from NoContent() also stores string.Empty (IdempotencyFilter.cs:544-549); the empty string is the signal the replay path uses to answer with a bare status code instead of a JSON content result. RequestBodyHash is the lowercase hex SHA-256 of the request body (IdempotencyFilter.cs:637-648). Location is resolved only for an ObjectResult (IdempotencyFilter.cs:535) and is null when the response carried none; ETag is whatever the action wrote to the response headers, null when empty (IdempotencyFilter.cs:517-518). RequestTargetHash is the lowercase hex SHA-256 of the request's Path value concatenated with its QueryString value, exactly as received (IdempotencyFilter.cs:658-662), and both cacheable result shapes store it (IdempotencyFilter.cs:537 and :549). The parameter docs note that Location and RequestTargetHash are null for records written before each field existed (IdempotencyRecord.cs:16 and IdempotencyRecord.cs:24-25), which is why the trailing parameters are optional.
  • Why it's built this way: keeping the record to primitives makes it provider-agnostic, so the same artifact round-trips through the in-memory cache or Redis with no serializer coupling. Adding fields as trailing optional parameters keeps a record cached before they existed deserializable: the replay simply skips a header it does not have (IdempotencyFilter.cs:437-441), and a record with no target hash is checked on its body alone and ages out within the retention window (IdempotencyFilter.cs:419-422). The target hash is its own field rather than folded into the body hash for the same reason: a record written before it existed still answers its own identical retry (IdempotencyFilter.cs:204-207). Distinguishing "empty body" from "no body" via the empty string (rather than a nullable) keeps the JSON shape stable across both cases, and the comment at IdempotencyFilter.cs:539-541 names that convention at the place a body-less status result is stored.
  • Where it's used: read by IdempotencyFilter through ICacheService (IdempotencyFilter.cs:399), built by its BuildRecord (IdempotencyFilter.cs:512), and written back with the configured expiration (IdempotencyFilter.cs:499).

IdempotencySettings

MMCA.Common.API · MMCA.Common.API.Idempotency · MMCA.Common/Source/Presentation/MMCA.Common.API/Idempotency/IdempotencySettings.cs:9 · Level 0 · class (sealed)

  • What it is: the options object bound from the Idempotency configuration section. It carries exactly one knob: how long a cached idempotent response is retained.
  • Depends on: System.ComponentModel.DataAnnotations for the [Range] attribute; bound through Microsoft.Extensions.Options.
  • Concept: the standard options pattern (see the primer). [Rubric §17, DevOps & Deployment] assesses whether a cross-cutting concern is configurable without becoming mandatory; the whole section is optional because the single property has a default, so a host that never mentions idempotency still behaves correctly (type doc, IdempotencySettings.cs:5-8).
  • Walkthrough: SectionName is a public static readonly string equal to "Idempotency" (IdempotencySettings.cs:12), so the binding key is a symbol rather than a magic string at the call site. CacheExpirationHours defaults to 24 (IdempotencySettings.cs:16) and is constrained by [Range(1, 168)] (IdempotencySettings.cs:15), one hour to one week. The property is init-only, so the value is fixed once bound.
  • Why it's built this way: AddAPI binds the section only when the caller passes an IConfiguration, and when it does it chains .ValidateDataAnnotations().ValidateOnStart() (MMCA.Common/Source/Presentation/MMCA.Common.API/DependencyInjection.cs:78-81), so an out-of-range CacheExpirationHours fails the host at startup rather than at the first idempotent POST. [Rubric §15, Best Practices & Code Quality]: fail fast, loudly, at composition time. RateLimitingSettings follows the same shape one directory over.
  • Where it's used: resolved as IOptions<IdempotencySettings> inside IdempotencyFilter at store time (IdempotencyFilter.cs:491-495). Note the deliberate GetService, not GetRequiredService: when the options are absent (the AddAPI overload called with no configuration) the filter falls back to its hard-coded 24-hour DefaultExpiration (IdempotencyFilter.cs:83) instead of throwing.

NonIdempotentAttribute

MMCA.Common.API · MMCA.Common.API.Idempotency · MMCA.Common/Source/Presentation/MMCA.Common.API/Idempotency/NonIdempotentAttribute.cs:23 · Level 0 · class (sealed)

  • What it is: a documentation-only marker declaring that a POST action is deliberately outside the Idempotency-Key contract, and why. It attaches no filter and changes no runtime behavior; its single member is the justification string.
  • Depends on: nothing but System.Attribute. Its counterpart is IdempotentAttribute, and its only consumer is the PostActionsDeclareIdempotencyIntent fitness function on ArchitectureRules (MMCA.Common/Source/Hosting/MMCA.Common.Testing.Architecture/Rules/Cqrs/ArchitectureRules.Idempotency.cs:44, where the attribute is matched by type NAME through the NonIdempotentAttributeName constant at ArchitectureRules.Idempotency.cs:9 so the rules package needs no ASP.NET reference).
  • Concept introduced (an attribute whose only job is to make an omission impossible). IdempotentAttribute is opt-in, which leaves one failure mode: an action that should deduplicate but is missing the attribute gets no protection, and nothing in the type system flags it. This attribute is the answer. POST is the one verb HTTP does not define as idempotent, so a client retrying a timed-out POST cannot know whether the first attempt landed, and the filter costs an existing client nothing because it no-ops for a request with no key header. That makes the only failure mode worth gating "an omission nobody noticed", so the fitness rule requires every POST action to carry one of the two attributes (rule remarks, ArchitectureRules.Idempotency.cs:20-29; the failure message spells out both remedies at :56-60), and this one carries a written reason (NonIdempotentAttribute.cs:3-9). [Rubric §34, Architecture Governance & Documentation] assesses whether decisions are recorded where they can be checked rather than remembered: the justification lives on the method and the build fails without it. [Rubric §15, Best Practices & Code Quality] covers [AttributeUsage(AttributeTargets.Method)] (NonIdempotentAttribute.cs:22), which makes a class-level application a compile error rather than a silent no-op.
  • Walkthrough: the whole type is a primary-constructor attribute, NonIdempotentAttribute(string justification) (NonIdempotentAttribute.cs:23), exposing public string Justification { get; } = justification; (NonIdempotentAttribute.cs:28). The parameter doc says the reason is required and is meant to be read by the next person who wonders whether the omission was intentional (NonIdempotentAttribute.cs:18-21).
  • Why it's built this way: the remarks (NonIdempotentAttribute.cs:11-17) narrow the legitimate cases sharply: this attribute is for actions where replaying a stored response would be actively wrong rather than merely unhelpful (token issuance and revocation, single-use code exchange, anything whose response is only valid for the call that produced it), and IdempotentAttribute is the default everywhere else. Making it a marker rather than a filter is what keeps it free: no pipeline stage, no DI registration, no runtime cost.
  • Where it's used: in the framework, on the four token-lifecycle actions of AuthControllerBase (login at AuthControllerBase.cs:76, refresh at :116, revoke at :143, per-session revoke at :206) and on OAuthControllerBase.ExchangeAsync (OAuthControllerBase.cs:314). Each justification names the concrete harm: a replayed login hands a retrying client tokens minted for an earlier call, a replayed refresh returns a token the rotation already invalidated, a replayed revoke reports success for a revocation that never ran, and a replayed exchange defeats the single-use burn on the OAuth code. Downstream the same discipline holds: ADC's session-selection enqueue is opted out because the queue's own pending set already deduplicates and a cached 202 would hide both an already-running refusal and a queue-full rejection (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.API/Controllers/Sessions/SessionSelectionController.cs:82), and Store opts its payments action out (MMCA.Store/Source/Modules/Sales/MMCA.Store.Sales.API/Controllers/PaymentsController.cs:58). Consumer repos inherit the rule through IdempotencyConventionTestsBase (MMCA.Common/Source/Hosting/MMCA.Common.Testing.Architecture/Bases/IdempotencyConventionTestsBase.cs).

DisabledFeatureHandler

MMCA.Common.API · MMCA.Common.API.FeatureManagement · MMCA.Common/Source/Presentation/MMCA.Common.API/FeatureManagement/DisabledFeatureHandler.cs:14 · Level 0 · class (sealed)

  • What it is: the one-method handler that decides what a [FeatureGate]-protected controller action returns when its feature flag is off. Instead of ASP.NET Core's default (a bare 404 with no body), it emits an RFC 9457 Problem Details payload so a disabled feature reads the same as any other framework error.
  • Depends on: IDisabledFeaturesHandler and FeatureGateAttribute from Microsoft.FeatureManagement.Mvc (NuGet); ProblemDetails, ObjectResult, and StatusCodes from ASP.NET Core. No first-party dependencies.
  • Concept introduced: feature gating at the HTTP edge. [Rubric §9, API & Contract Design] assesses whether every response, success or refusal, follows one uniform contract; this handler makes the disabled-feature path match the ApiControllerBase.HandleFailure shape rather than leaking a framework default. [Rubric §6, CQRS & Event-Driven Design] covers concerns applied uniformly across endpoints, and feature flags are exactly that. Note the split: this class gates controller actions decorated with [FeatureGate], while FeatureGateCommandDecorator<TCommand, TResult> gates CQRS handlers one layer deeper. The two surfaces cover the two entry points into a gated capability, which is precisely the dual-surface enforcement ADR-031 records.
  • Walkthrough: HandleDisabledFeatures(features, context) (DisabledFeatureHandler.cs:17) sets context.Result to an ObjectResult wrapping a ProblemDetails with Status = 404 and a fixed title/detail ("Feature not available", DisabledFeatureHandler.cs:19-24), and also sets the outer StatusCode = 404 (DisabledFeatureHandler.cs:26) so the response code and the body agree. It returns Task.CompletedTask (DisabledFeatureHandler.cs:29): the work is synchronous, there is nothing to await.
  • Why it's built this way: the payload deliberately does not name the disabled feature. An anonymous caller learns only that the endpoint is unavailable, not which flag is off, so the flag set is not enumerable from outside. The features parameter is available but unused for that reason.
  • Where it's used: registered as the app's IDisabledFeaturesHandler singleton inside AddAPI (MMCA.Common/Source/Presentation/MMCA.Common.API/DependencyInjection.cs:110, immediately after services.AddFeatureManagement().WithTargeting<CurrentUserTargetingContextAccessor>() on DependencyInjection.cs:108-109); invoked by Microsoft.FeatureManagement.Mvc whenever a [FeatureGate] action is hit with its flag disabled. In the framework itself that covers DataExportControllerBase<TQuery> while PrivacyFeatures.DataExport is off (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Privacy/DataExportControllerBase.cs:60) and the three notification controllers gated on NotificationFeatures.PushNotifications (Controllers/Notifications/DevicesController.cs:23, NotificationInboxController.cs:27, NotificationsController.cs:28).

RequestFingerprint

MMCA.Common.API · MMCA.Common.API.Idempotency · MMCA.Common/Source/Presentation/MMCA.Common.API/Idempotency/IdempotencyFilter.cs:589 · Level 0 · record struct (private, readonly, nested in IdempotencyFilter)

  • What it is: the pair of hashes a stored IdempotencyRecord must match before it is replayed: BodyHash, the lowercase hex SHA-256 of the request body, and TargetHash, the lowercase hex SHA-256 of the request path plus query string (parameter docs, IdempotencyFilter.cs:586-588).
  • Depends on: nothing; a private nested type of IdempotencyFilter, with no use outside that file.
  • Concept: introduced by IdempotencyFilter (a stored response is bound to the body and the target that produced it); this type is the request's side of that comparison, carried as one value through every path. [Rubric §11, Security]: the target half is what stops a key reused against another resource behind the same route template from being answered with a response for a resource the caller did not write.
  • Walkthrough: private readonly record struct RequestFingerprint(string BodyHash, string TargetHash) (IdempotencyFilter.cs:589). It is built once per keyed request in OnActionExecutionAsync from ComputeRequestBodyHashAsync and ComputeRequestTargetHash (IdempotencyFilter.cs:142-144), then passed unchanged into ExecuteUnderProcessLockAsync (:223), ExecuteUnderDistributedLockAsync (:262), ExecuteAndStoreAsync (:310), TryReplayAsync (:394), TryStoreAsync (:479) and BuildRecord (:514). TryReplayAsync compares BodyHash first (:411) and TargetHash second, only when the stored record carries one (:421-422); BuildRecord writes both halves into the record (:534 and :537 for an ObjectResult, :547 and :549 for a body-less status).
  • Why it's built this way: one value instead of two loose strings keeps every signature on the lock, replay and store paths to a single parameter, and a readonly record struct adds no allocation per request. It stays private because nothing outside the filter compares fingerprints; the persisted form is the two hash fields on IdempotencyRecord.
  • Where it's used: only inside IdempotencyFilter, at the sites listed in the walkthrough.

IdempotencyFilter

MMCA.Common.API · MMCA.Common.API.Idempotency · MMCA.Common/Source/Presentation/MMCA.Common.API/Idempotency/IdempotencyFilter.cs:70 · Level 3 · class (sealed, partial)

  • What it is: the ASP.NET Core filter that gives write operations client-driven idempotency. A client attaches an Idempotency-Key header; the first successful response for that key is cached and every subsequent request carrying the same key gets the stored response back, without re-running the action. It implements both IAsyncActionFilter and IAsyncResourceFilter (IdempotencyFilter.cs:71), which is the detail that makes body-aware deduplication possible.
  • Depends on: ICacheService and IDistributedLock, both resolved per request from RequestServices (IdempotencyFilter.cs:145 and IdempotencyFilter.cs:153); IdempotencyRecord; RequestFingerprint; IdempotencySettings via IOptions<>; IdempotencyMetrics; IdempotencyHeaders for the two header names; KeyedSemaphoreStripe as the no-distributed-lock fallback; ClaimsPrincipalExtensions for the caller's identity. Externals: SHA256, Encoding, System.Text.Json (with the host's MVC IOptions<JsonOptions> resolved per request when present), IUrlHelperFactory for reconstructing a created result's Location, and ILogger with source-generated [LoggerMessage] partials.
  • Concept introduced: idempotent mutation as a lock plus a caller-scoped key plus a body and target binding. [Rubric §29, Resilience & Business Continuity] assesses surviving client retries without duplicating side effects; [Rubric §9, API & Contract Design] covers safe retry semantics on non-safe verbs; [Rubric §11, Security] applies because the key derivation is a trust boundary, not just a cache detail; [Rubric §13, Observability & Operability] applies because every degraded path is counted rather than silent. Three ideas compose here.
    1. Double-check locking (doc comment, IdempotencyFilter.cs:23-33): read the cache with no lock (the common fast path); on a miss take the lock for this key; re-read, because a concurrent duplicate may have finished while this one waited; only then execute and store. Without the lock, two near-simultaneous retries of a slow create both miss and both execute.
    2. The lock must be visible to every replica. A per-process stripe only serializes duplicates that land on the same instance, and both deployed apps run more than one (IdempotencyFilter.cs:34-39, restated at IdempotencyFilter.cs:239-242), so the primary path uses an IDistributedLock and the stripe is only the fallback for a host that registers none.
    3. The key alone is not enough. A stored response is bound to the request body and the concrete path plus query that produced it, so a key reused with a different payload is refused (422) rather than replayed, which would otherwise silently swallow a genuinely new write, and so is a key reused against another resource behind the same route template (PUT /orders/1 then PUT /orders/2), which the cache key alone cannot tell apart because it holds only the template (IdempotencyFilter.cs:44-54).
  • Walkthrough
    • Constants and shared state: IdempotencyKeyHeader delegates to IdempotencyHeaders.IdempotencyKey (IdempotencyFilter.cs:76, defined at MMCA.Common/Source/Core/MMCA.Common.Shared/Http/IdempotencyHeaders.cs:19 as "Idempotency-Key"); CacheKeyPrefix returns "idempotency:" (IdempotencyFilter.cs:78); DefaultExpiration of 24 hours (IdempotencyFilter.cs:83); LockTimeToLive of 30 seconds and LockWait of 5 seconds (IdempotencyFilter.cs:100 and IdempotencyFilter.cs:107), sized so a slow action finishes under its own lock while a dead replica does not block a retry for long; and EmptyBodyHash, the SHA-256 of zero bytes (IdempotencyFilter.cs:113-114).
    • KeyLocks (IdempotencyFilter.cs:93) is a static KeyedSemaphoreStripe. The comment above it (IdempotencyFilter.cs:85-92) gives the reason for striping over one-semaphore-per-key: the key embeds a caller-supplied value, so a per-key table either grows without bound or needs an eager removal that races (a removal between another request's lookup and its wait lets a third request create a fresh semaphore, and both then execute concurrently).
    • Resource stage. OnResourceExecutionAsync (IdempotencyFilter.cs:122) runs before model binding, the last point at which the body can still be made replayable. It calls Request.EnableBuffering() only when the header is present (IdempotencyFilter.cs:124-125), so ordinary traffic on an [Idempotent] action pays nothing, then awaits next() (IdempotencyFilter.cs:127).
    • Action stage. OnActionExecutionAsync (IdempotencyFilter.cs:131): no header means straight through to next() with nothing else resolved (IdempotencyFilter.cs:134-139), so idempotency is opt-in per request as well as per action. Otherwise it derives the cache key (IdempotencyFilter.cs:141), builds the RequestFingerprint from the body hash and the target hash (:142-144), resolves ICacheService (:145), and tries the lock-free replay (:148-149). On a miss it picks a lock strategy: GetService<IDistributedLock>() returning null routes to the process-stripe path (:153-158), otherwise the distributed path (:160-161). The comment at :151-152 states the invariant that shapes both paths: the lock has to span execute-and-store, so a duplicate cannot slip in between the action finishing and its response reaching the cache.
    • ReadIdempotencyKey (IdempotencyFilter.cs:168-175) treats a missing or blank header as absent, and both stages call it so they agree on what "has a key" means.
    • ComputeRequestBodyHashAsync (IdempotencyFilter.cs:187-198): a stream that cannot seek was never buffered, so it takes EmptyBodyHash rather than throwing (:190-191), which leaves such a request deduplicated on its key alone. Otherwise it rewinds to 0, hashes with SHA256.HashDataAsync, and rewinds again (:193-195) because model binding still has to read the whole body.
    • ComputeRequestTargetHash (IdempotencyFilter.cs:208-212) hashes Path.Value concatenated with QueryString.Value, exactly as received, as UTF-8 SHA-256 in lowercase hex. Its remarks (:204-207) explain why it is stored as its own record field rather than mixed into the body hash: a record written before the field existed still answers its own identical retry.
    • ExecuteUnderProcessLockAsync (IdempotencyFilter.cs:218): acquires the stripe honoring RequestAborted inside a using so release survives a throw (:225), re-checks the cache (:228), then executes and stores (:231).
    • ExecuteUnderDistributedLockAsync (IdempotencyFilter.cs:257) is where the interesting policy lives, and it separates three outcomes that a naive implementation conflates (rationale in the remarks, :238-256).
      • The lock backend faults: counted on idempotency.degraded, logged, and the action runs unguarded (:272-278). There is no holder to wait for, so refusing would turn a cache blip into a write outage.
      • The wait expires with the lock still held elsewhere: the holder is executing this key right now, so it logs the timeout and re-checks the cache first, and only if still nothing is stored does it record an in_flight conflict and answer with InFlightDuplicateResult() (:280-292). That helper (:320-329) is a 409 ProblemDetails titled "Request in progress" telling the client to retry with the same key: retryable and honest, where executing would be the duplicate write.
      • The lock is acquired: await using on the handle (:294), double-check (:297), then execute and store (:300).
    • ExecuteAndStoreAsync (IdempotencyFilter.cs:305-314) is the two-line shared tail of all three paths: await next(), then TryStoreAsync the executed result.
    • TryReplayAsync (IdempotencyFilter.cs:390) serves both the fast path and every double-check, returning whether it short-circuited. A cache read that throws is reported as "nothing stored" after counting a degradation (:397-406). A stored record whose RequestBodyHash differs from the fingerprint's BodyHash (an ordinal comparison, :411) yields a body_mismatch conflict and BodyMismatchResult() (:411-417), a 422 whose remarks explain the status choice: 409 is already spent on "still in flight", which is retry-with-the-same-key, while key reuse with a different body is not retryable until the client picks a new key (:336-340). A record that carries a RequestTargetHash different from the fingerprint's TargetHash yields a target_mismatch conflict and TargetMismatchResult() (:421-428), the same 422 title with a detail naming a different request target (:359-368); a record with no target hash is checked on its body alone, since it predates the field and ages out within the retention window (:419-420). On a genuine hit it counts the replay (:430), appends X-Idempotent-Replay: true (:433, name from IdempotencyHeaders.cs:25), restores the stored Location and ETag headers when the record carries them (:435-441, so a replayed 201 still says where the resource is and a replayed response still carries its concurrency token), and short-circuits with a bare StatusCodeResult when the stored body is empty or a ContentResult with application/json otherwise (:443-450). That split is what makes a replayed 204 look like the original 204 instead of a 204 carrying a content type.
    • TryStoreAsync (IdempotencyFilter.cs:475) resolves the host's MVC JsonOptions and falls back to JsonSerializerOptions.Web only when none is registered (:482-485): the replayed body has to be shaped exactly like the original, which MVC wrote with the host's converters. It then builds the record and returns early when it is not cacheable (:487-489), reads the expiration from IdempotencySettings when registered and DefaultExpiration otherwise (:491-495), and swallows a failing SetAsync after counting it (:497-505): the action already ran, so failing here would push the client into the very retry the filter exists to deduplicate (:470-472).
    • BuildRecord (IdempotencyFilter.cs:512) decides what is cacheable. It first reads any ETag the action wrote to the response, storing null when it is empty (:517-518). An ObjectResult with a non-2xx status returns null (:525-527); a 2xx one stores its value serialized with the resolved options, or the empty string when the value is null so an Accepted() with no payload replays as a body-less status rather than a JSON null (:522-523 and :530; a plain comment at :529 records that serializing to a string is correctly synchronous, with no analyzer suppression around the call), together with the body hash, the resolved Location, the ETag and the target hash (:531-537). A StatusCodeResult with a 2xx status, which is what NoContent(), OkResult and StatusCode(int) produce, stores the empty string plus the body hash, the ETag and the target hash (:542-550). Everything else, including every redirect or file result, returns null and is not stored (:552-553); IsSuccess is the >= 200 and < 300 test (:584).
    • ResolveLocation (IdempotencyFilter.cs:561-582) exists because a created result writes its Location when the RESULT executes, after this filter has already run, so the filter computes it the same way the result will (:557-560): a CreatedResult gives its Location directly (:565-566), a CreatedAtRouteResult goes through IUrlHelperFactory and Link (:568-571), a CreatedAtActionResult through IUrlHelperFactory and Action with the request's scheme and host (:573-577), and any other ObjectResult yields null (:579-580).
    • BuildCacheKey (IdempotencyFilter.cs:598-612) is the security-relevant part: the subject is the caller's user-id claim via FindUserIdValue() (:600, MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/ClaimsPrincipalExtensions.cs:26, which reads sub and falls back to the mapped NameIdentifier) or, unauthenticated, anon:{remote address} (:601); the route is the attribute route template falling back to the request path (:603-605); those plus the HTTP method and the client key are joined with a newline (:607-608, a character valid in none of the components, so the tuple cannot be forged), SHA-256 hashed (:609), and emitted as idempotency:{lowercase hex} (:611). Because the route is the template, not the concrete path, the target hash on the RequestFingerprint is what separates two resources behind one template.
    • Logging is entirely source-generated [LoggerMessage] partials with instance forwarders (IdempotencyFilter.cs:614-672): one Information message for a served replay (:614-620) and seven Warnings covering body mismatch (:622-627), target mismatch (:629-634), in-flight duplicate (:636-641), lock-wait timeout (:643-648), cache-read failure (:650-656), cache-store failure (:658-664) and lock unavailability (:666-672). [Rubric §13, Observability & Operability]: each degraded path has both a counter and a log line naming the cache key.
  • Why it's built this way: keying on the bare client value would make the key space global, so two callers who happened to pick the same value would share an entry and one user's serialized body could be replayed to another; with services sharing one cache instance that collision reaches across endpoints and services (SECURITY note, IdempotencyFilter.cs:62-68; ADR-017). Hashing also bounds the stored key length regardless of what a client sends (:591-597). Non-2xx results are deliberately not stored (IdempotencyFilter.cs:459-462) because replaying a failure for the whole retention window would mean a client retrying after a transient 500 keeps receiving that 500 for 24 hours instead of the retry actually executing. The 204 case is explicitly covered rather than skipped (:465-468): skipping it left every command answering NoContent() with nothing stored, so the body-less writes, the ones most likely to be retried, were the ones idempotency did not actually cover. And the whole cache-and-lock layer is treated as best-effort infrastructure (IdempotencyFilter.cs:55-61): deduplication is an optimization over an at-least-once client retry, so a Redis outage must degrade dedup, not every write endpoint carrying the attribute.
  • Caveats / not-in-source: the replay restores the status code, the JSON body, and the Location and ETag headers stored on IdempotencyRecord (IdempotencyFilter.cs:435-441); any other header the original action set is not captured and is therefore not reproduced, and X-Idempotent-Replay is added. Location is reconstructed only for CreatedResult, CreatedAtRouteResult and CreatedAtActionResult, and for the two URL-helper cases only when an IUrlHelperFactory is registered (IdempotencyFilter.cs:569 and :575); a Location the action set on the response by hand is not captured. A record cached before these fields existed replays without them, and one cached before the target hash existed is matched on its body alone.
  • Where it's used: registered scoped in AddAPI (MMCA.Common/Source/Presentation/MMCA.Common.API/DependencyInjection.cs:87); the comment above it (:84-86) notes the filter itself takes only a logger and reads ICacheService (a singleton) from the request's services, and attached to actions through IdempotentAttribute. In the framework itself that is the create endpoint on AggregateRootEntityControllerBase<TEntity, TEntityDTO, TIdentifierType, TCreateRequest> (AggregateRootEntityControllerBase.cs:76), the update endpoint on CrudEntityControllerBase<TEntity, TEntityDTO, TIdentifierType, TCreateRequest, TUpdateRequest> (CrudEntityControllerBase.cs:90, alongside [SupportsIfMatch]), both actions of PasswordResetAuthControllerBase<TForgotPasswordCommand, TResetPasswordCommand> (PasswordResetAuthControllerBase.cs:76 and :100), and the send endpoint of NotificationsController (NotificationsController.cs:44). The token-issuing and revoking actions of AuthControllerBase, register included, opt out explicitly with NonIdempotentAttribute (AuthControllerBase.cs:76, :94, :118, :145, :208). Downstream, ADC marks its Engagement writes (check-ins, bookmarks, live polls, session questions) and its Conference collection writes, and Store marks its cart, order and catalog writes.

IdempotentAttribute

MMCA.Common.API · MMCA.Common.API.Idempotency · MMCA.Common/Source/Presentation/MMCA.Common.API/Idempotency/IdempotentAttribute.cs:22 · Level 5 · class (sealed)

  • What it is: the method-level marker that attaches IdempotencyFilter to a controller action. Putting [Idempotent] on an action opts it into the Idempotency-Key replay behavior; leaving it off means the action is never deduplicated.
  • Depends on: ServiceFilterAttribute from ASP.NET Core MVC; resolves IdempotencyFilter from DI.
  • Concept introduced: service filters (DI-resolved action filters). [Rubric §2, Design Patterns] covers the filter idiom and how the instance is obtained. A plain [TypeFilter] constructs the filter itself, which would confine it to constructor arguments MVC can supply; ServiceFilterAttribute (IdempotentAttribute.cs:22) resolves it from the container instead, which is what lets the filter be registered AddScoped and reach scoped services such as ICacheService (remarks, IdempotentAttribute.cs:10-20). [Rubric §15, Best Practices & Code Quality]: [AttributeUsage(AttributeTargets.Method)] (IdempotentAttribute.cs:21) makes misapplication at class level a compile error rather than a silent no-op.
  • Walkthrough: the entire type is one line, public sealed class IdempotentAttribute() : ServiceFilterAttribute(typeof(IdempotencyFilter)) (IdempotentAttribute.cs:22); the primary constructor forwards the filter type to the base. The doc notes the filter must be registered in DI, which AddAPI does (MMCA.Common/Source/Presentation/MMCA.Common.API/DependencyInjection.cs:87); without that registration, resolution fails at request time rather than at startup. It also states the no-op contract: an action carrying the attribute but reached by a request with no Idempotency-Key header executes normally (IdempotentAttribute.cs:5-9).
  • Why it's built this way: opt-in per action is the ADR-017 decision. Nothing is deduplicated unless the action declares it, so adding the attribute is additive and safe, and the client still decides per request whether to send a key at all (a keyless request short-circuits at IdempotencyFilter.cs:134-139). The flip side, that a POST which should be idempotent but is missing the attribute gets no protection, is closed by a fitness function rather than by inventory discipline: see NonIdempotentAttribute, whose PostActionsDeclareIdempotencyIntent rule requires every POST action to carry one of the two attributes (MMCA.Common/Source/Hosting/MMCA.Common.Testing.Architecture/Rules/Cqrs/ArchitectureRules.Idempotency.cs:44). Because that rule reads attributes with inherit: true, a concrete controller deriving from one of the framework bases already satisfies it through the base's method (ArchitectureRules.Idempotency.cs:30-36).
  • Where it's used: applied in the framework to the create endpoint of AggregateRootEntityControllerBase<TEntity, TEntityDTO, TIdentifierType, TCreateRequest> (AggregateRootEntityControllerBase.cs:76), the update endpoint of CrudEntityControllerBase<TEntity, TEntityDTO, TIdentifierType, TCreateRequest, TUpdateRequest> (CrudEntityControllerBase.cs:90), AuthControllerBase.RegisterAsync (AuthControllerBase.cs:101), the forgot-password and reset-password actions of PasswordResetAuthControllerBase<TForgotPasswordCommand, TResetPasswordCommand> (PasswordResetAuthControllerBase.cs:76, :100) and NotificationsController.SendAsync (NotificationsController.cs:44); and in the apps to the ADC Conference/Engagement/Identity and Store Sales/Catalog write endpoints listed under IdempotencyFilter.

AuditHistoryControllerBase

MMCA.Common.API · MMCA.Common.API.Controllers.Administration · MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Administration/AuditHistoryControllerBase.cs:48 · Level 6 · class (abstract)

  • What it is: the shipped base controller that serves the recorded change history of one entity: a single GET at {entity}/{key}, paged, newest change first. A subclass names the audited entity types it serves and mounts the route; the base owns the action, the entity lookup, and the refusals.
  • Depends on: ApiControllerBase (its base, for HandleFailure), IAuditTrailReader re-exposed as the protected Reader property (AuditHistoryControllerBase.cs:79), IAuditedEntity (the marker every served type must implement, checked at :142), AuditHistoryEntryDTO on the wire, Error for the two refusals, and HasPermissionAttribute with AdministrationPermissions.ViewAuditTrail on the class (:47). Externals: ASP.NET Core MVC and System.ComponentModel.DataAnnotations' [Range].
  • Concept (a closed entity vocabulary on an open route). [Rubric §9, API & Contract Design] assesses whether endpoints have a stable, predictable shape and error contract: the {entity} segment is not a free-form type name but a key into a map built once at construction, so an unknown name answers 404 with the stable code AuditHistory.UnknownEntity (:51, returned at :106-113) and a blank key answers 400 with AuditHistory.KeyRequired (:54, returned at :115-122), both as Problem Details through HandleFailure. [Rubric §11, Security]: the class-level [HasPermission(AdministrationPermissions.ViewAuditTrail)] (:47) gates the action on a capability rather than a role name, and only the types a subclass lists are reachable, so the route cannot be used to probe arbitrary tables.
  • Walkthrough
    • The constructor (:69-76) takes the reader and a params Type[] of served types, null-guards both, and builds AuditedEntityTypes (:82), a dictionary keyed by simple type name with StringComparer.OrdinalIgnoreCase (:136).
    • BuildAliasMap (:131-150) fails construction fast: it throws ArgumentException for an empty list (:134), a null entry (:140), a type that does not implement IAuditedEntity (:143), and two types sharing a simple name, which would make the route ambiguous (:146).
    • GetHistoryAsync(entity, key, page, pageSize, cancellationToken) ([HttpGet("{entity}/{key}")] at :93, method at :99-128) takes page as [Range(1, int.MaxValue)] defaulting to 1 (:102) and pageSize as [Range(1, 500)] defaulting to 50 (:103). After the two refusals it calls Reader.GetForEntityAsync(entityType.FullName!, key, page, pageSize, cancellationToken) (:124-125): the URL carries the short name, the reader is keyed by the full type name. It returns the entries as a bare array with Ok(entries) (:127), declared as IReadOnlyList<AuditHistoryEntryDTO> (:94).
  • Why it's built this way: ADR-075 records the audit trail; this base is its read surface. Taking the served types as constructor arguments keeps the knowledge of which entities a module audits in the module's own subclass, while the framework owns the HTTP shape and the validation once. Validating at construction turns a misconfigured list into a startup failure instead of a request-time 404.
  • Where it's used: ADC derives one subclass per module: Conference (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.API/Controllers/AuditHistory/AuditHistoryController.cs), Engagement (MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.API/Controllers/AuditHistoryController.cs) and Identity (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/Controllers/AuditHistory/AuditHistoryController.cs), each with its own test class. The UI reads it through IAuditHistoryUIService (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auditing/IAuditHistoryUIService.cs); the framework's coverage is AuditHistoryControllerBaseTests.
  • Caveats / not-in-source: the [Range] bounds are enforced by MVC model validation; whether IAuditTrailReader clamps the page size again is outside the cited span and not determinable from the lines read here.

FeatureFlagsControllerBase

MMCA.Common.API · MMCA.Common.API.Controllers.Administration · MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Administration/FeatureFlagsControllerBase.cs:38 · Level 6 · class (abstract)

  • What it is: the shipped base controller for runtime feature-flag administration: list every declared flag with its configured, stored and effective value, set one flag's stored override, and clear it again. A subclass mounts the route; the base owns the three actions.
  • Depends on: ApiControllerBase (its base, for HandleFailure), IFeatureFlagAdministrationService, taken as the primary-constructor parameter (FeatureFlagsControllerBase.cs:38) and re-exposed as the protected Administration property (:41), FeatureFlagStatusResponse and SetFeatureFlagOverrideRequest on the wire, and HasPermissionAttribute with AdministrationPermissions.ManageFeatures on the class (:37).
  • Concept (a thin admin surface over the override store). [Rubric §1, SOLID]: like the other admin bases in this group, every action is a one-line translation from HTTP to IFeatureFlagAdministrationService (DIP), mapping a failed Result through HandleFailure and a success to the response, so no flag rule lives in the controller. [Rubric §11, Security]: the class-level [HasPermission(AdministrationPermissions.ManageFeatures)] (:37) gates all three actions on a capability, so turning a flag on in production is an authorized, attributable act rather than a configuration edit.
  • Walkthrough
    • GetAllAsync(cancellationToken) ([HttpGet] at :49, method at :53-59) returns IReadOnlyList<FeatureFlagStatusResponse> from Administration.ListAsync: per the XML summary, each flag's kind, owner, configured value, stored override and effective value (:44-45).
    • SetOverrideAsync(name, request, cancellationToken) ([HttpPut("{name}")] at :68, method at :74-84) null-guards the body (:79) and calls Administration.SetOverrideAsync(name, request, cancellationToken) (:81), returning the flag's state afterwards. The request carries a required reason (:65); 400 and 404 are declared (:70, :73).
    • ClearOverrideAsync(name, cancellationToken) ([HttpDelete("{name}")] at :93, method at :98-103) removes the stored override so configuration is in force again and answers 204; clearing a flag that has no override succeeds (:87-88).
  • Why it's built this way: ADR-031 governs feature-flag management. Shipping the HTTP shape once means every module that hosts flags exposes the same three routes, which is what lets one shared admin page drive them. All actions are virtual, so a subclass can override one without re-declaring routing.
  • Where it's used: ADC mounts it in two modules, Conference (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.API/Controllers/FeatureFlags/AdminFeatureFlagsController.cs) and Engagement (MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.API/Controllers/AdminFeatureFlagsController.cs). The UI client is IFeatureFlagAdminUIService (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Administration/IFeatureFlagAdminUIService.cs); the framework's coverage is FeatureFlagsControllerBaseTests.

ViewAsGrantsAdminControllerBase

MMCA.Common.API · MMCA.Common.API.Controllers.Administration · MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Administration/ViewAsGrantsAdminControllerBase.cs:40 · Level 6 · class (abstract)

  • What it is: the shipped base controller for the view-as audit list: one GET that pages through the read-only support-access grants staff have opened, newest first, with each grant's status derived at read time. A subclass mounts the route.
  • Depends on: ApiControllerBase (its base), IViewAsGrantStore, IOptions<ViewAsSettings> and BCL TimeProvider, all resolved per action with [FromServices] (ViewAsGrantsAdminControllerBase.cs:60-62), ViewAsGrantListRequest bound from the query string (:59), ViewAsGrantSummaryResponse inside a PagedCollectionResult<T> with PaginationMetadata, and HasPermissionAttribute with AdministrationPermissions.ManageUsers on the class (:39).
  • Concept (status derived from a clock, not stored). [Rubric §14, Testability] assesses whether behavior can be exercised deterministically: the status of each grant is computed by g.StatusAt(now) (:90) against a now taken from the injected TimeProvider (:75), so a test pins the clock instead of waiting for a grant to expire. [Rubric §11, Security]: the list is the accountability half of view-as support access; it is gated on ManageUsers (:39) and dark (404) unless both ViewAs:Enabled and HostsGrantStore are true (:70-73).
  • Walkthrough
    • ListAsync(request, settings, grants, timeProvider, cancellationToken) ([HttpGet] at :53, method at :58-100) null-guards its four inputs (:65-68), returns 404 on a host without the grant store (:70-73), then calls grants.ListAsync(request, now, cancellationToken) for a (items, total) pair (:76).
    • It projects each grant to a ViewAsGrantSummaryResponse carrying the staff and target ids and display names, the reason, the granted, expiry and end times, and the derived status (:78-91).
    • The metadata reports the page actually served: Math.Clamp(request.PageSize, 1, ViewAsGrantListRequest.MaxPageSize) and Math.Max(request.PageNumber, 1) (:94-97), with a comment noting the store clamps the same way (:93). It returns Ok(new PagedCollectionResult<...>(rows, metadata)) (:99).
  • Why it's built this way: ADR-137 makes every view-as session a recorded grant; this endpoint is how an administrator reviews them. Resolving everything per action leaves the class with no constructor, so a subclass is a route and nothing else.
  • Where it's used: ADC's AdminViewAsGrantsController (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/Controllers/AdminViewAsGrantsController.cs); the UI client is IViewAsGrantsUIService (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Administration/IViewAsGrantsUIService.cs); coverage is ViewAsGrantsAdminEndpointTests. The grants themselves are opened by UsersAdminControllerBase<TUserDto>.StartViewAsAsync.

CurrentUserTargetingContextAccessor

MMCA.Common.API · MMCA.Common.API.FeatureManagement · MMCA.Common/Source/Presentation/MMCA.Common.API/FeatureManagement/CurrentUserTargetingContextAccessor.cs:68 · Level 8 · class (sealed)

  • What it is: the ITargetingContextAccessor that supplies the audience (a user id plus that user's groups, including a tenant:<tenantId> group when the request resolved a tenant) which the feature-management Targeting filter evaluates, read from the current HTTP request.
  • Depends on: Microsoft.FeatureManagement.FeatureFilters.ITargetingContextAccessor and TargetingContext, Microsoft.AspNetCore.Http.IHttpContextAccessor, System.Security.Claims, ClaimsPrincipalExtensions for the user-id read (FindUserIdValue) and the role read (GetRoleValues), and ITenantContext resolved from the request's own services (CurrentUserTargetingContextAccessor.cs:1-6). Registered by AddAPI; a sibling of DisabledFeatureHandler in the same folder.
  • Concept introduced: a percentage rollout that is sticky per user rather than random per request. A Percentage feature filter with no targeting rolls a die on every evaluation, so the same user sees the feature on one request and off the next: unusable for a UI. The Targeting filter fixes that by hashing the audience's user id, which makes the answer deterministic for a given user across requests and across instances, and this accessor is what supplies that id (:11-16). [Rubric §29, Resilience, Reliability & Business Continuity] assesses whether a cross-cutting toggle is applied uniformly; [Rubric §11, Security] and [Rubric §17, DevOps] both bear on the rollout being an operational lever rather than a deploy. See ADR-031. Two source decisions are worth carrying. First, the user id is the standard sub claim TokenService emits, read through ClaimsPrincipalExtensions so the ClaimTypes.NameIdentifier form the bearer handler maps it to resolves identically, the same read CurrentUserService and IdempotencyFilter perform (:18-22); the principal's name is the fallback for a token carrying neither. Second, the accessor is a singleton (that is the lifetime WithTargeting gives it), so it cannot take the scoped ICurrentUserService; it reads IHttpContextAccessor instead and takes the roles straight off the principal, which the doc calls out explicitly (:25-26). That role read is ClaimsPrincipalExtensions.GetRoleValues (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/ClaimsPrincipalExtensions.cs:60), the framework's one definition of "the caller's roles" (ClaimsPrincipalExtensions.cs:52-58), so the targeting groups cannot disagree with the authorization handler about which roles a caller holds.
  • Concept introduced: tenant as a targeting group. [Rubric §29, Resilience, Reliability & Business Continuity] and [Rubric §17, DevOps]: a flag can be turned on for one tenant without a per-tenant configuration store. When the request's ITenantContext has resolved a tenant (ADR-073), the groups also carry tenant:<tenantId>, so an audience group such as tenant:acme turns a flag on for every request of that tenant (:29-34). The prefix is the public constant TenantGroupPrefix = "tenant:" (:75), and the public TenantGroup(string tenantId) (:83) builds the name exactly as the accessor emits it (rejecting a null or blank id at :85, concatenating at :86), so configuration tooling and tests cannot spell the group differently. ITenantContext is scoped, so ResolveTenantGroups (:123) reads it from HttpContext.RequestServices (:125) rather than taking it as a dependency of this singleton, and a host that never registered it, or a request that resolved no tenant, contributes no group (:121-122, :126). The group only matters to an audience that names it, so a host that targets nothing by tenant sees no change (:33-34).
  • Walkthrough: GetContextAsync() (:95) reads the current HttpContext (:97), its principal (:98), and the tenant groups (:99) up front. An unauthenticated or absent principal yields a context with UserId = null and only the tenant groups (:101-108, Groups = tenantGroups at :106), so a targeted feature is off for anonymous callers unless the audience opts everyone in or names their tenant (:37-39); the method never returns null, because a feature filter must not be able to fail a request (:90-92). For an authenticated caller it collects the role values through user.GetRoleValues() (:110), which accepts each claim type the JWT middleware may produce: the standard ClaimTypes.Role URI when inbound claim mapping is on, or the raw role / roles claim when it is off (ClaimsPrincipalExtensions.cs:47-49), and appends the tenant groups (:111-112). Finally it builds the TargetingContext with user.FindUserIdValue() ?? user.Identity.Name (:116) and those groups (:117).
  • Why it's built this way: accepting three role claim types is not defensive padding, it is the concrete consequence of ASP.NET Core's inbound claim mapping being configurable; matching only ClaimTypes.Role would silently drop every group when a host turns mapping off, and a group-targeted rollout would then behave as an ungrouped one. Delegating that match to the shared GetRoleValues rather than a local claim filter keeps this accessor, ICurrentUserService and the permission handler reading roles one way. Folding the tenant into the existing Groups list, rather than adding a custom filter, keeps the stock Targeting filter and its configuration shape unchanged. The class doc carries a worked FeatureManagement configuration example (:41-65) showing a rollout that always includes one role (Reviewers) and every request of tenant acme, includes 25 percent of everyone else, and pins two named users, which is the fastest way to see what the context is actually feeding.
  • Where it's used: registered inside AddAPI as services.AddFeatureManagement().WithTargeting<CurrentUserTargetingContextAccessor>() (MMCA.Common/Source/Presentation/MMCA.Common.API/DependencyInjection.cs:108-109), immediately after AddHttpContextAccessor() (:107, which is TryAdd-based and therefore safe to call here as well as elsewhere, the reasoning recorded at :101-106). From there it is consumed only by the Targeting feature filter, whose verdicts reach the HTTP edge through [FeatureGate] and DisabledFeatureHandler, and the CQRS layer through FeatureGateCommandDecorator<TCommand, TResult>. Framework coverage is CurrentUserTargetingContextAccessorTests and, for the tenant group end to end, TenantTargetedFeatureFlagTests (MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/FeatureManagement/).

UsersAdminControllerBase<TUserDto>

MMCA.Common.API · MMCA.Common.API.Controllers.Administration · MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Administration/UsersAdminControllerBase.cs:68 · Level 8 · class (abstract, partial)

  • What it is: the shipped base controller for account administration: a single-account read, view-only lists of the account's live sessions and its sign-in history, the start of a read-only view-as session, lock/unlock, and a full role replacement. The write actions are guarded by a self-administration refusal, a privilege ceiling and, for roles, a second-factor enrollment check, and each completed write is logged and counted. A subclass supplies the app's TUserDto and mounts the route; the base owns every action.
  • Depends on: ApiControllerBase (its base, for HandleFailure), IUserAdministrationService<TUserDto> taken as the primary-constructor parameter (UsersAdminControllerBase.cs:68-69) and re-exposed as the protected Administration property (:72), UserIdentifierType, the per-action-resolved IUserSessionsAdministrationService with its RefreshSessionSummaryResponse and SignInSummaryResponse items, the per-action-resolved IViewAsService and IOptions<ViewAsSettings> with StartViewAsRequest and ViewAsGrantResponse, the request type SetUserRolesRequest, AdminActionMetrics for the completed-action counter, and, resolved optionally from the request's services, IPermissionRegistry (:477), ITwoFactorStore (:454) and IOptions<MultiFactorAuthorizationSettings> (:472). The ceiling evaluates permissions through PermissionAuthorizationHandler.Holds (:433), and the role action reads ErrorType.NotFound off a ceiling failure (:316). The class carries HasPermissionAttribute with AdministrationPermissions.ManageUsers (:67).
  • Concept (a thin admin surface with guards no service can forget). [Rubric §1, SOLID]: the controller depends on IUserAdministrationService<TUserDto> (DIP), not a concrete service, and every read is a thin translation from HTTP to that interface or to the framework's session and view-as services. [Rubric §11, Security]: the write actions add three refusals in a fixed order before the service runs. First, an administrator cannot lock, unlock or re-role their own account (IsCaller at :510-512), answered 403 with UserAdministration.Self (:343-347), because an administrator who locks themselves out cannot sign back in to undo it (:210-214). Second, the privilege ceiling: when the host registers an IPermissionRegistry, a request is refused 403 with UserAdministration.PrivilegeCeiling (:354-358) if the requested role, or the target's current role, grants a permission the caller does not hold; the refusal names no permission, and a role-only host with no registry applies no ceiling (class remarks at :49-55). Third, for roles only, a role listed under Authorization:MultiFactor:RequiredForRoles goes only to an account with two-factor authentication on, otherwise 409 UserAdministration.SecondFactorNotEnrolled (:366-370, remarks at :58-62). Every optional service is resolved per action or per request, so a host that never opts into sessions, view-as, permissions or two-factor does not need them registered. [Rubric §13, Observability & Operability]: each successful write logs one source-generated Information line naming the action, the target and the acting administrator (LogAdministered, :372-373) and adds one to mmca.auth.admin_action tagged with the action, and so does a successful view-as start.
  • Walkthrough
    • GetAsync(userId, cancellationToken) ([HttpGet("{userId}")] at :80, method at :85-92) reads one account through Administration.GetAsync.
    • GetSessionsAsync(userId, sessions, cancellationToken) ([HttpGet("{userId}/sessions")] at :101, method at :105-115) returns the account's live sessions, newest first, view only, as IReadOnlyList<RefreshSessionSummaryResponse>; it null-guards sessions (:110) and maps failures through HandleFailure (:114).
    • GetSignInsAsync(userId, sessions, cancellationToken) ([HttpGet("{userId}/sign-ins")] at :125, method at :129-139) returns the sign-in history through sessions.GetSignInsAsync (:136): one row per sign-in, ended ones included with how they ended, newest first, capped at the newest 50 per the XML summary (:118-119).
    • StartViewAsAsync(userId, request, settings, viewAs, cancellationToken) ([HttpPost("{userId}/view-as")] at :160, method at :168-198) additionally requires [HasPermission(AdministrationPermissions.ViewAsUsers)] (:161) and is [NonIdempotent] (:162) because each call writes a new grant row, the audit record of the access. It answers 404 unless ViewAs:Enabled and HostsGrantStore are both true (:178-181), 401 without a caller id (:183-186), and otherwise calls viewAs.StartAsync(staffUserId, userId, request?.Reason, cancellationToken) (:188-190); a failure goes through HandleFailure (:191-194), and a success records AdminActionMetrics.ViewAsStart (:196) before returning the grant. The XML summary lists the refusals the service applies: the caller's own account, a missing, deleted, locked or machine-client account, and an account that itself holds users:view-as (:142-146).
    • LockAsync and UnlockAsync ([HttpPost("{userId}/lock")] at :224 and [HttpPost("{userId}/unlock")] at :257, methods at :231-249 and :263-281) run the self refusal (:235, :267), then CheckTargetCeilingAsync (:240, :272), then Administration.SetLockedAsync(userId, locked, cancellationToken) (:246, :278), and finish through Completed with the Lock or Unlock metric action (:248, :280). Both are [NonIdempotent] (:225, :258): a lock is a state setter, and a cached 204 would answer a later unlock-then-lock cycle with a state the account is not in. The remarks on LockAsync (:203-220) state that a service derived from UserAdministrationServiceBase<TUser, TUserDto> makes the lock take effect at once by writing the soft-deleted user marker, so every host refuses the access tokens the account already holds, and by revoking its refresh sessions; a service that only revokes sessions leaves each issued access token working until it expires. When the marker does not reach the shared store, the lock is still saved and the sessions still revoked, but the answer is 503 with UserAdministration.LockMarkerNotWritten, because the access tokens already issued keep working until they expire (:215-219); LockAsync declares that 503 in its response metadata (:230).
    • SetRolesAsync(userId, request, cancellationToken) ([HttpPut("{userId}/roles")] at :291, method at :297-336) null-guards the request (:302), runs the self refusal (:304), CheckRoleChangeCeilingAsync (:309) and CheckSecondFactorEnrollmentAsync (:325), then replaces the account's complete role set through Administration.SetRolesAsync(userId, request.Roles, cancellationToken) (:331-333): it is a replace, not a merge. One ceiling failure is treated differently: when the ceiling's only error is a NotFound (an unknown target, which has no role to put a ceiling on), the action skips the enrollment check and calls Administration.SetRolesAsync anyway, returning its result through Completed (:316-321). Per the comment (:312-315), the service validates the requested role before it loads the account, so the caller receives the app's invalid-role refusal for an unknown role and not found for a valid one, and nothing is changed. Any other ceiling failure goes straight to HandleFailure (:322). Both completion paths pass the RoleChange metric action (:319, :335).
    • CheckRoleChangeCeilingAsync (:384-397) acts only when exactly one role is requested (roles is not [var requestedRole], :389); zero or several pass untouched so the service's exactly-one-role refusal is what the caller receives (doc, :375-383). It checks the requested role, then the target's current role through CheckTargetCeilingAsync (:407-423), which returns success with no registry and otherwise loads Administration.GetRoleAsync (:414), passing through the service's not-found failure for an unknown account (which LockAsync and UnlockAsync return as is, and SetRolesAsync handles as above). CallerHoldsEveryPermissionOf (:431-433) is the shared predicate.
    • CheckSecondFactorEnrollmentAsync (:446-464) passes without a load when there are no request services, no requested role is listed (RequestsAListedRole, :470-474, case-insensitive with blank entries ignored), or no ITwoFactorStore is registered; otherwise it requires state?.IsTwoFactorEnabled == true (:461-463).
    • Completed(result, action, metricAction, userId) (:489-505) maps a failure through HandleFailure; on success it records metricAction on AdminActionMetrics (:496), logs the administered line (:498-502) and returns 204 (:504). A refused or failed write is therefore never counted.
  • Why it's built this way: like the other admin and auth controller bases in this group, the HTTP shape (routes, status codes, ProblemDetails on every failure path) ships once in the framework and an app supplies only its TUserDto and its IUserAdministrationService<TUserDto> implementation, so the account-management surface stays identical across apps. Putting the self, ceiling and enrollment refusals in the base rather than in the app service means no app can ship an administration surface without them, and counting in the base means every app gets the same action tag values. View-as follows ADR-137, the session views follow ADR-097, and the idempotency markings follow ADR-017.
  • Where it's used: ADC's UsersAdminController is the current subclass (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/Controllers/UsersAdminController.cs), backed by UserAdministrationService (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/Administration/UserAdministrationService.cs) implementing IUserAdministrationService<TUserDto> (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Administration/IUserAdministrationService.cs). On the web host the same-origin proxy (MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/SameOriginProxy/SameOriginApiProxyEndpoint.cs) moves the view-as token into its overlay cookie, leaving the admin's own session untouched (:151-152), and the UI starts it from ViewAsButton (MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Auth/ViewAsButton.razor.cs). The framework's coverage is AdministrationControllerBaseTests, UsersAdminSessionsEndpointTests, UsersAdminSignInsEndpointTests and ViewAsEndpointTests.
  • Caveats / not-in-source: ADR-116 mentions this surface, but the opt-in mechanics it governs live outside the cited span. The 15-minute view-as lifetime and the refusal list are stated in the XML summary (:142-146) and enforced inside IViewAsService, outside this file; likewise the 503 UserAdministration.LockMarkerNotWritten failure is produced by the service, not by this controller. Whether ADC registers an IPermissionRegistry or an ITwoFactorStore (and so applies the ceiling and the enrollment check) is not determinable from the lines read here.

RolesAdminControllerBase

MMCA.Common.API · MMCA.Common.API.Controllers.Administration · MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Administration/RolesAdminControllerBase.cs:69 · Level 10 · class (abstract)

  • What it is: the shipped base controller for role-permission administration: list every role with its compiled and stored permissions, read the role/permission catalog, read one role, and replace one role's stored grants under a privilege ceiling.
  • Depends on: ApiControllerBase (its base, for HandleFailure), IRoleAdministrationService re-exposed as the protected Administration property (RolesAdminControllerBase.cs:74), and ICurrentUserService, re-exposed as CurrentUserService (:77), taken together as primary-constructor parameters (:69-71); IPermissionRegistry, resolved optionally from the request's services (:182), and PermissionAuthorizationHandler.Holds (:188) for the ceiling. The class carries HasPermissionAttribute with AdministrationPermissions.ManageRoles (:68).
  • Concept (a closed-set catalog endpoint routed ahead of its own parameterized sibling). [Rubric §1, SOLID]: like UsersAdminControllerBase<TUserDto>, the controller holds no permission rule of its own, only translation to IRoleAdministrationService (DIP) plus the caller-derived inputs that service needs. The routing choice on GetCatalogAsync is the notable design point: [HttpGet("catalog")] (:106) is a literal segment that ASP.NET Core routing matches before the [HttpGet("{role}")] template (:124) below it, and the XML remarks on the method say so explicitly (:100-103), which is also why no role can be named "catalog": it would be unreachable through the {role} route. [Rubric §11, Security]: a set edits data, never code, so no request here can take away a capability the host compiled into its registry (class remarks, :36-40); it is refused 400 when the submitted set names ManageRoles itself or a permission outside the catalog (:41-57); and no operator grants more than they hold: with an IPermissionRegistry registered, a set that ADDS a permission the caller does not hold is refused 403 with the users-admin code UserAdministration.PrivilegeCeiling, while keeping or removing one is allowed because the request replaces the whole stored list (:58-64). SetPermissionsAsync also records who made the change through ResolveChangedBy() (:160, method at :171-172), which defaults to the caller's own CurrentUserService.UserId and is virtual so an app can substitute a display name instead.
  • Walkthrough
    • GetAllAsync(cancellationToken) ([HttpGet] at :84, method at :88-94) lists every role via Administration.ListRolesAsync (:91), returning IReadOnlyList<RolePermissionsResponse>.
    • GetCatalogAsync(cancellationToken) ([HttpGet("catalog")] at :106, method at :110-116) returns the closed sets a role editor needs: the roles this surface lists and the permissions a stored grant may name, via Administration.GetCatalogAsync (:113).
    • GetAsync(role, cancellationToken) ([HttpGet("{role}")] at :124, method at :129-136) reads one role's compiled and stored permissions via Administration.GetRoleAsync (:133).
    • SetPermissionsAsync(role, request, cancellationToken) ([HttpPut("{role}/permissions")] at :145, method at :152-164) guards the request (:157), then replaces the role's stored permission grants via Administration.SetStoredPermissionsAsync(role, request.Permissions, CallerHoldsPermission(), ResolveChangedBy(), cancellationToken) (:159-161), returning the role's post-edit state. It declares a 409 (:151) besides the 400, 403 and 404: the framework's edit unit answers Conflict when another change to the same role's permissions is in progress (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/Administration/PermissionRoleEditUnit.cs:56).
    • ResolveChangedBy() (:171-172) is CurrentUserService.UserId?.ToString(CultureInfo.InvariantCulture), or null when the caller cannot be identified.
    • CallerHoldsPermission() (:180-189) builds the ceiling predicate the service applies to every permission the set adds: null (no ceiling) when the request's services hold no IPermissionRegistry (:182-185), otherwise a closure over the caller that evaluates PermissionAuthorizationHandler.Holds(caller, registry, permission) (:187-188), the same evaluation the authorization handler uses. The service computes the additions as the submitted set minus the stored one, under the role's edit lock, and a null predicate is meant for a trusted caller with no principal (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Administration/IRoleAdministrationService.cs:75-79).
  • Why it's built this way: the same admin-base pattern as UsersAdminControllerBase<TUserDto>: the HTTP shape ships once in the framework. Unlike the user surface it needs no app-supplied service: AddStoredPermissionGrants() registers a complete IRoleAdministrationService over the framework's own registry and grant store, and an app implements the interface only to change that behavior (class remarks, :30-35). The ceiling follows the users-admin rule (no registry, no ceiling) and reuses its error code, so an operator sees one refusal shape across both surfaces; the controller supplies the predicate because only the HTTP layer holds the caller's principal. Keeping ResolveChangedBy virtual rather than hardcoding the user identifier lets an app record a friendlier audit label without touching the write path itself.
  • Where it's used: ADC's AdminRolesController is the current subclass (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/Controllers/AdminRolesController.cs), consumed from the UI at MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.UI/Pages/Roles/RoleList.razor.cs. The framework's own coverage is in AdministrationControllerBaseTests.
  • Caveats / not-in-source: ADR-116 mentions this surface, but the opt-in mechanics it governs live outside the cited span; not determinable from the lines read here. The 400, 403 and 409 refusals are produced by the service, not by this controller, which only declares them and supplies the ceiling predicate.

JsonRequestBodyLimitMiddleware

MMCA.Common.API · MMCA.Common.API.Middleware · MMCA.Common/Source/Presentation/MMCA.Common.API/Middleware/JsonRequestBodyLimitMiddleware.cs:28 · Level 0 · class (sealed, internal)

  • What it is: convention-based middleware that caps the body of a JSON request at Api:MaxJsonBodyBytes (default 1 MiB) on every endpoint that states no request size of its own. A JSON request whose declared Content-Length is over the cap is answered 413 Payload Too Large before anything reads the body; otherwise the server's per-request body cap is lowered to the limit, so a chunked body is cut off with the same 413 once it crosses it. Every other request (a multipart upload, a form post, an endpoint with its own limit) keeps the server's limit unchanged (class summary, JsonRequestBodyLimitMiddleware.cs:12-22).
  • Depends on: RequestDelegate and IConfiguration (primary constructor, JsonRequestBodyLimitMiddleware.cs:28); ASP.NET Core's IRequestSizeLimitMetadata, IHttpMaxRequestBodySizeFeature and IProblemDetailsService (the last resolved optionally from the request's services, :121-122). Its oversize-chunked-body path ends at GlobalExceptionHandler.
  • Concept introduced: a default ceiling, deferred to explicit endpoint metadata. [Rubric §11, Security] assesses whether an unauthenticated caller can make the server buffer and deserialize an arbitrarily large payload; Kestrel's own default request cap is far larger than any JSON command needs, so this middleware gives every JSON endpoint a small ceiling without each controller remembering [RequestSizeLimit]. [Rubric §9, API & Contract Design] covers the contract: an endpoint that does declare a size ([RequestSizeLimit], [DisableRequestSizeLimit] or the minimal-API equivalents, all surfacing as IRequestSizeLimitMetadata) is left entirely alone (:14-17), so the explicit statement always wins over the default.
  • Walkthrough:
    • MaxJsonBodyBytesConfigKey ("Api:MaxJsonBodyBytes", :31) and DefaultMaxJsonBodyBytes (1024 * 1024, :34) are internal const, and the limit is resolved once into _maxJsonBodyBytes by ResolveLimit(configuration) (:36).
    • ResolveLimit (:93-110) reads the key as long?, returns the 1 MiB default when it is absent (:97-101), and throws InvalidOperationException naming the key when the configured value is zero or negative (:103-107), so a misconfiguration fails when the middleware is constructed rather than disabling the cap.
    • InvokeAsync (:43): a request out of scope passes straight to next (:47-50). In scope, a declared ContentLength over the limit short-circuits to WritePayloadTooLargeAsync (:52-55). Otherwise it reads IHttpMaxRequestBodySizeFeature and, when the feature is still writable and its current cap is unbounded or larger than the limit, lowers MaxRequestBodySize to the limit (:57-62); it never raises a cap that is already smaller. Then next runs (:64).
    • IsInScope (:72-74): the content type is JSON (HasJsonContentType(), which matches application/json and application/*+json, or text/json via IsTextJson, :83-85, because the MVC JSON input formatter accepts it and HasJsonContentType does not, :76-82) and the selected endpoint carries no IRequestSizeLimitMetadata.
    • WritePayloadTooLargeAsync (:116-138) sets 413 (:118), resolves IProblemDetailsService from RequestServices with a null-tolerant read (RequestServices is null outside a request pipeline, :120-122), returns with an empty body when none is registered (:123-126), and otherwise writes a problem document titled "Payload Too Large" with the detail "The request body exceeds the size this endpoint accepts." (:128-137).
  • Why it's built this way: the decision reads the selected endpoint's metadata, so the middleware must run after routing (remarks, :25-27). The 413 written here deliberately uses the same title and detail GlobalExceptionHandler writes for a BadHttpRequestException carrying 413 (MMCA.Common/Source/Presentation/MMCA.Common.API/Middleware/GlobalExceptionHandler.cs:102-107), which is exactly what Kestrel throws when the lowered cap is crossed by a chunked body; both rejection paths therefore produce one response shape (doc comment, JsonRequestBodyLimitMiddleware.cs:112-115). Checking IsReadOnly first matters because the feature becomes read-only once the body has started to be read, and setting it then would throw.
  • Where it's used: the JsonBodySizeLimit step of the default pipeline (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/Pipeline/MiddlewarePipelineBuilder.cs:82-86), placed immediately after Routing (:78-80) and ahead of everything that reads the body, starting with Cors (:88-92). The step name is MiddlewarePipelineStepNames.JsonBodySizeLimit (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/Pipeline/MiddlewarePipelineStepNames.cs:42), whose doc restates the key and default (:37-41). The class is internal, so a host tunes it only through the configuration key or by declaring size metadata on an endpoint.
  • Caveats / not-in-source: the tests exercise it as a pipeline step (MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/Startup/Pipeline/JsonBodySizeLimitStepTests.cs) rather than in a middleware-named test class. Which hosts set Api:MaxJsonBodyBytes is configuration, not determinable from this file.

OperationCanceledExceptionHandler

MMCA.Common.API · MMCA.Common.API.Middleware · MMCA.Common/Source/Presentation/MMCA.Common.API/Middleware/OperationCanceledExceptionHandler.cs:36 · Level 0 · class (sealed)

  • What it is: the handler that maps a cancellation caused by the client hanging up mid-request (HttpContext.RequestAborted is cancelled) to HTTP 499 Client Closed Request instead of letting it inflate the 500 rate. "A cancellation" means one of three shapes: an OperationCanceledException, a provider DbException, or an EF Core DbUpdateException wrapping either (see below). Any other cancellation, and any other exception type, is deliberately left alone.
  • Depends on: IProblemDetailsService, ILogger<OperationCanceledExceptionHandler>; System.Data.Common.DbException and EF Core's DbUpdateException for the type test (OperationCanceledExceptionHandler.cs:1, :5); chain concept at DbUpdateExceptionHandler.
  • Concept: [Rubric §13, Observability & Operability] assesses whether the signals operators alert on distinguish real faults from normal client behavior. 499 is a non-standard nginx-origin code (class comment, OperationCanceledExceptionHandler.cs:11-14) that monitoring stacks read as "the caller gave up", so client cancellations stop looking like server errors on a dashboard. The same comment draws the other half of the line (:15-16): a cancellation the client did not cause (a downstream HttpClient timeout, an internal token) IS a server error and must still count as one. A second paragraph (:17-24) explains why a DbException is claimed too: a data provider may report the cancelled command as its own exception rather than an OperationCanceledException (SqlClient answers "Operation cancelled by user." as a SqlException), nobody reads that response any more, and the exception is still logged with its stack at Warning so a database fault that coincides with a disconnect stays visible. A third paragraph (:25-32) covers the write path: during SaveChanges EF Core wraps the provider's report in a DbUpdateException, which is neither of those two types, so without its own match a client abort inside a save would reach DbUpdateExceptionHandler and be answered 409 "data conflict" with an Error log.
  • Walkthrough: TryHandleAsync (OperationCanceledExceptionHandler.cs:42) applies a two-part guard (:47): it returns false unless IsCancellationShaped(exception) holds and httpContext.RequestAborted.IsCancellationRequested is true. IsCancellationShaped (:74-76) is a single pattern: exception is OperationCanceledException or DbException or DbUpdateException { InnerException: DbException or OperationCanceledException }, so a DbUpdateException qualifies only when its inner exception is itself a cancellation shape. Past the guard it logs the exception itself (not a narrowed cancellation variable) at LogWarning with a client-disconnected message (:52), sets StatusCodes.Status499ClientClosedRequest (:54), and still builds a problem document titled "Operation Canceled Exception" (:55-65) which it writes through TryWriteAsync (:67). Note that Status499ClientClosedRequest is a real constant on ASP.NET Core's StatusCodes, so the non-standard code is spelled symbolically, not as a magic number.
  • Why it's built this way: it is registered first in the chain (MMCA.Common/Source/Presentation/MMCA.Common.API/DependencyInjection.cs:162). That position matters: a client abort propagating out of a CancellationToken would otherwise be claimed by nothing until GlobalExceptionHandler turned it into a 500, and the wrapped save-time shape would be claimed by DbUpdateExceptionHandler (registered second, DependencyInjection.cs:163) as a 409. The RequestAborted check is the reverse protection: an OperationCanceledException thrown while the client is still connected (a timeout inside the request) falls through to GlobalExceptionHandler and is answered and logged as the 500 it is, and a genuine conflict on a live request still gets its 409 (:31), rather than either being hidden as a 499 Warning. It is also why every catch in the cache-touching middleware and limiters filters OperationCanceledException out explicitly rather than swallowing it (for example SoftDeletedUserMiddleware.cs:98 and RedisFixedWindowRateLimiter.cs:223).
  • Where it's used: AddCommonExceptionHandlers() (DependencyInjection.cs:162); it fires for request-abort propagation from any handler that honors its CancellationToken, and only while RequestAborted is signalled.
  • Caveats / not-in-source: whether the 499 body actually reaches a disconnected client is not determinable from this file; once the guard passes, the write is attempted unconditionally at :67.

ValidationExceptionHandler

MMCA.Common.API · MMCA.Common.API.Middleware · MMCA.Common/Source/Presentation/MMCA.Common.API/Middleware/ValidationExceptionHandler.cs:17 · Level 0 · class (sealed)

  • What it is: the handler that converts FluentValidation's ValidationException into a 400 whose problem document carries an errors extension shaped as { "PropertyName": ["message", ...] }.
  • Depends on: FluentValidation.ValidationException, IProblemDetailsService, ILogger<ValidationExceptionHandler>; chain concept at DbUpdateExceptionHandler.
  • Concept: [Rubric §9, API & Contract Design] assesses whether one failure family always serializes the same way, and [Rubric §24, Forms/Validation/UX Safety] assesses whether a client can bind failures back to the fields that caused them. The grouped shape is chosen to match what ASP.NET Core's own model-state validation emits (comment, ValidationExceptionHandler.cs:46-47), so a client form component can render field errors with one code path regardless of whether the failure came from model binding or from a validator running in the CQRS validating decorator.
  • Walkthrough: TryHandleAsync (ValidationExceptionHandler.cs:23) type-tests and passes on non-validation exceptions (:28-29), logs at LogWarning (:31, not LogError: an invalid payload is a client mistake, not a system fault), sets 400 (:33), builds the problem document titled "Validation Exception" (:34-44), then groups validationException.Errors by PropertyName into a Dictionary<string, string[]> (:48-53) and adds it under the "errors" extension key (:54) before writing (:56).
  • Why it's built this way: the grouping consolidates several failures for one field into one array, which is exactly the ModelStateDictionary serialization front ends already understand. Note the key is the raw PropertyName from FluentValidation, not a camelCased alias, and that Extensions.Add (:54) would throw on a duplicate key, which cannot happen here because the document was just constructed.
  • Where it's used: registered fourth (MMCA.Common/Source/Presentation/MMCA.Common.API/DependencyInjection.cs:164), just before the catch-all; it is the exception path that complements the Result-based validation failures returned by ApiControllerBase.

ViewAsEndEndpointAttribute

MMCA.Common.API · MMCA.Common.API.Middleware · MMCA.Common/Source/Presentation/MMCA.Common.API/Middleware/ViewAsGuardMiddleware.cs:245 · Level 0 · class (internal sealed, attribute)

  • What it is: a marker attribute for the one action a view-as token may call with a non-safe HTTP method: ending the view. It has no members; its presence in the routed endpoint's metadata is the whole signal.
  • Depends on: System.Attribute only. It is declared with [AttributeUsage(AttributeTargets.Method, Inherited = true)] (ViewAsGuardMiddleware.cs:244) in the same file as its only reader, ViewAsGuardMiddleware.
  • Concept: endpoint metadata as an allow-list. [Rubric §11, Security] assesses whether a read-only support session (ADR-137) can reach a write: the guard refuses every non-safe method under a view-as token, and this attribute is the single exemption, read from the endpoint rather than matched by path, so the exemption follows the action wherever a host routes its auth controller (doc comment, ViewAsGuardMiddleware.cs:238-243).
  • Walkthrough: the declaration is one line, internal sealed class ViewAsEndEndpointAttribute : Attribute; (ViewAsGuardMiddleware.cs:245). The guard's IsEndViewAsEndpoint (:109-111) treats a request as the end-view-as call only when the method is POST and context.GetEndpoint()?.Metadata.GetMetadata<ViewAsEndEndpointAttribute>() is not null.
  • Why it's built this way: it is internal on purpose: no other write is ever allowed under a view-as token, so a consumer cannot mark a second action with it (:241-242). A host that must expose a read served over POST (gRPC is always POST) uses the public ViewAsReadOnlyEndpointAttribute instead, which exempts the method rule but not the grant check (:113-119).
  • Where it's used: the POST view-as/end action on AuthControllerBase (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/AuthControllerBase.cs:404-405), whose handler also writes the ViewAsEndedMarker (AuthControllerBase.cs:439).

ErrorResourceSource

MMCA.Common.API · MMCA.Common.API.Localization · MMCA.Common/Source/Presentation/MMCA.Common.API/Localization/ErrorResourceSource.cs:13 · Level 0 · class (sealed)

  • What it is: one registered resource set that IErrorLocalizer consults when translating an error code. It is a thin wrapper around a single IStringLocalizer, which is itself backed by one .resx family. Common registers one for its own ErrorResources anchor; each module registers its own additively.
  • Depends on: Microsoft.Extensions.Localization.IStringLocalizer; produced from a resource anchor type such as ErrorResources (MMCA.Common/Source/Presentation/MMCA.Common.API/Resources/ErrorResources.cs:9, an empty sealed class whose only job is to name the .resx family).
  • Concept introduced: an ordered, additive localization registry. The alternative design is one global resource file that every module has to edit. Instead, the framework registers a set of ErrorResourceSource instances into DI, and the localizer walks that set returning the first match, module sources first (in registration order) and Common's own last, whatever order they were registered in, so the more specific source wins and Common is the fallback (type doc, ErrorResourceSource.cs:5-11). The wrapper type exists purely so DI can hold several IStringLocalizers as a distinguishable IEnumerable<ErrorResourceSource> (a bare IEnumerable<IStringLocalizer> would collide with every other localizer in the container). [Rubric §27, i18n] assesses whether user-facing text is externalized and extensible per feature; the additive set means adding a module never touches Common's resources. [Rubric §7, Microservices Readiness] assesses whether a module can be lifted out intact; because the module owns its own source registration, an extracted service carries its own translations with it. See ADR-027.
  • Walkthrough: the whole type is a primary-constructor class taking IStringLocalizer localizer (ErrorResourceSource.cs:13) and exposing it as a single get-only property, public IStringLocalizer Localizer { get; } = localizer (ErrorResourceSource.cs:16). The one extra member is the marker internal bool IsFramework { get; init; } (ErrorResourceSource.cs:22), true only for the framework's own ErrorResources source and set only by AddErrorLocalization (DependencyInjection.cs:132). The enumeration and first-match logic live in ErrorLocalizer.
  • Why it's built this way: the IsFramework flag, not registration order, decides priority between Common and modules: a module's translation of a code is never shadowed by Common's, even when the module registered first, and init plus internal keep modules from claiming framework status. A distinct wrapper type is what makes the set expressible in the container. AddErrorResources<TResource>() registers each module source as a singleton whose factory asks IStringLocalizerFactory.Create(typeof(TResource)) (MMCA.Common/Source/Presentation/MMCA.Common.API/DependencyInjection.cs:146-147), so the anchor type is the only thing a module has to supply.
  • Where it's used: injected as IEnumerable<ErrorResourceSource> into ErrorLocalizer (ErrorLocalizer.cs:13). Common's own source is registered inside AddErrorLocalization() (DependencyInjection.cs:129-133), which DependencyInjection's AddAPI calls automatically (DependencyInjection.cs:113); modules add theirs by calling AddErrorResources<TResource>() (DependencyInjection.cs:144).

IErrorLocalizer

MMCA.Common.API · MMCA.Common.API.Localization · MMCA.Common/Source/Presentation/MMCA.Common.API/Localization/IErrorLocalizer.cs:9 · Level 0 · interface

  • What it is: the contract for localizing a domain Error's human-readable message at the HTTP edge, keyed by its stable machine Code. Domain, handler, and Result code stays culture-agnostic; only the edge speaks a culture.
  • Depends on: nothing beyond the BCL. Implemented by ErrorLocalizer; consumed by ErrorHttpMapping.
  • Concept introduced: edge localization keyed by a stable code. The domain raises errors carrying a machine Code such as "Email.Empty" plus an English message (IErrorLocalizer.cs:15-16). Translating on the Code rather than on the English prose is what keeps culture out of the Error type: the same code resolves to any registered culture, and rewording the English text never invalidates a translation. The contract also pins the failure mode: when the code is empty or no registered resource has a key, the caller's fallbackMessage is returned unchanged (IErrorLocalizer.cs:11-14), so an untranslated code degrades to English rather than throwing or emitting a raw resource key. [Rubric §27, i18n] assesses whether text is translatable without leaking locale into the core, and the split (code in the domain, culture at the edge) is the clean version of that. [Rubric §9, API & Contract Design] applies to the graceful-degradation clause: an error response never becomes an error itself because a translation is missing.
  • Walkthrough: a single method, string Localize(string code, string fallbackMessage) (IErrorLocalizer.cs:17). The XML doc is the specification: resolve code against the current UI culture, otherwise return fallbackMessage (IErrorLocalizer.cs:11-16).
  • Why it's built this way: consumers depend on the abstraction while the additive resource-source enumeration stays an implementation detail (see ErrorLocalizer). Registration uses TryAddSingleton (MMCA.Common/Source/Presentation/MMCA.Common.API/DependencyInjection.cs:128), so an app that wants a different localization strategy registers its own first and the framework's default steps aside. See ADR-027.
  • Where it's used: resolved optionally at five edge call sites, via GetService rather than GetRequiredService: ApiControllerBase.HandleFailure (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/ApiControllerBase.cs:72), UnhandledResultFailureFilter (MMCA.Common/Source/Presentation/MMCA.Common.API/Middleware/UnhandledResultFailureFilter.cs:46), the precondition failure path of SupportsIfMatchAttribute (MMCA.Common/Source/Presentation/MMCA.Common.API/Concurrency/SupportsIfMatchAttribute.cs:268), the machine-client refusal of RefuseMachineClientsAttribute (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/RefuseMachineClientsAttribute.cs:74), and the step-up refusal of MultiFactorRefusalResultHandler (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/MultiFactor/MultiFactorRefusalResultHandler.cs:65), which also localizes the Problem Details Detail (MultiFactorRefusalResultHandler.cs:73). All five hand it to ErrorHttpMapping.BuildErrorsExtension (MMCA.Common/Source/Presentation/MMCA.Common.API/Middleware/ErrorHttpMapping.cs:65), which accepts a null localizer and leaves messages in English (ErrorHttpMapping.cs:69) while leaving the machine Code verbatim so clients can still branch on it (ErrorHttpMapping.cs:60-62).

DbUpdateExceptionHandler

MMCA.Common.API · MMCA.Common.API.Middleware · MMCA.Common/Source/Presentation/MMCA.Common.API/Middleware/DbUpdateExceptionHandler.cs:28 · Level 1 · class (sealed)

  • What it is: the IExceptionHandler that turns an EF Core DbUpdateException into an HTTP 409 Conflict RFC 9457 response with a deliberately generic body, while the full exception is logged server-side, at Warning for a conflict concurrent use produces on its own and at Error for everything else.
  • Depends on: Microsoft.AspNetCore.Diagnostics.IExceptionHandler, Microsoft.AspNetCore.Http.IProblemDetailsService, Microsoft.EntityFrameworkCore.DbUpdateException, the internal ConcurrencyConflictMetrics counter (using MMCA.Common.API.Concurrency; at DbUpdateExceptionHandler.cs:7), and an optional IUniqueConstraintViolationDetector resolved from the request's services (using at :8, read at :86). Siblings in the same chain: OperationCanceledExceptionHandler, ValidationExceptionHandler, and the catch-all GlobalExceptionHandler.
  • Concept introduced: the IExceptionHandler chain. ASP.NET Core resolves registered IExceptionHandler implementations in registration order and calls TryHandleAsync on each: returning true claims the exception and stops the chain, returning false passes it on. The framework registers the chain in AddCommonExceptionHandlers() (MMCA.Common/Source/Presentation/MMCA.Common.API/DependencyInjection.cs:157-168) as OperationCanceled (:162), then DbUpdate (:163), then Validation (:164), then Global (:165), and that same method calls AddProblemDetails with a customization that stamps a requestId extension from HttpContext.TraceIdentifier onto every problem document (DependencyInjection.cs:159-161). [Rubric §9, API & Contract Design] assesses whether errors have one uniform, standards-based shape: every handler here writes RFC 9457 application/problem+json through the same IProblemDetailsService, so controllers never need a try/catch. [Rubric §11, Security] applies to this handler specifically, see below.
  • Walkthrough: TryHandleAsync (DbUpdateExceptionHandler.cs:34):
    • Type-tests with is not DbUpdateException dbUpdateException and returns false (DbUpdateExceptionHandler.cs:39-40) so the rest of the chain still gets its turn.
    • Picks the log level with IsExpectedConflict (:42-49, defined at :84-86): a DbUpdateConcurrencyException, or a failure the host's IUniqueConstraintViolationDetector classifies as a unique-key violation, is logged at LogWarning as a 409-answered conflict (:44); anything else is logged at LogError (:48). The detector is read with RequestServices?.GetService<...>(), so with none registered only the concurrency kind counts as expected (:79-83).
    • When the exception is the DbUpdateConcurrencyException subtype, calls ConcurrencyConflictMetrics.RecordConflict(concurrencyException) (:53-56), which adds one to the persistence.concurrency.conflict counter tagged by entity type (MMCA.Common/Source/Presentation/MMCA.Common.API/Concurrency/ConcurrencyConflictMetrics.cs:37-47). The comment at DbUpdateExceptionHandler.cs:51-52 states why only that subtype is counted: a unique-key or foreign-key failure has its own remedy, and folding it in would hide the contention signal.
    • Sets StatusCodes.Status409Conflict (:58) for every DbUpdateException, concurrency or not.
    • Builds the client-facing detail as the fixed string "A data conflict occurred. Please retry or contact support." (:62), with the comment stating why (:60-61): leaking the EF message would expose table, column and constraint names. The full exception is already in the log.
    • Assembles a ProblemDetailsContext titled "Database Update Exception" (:64-74) and returns await problemDetailsService.TryWriteAsync(context) (:76), so the response body is whatever the configured ProblemDetailsService writes.
  • Why it's built this way: 409 is the honest status for a write rejected by a constraint or a concurrency token, and the split between a rich server-side log and a generic client body is the standard information-disclosure posture. The log-level split is an [Rubric §13, Observability & Operability] decision stated in the class doc (DbUpdateExceptionHandler.cs:17-24): two users saving the same row, or inserting the same key, is normal traffic and belongs at Warning, while a foreign-key failure, truncation, a check constraint or an unclassified provider error stays at Error because no retry fixes it and somebody has to look. Only the SQL Server registration supplies a detector (:19-20), so on other engines a unique-key race still logs at Error.
  • Where it's used: registered second in AddCommonExceptionHandlers() (MMCA.Common/Source/Presentation/MMCA.Common.API/DependencyInjection.cs:163), ahead of GlobalExceptionHandler. Note that a DbUpdateConcurrencyException on an action carrying SupportsIfMatchAttribute never reaches this handler: that filter converts it to 412, records the same conflict metric itself, and sets ExceptionHandled = true (MMCA.Common/Source/Presentation/MMCA.Common.API/Concurrency/SupportsIfMatchAttribute.cs:181-188). A given exception reaches exactly one of the two, so each conflict is counted once (ConcurrencyConflictMetrics.cs:14-17).
  • Caveats / not-in-source: no alert ships on the conflict counter (ConcurrencyConflictMetrics.cs:20-21); a sustained rate on one entity type is read as a design question about contended rows, not an incident. The class doc comment (DbUpdateExceptionHandler.cs:12-16) matches the code: a fixed generic detail, no constraint name leaked. The inline comment beside the detail still says the exception is "captured by the LogError call above" (:61), although an expected conflict is now logged at Warning; either way the full exception is logged. A client abort during SaveChanges that EF Core wraps in a DbUpdateException never reaches this handler while RequestAborted is signalled: OperationCanceledExceptionHandler, registered first, claims it as a 499.

ErrorLocalizer

MMCA.Common.API · MMCA.Common.API.Localization · MMCA.Common/Source/Presentation/MMCA.Common.API/Localization/ErrorLocalizer.cs:13 · Level 1 · class (sealed, internal)

  • What it is: the default IErrorLocalizer. It resolves an error code against an ordered set of registered ErrorResourceSources using the current UI culture, module sources first (in registration order) and the framework's own source last, so the more specific source wins and Common is the fallback, and falls back to the caller's English message when the code is empty or unknown to every source.
  • Depends on: IErrorLocalizer (implements), ErrorResourceSource (injected as a collection); Microsoft.Extensions.Localization.LocalizedString.
  • Concept introduced: first-match-wins over an ordered source list. The interesting mechanism is how "not found" is detected. IStringLocalizer's indexer never returns null: on a miss it hands back a LocalizedString whose Value is the key itself and whose ResourceNotFound flag is true. Testing that flag (ErrorLocalizer.cs:29) rather than comparing strings is what lets the loop distinguish a genuine translation from an echoed code, and therefore what lets it keep walking to the next source instead of returning "PhoneNumber.Empty" to a user. [Rubric §27, i18n] assesses translation coverage and layering; first-match ordering lets Common ship base translations while a module extends the set additively. See ADR-027.
  • Walkthrough: the primary constructor takes IEnumerable<ErrorResourceSource> sources (ErrorLocalizer.cs:13), materialized once into _sources with a collection expression that concatenates the non-framework sources (registration order) followed by the IsFramework ones (ErrorLocalizer.cs:15-16). Localize (ErrorLocalizer.cs:19): returns fallbackMessage immediately when code is null or empty (ErrorLocalizer.cs:21-24); otherwise walks _sources in that order, reading source.Localizer[code] and returning localized.Value on the first entry where !localized.ResourceNotFound (ErrorLocalizer.cs:26-33); if no source matches it returns fallbackMessage (ErrorLocalizer.cs:35). The current UI culture is never read explicitly: IStringLocalizer resolves it per call, which is why one singleton can serve requests in different cultures concurrently.
  • Why it's built this way: internal sealed keeps the implementation behind the IErrorLocalizer abstraction, so nothing downstream can bind to the enumeration strategy. Snapshotting and reordering the DI collection once (rather than enumerating it per lookup) matters because this runs on every failing request, and the reorder is what lets a module override a Common translation regardless of registration order. Registering it with TryAddSingleton (DependencyInjection.cs:128) is safe precisely because the type holds no per-request state.
  • Where it's used: registered by AddErrorLocalization() (DependencyInjection.cs:125-135, which also calls services.AddLocalization() at :127), and that method is called by AddAPI (DependencyInjection.cs:113); reached at runtime only through the IErrorLocalizer handle that ApiControllerBase, UnhandledResultFailureFilter and SupportsIfMatchAttribute pass into ErrorHttpMapping.

CorrelationIdMiddleware

MMCA.Common.API · MMCA.Common.API.Middleware · MMCA.Common/Source/Presentation/MMCA.Common.API/Middleware/CorrelationIdMiddleware.cs:20 · Level 9 · class (sealed)

  • What it is: convention-based middleware that establishes one correlation ID per request, publishes it on the scoped ICorrelationContext, and echoes it back to the caller in the X-Correlation-ID response header.
  • Depends on: ICorrelationContext (injected per invoke, so it is resolved from the request scope) and System.Diagnostics.Activity (CorrelationIdMiddleware.cs:1-3).
  • Concept: distributed trace correlation is introduced at ICorrelationContext; this is the type that populates it. [Rubric §13, Observability & Operability] assesses whether one logical operation can be reconstructed across log entries and services: with this middleware second in the pipeline, every later log line, outbox row and downstream call can carry the same ID.
  • Walkthrough
    • HeaderName = "X-Correlation-ID" (CorrelationIdMiddleware.cs:23) is a public const, so clients, tests and downstream code all name the header from one place.
    • MaxLength = 64 (:26) is an internal const: the width of the persisted correlation columns (its doc comment at :25).
    • InvokeAsync(HttpContext, ICorrelationContext) (:35): the second parameter is per-invoke injected, which is how convention-based middleware consumes a scoped service from a singleton middleware instance. Both arguments are null-guarded (:37-38).
    • The resolution waterfall (:40-43): an inbound X-Correlation-ID header wins when it is not null, empty or whitespace (string.IsNullOrWhiteSpace) and survives Sanitize (:41); otherwise Activity.Current?.TraceId (the W3C trace ID that OpenTelemetry propagates, :42), else ASP.NET's HttpContext.TraceIdentifier (:43). The chain is null-coalescing, so a header that Sanitize rejects falls through to the generated ID exactly as a blank one does. A usable caller-supplied ID is therefore honored, and the ID always exists.
    • Sanitize (:61-65) cuts a caller value longer than MaxLength to its first 64 characters with a range slice (:63), then keeps it only when every character is printable ASCII, >= ' ' and <= '~' (:64); any other character yields null.
    • correlationContext.SetCorrelationId(correlationId) (:45) publishes it, then context.Response.OnStarting(...) (:46-50) registers a callback that writes the response header. Writing it in OnStarting rather than after next(...) completes is the only safe way: once the response has begun, header writes throw.
    • return next(context) (:52) continues the pipeline. InvokeAsync is a plain Task-returning method, not async (:35): it has no work after the call, so it hands back the downstream task directly instead of allocating a state machine.
  • Why it's built this way: accepting the client's ID makes cross-system correlation possible when the caller already has a trace, and falling back to Activity.Current means the correlation ID and the OpenTelemetry trace ID are the same value in a normally instrumented host. Truncating at the boundary rather than at the database means the id echoed in the response header is exactly the one stored (class comment, :13-15), and treating a blank header as absent keeps an empty value from displacing the trace-ID fallback. Replacing a non-ASCII or control-character value with the generated ID is a defense for the echo itself: Kestrel refuses to write such a value into a response header, which would fail the request after its handler had already run (class comment, :15-17).
  • Where it's used: it is the second step of the default pipeline, right after the exception handler (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/Pipeline/MiddlewarePipelineBuilder.cs:38-40, following ExceptionHandler at :34-36), so everything downstream (including the exception handlers above) logs under a known ID. The step is named MiddlewarePipelineStepNames.CorrelationId (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/Pipeline/MiddlewarePipelineStepNames.cs:20), which is the handle a host uses to insert its own middleware around it. The CQRS logging decorators read the same context.

ErrorHttpMapping

MMCA.Common.API · MMCA.Common.API.Middleware · MMCA.Common/Source/Presentation/MMCA.Common.API/Middleware/ErrorHttpMapping.cs:14 · Level 3 · class (internal static)

  • What it is: the single table that maps domain ErrorType values to HTTP status codes, the ranking rule that picks one status for a whole failure, and the builder for the errors extension array that problem documents carry.
  • Depends on: Error, ErrorType, ErrorTypeSeverity, IErrorLocalizer; System.Collections.Frozen and ASP.NET StatusCodes (ErrorHttpMapping.cs:1-4).
  • Concept: the Result-to-HTTP translation table. This is where the Result pattern meets the HTTP contract. [Rubric §9, API & Contract Design] assesses whether error responses are consistent across the whole surface: because both ApiControllerBase and UnhandledResultFailureFilter call into this one class, they cannot drift (the class doc says exactly that, ErrorHttpMapping.cs:8-13). [Rubric §7, Microservices Readiness] applies to the ranking: the severity order itself lives in MMCA.Common.Shared (MMCA.Common/Source/Core/MMCA.Common.Shared/Abstractions/ErrorTypeSeverity.cs:72) so the gRPC edge classifies the same aggregate identically (ErrorHttpMapping.cs:49-50, and see MMCA.Common/Source/Presentation/MMCA.Common.Grpc/ResultGrpcExtensions.cs:110). [Rubric §27, i18n] applies through the localizer parameter.
  • Walkthrough
    • TargetPlaceholder = "{0}" (ErrorHttpMapping.cs:17): the private constant a translated message uses to carry the error's Target (see LocalizeMessage below).
    • ErrorTypeToStatusCode (ErrorHttpMapping.cs:23-35): a FrozenDictionary<ErrorType, int> with Validation to 400, Invariant to 400, NotFound to 404, Conflict to 409, Unauthorized to 401, Forbidden to 403, UnprocessableEntity to 422, Unexpected to 500, TooManyRequests to 429 (:33), and Unavailable to 503 (:34), the one type that tells the caller a retry later can succeed. There is no Failure row: that member is gone from the enum and its value 7 is retired (MMCA.Common/Source/Core/MMCA.Common.Shared/Abstractions/ErrorType.cs:17, with Unavailable = 10 at :67). FrozenDictionary is the right structure for a table built once at startup and read on every failed request: it trades slower construction for the fastest lookups (:19-22).
    • GetStatusCode(ErrorType) (:41-42) uses GetValueOrDefault(..., Status400BadRequest), so a future error type falls back to 400 rather than throwing inside an error path.
    • GetStatusCode(IReadOnlyList<Error>) (:54-55) is the overload callers actually use for a failed result: it delegates to ErrorTypeSeverity.MostSevere(errors).Type, so the status reflects the most severe error present rather than whichever one happened to be first. Ties keep the earliest error, so a list of same-rank errors behaves exactly as a positional selection would, and every error still travels in the errors array either way (:44-53).
    • BuildErrorsExtension(IReadOnlyList<Error>, IErrorLocalizer?) (:65-74) projects each error into an anonymous object with Code, Message, Type (stringified), Source and Target. Only Message is localized, and only when a localizer was supplied (:69, through LocalizeMessage); a null localizer leaves the original English text. Code, Type, Source and Target stay verbatim so clients can branch on them regardless of culture (:57-64).
    • LocalizeMessage(IErrorLocalizer, Error) (:82-94) asks the localizer for the text keyed by Code (:84). When the result is the English message itself, or carries no {0}, it is returned as is (:85-89). Otherwise the placeholder is filled with the error's Target, so runtime detail survives translation (the CSV reader puts the malformed line there for Csv.Malformed, :76-81); a translation with a placeholder but no Target to fill it falls back to the English message, which names the detail itself (:91-93).
  • Why it's built this way: internal visibility (:14) keeps the table an implementation detail of the API package. Localizing at this exact point is ADR-027: the domain produces culture-free codes, and the edge does the translation, keyed by the stable Code.
  • Where it's used: ApiControllerBase.HandleFailure when converting a failed Result into an ObjectResult (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/ApiControllerBase.cs:63 and :58), and UnhandledResultFailureFilter as the backstop (MMCA.Common/Source/Presentation/MMCA.Common.API/Middleware/UnhandledResultFailureFilter.cs:36 and :47).

TenantResolutionMiddleware

MMCA.Common.API · MMCA.Common.API.Middleware · MMCA.Common/Source/Presentation/MMCA.Common.API/Middleware/TenantResolutionMiddleware.cs:37 · Level 3 · class (sealed)

  • What it is: middleware that resolves the current request's tenant (from a claim or a header), publishes it on the scoped ITenantContext, and rejects a request that has none when tenancy is required.
  • Depends on: ITenantContext, TenancySettings (via IOptions<T>), and IProblemDetailsService (TenantResolutionMiddleware.cs:51-55). The persistence layer's query filter, save interceptor and per-tenant database routing all read the context this middleware sets (:10-12).
  • Concept introduced: request-scoped tenant resolution that fails closed. [Rubric §11, Security] assesses whether data isolation holds by default: an unscoped request in a multi-tenant database reads across every tenant, which is the exact outcome tenancy exists to prevent, so with Tenancy:RequireTenant (the default) an unresolved tenant is answered 400 Bad Request rather than allowed through (class remarks, TenantResolutionMiddleware.cs:28-34). [Rubric §8, Data Architecture] applies because the value published here is what scopes the EF global filter. [Rubric §17, DevOps & Deployment]: hosts that never opted in pay nothing, since IOptions<TenancySettings> resolves to defaults with Enabled false and the middleware passes every request straight through (:15-20).
  • Walkthrough
    • UnresolvedTenantTitle (TenantResolutionMiddleware.cs:40): the internal const problem title, shared with the tests.
    • InvokeAsync(HttpContext, ITenantContext, IOptions<TenancySettings>, IProblemDetailsService) (:51-55): per-invoke injection, null-guarding its first three arguments (:57-59).
    • Fast exit (:63-67): if !settings.Enabled or IsExcluded(...), call next and return. IsExcluded (:90-95) matches settings.EffectiveExcludedPathPrefixes with StartsWithSegments under OrdinalIgnoreCase, which is how health, liveness and discovery endpoints keep answering before any tenant exists.
    • Resolution (:69-74): Resolve(...) returns the first non-blank candidate, and on success the tenant is published with tenantContext.SetTenant(tenantId) (:71) before the pipeline continues.
    • Resolve (:105-122) walks settings.EffectiveResolutionOrder and switches on the strategy: Claim reads context.User?.FindFirst(settings.ClaimType)?.Value (:111), and Header reads settings.HeaderName only when settings.TrustTenantHeader is set (:112-113). Every other case, including a listed header the host has not trusted, yields null (:114); an undefined strategy value can only arrive if options validation was bypassed (:101-104). The claim is the default order and the trustworthy source; the header is an explicit opt-in because a caller-supplied header lets any caller name any tenant (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Tenancy/TenancySettings.cs:15-21 and :100-107). Candidates are trimmed (:118).
    • Opt-out (:76-82): with RequireTenant false an unresolved request still runs, but with no tenant: it reaches endpoints over global data and reads no tenant-owned rows, because the query filter itself fails closed (:78-79, and TenancySettings.cs:95-101).
    • RejectAsync (:131-154) sets 400 (:136) and writes a problem document that names the configured claim and header (:145-149), so the caller can fix the request without reading the source. Its doc comment (:124-130) states that both are named regardless of EffectiveResolutionOrder, so the detail can name a source that Resolve did not consult (for example a header when the order is claim-only).
  • Why it's built this way: see ADR-073. The registration position is load-bearing: it runs immediately after UseAuthentication() because the claim strategy reads HttpContext.User, which has no token claims until authentication has run (:21-26). Registering it earlier would resolve no tenant from the claim at all: under the default claim-only order every request would be rejected, and under an order that opts into the header every request would silently fall through to it (:24-26). So the adjacency is not left to convention: MiddlewarePipelineBuilder.Build() enforces it with RequireImmediatelyBefore(Authentication, TenantResolution, ...) (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/Pipeline/MiddlewarePipelineBuilder.cs:258-261), so a host that reorders the pipeline fails at startup rather than misrouting tenants.
  • Where it's used: the TenantResolution step of the default pipeline (MiddlewarePipelineBuilder.cs:98-104), which WebApplicationExtensions.UseCommonMiddlewarePipeline() applies. It is wired unconditionally and inert by default.

GlobalExceptionHandler

MMCA.Common.API · MMCA.Common.API.Middleware · MMCA.Common/Source/Presentation/MMCA.Common.API/Middleware/GlobalExceptionHandler.cs:42 · Level 4 · class (sealed)

  • What it is: the last handler in the IExceptionHandler chain. It claims anything the specific handlers declined and answers HTTP 500 as RFC 9457 problem details, with three exception types mapped on the way: a CrossTenantWriteException is answered 400 instead, a BadHttpRequestException is answered with the status it carries (413 or 400 typically), and a TransactionCommitAmbiguousException stays a 500 but a coded one that tells the client the commit outcome is unknown.
  • Depends on: IProblemDetailsService and ILogger<GlobalExceptionHandler> (primary-constructor injected, GlobalExceptionHandler.cs:42-45), plus CrossTenantWriteException from MMCA.Common.Infrastructure.Persistence.Interceptors (imported at :8), TransactionCommitAmbiguousException from MMCA.Common.Infrastructure.Persistence.DbContexts.Factory (:7), CommitOutcomeUnknown from MMCA.Common.Shared.Http (:10), Error, ErrorHttpMapping and an optional IErrorLocalizer. Chain concept introduced at DbUpdateExceptionHandler.
  • Concept: [Rubric §13, Observability & Operability] assesses whether error handling is factored out of business code, and [Rubric §13, Observability & Operability] whether failures are always recorded. This handler is the guarantee for both: no exception can escape the pipeline as a raw stack trace or an unlogged 500, because it never returns false on a type test. [Rubric §11, Security] covers the second half: the cross-tenant detail is deliberately free of everything the exception carries, because echoing a tenant id back tells an unauthorized caller which tenant owns the row it just tried to write (GlobalExceptionHandler.cs:50-55). The bad-request path applies the same restraint: its detail is a fixed sentence, never the exception message (:105-107). [Rubric §9, API & Contract Design] covers the commit-unknown path: a client can tell "the write may or may not have landed" from an ordinary server fault by a machine code and a response header, and so knows not to resend it blindly (:32-38).
  • Walkthrough: TryHandleAsync (GlobalExceptionHandler.cs:61) has four paths.
    • CrossTenantWriteTitle (:48) and CrossTenantWriteDetail (:56-58) are internal const strings, so the tests assert against the same literals the handler writes.
    • The tenant-boundary path (:66-84): a CrossTenantWriteException is logged at LogWarning (:70), because the request was refused exactly as designed and a tenant-scoped API answering 400 to an untenanted write is routine rather than a server fault (:68-69). It sets Status400BadRequest (:72) and returns TryWriteAsync with the two constants (:73-83).
    • The bad-request path (:86-110): a BadHttpRequestException (Kestrel or model binding rejected a malformed or oversize request) is a caller fault, so it is logged at LogWarning with its status code (:92) and answered with the status the exception already carries, passed through unchanged (:94). The title is "Payload Too Large" when that status is Status413PayloadTooLarge and "Bad Request" otherwise (:102-104), and the detail follows the same split (:105-107).
    • The commit-unknown path (:112-115): a TransactionCommitAmbiguousException is handed to WriteCommitOutcomeUnknownAsync (:139-162), which logs at LogError (:141), sets 500 (:143), stamps the CommitOutcomeUnknown.HeaderName header with CommitOutcomeUnknown.HeaderValue (:144), builds a problem document titled "Commit outcome unknown" whose detail is CommitOutcomeUnknown.Message (:146-151), and attaches an errors extension built by ErrorHttpMapping.BuildErrorsExtension from one Error.Unexpected(CommitOutcomeUnknown.Code, CommitOutcomeUnknown.Message), localized when an IErrorLocalizer is registered (:152-154), before writing it (:156-161). Its doc states why the detail never says "try again" (:133-138): a blind resend re-executes the handler, because the idempotency record is stored only for a 2xx.
    • The catch-all path (:117-130): logs "Unhandled exception occurred" with the exception at LogError (:117), sets StatusCodes.Status500InternalServerError (:119), and returns the result of problemDetailsService.TryWriteAsync(...) (:120-130) with the generic title "Internal Server Error" and a "please try again" detail (:127-128). The exception object is attached to the ProblemDetailsContext (:123) so a configured customization can enrich the document (in development, for example) without this class deciding what to expose.
  • Why it's built this way: the class doc explains why the cross-tenant mapping lives here rather than in a handler of its own (GlobalExceptionHandler.cs:19-23): CrossTenantWriteException derives from InvalidOperationException, so nothing ahead of this handler claims it, while every other save-time invariant failure of that family still ends at the 500. The BadHttpRequestException mapping is documented beside it (:25-31): the exception already knows which client status applies, so the handler passes it through rather than collapsing an oversize body into a 500. The commit-unknown mapping (:32-38) keeps the honest 500 status and Error log, and adds only the code and header a client needs to avoid a duplicate write. Returning TryWriteAsync's own boolean rather than a hard-coded true keeps the handler honest: if no problem-details writer can serve the request, the framework is told the exception was not fully handled instead of silently swallowing it. Registration order is the only thing that makes it the fallback, so it is registered last (MMCA.Common/Source/Presentation/MMCA.Common.API/DependencyInjection.cs:165); its own doc says so (DependencyInjection.cs:153-154).
  • Where it's used: AddCommonExceptionHandlers() (DependencyInjection.cs:165); every host that calls it inherits the same 500 contract, the same tenant-boundary 400, the same bad-request pass-through and the same coded commit-unknown 500. JsonRequestBodyLimitMiddleware writes its pre-read 413 with the same title and detail as the bad-request path here.

UnhandledResultFailureFilter

MMCA.Common.API · MMCA.Common.API.Middleware · MMCA.Common/Source/Presentation/MMCA.Common.API/Middleware/UnhandledResultFailureFilter.cs:22 · Level 4 · class (sealed, partial)

  • What it is: a globally registered IAlwaysRunResultFilter that catches an action which returned a failed Result inside an Ok(...) (or any ObjectResult) and rewrites the response as a proper problem document at the right status code.
  • Depends on: Result, Error, ErrorHttpMapping, IErrorLocalizer; Microsoft.AspNetCore.Mvc.Filters.IAlwaysRunResultFilter (UnhandledResultFailureFilter.cs:1-7).
  • Concept introduced: the always-run result filter as a safety net. A regular result filter can be bypassed on short-circuit paths; IAlwaysRunResultFilter runs for every result MVC is about to execute. [Rubric §9, API & Contract Design] assesses whether a domain failure can leak as 200 OK with error JSON in the body (a client would treat it as success), which the class doc names as the exact defect it prevents (UnhandledResultFailureFilter.cs:11-21). [Rubric §15, Best Practices & Code Quality] assesses defense in depth: this filter converts a class of controller mistakes into a correct response plus a warning log instead of a silent wrong answer.
  • Walkthrough: OnResultExecuting (UnhandledResultFailureFilter.cs:26):
    • The guard context.Result is not ObjectResult { Value: Result result } || result.IsSuccess (:28-31) makes the filter a no-op for everything except an ObjectResult carrying a failed Result. Note the pattern matches the base Result, so Result<T> values are caught too.
    • Logs at Warning with the action's display name and the errors (:33, message template at :57-59), which is how an operator learns which action leaked.
    • Derives the status through ErrorHttpMapping.GetStatusCode(result.Errors) when there is at least one error (:35-37), so the code reflects the most severe error present, matching ApiControllerBase.HandleFailure exactly (:17-19); with no errors at all it falls back to 500, since a failure with nothing to report is a framework-level anomaly rather than a client error.
    • Builds a ProblemDetails titled "Unhandled result failure" whose detail names the defect in plain words (:39-44).
    • Resolves IErrorLocalizer from HttpContext.RequestServices with GetService (:46, so a host without localization simply passes null) and attaches the localized errors extension (:47).
    • Replaces context.Result with an ObjectResult(problemDetails) { StatusCode = statusCode } (:49).
    • OnResultExecuted (:53-55) is intentionally empty: there is nothing to do after the response ran.
  • Why it's built this way: the logging uses the [LoggerMessage] source generator (:57-63) with a small private instance forwarder (:65-66) so the filter's primary-constructor logger is used without an allocation per call. The class is partial for that generator.
  • Where it's used: added as a global MVC filter inside AddAPI(...) (MMCA.Common/Source/Presentation/MMCA.Common.API/DependencyInjection.cs:50), so it applies to every controller action in every host.

ViewAsEndedMarker

MMCA.Common.API · MMCA.Common.API.Middleware · MMCA.Common/Source/Presentation/MMCA.Common.API/Middleware/ViewAsEndedMarker.cs:32 · Level 5 · class (internal static, partial)

  • What it is: the shared-cache "view-as grant ended" marker for a multi-service host. Only the service that holds the grant store (ViewAs:HostsGrantStore) can read a grant row; every other service checks this marker in the distributed cache they all share (class summary, ViewAsEndedMarker.cs:15-20).
  • Depends on: ICacheService, CrossServiceCacheKeys, ViewAsGrant (for MaxLifetime), IOptionsMonitor<JwtBearerOptions> and TimeProvider, all resolved from the request's services (ViewAsEndedMarker.cs:1-11).
  • Concept: the same pattern as SoftDeletedUserCache, applied to support access. [Rubric §7, Microservices Readiness] assesses whether a security decision still holds once modules run as separate services: ending a view on the store host must take effect on every service on the next request, not at token expiry (ADR-137). [Rubric §11, Security] applies to the lifetime: the marker must outlive every token the services still accept.
  • Walkthrough
    • KeyFor(Guid grantId) (ViewAsEndedMarker.cs:41) builds {CrossServiceCacheKeys.Prefix}viewas:ended:{grantId:D}. It is a cross-service key because the store host writes it and every other service reads it, so it must not carry any one host's namespace (:34-40).
    • TryGetTokenExpiry(ClaimsPrincipal, out DateTimeOffset) (:47-58) parses the exp claim as invariant-culture Unix seconds and accepts it only within 0..DateTimeOffset.MaxValue seconds, so a malformed claim never throws.
    • WriteAsync(IServiceProvider?, ClaimsPrincipal, Guid, CancellationToken) (:79): returns without writing when the services or the cache are absent (:85-88), computes the lifetime as the token's remaining life plus the bearer clock skew (:90-91) and writes true under KeyFor(grantId) (:95). A failed write (other than cancellation) is logged through the [LoggerMessage] error LogMarkerWriteFailed (:97-102, :124-125), not thrown: the grant row is already ended and a service that cannot reach the cache refuses every view-as request anyway (:71-78).
    • RemainingTokenLife (:106-114) is expiresAt - now, floored at zero, or ViewAsGrant.MaxLifetime when the token carries no expiry (:110).
    • ClockSkew(IServiceProvider) (:117-122) reads TokenValidationParameters.ClockSkew from the JwtBearerDefaults.AuthenticationScheme options and falls back to TokenValidationParameters.DefaultClockSkew (the library's 5 minutes, :71-75).
  • Why it's built this way: the marker lives for the token's remaining life plus the skew because a service accepts the token until its expiry plus that skew; a marker that lapsed first would let the ended token through again (:61-65). The class is internal because the writer and the reader both live in this package (:28-30), and the end endpoint is the only writer, since it is the only path that ends a grant before expiry (:22-27).
  • Where it's used: written by the view-as/end action of AuthControllerBase (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/AuthControllerBase.cs:439); read by ViewAsGuardMiddleware through KeyFor and TryGetTokenExpiry (ViewAsGuardMiddleware.cs:186, :213); ClockSkew is also reused by SoftDeletedUserMiddleware to size its own marker (SoftDeletedUserMiddleware.cs:179).

ViewAsGuardMiddleware

MMCA.Common.API · MMCA.Common.API.Middleware · MMCA.Common/Source/Presentation/MMCA.Common.API/Middleware/ViewAsGuardMiddleware.cs:42 · Level 6 · class (sealed, partial)

  • What it is: the HTTP half of read-only view-as. For a request whose principal carries a view-as token (act_sub), it refuses every method other than GET, HEAD and OPTIONS with 403 (with two exemptions), and refuses with 401 a token whose grant is no longer live. Every other request passes after one claim lookup (class summary, ViewAsGuardMiddleware.cs:13-33).
  • Depends on: IViewAsService (resolved only for a view-as request), ViewAsSettings via IOptions<T>, ICacheService, AuthClaimTypes, ViewAsEndEndpointAttribute, ViewAsReadOnlyEndpointAttribute and ViewAsEndedMarker.
  • Concept introduced: a fail-closed guard, and why it differs from its neighbor. [Rubric §11, Security] assesses whether a support session can act in someone else's name: several writes never pass through a command (sign-in, refresh, password and preference changes, device registration), so the ViewAsCommandDecorator<TCommand, TResult> alone cannot keep the session read-only, and this middleware is the first layer (:17-21, :31-32). [Rubric §29, Resilience & Business Continuity] assesses how an outage degrades: unlike SoftDeletedUserMiddleware, the grant check fails CLOSED, because the exposure is the other way round (an outage here costs one staff user's support session, while failing open there would cost every user's every request) (:34-40, :152-160). See ADR-137.
  • Walkthrough: InvokeAsync(HttpContext, ILogger<ViewAsGuardMiddleware>) (ViewAsGuardMiddleware.cs:53):
    • Not a view-as principal (:58-62): call next and return.
    • View-as switched off or never configured (:66-72): when ViewAsSettings is unresolvable or Enabled is false, log and answer 401, so a token minted while view-as was on is honored for nothing.
    • Method rule (:74-79): a request that is not GET, HEAD or OPTIONS (IsSafeMethod, :106-107), not a POST to an action carrying ViewAsEndEndpointAttribute (:109-111), and not a POST to an endpoint marked ViewAsReadOnlyEndpointAttribute (:117-119; gRPC is always POST) is answered 403.
    • Grant check (:81-85), via IsGrantLiveOnThisHostAsync (:94-104), which branches on ViewAs:HostsGrantStore. On the store host it resolves IViewAsService (no service means refuse), parses the grant, actor and subject claims (:127-133) and calls IsGrantActiveAsync(grantId, staffUserId, targetUserId, ...) (:137). On a service without the store, IsGrantLiveWithoutTheStoreAsync (:161-201) requires the same three claims plus a usable exp (TryReadTokenWithoutTheStore, :207-214), refuses an expired token (:169-174), refuses when no ICacheService is registered (:176-181), and reads the ended marker with GetFromSharedStoreAsync<bool?>(ViewAsEndedMarker.KeyFor(grantId), ...) (:185-187), refusing when it is set (:188-192). Any lookup exception other than cancellation is logged and refused (:139-143, :196-200). A failed check answers 401.
    • Otherwise next runs (:87).
    • Seven [LoggerMessage] methods (:216-235) name each refusal: expired token, no shared cache, grant ended, write refused, view-as disabled, malformed token and lookup failed.
  • Why it's built this way: IViewAsService is resolved from the request's services only for a view-as request, so an ordinary request resolves nothing and a host without it fails closed (:48-52). The grant lookup is one primary-key read and is not cached, because a cached "live" answer on one replica would outlive an End handled on another (:37-39); for the same reason the marker is read from the shared store, never a replica's local copy (:158-160). The middleware is always in the pipeline, enabled or not, so switching view-as off takes effect on tokens already issued.
  • Where it's used: the ViewAsGuard step of the default pipeline (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/Pipeline/MiddlewarePipelineBuilder.cs:118-125), after SoftDeletedUserFilter (:122-124) and before Authorization (:135-137): after authentication so act_sub is on the principal, and after routing so the end action's metadata is readable (:128-132). The step name is MiddlewarePipelineStepNames.ViewAsGuard (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/Pipeline/MiddlewarePipelineStepNames.cs:66).

SoftDeletedUserMiddleware

MMCA.Common.API · MMCA.Common.API.Middleware · MMCA.Common/Source/Presentation/MMCA.Common.API/Middleware/SoftDeletedUserMiddleware.cs:40 · Level 9 · class (sealed, partial)

  • What it is: middleware that rejects an authenticated request with 401 when the calling user has been soft-deleted or locked (BR-133), by reading a deleted-or-locked marker from the shared cache store, and (on a host that registers the validator) falling back to a database query when no marker is set. A "not deleted" answer is never cached.
  • Depends on: ICurrentUserService, ICacheService, ISoftDeletedUserValidator and ITokenService (both resolved lazily), SoftDeletedUserCache for the key and the marker duration (SoftDeletedUserMiddleware.cs:67-71), and ViewAsEndedMarker for the host's JWT bearer clock skew (:179).
  • Concept introduced: a fail-open security check, and why. [Rubric §11, Security] assesses whether revoked principals stop being served, and [Rubric §29, Resilience & Business Continuity] assesses how a dependency outage degrades. The class remarks (SoftDeletedUserMiddleware.cs:25-39) document the trade-off explicitly: this check runs on the hot path of every authenticated request, so failing closed would turn any cache or database blip into a total outage. Failing open is bounded instead, because access tokens live 15 minutes and the deletion or lock already revoked the refresh token, so no new access token can be minted. The residual exposure is one already-issued token's remaining lifetime, and only while a dependency is unhealthy. The marker means "deleted or locked": an erasure, an administrator's lock or a machine-client revocation writes it, and an unlock clears it (class summary, :13-16). The validator query checks deletion only, so a lock is enforced here by the marker alone, and after the marker expires by the sign-in and refresh gates (:17-20). [Rubric §12, Performance & Scalability] covers the cache: the default marker lives 20 minutes (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/SoftDeletedUserCache.cs:44), the default 15-minute access-token lifetime plus the library's 5-minute bearer clock skew (SoftDeletedUserCache.cs:36-38), so it outlives any token issued before the delete or lock. The trade is that a live user costs one shared-store read, plus one validator query on the Identity host, per authenticated request (class comment, SoftDeletedUserMiddleware.cs:20-22). This middleware is the fail-open counterpart of ViewAsGuardMiddleware, which fails closed on the same kind of outage.
  • Walkthrough: InvokeAsync(HttpContext, ICurrentUserService, ICacheService, ILogger<SoftDeletedUserMiddleware>) (SoftDeletedUserMiddleware.cs:67-71), per-invoke injected including the logger (the reason is stated at :62-65):
    • Anonymous fast path (:75-83): no UserId, call next and return. The comment notes this is the common case in extracted services, which see internal gRPC/HTTP traffic with no user.
    • Cache read (:85-106): key from SoftDeletedUserCache.KeyFor(userId.Value) (:85). The read is GetFromSharedStoreAsync<bool?> (:94-96), never the replica's local L1 copy, because the marker is written by whichever replica handled the delete and a local read could miss it for the local cache duration (:91-93). A cache exception that is not an OperationCanceledException is logged and treated as a miss (:98-106), and cacheReachable goes false so the write is skipped too.
    • cachedResult is true (:108-115): the user is known deleted or locked, respond 401 and stop the pipeline. This happens before the validator is looked up, so the marker is honored on every host, including one that does not host Identity.
    • Validator resolution (:117-125): context.RequestServices.GetService<ISoftDeletedUserValidator>(). The validator is implemented by the Identity module, so a service that does not host Identity has none registered; lazy resolution lets the middleware no-op there instead of 500-ing every request (remarks at :51-61). On such a host a cache miss or unreachable cache simply passes the request through. This is the "wired unconditionally, inert when not applicable" convention that TenantResolutionMiddleware later copied by name (TenantResolutionMiddleware.cs:16).
    • No marker (:127-144): any shared-store value other than true (no entry, an unreachable cache, or a stray false entry) falls through to the database, so a cached "not deleted" answer is never treated as authoritative. It queries IsUserSoftDeletedAsync (:133-135). If that throws (again excluding cancellation) the request is allowed through with a warning (:137-144), which is the fail-open path.
    • A deleted user (:146-167): the marker is written with SetAsync(cacheKey, true, MarkerDurationFor(context.RequestServices), ...) when the cache is reachable (:148-163, a failed write only costs the next request a lookup), then 401 (:165-166). A live answer is never written back, because each replica keeps its own local copy of a cached value and a cached live answer would outlive a delete made on another replica (:127-129).
    • Otherwise next runs (:169).
    • MarkerDurationFor(IServiceProvider?) (:177-180): when an ITokenService is registered, the lifetime is SoftDeletedUserCache.MarkerDurationFor(tokens.AccessTokenLifetime, ViewAsEndedMarker.ClockSkew(services)), which is the access-token lifetime plus the bearer clock skew and never less than the 20-minute default (SoftDeletedUserCache.cs:54-58); with no token service the lifetime is unknown on this host, so SoftDeletedUserCache.MarkerDuration is written (:172-176).
    • Three [LoggerMessage] warnings (:182-204) name the failure precisely: cache read (which says it falls back to the validator query when one is registered), cache write, validator, each stating what the request did next.
  • Why it's built this way: every catch filters out OperationCanceledException (:98, :137, :157), so a client disconnect is never misread as a dependency outage and is left to OperationCanceledExceptionHandler. Returning a bare 401 status with no body (:113, :165) is deliberate: a revoked principal gets no detail to work with. Sizing the marker from the host's own token lifetime and skew means a host that raises either still writes a marker that outlasts its tokens.
  • Where it's used: the SoftDeletedUserFilter step of the default pipeline (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/Pipeline/MiddlewarePipelineBuilder.cs:114-116), placed after RateLimiting (:106-112) and before ViewAsGuard (:118-125) and Authorization (:127-129), so it runs only once a principal exists and before any policy grants access. The step name is MiddlewarePipelineStepNames.SoftDeletedUserFilter (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/Pipeline/MiddlewarePipelineStepNames.cs:60).

ErrorResources

MMCA.Common.API · MMCA.Common.API.Resources · MMCA.Common/Source/Presentation/MMCA.Common.API/Resources/ErrorResources.cs:9 · Level 0 · class (sealed)

  • What it is: an empty marker class whose only job is to be a typeof(...) anchor for the framework's own translation files, ErrorResources.resx and ErrorResources.es.resx, which sit beside it in Resources/. It has no members: public sealed class ErrorResources; at MMCA.Common/Source/Presentation/MMCA.Common.API/Resources/ErrorResources.cs:9 is the entire declaration, written in the body-less semicolon form.
  • Depends on: nothing, first-party or otherwise. It has no using directives and no base type. Dependencies point the other way: ErrorResourceSource wraps the IStringLocalizer built from this type, and ErrorLocalizer (the default IErrorLocalizer) enumerates those sources.
  • Concept introduced (the resource anchor type). .NET's IStringLocalizerFactory.Create(Type) locates a resource set from a type's assembly plus its namespace-relative name, so a .resx needs a co-located type to point at even when that type has no behavior of its own. Keeping the anchor a real, public, empty class makes the resource set addressable in a refactor-safe way (rename the class and the resx alongside it, and no magic base-name string goes stale) and gives every module a one-line pattern to copy. Tag [Rubric §27, i18n], which assesses whether user-facing text is externalized and culture-resolved rather than hard-coded: the 154 entries in each of the two resx files are keyed by the stable machine error Code ("Error.NotFound", "Email.Empty", "Money.CurrencyMismatch", and so on; Resources/ErrorResources.resx:61, :70, :88), never by the English message, so a translation survives any rewording of the domain's fallback text. Tag [Rubric §9, API & Contract Design], which assesses whether the API's error shape is stable across clients: the localized text moves while the Code a client branches on stays invariant. Tag [Rubric §3, Clean Architecture], which assesses whether concerns sit in the right layer: this anchor and its resx live in the Presentation assembly MMCA.Common.API, so the Domain and Application layers that produce Error values never take a localization dependency.
  • Walkthrough: there is nothing to trace inside the type; all of its meaning is in the doc comment and in the two resx siblings. What is worth walking is the three-step path the anchor sits on.
    1. Registration. AddErrorLocalization() calls services.AddLocalization(), registers ErrorLocalizer behind IErrorLocalizer with TryAddSingleton, and then contributes the framework's own set as a singleton ErrorResourceSource built from Create(typeof(ErrorResources)) with IsFramework = true (MMCA.Common/Source/Presentation/MMCA.Common.API/DependencyInjection.cs:125-135, the source at :129-133). AddErrorLocalization() is called automatically from AddAPI (DependencyInjection.cs:113), so no host has to opt in.
    2. Source construction. The generic AddErrorResources<TResource>() registers a singleton factory that resolves IStringLocalizerFactory, calls Create(typeof(TResource)), and wraps the result in an ErrorResourceSource (DependencyInjection.cs:144-148). ErrorResources does not go through that method: AddErrorLocalization() builds the framework's source directly and marks it IsFramework = true (DependencyInjection.cs:129-133), while each module passes its own anchor to AddErrorResources<TResource>(), which is why translations are additive rather than an edit to a framework file.
    3. Lookup. ErrorLocalizer snapshots the registered sources with every module source first, in registration order, and the IsFramework source last (MMCA.Common/Source/Presentation/MMCA.Common.API/Localization/ErrorLocalizer.cs:15-16, so a module's translation of a code wins and Common's set is the fallback), returns the caller's fallback immediately for an empty code (ErrorLocalizer.cs:21-24), then walks the sources and returns the first hit whose ResourceNotFound is false (:26-33). A code no source knows falls through to the original English message (:35), so an untranslated code degrades instead of throwing or rendering a key.
  • Why it's built this way: see ADR-027 (multi-locale i18n). Localizing at the HTTP edge rather than inside the domain keeps Error.Code and the fallback message culture-free all the way through the Application layer, and one anchor per resource set turns "add Spanish for my module's errors" into a new resx plus one AddErrorResources<T>() call instead of a merge into shared framework resources.
  • Where it's used: registered as the framework's own source at MMCA.Common/Source/Presentation/MMCA.Common.API/DependencyInjection.cs:129-133. The text it supplies reaches clients through three call sites that resolve IErrorLocalizer from the request container: ApiControllerBase when it turns a failed Result into a response (Controllers/ApiControllerBase.cs:72), UnhandledResultFailureFilter (Middleware/UnhandledResultFailureFilter.cs:46), and SupportsIfMatchAttribute when it shapes a precondition failure (Concurrency/SupportsIfMatchAttribute.cs:268); all three hand the localizer to ErrorHttpMapping.BuildErrorsExtension (Middleware/ErrorHttpMapping.cs:65), which is where the code-to-text substitution happens. Module anchors follow the same shape: ConferenceErrorResources, EngagementErrorResources, and IdentityErrorResources.
  • Caveats / not-in-source: the class file tells you nothing about which codes are covered. The key set lives in the two resx assets beside it (154 <data> entries each today, the same count in English and Spanish), and nothing in this type enforces that the two files stay in sync or that every framework Error.Code has an entry.

OptInActionAttribute

MMCA.Common.API · MMCA.Common.API.Pagination · MMCA.Common/Source/Presentation/MMCA.Common.API/Pagination/OptInActionAttribute.cs:17 · Level 0 · class (internal sealed)

  • What it is: a method attribute that is also an MVC IActionModelConvention. Placed on a base-controller action, it removes that action from the application model of every controller that does not carry a named opt-in attribute, so the endpoint exists only where a controller asked for it.
  • Depends on: Microsoft.AspNetCore.Mvc.ApplicationModels (ActionModel, IActionModelConvention; OptInActionAttribute.cs:1), nothing first-party. The opt-in markers it is given today are SupportsCursorPagingAttribute and SupportsChangeFeedAttribute.
  • Concept introduced (an action convention as an opt-in switch). A generic base controller such as EntityControllerBase can declare an action once for every entity, but not every entity should expose it. MVC runs each IActionModelConvention found on an action while it builds the application model, before routing and the API explorer read that model, so a convention that deletes the action leaves no route and no API description behind. The doc states the consequence (OptInActionAttribute.cs:10-14): a controller that did not opt in is documented exactly as if the action did not exist, and because the convention is read off the base action, an override that does not opt in is removed as well. [Rubric §9, API & Contract Design] assesses whether the published contract matches what a resource actually supports: here an un-opted controller's OpenAPI document is unchanged rather than listing an endpoint that would answer 500.
  • Walkthrough
    • [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)] (OptInActionAttribute.cs:16) and a primary constructor taking the opt-in attribute type (:17).
    • OptInAttributeType (:20) stores that type, throwing ArgumentNullException for null.
    • Apply(ActionModel) (:24-33) null-guards the action (:26), returns early when the action has no controller or when any of controller.Attributes is an instance of OptInAttributeType (:28-30), and otherwise calls controller.Actions.Remove(action) (:32). IsInstanceOfType means a marker inherited from an abstract base controller counts, since controller.Attributes carries inherited attributes (doc :5-8).
  • Why it's built this way: one generic convention parameterized by a Type keeps each feature's switch a body-less public marker class while the mechanism stays internal (:17), so consumers see only the markers. Removing the action at model-build time, rather than returning 404 at request time, is what keeps the API document honest for both opted-in and un-opted controllers. See ADR-145 (opt-in cursor paging) and ADR-144 (delta reads).
  • Where it's used: on two actions of EntityControllerBase: GetCursorPageAsync with [OptInAction(typeof(SupportsCursorPagingAttribute))] (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/EntityControllerBase.cs:416-417) and GetChangesAsync with [OptInAction(typeof(SupportsChangeFeedAttribute))] (EntityControllerBase.cs:469-470). Exercised by MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/Controllers/EntityControllerBaseCursorTests.cs and EntityControllerBaseChangeFeedTests.cs in the same folder.

RateLimitAlgorithm

MMCA.Common.API · MMCA.Common.API.RateLimiting · MMCA.Common/Source/Presentation/MMCA.Common.API/RateLimiting/RateLimitAlgorithm.cs:8 · Level 0 · enum

  • What it is: a two-value enum selecting the limiting algorithm used by the in-memory rate-limit partitions that AddCommonRateLimiting registers.
  • Depends on: nothing. Read by RateLimitingSettings.Algorithm and switched on inside WebApplicationBuilderExtensions.CreateLimitedPartition.
  • Concept (naming the window-replenishment trade). Both values use the same one-minute window and the same partition keys, so switching between them changes only how permits are replenished (RateLimitAlgorithm.cs:3-7). [Rubric §12, Performance & Scalability] assesses whether a throttle is understood rather than guessed: the two doc comments state the trade in one sentence each, which is what makes the setting safe to move in production.
  • Walkthrough
    • FixedWindow (RateLimitAlgorithm.cs:15) is the default and the cheapest to run: the whole allowance becomes available again at the window boundary, which lets a caller spend the allowance twice across a boundary, once at the end of one window and once at the start of the next (:10-14).
    • SlidingWindow (:22) divides the one-minute window into SegmentsPerWindow segments and returns each segment's permits as it ages out, smoothing that boundary burst away at the cost of tracking one counter per segment (:17-21).
  • Why it's built this way: an enum rather than a boolean keeps the configuration self-describing in appsettings.json ("Algorithm": "SlidingWindow") and leaves room for a third algorithm without a breaking rename. The distributed Redis path is deliberately not an algorithm value: it is the separate Distributed flag on RateLimitingSettings, because it changes where the counter lives rather than how it replenishes, and RedisFixedWindowRateLimiter implements only the fixed window.
  • Where it's used: RateLimitingSettings.Algorithm defaults it to FixedWindow (MMCA.Common/Source/Presentation/MMCA.Common.API/RateLimiting/RateLimitingSettings.cs:49), and CreateLimitedPartition branches on it (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/WebApplicationBuilderExtensions.RateLimiting.cs:287) to build either a SlidingWindowRateLimiterOptions partition (:239-246) or a FixedWindowRateLimiterOptions one (:249-255).

RedisRateLimitLease

MMCA.Common.API · MMCA.Common.API.RateLimiting · MMCA.Common/Source/Presentation/MMCA.Common.API/RateLimiting/RedisFixedWindowRateLimiter.cs:305 · Level 0 · class (internal sealed)

  • What it is: the lease type RedisFixedWindowRateLimiter hands back: two shared instances, Acquired and Undecided, plus a Rejected(TimeSpan?) factory that allocates a refusal carrying a retry-after hint.
  • Depends on: System.Threading.RateLimiting.RateLimitLease (BCL abstract base) and its MetadataName.RetryAfter key. It lives in the same file as the limiter that produces it.
  • Concept (share the stateless leases, allocate the one that carries data). ASP.NET Core's rate-limiting middleware asks a limiter for a RateLimitLease on every request and disposes it afterwards. A lease with no metadata can be one shared immutable instance; a lease that carries a value has to be allocated per call. The doc states the split directly (RedisFixedWindowRateLimiter.cs:298-304): Acquired and Undecided are stateless and shared by every request, while a rejection is allocated per call because it carries MetadataName.RetryAfter, the time until the partition's window resets, which the rate-limiter OnRejected callback turns into the 429's Retry-After header. [Rubric §12, Performance & Scalability] assesses allocation on a per-request hot path: the permitted path (the common one) allocates nothing, and only a refused request pays for a lease.
  • Walkthrough: RetryAfterMetadataNames (RedisFixedWindowRateLimiter.cs:307) is a static one-element array holding MetadataName.RetryAfter.Name. Acquired = new(isAcquired: true, retryAfter: null) (:219) and Undecided = new(isAcquired: false, retryAfter: null) (:226) are the two shared instances. Undecided is not acquired yet is kept distinct from a rejection: it is what the synchronous path returns, so the middleware falls through to the asynchronous path, and because nothing was counted and nothing was refused it carries no retry-after metadata (:221-225). The private constructor sets IsAcquired and the _retryAfter field (:228, :230-234). IsAcquired is an override with a get-only auto property (:237). MetadataNames returns an empty collection when _retryAfter is null and RetryAfterMetadataNames otherwise (:240). Rejected(TimeSpan? retryAfter) (:250) is the internal static factory for an exhausted window; its doc says a null hint means no later window can satisfy the request (:242-249). TryGetMetadata (:253) returns the TimeSpan and true only when a hint is present and the requested name ordinally equals MetadataName.RetryAfter.Name (:255-260); otherwise it nulls the out parameter and returns false (:262-263).
  • Why it's built this way: internal sealed (:214) keeps it an implementation detail of the limiter. Every instance is immutable, so sharing Acquired and Undecided across concurrent requests is safe by construction and there is no dispose-time state to reset. Reporting the hint through the BCL's standard MetadataName.RetryAfter rather than a custom key is what lets the framework's generic OnRejected wrapper read it without knowing which limiter refused the request.
  • Where it's used: returned by RedisFixedWindowRateLimiter from AttemptAcquireCore (:145, always Undecided) and from AcquireAsyncCore on all three of its outcomes: the oversized request (:159, Rejected(retryAfter: null)), the counted decision (:175-177, Acquired or Rejected(TimeUntilNextWindow(now, window))), and the fail-open path after a Redis fault (:186, Acquired). Its hint is read by RetryAfterRejection.WithRetryAfterHeader (MMCA.Common/Source/Build/RateLimiting/RetryAfterRejection.cs:42-52), which AddCommonRateLimiting installs as the OnRejected callback (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/WebApplicationBuilderExtensions.RateLimiting.cs:451) and which formats it through its own Format (RetryAfterRejection.cs:27-31), a test-pinned copy of RetryAfterHeader.Format (RetryAfterRejection.cs:15-17).

SupportsChangeFeedAttribute

MMCA.Common.API · MMCA.Common.API.Pagination · MMCA.Common/Source/Presentation/MMCA.Common.API/Pagination/SupportsChangeFeedAttribute.cs:14 · Level 0 · class (sealed)

  • What it is: a body-less marker attribute (public sealed class SupportsChangeFeedAttribute : Attribute;, SupportsChangeFeedAttribute.cs:14) that opts an entity controller in to the change-feed action, GET {controller}/changes?since=&cursor=&pageSize=, served by EntityControllerBase.GetChangesAsync: the rows changed at or after since, with soft-deleted rows returned as tombstones (doc :3-8).
  • Depends on: nothing; it has no members. OptInActionAttribute reads it.
  • Concept: the change feed is the delta-read half of ADR-144: an offline client keeps the largest changedOn it has seen and asks only for what moved since (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/EntityControllerBase.cs:447-468). It is opt-in per controller through the OptInActionAttribute convention, so a controller without the marker has no such endpoint and an unchanged API document (SupportsChangeFeedAttribute.cs:7). [Rubric §9, API & Contract Design].
  • Walkthrough: [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)] (:13). Inherited = true is what makes the remark at :10 work: declared on an abstract base controller it opts in every controller derived from it.
  • Why it's built this way: the doc remark (:10-11) names the dependency the marker turns on: the query service's GetChangesSinceAsync serves the page, and a service that predates it answers 500. Keeping the action opt-in is what stops that 500 from appearing on every entity controller by default.
  • Where it's used: named by [OptInAction(typeof(SupportsChangeFeedAttribute))] on GetChangesAsync (EntityControllerBase.cs:469-470) and referenced in that action's doc (:451). No controller in MMCA.Common/Source or MMCA.ADC/Source carries it today; it is exercised by MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/Controllers/EntityControllerBaseChangeFeedTests.cs.

SupportsCursorPagingAttribute

MMCA.Common.API · MMCA.Common.API.Pagination · MMCA.Common/Source/Presentation/MMCA.Common.API/Pagination/SupportsCursorPagingAttribute.cs:14 · Level 0 · class (sealed)

  • What it is: a body-less marker attribute (public sealed class SupportsCursorPagingAttribute : Attribute;, SupportsCursorPagingAttribute.cs:14) that opts an entity controller in to the cursor (keyset) list action, GET {controller}/cursor?sortColumn=&sortDirection=&cursor=&pageSize=, served by EntityControllerBase.GetCursorPageAsync (doc :3-8).
  • Depends on: nothing; it has no members. OptInActionAttribute reads it.
  • Concept: keyset ("seek") paging returns the rows after an opaque cursor, ordered by a sort column with Id as tie-break, so a deep page costs the same as the first one (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/EntityControllerBase.cs:400-415). Unlike the offset-paged list there is no total, no pagination header, no field projection, no includes and no filter dictionary (EntityControllerBase.cs:412-414). It is opt-in per controller (ADR-145), so a controller without the marker has no such endpoint and an unchanged API document (SupportsCursorPagingAttribute.cs:6-7). [Rubric §12, Performance & Scalability] assesses whether large reads stay bounded; [Rubric §9, API & Contract Design] applies because the endpoint is advertised only where it is served.
  • Walkthrough: [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)] (:13); declared on an abstract base controller it opts in every controller derived from it (:10).
  • Why it's built this way: the remark (:10-11) records the reason it is a switch rather than always on: the query service's GetPageByCursorAsync serves the page, and a service that predates it answers 500.
  • Where it's used: named by [OptInAction(typeof(SupportsCursorPagingAttribute))] on GetCursorPageAsync (EntityControllerBase.cs:416-417) and referenced in that action's doc (:403). No controller in MMCA.Common/Source or MMCA.ADC/Source carries it today; it is exercised by MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/Controllers/EntityControllerBaseCursorTests.cs.

ApiParameterDescriptorBackfillProvider

MMCA.Common.API · MMCA.Common.API.OpenApi · MMCA.Common/Source/Presentation/MMCA.Common.API/OpenApi/ApiParameterDescriptorBackfillProvider.cs:43 · Level 0 · class (internal sealed)

  • What it is: a defensive IApiDescriptionProvider that walks every API description MVC produced and fills in a placeholder ParameterDescriptor wherever the API explorer left one null, so an OpenAPI transformer that dereferences the property cannot turn document generation into a 500.
  • Depends on: Microsoft.AspNetCore.Mvc.Abstractions.ParameterDescriptor and Microsoft.AspNetCore.Mvc.ApiExplorer.IApiDescriptionProvider (ASP.NET Core), nothing first-party. Registered by AddCommonApiVersioning() and AddCommonOpenApi() on WebApplicationBuilderExtensions.
  • Concept introduced: the API-explorer provider chain as a repair point. MVC builds its OpenAPI input (the ApiDescription list) by running a chain of IApiDescriptionProvider instances; OnProvidersExecuting runs in ascending Order, OnProvidersExecuted in descending order, so the lowest order gets the last word (MMCA.Common/Source/Presentation/MMCA.Common.API/OpenApi/ApiParameterDescriptorBackfillProvider.cs:34-41). That makes the chain a legitimate place to normalize data other components will read. [Rubric §9, API & Contract Design] assesses whether the machine-readable contract is dependable: here the whole point is that GET /openapi/{documentName}.json must not fail for a consumer that adopts URL-segment versioning. [Rubric §32, Dependency & Supply-Chain] assesses what a framework does about defects in packages it forces on its consumers: this is a local guard around a third-party bug, written so it can be deleted without a behavior change once upstream adds the null check.
  • Walkthrough
    • Order => int.MinValue (ApiParameterDescriptorBackfillProvider.cs:46): last to observe the results, so it sees the parameters VersionedApiDescriptionProvider contributed as well as MVC's own.
    • OnProvidersExecuting (ApiParameterDescriptorBackfillProvider.cs:49-53) is intentionally empty, and the comment says why (:51-52): the descriptions this guard repairs do not exist yet at that point.
    • OnProvidersExecuted (ApiParameterDescriptorBackfillProvider.cs:56) null-guards the context (:58), flattens context.Results.SelectMany(description => description.ParameterDescriptions) (:60) and applies parameter.ParameterDescriptor ??= new ParameterDescriptor { ... } (:65-71). The ??= is the load-bearing operator: an existing descriptor (a ControllerParameterDescriptor, which carries the ParameterInfo that XML-comment lookups prefer) is never replaced, and the comment states that rule explicitly (:62-64). The synthesized replacement takes parameter.Name ?? string.Empty (:67), and the type falls back through parameter.Type, then ModelMetadata?.ModelType, then typeof(string) (:68-70).
  • Why it's built this way: the class remarks (ApiParameterDescriptorBackfillProvider.cs:12-42) document the exact failure it guards. MVC leaves ParameterDescriptor null for a route-template token with no matching action parameter (normal for [Route("api/v{version:apiVersion}/orders")] or [Route("api/{tenant}/orders")]), while Asp.Versioning.OpenApi 10.2.1 reads arg.ParameterDescriptor.Name without a null check (:21-27). The fix is deliberately general (any unbound route token, not just the version token) so a {tenant} or {region} segment is covered by the same guard (:28-33).
  • Where it's used: registered once through the private AddApiParameterDescriptorBackfill() helper (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/WebApplicationBuilderExtensions.cs:132-134), which uses TryAddEnumerable so calling both AddCommonApiVersioning() (WebApplicationBuilderExtensions.cs:39, which calls the helper at :261) and AddCommonOpenApi() (:403, calling at :406) still yields exactly one instance. The de-duplication rationale is on the helper's own doc (:411-417).

McpCallerKey

MMCA.Common.API · MMCA.Common.API.RateLimiting · MMCA.Common/Source/Presentation/MMCA.Common.API/RateLimiting/McpCallerKey.cs:23 · Level 1 · class (internal static)

  • What it is: the one function that decides who an MCP caller is for rate limiting. Both MCP limiters partition by it: the endpoint-wide mcp rate-limit policy and the per-tool limit in MMCA.Common.Mcp (Mcp:Tools:<name>:PermitsPerMinute), so a caller is the same partition at both (MMCA.Common/Source/Presentation/MMCA.Common.API/RateLimiting/McpCallerKey.cs:8-14).
  • Depends on: ClaimsPrincipalExtensions.FindUserIdValue (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/ClaimsPrincipalExtensions.cs:26) for the subject claim, and ClientAddressKey (MMCA.Common/Source/Build/RateLimiting/ClientAddressKey.cs:31, linked into this package at MMCA.Common/Source/Presentation/MMCA.Common.API/MMCA.Common.API.csproj:41) for the address fallback; BCL ClaimsPrincipal and IPAddress (McpCallerKey.cs:1-4).
  • Concept introduced (one caller key shared by two limiters). When two limiters guard the same caller at different granularities (here the whole endpoint and one tool), they must agree on what "one caller" means, or a client can fill one window under one key while the other limiter counts it under a different one. The type doc states the goal directly: the per-tool window "can never be dodged by a key the endpoint reads differently" (McpCallerKey.cs:11-13). [Rubric §3, DRY] applies because the precedence chain lives once instead of being restated in MMCA.Common.Mcp. The second decision is what an unattributable caller gets: it is limited in one shared bucket, not waved through (McpCallerKey.cs:18-21). Behind the gateway every request carries a remote address, so a request with none is an in-process host or a misconfigured proxy, and either should share one window rather than escape limiting. That is the opposite choice from the auth-ip and wellknown policies, which give a null client IP no limiter at all (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/WebApplicationBuilderExtensions.RateLimiting.cs:338-339, :360-361). [Rubric §12, Performance & Scalability] assesses whether a throttle covers every path into an expensive endpoint; an MCP tool call is a module query, so no caller shape escapes metering.
  • Walkthrough
    • Unattributable (McpCallerKey.cs:26) is the internal const partition key "__unattributable-mcp-caller" shared by every caller with no user and no remote address.
    • For(ClaimsPrincipal? user, IPAddress? remoteIpAddress) (McpCallerKey.cs:32-36) is a single null-coalescing chain: the user id (user.FindUserIdValue(), the subject claim), else user?.Identity?.Name, else ClientAddressKey.For(remoteIpAddress) (IPv6 masked to /64, IPv4-mapped addresses unmapped, doc :16-17), else Unattributable. The result is never null (:31). The subject claim leads for the same reason it leads in the global partition: it is unique per account, while a name claim can be shared (WebApplicationBuilderExtensions.RateLimiting.cs:154-155).
  • Why it's built this way: the global partition builds a near-identical chain inline but ends in a plain "authenticated" bucket (WebApplicationBuilderExtensions.RateLimiting.cs:178-181), because it only ever sees authenticated callers. The MCP endpoint also serves anonymous callers of public tools, so the key needed its own fallback and its own home that a second package can call. It stays internal (McpCallerKey.cs:21): MMCA.Common.API.csproj grants InternalsVisibleTo to the test project and to MMCA.Common.Mcp for exactly this type (MMCA.Common.API.csproj:30-33), so the key is shared without becoming public API. See ADR-138 (the MCP endpoint) and ADR-019 (rate limiting).
  • Where it's used: McpRateLimitPartition keys the mcp policy with McpCallerKey.For(httpContext.User, httpContext.Connection.RemoteIpAddress) (WebApplicationBuilderExtensions.RateLimiting.cs:203-211, the call at :206, doc :193-202), registered in AddCommonRateLimiting(RateLimitingSettings) at :458. In MMCA.Common.Mcp, McpToolGovernance.CallerKey calls it with the request's remote address from IHttpContextAccessor (MMCA.Common/Source/Presentation/MMCA.Common.Mcp/McpToolGovernance.cs:148-149) and hands the result to the per-tool limiter (MMCA.Common/Source/Presentation/MMCA.Common.Mcp/McpToolRateLimiter.cs:29). Exercised by MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/RateLimiting/McpCallerKeyTests.cs and MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/Startup/RateLimitPartitionTests.cs.

RateLimitingSettings

MMCA.Common.API · MMCA.Common.API.RateLimiting · MMCA.Common/Source/Presentation/MMCA.Common.API/RateLimiting/RateLimitingSettings.cs:21 · Level 1 · class (sealed)

  • What it is: the options object bound from the RateLimiting configuration section. It carries five permit counts (global, auth-ip, mcp, anonymous hub and wellknown), the algorithm choice, the sliding-window segment count, the hub path prefixes that get anonymous metering, and the flag that moves the counter into Redis.
  • Depends on: RateLimitAlgorithm for the Algorithm property; System.ComponentModel.DataAnnotations for the [Range] attributes (RateLimitingSettings.cs:1). Consumed by WebApplicationBuilderExtensions.AddCommonRateLimiting and, through the permit limit it is handed, by RedisFixedWindowRateLimiter.
  • Concept (settings that cannot change behavior by existing). The load-bearing property of this class is stated in its own doc comment (RateLimitingSettings.cs:5-10): every property defaults to the value the parameterized AddCommonRateLimiting overload has always used, so the section is optional in appsettings.json and a host that omits it keeps the previous behavior exactly. The doc's own example (:11-20) sets only GlobalPermitLimit, Algorithm, SegmentsPerWindow and Distributed. That is what made the settings-driven overload safe to add to a framework whose consumers upgrade in lockstep (ADR-016 for the sweep rule, ADR-019 for the limiter itself). [Rubric §17, DevOps & Deployment] assesses whether a cross-cutting concern is configurable without becoming mandatory; [Rubric §17, DevOps] applies because moving a limit is a config change rather than a release. The [Range] attributes make an impossible value a startup failure rather than a runtime surprise: the configuration overload binds the section with ValidateDataAnnotations().ValidateOnStart() (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/WebApplicationBuilderExtensions.RateLimiting.cs:422-425), the same discipline IdempotencySettings uses.
  • Walkthrough
    • SectionName = "RateLimiting" (RateLimitingSettings.cs:24) is a public static readonly string, the binding key as a symbol rather than a literal repeated at the call site.
    • Three bounded, init-only permit counts, each [Range(1, 1_000_000)]: GlobalPermitLimit 300 per authenticated user for the always-on global limiter (:27-28), AuthIpPermitLimit 30 per client IP for the auth-ip policy that throttles anonymous authentication attempts (:34-35), and McpPermitLimit 60 for the mcp policy on the MCP endpoint, keyed per user (subject claim, then name) or, for an anonymous caller, per client IP, where one tool call is one request and a client also lists tools (:37-43, ADR-138); the key itself is McpCallerKey, which also puts a caller with neither a user nor an address into one shared bucket. There is no queue-depth setting: every partition is built with queueLimit: 0.
    • Algorithm (:49) defaults to RateLimitAlgorithm.FixedWindow, which is what the framework has always used; SegmentsPerWindow (:58, [Range(1, 60)], default 4) is the number of segments the one-minute window is divided into when the algorithm is SlidingWindow, and is ignored otherwise (:51-56).
    • Distributed (:68, default false) is the interesting one. Its doc (:60-67) states the whole contract: it makes the global limiter, the anonymous hub partition, the mcp policy and the auth-ip policy count against a shared Redis counter instead of per-instance memory, so a limit means the same thing behind a load balancer as it does on one node; it requires an IConnectionMultiplexer in the container, and when none is registered the limiters silently fall back to the in-memory behavior rather than failing startup. A Redis fault at runtime splits the four: the first three fail open, while auth-ip keeps counting per instance until Redis recovers (:65-66). The doc names four, but the wellknown partition is built by the same CreateLimitedPartition factory, so it shares the Redis counter too and fails open on a fault (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/WebApplicationBuilderExtensions.RateLimiting.cs:362-369).
    • HubPathPrefixes (:87, default ["/hubs"]) and AnonymousHubPermitLimit (:95, [Range(1, 1_000_000)], default 60) are a pair added for SEC-ADC-25 (RateLimitingSettings.cs:70-87, :89-95). The global limiter exempts anonymous callers everywhere else on purpose (public reads are output-cached, server-rendered Blazor traffic shares one host IP); a real-time hub is the exception, because a gateway that bypasses /hubs at the edge (ADR-024 requires it, since the hub authenticates from a query-string token the edge cannot read) left anonymous /hubs/*/negotiate traffic metered nowhere. HubPathPrefixes names which paths get that anonymous-IP metering, and AnonymousHubPermitLimit is deliberately generous, since one browser tab reconnecting behind a flaky network legitimately negotiates several times a minute.
    • WellKnownPermitLimit (:105, [Range(1, 1_000_000)], default 60) is the per-client-IP budget for the wellknown policy that the JWKS (/.well-known/jwks.json) and OpenID discovery (/.well-known/openid-configuration) endpoints carry, anonymous or not (:97-103). It is generous because token validators cache both documents and a fleet of replicas behind one address refreshes them together; a caller with no resolvable client IP is not limited.
  • Why it's built this way: bundling the knobs into one bound object is what let AddCommonRateLimiting grow a configuration overload without changing the two-parameter one, and the "same defaults" rule means the overloads are observationally identical for a host that configures nothing (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/WebApplicationBuilderExtensions.RateLimiting.cs:403-408, AddCommonRateLimiting(int globalPermitLimit = 300, int authIpPermitLimit = 30), builds an instance from its two parameters). The fall-back-rather-than-fail choice on Distributed is deliberate: a rate limiter that refuses to start is a worse outage than one that limits per instance. The runtime fault split follows the same reasoning per policy: capacity protection must never reject a healthy request, but a login throttle that fails open for the length of an outage is a worse trade than one that keeps counting locally (WebApplicationBuilderExtensions.RateLimiting.cs:240-245). The AuthIpPermitLimit default of 30 is itself argued in the overload's parameter doc (WebApplicationBuilderExtensions.RateLimiting.cs:395-402): Blazor Server circuits issue the login call server-side, so every Server-circuit user shares the UI host's IP and a tighter cap would throttle real logins.
  • Where it's used: bound in AddCommonRateLimiting(IConfiguration) (WebApplicationBuilderExtensions.RateLimiting.cs:418-430), which registers validated options for the section and builds the instance with section.Get<RateLimitingSettings>() ?? new RateLimitingSettings() (:427), then hands it to AddCommonRateLimiting(RateLimitingSettings) (:441-478). That overload threads it through every partition selector: the global limiter (GlobalRateLimitPartition, :166-191, registered at :453-454), the mcp policy (McpRateLimitPartition, :203-211, registered at :458, reads McpPermitLimit at :208), the auth-ip policy (AuthIpRateLimitPartition, :333-348, registered at :468-470, the only caller passing countLocallyOnRedisFault: true at :347) and the wellknown policy (WellKnownRateLimitPartition, :356-370, registered at :474-476, reads WellKnownPermitLimit at :366). Each ends in CreateLimitedPartition (:246), which reads Distributed (:255), Algorithm (:287) and SegmentsPerWindow (:292). HubPathPrefixes and AnonymousHubPermitLimit are read by AnonymousPartition (WebApplicationBuilderExtensions.RateLimiting.cs:86-96) and IsAnonymousHubRequest (:106-116, internal so InternalsVisibleTo lets it be unit-tested directly): an unauthenticated request that matches a hub prefix is metered per client IP through CreateLimitedPartition with redisScope: "hub" and countLocallyOnRedisFault: false (:88-95); every other anonymous request keeps taking RateLimitPartition.GetNoLimiter("__anonymous") (:96).

RedisFixedWindowRateLimiter

MMCA.Common.API · MMCA.Common.API.RateLimiting · MMCA.Common/Source/Presentation/MMCA.Common.API/RateLimiting/RedisFixedWindowRateLimiter.cs:52 · Level 1 · class (sealed, partial)

  • What it is: a RateLimiter that counts a fixed one-minute window in Redis, so every instance behind a load balancer shares one allowance per partition instead of each getting its own.
  • Depends on: StackExchange.Redis.IConnectionMultiplexer, System.Threading.RateLimiting.RateLimiter, TimeProvider, and ILogger with a source-generated [LoggerMessage] partial (RedisFixedWindowRateLimiter.cs:1-6), RedisCounterScript for the shared increment script (MMCA.Common/Source/Build/Redis/RedisCounterScript.cs:15), and RedisOutageCircuit for the per-connection open-circuit window (MMCA.Common/Source/Build/Redis/RedisOutageCircuit.cs:27). It hands back RedisRateLimitLease leases (the shared Acquired and Undecided instances, and a per-call Rejected(TimeSpan?)) and is selected by RateLimitingSettings.Distributed.
  • Concept introduced (a distributed counter, and the honest compromises it makes). A per-process limiter means "300 requests a minute" actually means 300 times the replica count, which is not the number an operator configured. Moving the counter to Redis fixes that, and the type doc records the trades it accepts to do so, plus the one policy that answers a fault differently.
    1. Layering (RedisFixedWindowRateLimiter.cs:18-23): the limiter lives in MMCA.Common.API rather than behind an abstraction implemented in Infrastructure, because API already references Infrastructure (which owns the StackExchange.Redis dependency), so using the client here adds no new dependency edge and breaks no rule in MMCA.Common.LayerEnforcement.targets. An extra interface plus an Infrastructure implementation would buy nothing but indirection, since the limiter is a presentation concern only the rate-limiting middleware constructs. [Rubric §3, Clean Architecture] assesses whether a layer boundary is respected and whether an abstraction is added where it earns its keep; this is the second half.
    2. Storage and precision (:26-36): one key per partition per window, rl:{partitionKey}:{unixMinute}, where the partition key already carries {application namespace}:{scope}: so two MMCA applications on one Redis do not share a counter by default (the namespace defaults to the host's application name, so two hosts deliberately given the same Application:Namespace do share counters, :28-29), incremented and given a TTL slightly longer than the window on the increment that creates it. Increment and TTL happen as one atomic server-side Lua step (RedisCounterScript.Increment, MMCA.Common/Source/Build/Redis/RedisCounterScript.cs:24-27, one linked internal source shared with the framework's counter store), so a fault cannot leave a counter key without an expiry. Keys expire on their own so nothing has to sweep them, and a window rollover is a new key rather than a reset. The counter is still not transactional with the permit decision (the script returns the count, the limiter then compares), which can let a burst arriving in the same instant overshoot the limit slightly; that is the accepted trade for one round trip per request. [Rubric §12, Performance & Scalability].
    3. Fail open (:39-43): any Redis fault permits the request and logs at warning level, at most once per window across the process. Rate limiting protects capacity, so it must never become the reason an otherwise healthy request is rejected. A fault also opens the connection's RedisOutageCircuit: for its window (OpenDuration, 10 seconds, MMCA.Common/Source/Build/Redis/RedisOutageCircuit.cs:30) every request takes the fault answer at once instead of waiting out the client timeout again, and one request probes Redis once the window has passed (RedisFixedWindowRateLimiter.cs:41-43). Without the circuit each call against an unreachable server waited about six seconds for the client to give up before falling back (RedisOutageCircuit.cs:13-19). [Rubric §29, Resilience & Business Continuity].
    4. Count locally instead (:45-50, the auth-ip policy only): a login throttle that fails open for the length of an outage is a worse trade than one that keeps counting in this process, so a limiter built with a local fallback answers a Redis fault from a per-instance count of the same window, rejected with the same Retry-After hint, until Redis answers again. [Rubric §29, Resilience & Business Continuity] again, read the other way: here the failure mode chosen is the one that keeps brute-force protection.
  • Walkthrough
    • One internal constant leads the type: KeyTtlSeconds = 65 (RedisFixedWindowRateLimiter.cs:59). The 65 seconds of skew past the window covers clock drift between instances, since an early-expiring key would hand the partition a fresh allowance inside the same window (:54-58). The Lua script itself lives in RedisCounterScript: INCRBY, then EXPIRE only when the new count is no more than the requested amount (the increment that created the key), because re-stamping the TTL on every request would slide the window forward for a caller who keeps hitting it and the allowance would never reset (MMCA.Common/Source/Build/Redis/RedisCounterScript.cs:17-27).
    • _lastLoggedFailureWindow (RedisFixedWindowRateLimiter.cs:66) is static and initialized to -1: a dead Redis produces one warning a minute for the whole process rather than one per request, and the doc explains that a fault is a property of the connection, which every partition shares (:61-65).
    • Instance fields hold the connection, partition key, permit limit, logger, clock, the _countLocallyOnFault flag and the _circuit (:68-74), plus _lastUsedTimestamp seeded from Stopwatch.GetTimestamp() (:79). Three more fields back the local fallback: a Lock _localGate (:77), _localWindow initialized to -1 (:82) and _localCount (:85).
    • Two constructors. The public one (:101) keeps the original five-parameter shape and chains to the internal one with countLocallyOnFault: false (:107), so a caller outside the framework always gets fail-open behavior; its timeProvider doc names it the substitution point tests use to pin a window (:97-100). The internal one (:124, doc :111-123) adds countLocallyOnFault, guards all four required inputs (:132-135, including ThrowIfLessThan(permitLimit, 1)), defaults timeProvider to TimeProvider.System (:141), stores the flag (:142) and fetches the connection's circuit with RedisOutageCircuit.For(connection) (:143). That lookup goes through a ConditionalWeakTable keyed on the multiplexer (MMCA.Common/Source/Build/Redis/RedisOutageCircuit.cs:32, :40-41), so every partition on one connection shares one circuit, since a fault is a property of the connection.
    • IdleDuration (:152-153) reports Stopwatch.GetElapsedTime(Volatile.Read(ref _lastUsedTimestamp)). The doc (:146-151) explains why it is reported rather than left null: partition keys embed user identity, so never reporting idleness would grow the owning PartitionedRateLimiter table with one entry per user seen since start-up.
    • GetStatistics() (:160) returns null on purpose: the counter lives in Redis and reporting it would cost a round trip per call for a diagnostic the middleware does not require (:155-159).
    • AttemptAcquireCore(int) (:178) stamps the last-used timestamp and returns RedisRateLimitLease.Undecided (:180-181), a lease that is not acquired, without touching Redis. This is load-bearing (doc :162-175): the ASP.NET Core middleware calls the synchronous AttemptAcquire first on every request and calls AcquireAsync only when that lease is not acquired, disposing the synchronous lease without reading its metadata. Granting here would admit every request uncounted so the limit would never be enforced, and deciding here would block a request thread on a Redis round trip. The consequence the doc states: a caller that uses only the synchronous path is always refused, and the middleware is the supported consumer.
    • AcquireAsyncCore (:185) is the real path: stamp the timestamp (:189), then reject outright with RedisRateLimitLease.Rejected(retryAfter: null) when permitCount > _permitLimit (:191-196); the comment (:193-194) explains the missing hint: no later window can hold a request larger than the whole allowance, so telling the client when to come back would be a lie. It reads the clock once into now (:198), computes the window as now.ToUnixTimeSeconds() / 60 (:199) and builds the invariant-culture key (:200). Next comes the circuit check (:202-207): when _circuit.ShouldAttempt(_timeProvider) is false, Redis faulted moments ago, so the limiter answers as a fault would without calling Redis (AcquireLocally with _countLocallyOnFault, otherwise Acquired) and logs nothing, since the fault that opened the circuit already logged. Otherwise it runs ScriptEvaluateAsync(RedisCounterScript.Increment, [key], [permitCount, KeyTtlSeconds]) (:212-215), casts the result to long (:216) and closes the circuit with _circuit.RecordSuccess() (:217). The increment and the conditional TTL are one atomic server-side step. The decision is the final compare (:219-221): Acquired within the limit, otherwise Rejected(TimeUntilNextWindow(now, window)). The catch (:223-244) excludes OperationCanceledException, opens the circuit with _circuit.RecordFault(_timeProvider) (:225) and computes firstInWindow once via Interlocked.Exchange on the static field (:226). With _countLocallyOnFault set it logs the counting-locally warning on the first fault of the window and returns AcquireLocally(permitCount, now, window) (:228-236); otherwise it logs the fail-open warning on the first fault of the window (:238-241) and returns Acquired (:243).
    • AcquireLocally (:256, doc :247-255, private) is the per-instance answer to a fault. Under _localGate (:258) it resets the tally to zero when the window has rolled over (:260-264), rejects with Rejected(TimeUntilNextWindow(now, window)) when the tally plus the request would pass the limit (:266-269), and otherwise adds the permits and returns Acquired (:271-272). The Retry-After hint is therefore the same one the Redis path gives.
    • TimeUntilNextWindow(DateTimeOffset now, long window) (:284-285, internal static) is the retry-after arithmetic: DateTimeOffset.FromUnixTimeSeconds((window + 1) * 60) - now, the time until the next window opens and the partition's allowance resets, in the same unix-minute arithmetic the key uses (doc :276-283). Reusing the now that chose the window keeps the hint consistent with the counter it was refused by.
  • Why it's built this way: partial plus two [LoggerMessage] declarations gives source-generated, allocation-free warnings that name the partition and state plainly what happens until Redis recovers: requests permitted uncounted (LogRedisUnavailable, :287-290) or the limit applied per instance (LogRedisUnavailableCountingLocally, :292-295). The partition key arrives already scoped by the caller (for example {namespace}:global:alice, :92-93) so two policies limiting the same user never share one counter; that scoping is applied in CreateLimitedPartition as $"{RateLimitKeyNamespace(requestServices!)}:{redisScope}:{key}" (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/WebApplicationBuilderExtensions.RateLimiting.cs:275), whose leading namespace (the configured Cache:KeyPrefix without its trailing colon, else the ApplicationNamespace, :219-225) keeps two MMCA apps on one Redis from sharing counters (SEC-Common-53, :268-270). The scopes in use are global, hub, mcp, auth-ip and wellknown (:186, :91, :207, :343, :365). Keeping the fail-open choice on the public constructor and the local-count choice on an internal one means only the framework's own partition factory can opt a partition out of failing open. The circuit is a linked internal source shared with the framework's Redis counter store, and each package holds its own copy of the circuit table, so the store and the limiter open their circuits independently (MMCA.Common/Source/Build/Redis/RedisOutageCircuit.cs:6-9, :21-24).
  • Where it's used: constructed only inside CreateLimitedPartition (WebApplicationBuilderExtensions.RateLimiting.cs:271-279) through the internal constructor, and only when settings.Distributed is true (:255) and an IConnectionMultiplexer resolves (:261-263); the logger falls back to NullLogger when none is registered (:265-266), and RequestServices is read through a nullable local because it is null outside a request pipeline (:257-260). When no multiplexer is registered the code falls through to the in-memory limiters rather than failing startup (:282-284). The factory forwards its countLocallyOnRedisFault argument (documented at :240-245): the global, hub, mcp and wellknown partitions pass false (:190, :95, :211, :369), and the auth-ip policy passes true (WebApplicationBuilderExtensions.RateLimiting.cs:347), so login throttling shares the Redis counter but degrades to a per-instance count, not to no limit, during a Redis outage.

PaginationHeaderExtensions

MMCA.Common.API · MMCA.Common.API.Pagination · MMCA.Common/Source/Presentation/MMCA.Common.API/Pagination/PaginationHeaderExtensions.cs:12 · Level 1 · class (static)

  • What it is: the one place that writes a page's PaginationMetadata onto the HTTP response. A static class with the header-name constant and a single extension(HttpResponse) member.
  • Depends on: PaginationMetadata (the payload), HttpResponse (the extended type), and System.Text.Json (JsonSerializerOptions.Web).
  • Concept (one wire shape for every paged endpoint). [Rubric §3, DRY]: the header name and its serialization options are fixed in one helper, so every paged endpoint emits the same camelCase JSON in the same header and clients parse one shape (PaginationHeaderExtensions.cs:27-30, doc at :34-37).
  • Walkthrough
    • HeaderName = "X-Pagination" (PaginationHeaderExtensions.cs:30) is the public constant clients and tests read.
    • AppendPaginationHeader(PaginationMetadata) (PaginationHeaderExtensions.cs:27-33), declared inside an extension(HttpResponse response) block (:19), null-guards both arguments (:29-30) and appends HeaderName with the metadata serialized using JsonSerializerOptions.Web (:32).
  • Why it's built this way: pulling the append out of individual controllers keeps the header name and casing from drifting between endpoints; the extension block lets callers write Response.AppendPaginationHeader(metadata).
  • Where it's used: the only usage site found in source is its test, MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/Pagination/PaginationHeaderExtensionsTests.cs. Other framework callers: not determinable from the brief's usage sites.

RateLimitPartitions

MMCA.Common.API · MMCA.Common.API.RateLimiting · MMCA.Common/Source/Presentation/MMCA.Common.API/RateLimiting/RateLimitPartitions.cs:11 · Level 2 · class (static)

  • What it is: public partition factories for a host's own rate-limit policies, built on the same limiter AddCommonRateLimiting uses, so a consumer policy answers a rejection the way the framework's policies do (RateLimitPartitions.cs:6-10). It has one factory today, FixedWindowWithRemainingRetryAfter<TKey>.
  • Depends on: System.Threading.RateLimiting (RateLimitPartition, FixedWindowRateLimiterOptions, QueueProcessingOrder) and RemainingWindowFixedWindowRateLimiter, the internal limiter compiled into this package from the linked source MMCA.Common/Source/Build/RateLimiting/RemainingWindowFixedWindowRateLimiter.cs:31 (namespace MMCA.Common.RateLimiting, RateLimitPartitions.cs:2).
  • Concept introduced (an honest Retry-After for host policies). The BCL's RateLimitPartition.GetFixedWindowLimiter stamps every rejection with the whole window length as its MetadataName.RetryAfter hint, so a 429 says "come back in 60 seconds" however much of the minute is left. The framework's own in-memory fixed window does not use it (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/WebApplicationBuilderExtensions.RateLimiting.cs:299-301), and this class gives a host the same partition, so a policy a consumer declares with AddPolicy tells the client how long it actually has to wait (doc RateLimitPartitions.cs:13-20). [Rubric §9, API & Contract Design] assesses whether response headers mean what they say; [Rubric §3, DRY] applies because the host reuses the framework's limiter instead of re-implementing the window arithmetic.
  • Walkthrough
    • FixedWindowWithRemainingRetryAfter<TKey>(TKey partitionKey, int permitLimit, TimeSpan window) (RateLimitPartitions.cs:26-27) is the public entry point; it forwards with timeProvider: null.
    • The internal overload (:39-57) adds a TimeProvider? so tests can drive the hint (doc :29-32). It rejects a non-positive permitLimit (ThrowIfNegativeOrZero, :45) and a non-positive window (:46), then returns RateLimitPartition.Get(partitionKey, _ => new RemainingWindowFixedWindowRateLimiter(...)) (:48-56) with Window, PermitLimit, QueueLimit = 0 and QueueProcessingOrder.OldestFirst (:51-54). With no queue, a request over the limit is rejected at once (doc :18-19).
  • Why it's built this way: the limiter itself is an internal type linked into several packages, so a public static factory is the one supported way for a consumer to reach it without widening the public API to the limiter class. Returning a RateLimitPartition<TKey> lets the result drop straight into a PartitionedRateLimiter.Create or AddPolicy selector (:25).
  • Where it's used: no caller in MMCA.Common/Source or MMCA.ADC/Source; the framework's own partitions build the same limiter directly inside CreateLimitedPartition (WebApplicationBuilderExtensions.RateLimiting.cs:301). It is exercised by MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/RateLimiting/RateLimitPartitionsTests.cs. Consumer callers outside those two trees: not determinable from source read for this unit.

StronglyTypedIdSchemaTransformer

MMCA.Common.API · MMCA.Common.API.OpenApi · MMCA.Common/Source/Presentation/MMCA.Common.API/OpenApi/StronglyTypedIdSchemaTransformer.cs:24 · Level 3 · class (sealed)

  • What it is: an IOpenApiSchemaTransformer that rewrites the OpenAPI schema for a strongly typed identifier (ADR-115) so the generated document describes it as the primitive it wraps (an integer or a string), not as the wrapper's own object shape.
  • Depends on: Microsoft.AspNetCore.OpenApi.IOpenApiSchemaTransformer, Microsoft.OpenApi.Models.OpenApiSchema and JsonSchemaType; the shared StronglyTypedId.TryDescribe helper that both this type and StronglyTypedIdParameterTransformer call to recognize a wrapper and extract its underlying value type.
  • Concept introduced: OpenAPI schema transformers as the escape hatch for a type the JSON pipeline flattens but the schema generator does not. AddStronglyTypedIds teaches System.Text.Json to serialize a wrapper as its bare value, but ASP.NET Core's OpenAPI generator still reflects the wrapper's own properties unless something intervenes; IOpenApiSchemaTransformer is exactly that intervention point, run once per discovered schema. [Rubric §9, API & Contract Design] assesses whether the published contract matches the wire format: without this transformer a client generator would model OrderId as { "value": 123 } instead of a bare integer, which is not what the JSON converter actually emits.
  • Walkthrough: TransformAsync(OpenApiSchema, OpenApiSchemaTransformerContext, CancellationToken) (StronglyTypedIdSchemaTransformer.cs:28-45):
    • Null-guards schema and context (:33-34).
    • StronglyTypedId.TryDescribe(context.JsonTypeInfo.Type, out _, out var valueType) (:36): a no-op return when the schema being generated is not for a strongly typed identifier (:37).
    • For a match, it clears schema.Properties and schema.Required (:39-40), which erases the object shape the reflection-based generator would otherwise have built, then sets schema.Type = MapType(valueType) and schema.Format = MapFormat(valueType) (:41-42).
    • MapType (:47-50, internal static) returns JsonSchemaType.Integer for int/long, else JsonSchemaType.String. MapFormat (:52-61) returns "int32", "int64", "uuid" (for Guid), or null, matching the OpenAPI format vocabulary a client generator already understands.
  • Why it's built this way: both mapping methods are internal static rather than private, so StronglyTypedIdParameterTransformer reuses the identical type/format decision for route and query parameters instead of duplicating the switch; the two transformers can never disagree about how one wrapper renders.
  • Where it's used: registered unconditionally inside AddCommonOpenApi() via options.AddSchemaTransformer(new StronglyTypedIdSchemaTransformer()) on every OpenApiOptions instance (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/WebApplicationBuilderExtensions.cs:118, inside the ConfigureAll<OpenApiOptions> block at :502-506, whose comment states it is inert in a host that declares no wrappers, :498-501). ConfigureAll rather than a single named document is deliberate: AddOpenApi() creates one OpenApiOptions per discovered API version, and the wire shape is identical in every one.

StronglyTypedIdParameterTransformer

MMCA.Common.API · MMCA.Common.API.OpenApi · MMCA.Common/Source/Presentation/MMCA.Common.API/OpenApi/StronglyTypedIdSchemaTransformer.cs:74 · Level 4 · class (sealed)

  • What it is: an IOpenApiOperationTransformer that rewrites the per-operation parameter schema for a strongly typed identifier bound from a route segment or a query string, the operation-level counterpart to StronglyTypedIdSchemaTransformer.
  • Depends on: Microsoft.AspNetCore.OpenApi.IOpenApiOperationTransformer, Microsoft.OpenApi.Models.OpenApiParameter/OpenApiSchema; StronglyTypedIdSchemaTransformer.MapType/.MapFormat for the type/format decision, and StronglyTypedId.TryDescribe to recognize a wrapper.
  • Concept: a component-level schema and a parameter-level schema are generated by two different ASP.NET Core OpenAPI extension points, so fixing the component schema alone leaves an operation's own parameter list still describing the wrapper's object shape; the framework installs one transformer of each kind so both descriptions agree. [Rubric §9, API & Contract Design] applies for the same reason as the sibling type: a client generator reading only the operation's parameters (the common case for a route or query parameter) needs the primitive shape too.
  • Walkthrough: TransformAsync(OpenApiOperation, OpenApiOperationTransformerContext, CancellationToken) (StronglyTypedIdSchemaTransformer.cs:77-109):
    • Null-guards operation and context (:82-83), then exits early when operation.Parameters is null (:85-86).
    • Iterates context.Description.ParameterDescriptions (:88), one entry per bound parameter on the action. For each, it resolves the effective type as described.ModelMetadata?.ModelType ?? described.Type (:90) and skips it when that type is null or is not a strongly typed identifier per StronglyTypedId.TryDescribe (:91-92).
    • Matches the description back to the operation's OpenApiParameter by name: operation.Parameters.OfType<OpenApiParameter>().FirstOrDefault(p => string.Equals(p.Name, described.Name, StringComparison.Ordinal)) (:94-96), and skips a miss (:98-99).
    • Replaces parameter.Schema outright with a new OpenApiSchema { Type = StronglyTypedIdSchemaTransformer.MapType(valueType), Format = StronglyTypedIdSchemaTransformer.MapFormat(valueType) } (:101-105), rather than mutating the existing schema in place, since the wrapper's original parameter schema carries nothing worth preserving.
  • Why it's built this way: reusing the sibling transformer's MapType/MapFormat instead of re-deriving the mapping keeps the component schema and every parameter schema for the same wrapper type identical by construction; there is no separate table to fall out of sync.
  • Where it's used: registered unconditionally alongside its sibling inside AddCommonOpenApi() via options.AddOperationTransformer(new StronglyTypedIdParameterTransformer()) (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/WebApplicationBuilderExtensions.cs:119), inside the same ConfigureAll<OpenApiOptions> block (:502-506) that installs StronglyTypedIdSchemaTransformer.

CommonForwardedHeaders

MMCA.Common.API · MMCA.Common.API.Startup · MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/CommonForwardedHeaders.cs:27 · Level 0 · class (static)

  • What it is: a two-member helper that names the framework's default forwarded-header mask and builds a fresh ForwardedHeadersOptions with that mask and a cleared proxy/network allowlist. It is the shared posture behind ASP.NET Core's own UseForwardedHeaders middleware.
  • Depends on: Microsoft.AspNetCore.HttpOverrides.ForwardedHeaders and ForwardedHeadersOptions only. CommonForwardedHeadersExtensions and MiddlewarePipelineBuilder both call Create.
  • Concept (one named default, cleared allowlists by default). [Rubric §13, Observability & Operability]: forwarded-header handling decides what scheme, host and client address every downstream component sees, so naming the default mask once (X-Forwarded-For, X-Forwarded-Proto, X-Forwarded-Host, CommonForwardedHeaders.cs:31-32) keeps every host consistent instead of re-typing the three-flag combination. Clearing KnownProxies and KnownIPNetworks rather than leaving ASP.NET Core's own defaults in place is deliberate: those lists exist to restrict which upstream hop is trusted, and a containerized host behind Aspire/DCP or an Azure ingress has no fixed proxy IP to allowlist, so the framework accepts the forwarded values from any hop and relies on the ingress topology itself to keep the header trustworthy.
  • Walkthrough
    • DefaultHeaders (:31-32) is a static get-only property returning the three-flag ForwardedHeaders mask.
    • Create(ForwardedHeaders? headers = null) (:40) builds a ForwardedHeadersOptions with ForwardedHeaders = headers ?? DefaultHeaders (:42-45), clears both allowlists (:47-48), and returns the new instance (:50).
  • Why it's built this way: returning a fresh options instance rather than a cached singleton means a caller that mutates the result (adding back a known proxy, say) never affects another caller's options.
  • Where it's used: MiddlewarePipelineBuilder calls CommonForwardedHeaders.Create() for the default pipeline's forwarded-headers step (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/Pipeline/MiddlewarePipelineBuilder.cs:54), and CommonForwardedHeadersExtensions calls it from the UI-host convenience wrapper. Both ADR-079 (shared HTTP middleware pipeline) and ADR-124 (Blazor circuit ceiling and UI edge) discuss forwarded-header handling at the edge.
  • Caveats / not-in-source: nothing here restricts which upstream hop is trusted; that is left entirely to the hosting environment's own network boundary.

JwtAudience

MMCA.Common.API · MMCA.Common.API.Startup.Auth · MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/Auth/JwtAudience.cs:17 · Level 0 · class (static)

  • What it is: the configuration contract for the audience of the access tokens the Identity service mints (JwtAudience.cs:3-7). It names one configuration key and offers one guard that turns a missing value into a startup failure, so every service host that validates those tokens through AddForwardedJwtBearer reads the audience the same way.
  • Depends on: nothing first-party; BCL InvalidOperationException and string only. The file has no using directives. Its sibling in the same folder is JwtAuthorityExtensions, and both feed AddForwardedJwtBearer on WebApplicationBuilderExtensions.
  • Concept, fail fast on missing configuration. The remarks (JwtAudience.cs:8-16) state the failure this prevents: a host that silently fell back to a hard-coded audience would boot with a value nobody configured and answer every request with a 401 "that reads like a token problem instead of a wiring problem." [Rubric §11, Security] assesses token validation correctness: the audience check is only meaningful if the value is deliberately configured, never defaulted. [Rubric §13, Observability & Operability] assesses how quickly a misconfiguration surfaces: throwing at startup with a message that names the key turns a confusing runtime 401 into a boot-time error that says what to set. [Rubric §7, Microservices Readiness]: the type lives in MMCA.Common.API, so each extracted service host consumes one key and one guard rather than re-declaring them.
  • Walkthrough: public const string ConfigKey = "Jwt:Audience" (JwtAudience.cs:20), documented (:19) as Jwt__Audience when supplied as an environment variable. RequireConfigured(string? configuredValue) (:28-32) is an expression-bodied guard: when string.IsNullOrWhiteSpace is true it throws InvalidOperationException with the message "Jwt:Audience is not configured. Set it in the service's appsettings.json or as the Jwt__Audience environment variable." (the key interpolated from ConfigKey); otherwise it returns the value unchanged. Blank and whitespace-only values are rejected exactly like null.
  • Why it's built this way: taking the already-read value (rather than an IConfiguration) keeps the guard a pure function with no framework dependency and trivially unit-testable. The value itself lives only in configuration (each service's appsettings.json and, in Azure, the deployment template, per :9-11). The remarks (:12-15) prescribe the call shape, JwtAudience.RequireConfigured(builder.Configuration[JwtAudience.ConfigKey]), never a ?? fallback, and ForwardedJwtAudienceTestsBase in MMCA.Common.Testing.Architecture pins that shape in each consumer (MMCA.Common/Source/Hosting/MMCA.Common.Testing.Architecture/Bases/Api/ForwardedJwtAudienceTestsBase.cs).
  • Where it's used: the composed service host passes the guarded value as the audience: argument of AddForwardedJwtBearer(...) for every host that is not a token issuer (MMCA.Common/Source/Hosting/MMCA.Common.ServiceHost/ServiceHostBuilderExtensions.cs:138-140), so the three ADC non-Identity service hosts get it through their builder.AddMmcaServiceHost(...) call: MMCA.ADC/Source/Services/MMCA.ADC.Conference.Service/Program.cs:88, MMCA.ADC/Source/Services/MMCA.ADC.Engagement.Service/Program.cs:59 and MMCA.ADC/Source/Services/MMCA.ADC.Notification.Service/Program.cs:58. Unit-tested by MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/Startup/Auth/JwtAudienceTests.cs: a configured value is returned as-is (:14-16), blank or missing values throw naming the key and the environment variable (:18-26), and the key itself is pinned (:30-33). Architecture fixtures exercise the rule in MMCA.Common/Tests/Architecture/MMCA.Common.Architecture.Tests/Api/ForwardedJwtAudienceFitnessTests.cs.
  • Caveats / not-in-source: the Identity service host (the token issuer) does not call this guard in the files inspected; how it sources the audience it stamps into minted tokens is Not determinable from source within this unit.

JwtAuthorityExtensions

MMCA.Common.API · MMCA.Common.API.Startup.Auth · MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/Auth/JwtAuthorityExtensions.cs:15 · Level 0 · class (static, extension block)

  • What it is: a two-member helper that names the one configuration key carrying a service host's JWT/JWKS authority, and reads it with a fail-fast guard. Every extracted service that is not the token issuer calls it immediately before AddForwardedJwtBearer.
  • Depends on: Microsoft.Extensions.Configuration.IConfiguration only. Its consumer is AddForwardedJwtBearer on WebApplicationBuilderExtensions.
  • Concept introduced (fail fast on missing wiring, and hoist the key so it cannot drift). The failure this exists to prevent is diagnostically nasty: a host that boots with no authority configured answers every authenticated request with a 401, which looks like a token problem to whoever is debugging it rather than the wiring problem it actually is (JwtAuthorityExtensions.cs:8-13). Converting that into a startup exception with an actionable message is the whole point. [Rubric §13, Observability & Operability] assesses whether an operator can tell what actually went wrong; the thrown message names both the key and the AppHost call that sets it. [Rubric §34, Architecture Governance & Documentation] also applies: the key string lived inline in five host Program.cs files before it was hoisted here, and the constant is what lets the compiler (and a test) find every consumer if it ever changes.
  • Walkthrough: two members.
    • JwtAuthorityConfigKey (JwtAuthorityExtensions.cs:21, value "Authentication:JwtBearer:Authority"): the key the AppHost's WithJwksDiscovery(identityService, gateway) sets, and that the Azure deployment template sets in production (:17-20).
    • GetRequiredJwtAuthority() (:36), an extension(IConfiguration configuration) member. It null-guards the configuration itself (:38), then reads the key and throws an InvalidOperationException naming the key and the fix ("Wire .WithJwksDiscovery(identityService, gateway) in the AppHost.") when it is absent (:40-43).
  • Why it's built this way: the guard is deliberately a null check, not a blank check, and the member's XML doc now states that contract on its face: a present but blank value is returned as-is (:27-28). A configured-but-empty authority therefore passes through unchanged and is rejected one line later by AddForwardedJwtBearer's own ArgumentException.ThrowIfNullOrWhiteSpace (WebApplicationBuilderExtensions.Authentication.cs:59), so the hoist stayed behavior-identical to the five inline guards it replaced; the test that pins this says so directly (MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/Startup/Auth/JwtAuthorityExtensionsTests.cs:40-45). The key itself is pinned by a second test whose failure message spells out the coupling: WithJwksDiscovery sets Authentication__JwtBearer__Authority, so renaming the key silently breaks every service host (JwtAuthorityExtensionsTests.cs:48-51).
  • Where it's used: the composed service host calls it at its AddForwardedJwtBearer call site (MMCA.Common/Source/Hosting/MMCA.Common.ServiceHost/ServiceHostBuilderExtensions.cs:139), so every non-issuer service host reaches it through builder.AddMmcaServiceHost(...). ADC: Conference (MMCA.ADC/Source/Services/MMCA.ADC.Conference.Service/Program.cs:88), Engagement (:58 of its own Program.cs) and Notification (:58). Store: Sales (MMCA.Store/Source/Services/MMCA.Store.Sales.Service/Program.cs:51) and Catalog (MMCA.Store/Source/Services/MMCA.Store.Catalog.Service/Program.cs:32). The Identity services do not reach it: they set Authentication = ServiceHostAuthentication.TokenIssuer (MMCA.ADC/Source/Services/MMCA.ADC.Identity.Service/Program.cs:114, MMCA.Store/Source/Services/MMCA.Store.Identity.Service/Program.cs:67), issue the tokens and validate in process through AddCommonAuthentication instead (ServiceHostBuilderExtensions.cs:132-135) (ADR-004).
  • Caveats / not-in-source: what value the AppHost or the Azure template actually injects is deployment configuration, not code. This type only guarantees that something was injected.

CommonForwardedHeadersExtensions

MMCA.Common.API · MMCA.Common.API.Startup · MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/CommonForwardedHeadersExtensions.cs:9 · Level 1 · class (static, extension block)

  • What it is: a one-member extension(IApplicationBuilder app) wrapper, UseCommonUiForwardedHeaders, that a server-rendered UI host calls to adopt forwarded headers with the CommonForwardedHeaders posture.
  • Depends on: CommonForwardedHeaders.Create and ASP.NET Core's UseForwardedHeaders extension.
  • Concept (a UI-specific entry point, ordered first). The doc comment (CommonForwardedHeadersExtensions.cs:14-17) states the ordering contract directly: call it FIRST in a server-rendered UI host's pipeline, before anything reads the scheme, the host, or the client address (security headers, rate limiting, HTTPS redirection, antiforgery). [Rubric §13, Observability & Operability] and [Rubric §29, Resilience & Business Continuity] both apply: a UI host that reads the wrong scheme before forwarded headers are adopted can mis-evaluate an HTTPS-only cookie or antiforgery check.
  • Walkthrough: UseCommonUiForwardedHeaders(ForwardedHeaders? headers = null) (:24-25) is a one-line extension member that calls app.UseForwardedHeaders(CommonForwardedHeaders.Create(headers)).
  • Why it's built this way: a named extension on IApplicationBuilder rather than a bare call to CommonForwardedHeaders.Create() plus UseForwardedHeaders gives UI hosts one call to place first, matching the naming convention of the service-host pipeline members on WebApplicationExtensions. CommonForwardedHeaders's own doc comment cross-references this member (CommonForwardedHeaders.cs:9) so a reader lands on the UI-host entry point from either type.
  • Where it's used: the shared Blazor Web pipeline calls it first (MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/Hosting/BlazorWebHostExtensions.cs:185, inside UseMmcaBlazorWebPipeline at :181), so the ADC Blazor UI host gets it through its app.UseMmcaBlazorWebPipeline(...) call (MMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI.Web/Program.cs:120, :130 on the net10.0 line).
  • Caveats / not-in-source: nothing enforces the "call it first" contract; a host that places it later gets whatever scheme and host the raw connection reports until this call runs.

MiniProfilerExtensions

MMCA.Common.API · MMCA.Common.API.Startup · MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/MiniProfilerExtensions.cs:11 · Level 1 · class (static, extension block)

  • What it is: a conditional MiniProfiler registration helper. When ApplicationSettings.UseMiniProfiler is true it registers MiniProfiler plus its Entity Framework integration; otherwise it does nothing.
  • Depends on: ApplicationSettings and StackExchange.Profiling (NuGet).
  • Concept (opt-in, settings-gated profiling). [Rubric §13, Observability & Operability] assesses whether diagnostics exist and whether they cost anything when switched off. One configuration flag turns a cross-cutting profiler on or off with no application code involved, and when off the MiniProfiler services are never registered at all, so there is no middleware and no per-request work.
  • Walkthrough: one public member, AddMiniProfilerIfEnabled(ApplicationSettings) (MiniProfilerExtensions.cs:26). It tests applicationSettings.UseMiniProfiler (:28) and only then calls AddMiniProfiler(...) with a /profiler route base, PopupShowTimeWithChildren and the dark color scheme (:30-34), sets both ResultsAuthorize and ResultsListAuthorize to the private IsDevelopment predicate (:35-36), and chains .AddEntityFramework() (:37) so EF and SQL timings appear inline. It returns services either way (:40) so the call chains. IsDevelopment(HttpRequest) (:45-46) resolves IHostEnvironment from the request's services with GetService, so a missing environment registration reads as "not Development" and the result routes stay closed.
  • Why it's built this way: gating on a settings flag rather than #if DEBUG lets one specific environment (a staging slot, say) enable profiling without a rebuild, while production leaves it off and pays nothing. The result routes are locked to Development by default because a profile shows SQL text and timings (doc comment :17-24); the flag that turns profiling on in a shared environment does not by itself publish those profiles to any caller.
  • Where it's used: the composed service host calls it (MMCA.Common/Source/Hosting/MMCA.Common.ServiceHost/ServiceHostBuilderExtensions.cs:151), passing the ModuleHostContext.ApplicationSettings. AddAPI(...) in MMCA.Common/Source/Presentation/MMCA.Common.API/DependencyInjection.cs does not invoke it, and no ADC or Store source calls it directly; a host reaches it through AddMmcaServiceHost or by calling it itself.
  • Caveats / not-in-source: the helper registers services only; the middleware is mapped elsewhere. Under the same flag the composed service host inserts UseMiniProfiler() right after tenant resolution (MMCA.Common/Source/Hosting/MMCA.Common.ServiceHost/ServiceHostProfiling.cs:24-27), so a host on AddMmcaServiceHost turns profiling on with ApplicationSettings:UseMiniProfiler alone; a host composing its own pipeline calls UseMiniProfiler() itself. The /profiler result routes answer only in Development (401 elsewhere) unless the host overrides MiniProfilerOptions.ResultsAuthorize and ResultsListAuthorize with services.Configure<MiniProfilerOptions>(...) after this call (doc comment MiniProfilerExtensions.cs:17-24). Which deployments set ApplicationSettings:UseMiniProfiler is configuration, not determinable from this source.

JwtKeyStrengthValidator

MMCA.Common.API · MMCA.Common.API.Startup.Auth · MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/Auth/JwtKeyStrengthValidator.cs:22 · Level 3 · class (internal, sealed, partial)

  • What it is: an IValidateOptions<JwtSettings> that measures every configured asymmetric JWT key against the strength floor at startup: an RSA key needs at least Jwt:MinimumRsaKeySizeBits bits, an EC key must sit on P-384. Outside Development a shortfall fails options validation (and with it host startup); in Development it logs one warning and passes.
  • Depends on: JwtSettings (the keys and MinimumRsaKeySizeBits, default 3072 with a [Range(2048, int.MaxValue)] floor, MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/JwtSettings.cs:80-81) and its JwtSigningAlgorithm; JwtAlgorithms (IsAsymmetric, UsesEcKey) and JwtKeyMaterial.StrengthShortfall, which does the actual measuring (MMCA.Common/Source/Build/Auth/JwtKeyMaterial.cs:109); IHostEnvironment, ILogger<T> and the source-generated [LoggerMessage].
  • Concept introduced (a key-strength floor enforced as options validation, relaxed only in Development). [Rubric §11, Security] assesses whether weak cryptographic material can reach production: hooking the check into IValidateOptions<T> means a 2048-bit RSA key or a P-256 EC key fails ValidateOnStart like any other configuration error, before a single token is signed or validated. The same mechanism gives fail-fast configuration (ADR-070): the failure message names the setting that holds the weak key and the setting that sets the floor, so the operator knows which knob to turn. See ADR-149.
  • Walkthrough: one public member, two internal static helpers the JWKS sibling reuses, and one log message.
    • The primary constructor takes the logger and an optional IHostEnvironment (JwtKeyStrengthValidator.cs:22-24). MinimumRsaKeySizeBitsKey (:27, "Jwt:MinimumRsaKeySizeBits") is the configuration key named in every RSA failure.
    • Validate(string?, JwtSettings) (:30) null-guards the options (:32) and returns success at once for HS256, which has no asymmetric key to measure (:34-38). For ES384 it measures Jwt:EcPrivateKeyPem and Jwt:EcPublicKeyPem (:41-45); for RS256 and PS256 it measures Jwt:RsaPrivateKeyPem and Jwt:RsaPublicKeyPem (:46-50), then hands the collected shortfalls to Outcome (:52).
    • AddShortfall(...) (:64) skips a key that is not configured (:71-74), asks JwtKeyMaterial.StrengthShortfall for a description (:76), and words the message by key family: an EC shortfall ends with "{algorithm} requires a P-384 key.", an RSA one with "set by Jwt:MinimumRsaKeySizeBits." (:78-80). StrengthShortfall returns null for a key it cannot read, because reading the key is the loader's check, not this one (JwtKeyMaterial.cs:106-107, :128-131).
    • Outcome(...) (:92) turns the list into the result: success when it is empty (:97-100), one warning plus success in Development (:102-106), otherwise ValidateOptionsResult.Fail(shortfalls) carrying every message (:108).
    • LogWeakKeyInDevelopment (:111-114) is a Warning-level [LoggerMessage] whose text says the key is accepted only because the environment is Development and that outside Development this fails startup.
  • Why it's built this way: an options validator runs where configuration errors already surface, so no separate startup hook is needed, and TryAddEnumerable registration (WebApplicationBuilderExtensions.Authentication.cs:148-149) keeps a host that calls AddCommonAuthentication twice from validating twice. The environment parameter is nullable and the check is environment?.IsDevelopment() == true (:102), so an unknown environment is treated as production: the relaxation is the exception that has to be proven, not the default. AddShortfall and Outcome are internal static rather than private so JwksKeyStrengthValidator applies the same wording and the same Development rule to the JWKS keys instead of restating them.
  • Where it's used: registered only by AddCommonAuthentication on WebApplicationBuilderExtensions (WebApplicationBuilderExtensions.Authentication.cs:148-149), the in-process validation mode; the forwarded JWKS mode (AddForwardedJwtBearer) holds no key and registers neither validator. JwksKeyStrengthValidator calls its two helpers. Startup behavior around the floor is exercised in MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/Startup/Auth/JwtKeyStrengthStartupTests.cs.
  • Caveats / not-in-source: a key that cannot be parsed passes this validator (StrengthShortfall returns null) and is left to the key loader to reject. Which key sizes a given deployment actually configures, and whether any deployment runs as Development, is configuration and not determinable from source.

ModuleHostContext

MMCA.Common.API · MMCA.Common.API.Startup · MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/ModuleHostContext.cs:21 · Level 3 · class (sealed)

  • What it is: the return value of AddModuleHost (see ModuleHostExtensions). It carries the two settings objects a module-hosting service binds once at startup, the ModuleLoader that discovers its modules, and a single method the host registers as a step of its application pipeline to actually run discovery.
  • Depends on: ModuleLoader, ApplicationSettings and ModulesSettings; IConfigurationManager, IServiceCollection and System.Reflection.Assembly from the BCL. It is constructed only by ModuleHostExtensions.
  • Concept introduced (deferring a registration step so the host keeps control of its position). The obvious design would have AddModuleHost bind the settings and run module discovery in one call. It deliberately does not, and the doc comment (ModuleHostContext.cs:11-19) states why: discovery has to happen inside the host's ADR-014 application pipeline, between AddApplication() and AddApplicationDecorators(), so every module's handlers land in the container before the decorator pipeline is closed and sealed. Where discovery sits relative to a host's other pipeline steps (gRPC client replacements, broker messaging) is a per-host decision. So the discovery call is handed back to the host as a void-returning method it can register as a delegate, and the helper stays a settings-and-loader factory. [Rubric §1, SOLID] assesses whether responsibilities are separated: binding and constructing (this call) versus registering handlers at a host-chosen point (a later call) really are two decisions with different owners. [Rubric §15, Best Practices & Code Quality] also applies: pre-capturing the four discovery arguments in the object means a host writes pipeline.Register(moduleHost.RegisterModules) and cannot get the argument list wrong.
  • Walkthrough: two captured fields, three read-only properties, one public method and one internal guard.
    • _configuration and _moduleAssemblies (ModuleHostContext.cs:23-24) are the discovery arguments captured at AddModuleHost time that are not also exposed as properties, so the deferred call needs no state from the caller. No environment name is captured: ModuleLoader.DiscoverAndRegister no longer takes one (doc cref at :54).
    • The internal constructor (:26-38) means only ModuleHostExtensions in the same assembly can build one; a host receives an instance, it never constructs one.
    • ApplicationSettings (:41) and ModulesSettings (:44) expose the bound sections, so the host can pass them onward without re-reading configuration (ADC passes moduleHost.ModulesSettings straight into AddAPI, MMCA.ADC/Source/Services/MMCA.ADC.Conference.Service/Program.cs:386).
    • ModuleLoader (:51) exposes the loader that AddModuleHost registered as a singleton. Its doc comment names the two later calls that need it: AddModuleHealthChecks after the pipeline has run discovery, and InitializeDatabaseAsync (:46-50).
    • RegisterModules(IServiceCollection services) (:69) null-guards the collection (:71), calls ModuleLoader.DiscoverAndRegister with the captured configuration, both settings objects and the assemblies (:73-78), then runs ThrowWhenNoModuleIsEnabled(ModuleLoader) (:80). The signature match with DiscoverAndRegister is the whole point of the captured fields. The XML doc declares the second failure mode beside ArgumentNullException: an InvalidOperationException when modules were discovered but none is enabled (:63-68).
    • ThrowWhenNoModuleIsEnabled(ModuleLoader) (:87, internal static) returns quietly when the loader has at least one enabled module or discovered no module at all (:89), so a host that names no module assembly is left alone. Otherwise it throws an InvalidOperationException that lists every disabled module and names the enabling key, Modules:{Name}:Enabled, with the first disabled module as the example (:94-99).
  • Why it's built this way: the ordering constraint is real, not stylistic. Module handlers registered after AddApplicationDecorators() would run undecorated (no logging, no caching, no transaction), and the ADR-014 pipeline seals itself, so a late registration throws instead. Exposing RegisterModules as a method group rather than running it eagerly is what lets each host place discovery exactly where its own pipeline needs it while still getting the settings-bind collapsed into one call. See ADR-014. The all-disabled guard exists because a module is enabled only by an explicit Modules:{Name}:Enabled=true: the doc comment (:63-68) records that a host whose Modules section is missing or misspelled would otherwise start healthy with no controllers, handlers or consumers, an outage that looks like a successful deploy. Failing start-up turns that into a visible deploy failure.
  • Where it's used: every ADC and Store service host holds one as moduleHost and touches it three times: moduleHost.ModulesSettings into AddAPI, pipeline.Register(moduleHost.RegisterModules) inside AddMmcaApplicationPipeline, and moduleHost.ModuleLoader into AddModuleHealthChecks (MMCA.ADC/Source/Services/MMCA.ADC.Conference.Service/Program.cs:386, :348, :364; the Identity, Engagement and Notification services and MMCA.Store/Source/Services/MMCA.Store.Sales.Service/Program.cs:131 follow the same shape). ModuleHostExtensionsTests (MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/Startup/ModuleHostExtensionsTests.cs) covers the properties, the null guard (:144), the all-disabled failure (:158) and the enabled-module pass (:170).
  • Caveats / not-in-source: nothing in this type enforces that RegisterModules is ever called, or called in the right place. A host that builds a ModuleHostContext and never registers the step gets a container with no module handlers in it, and the failure surfaces later as an unresolved handler rather than here; the all-disabled guard only runs inside RegisterModules. The test file records that there is deliberately no test driving RegisterModules through to a real discovery pass (ModuleHostExtensionsTests.cs:140).

SignalRExtensions

MMCA.Common.API · MMCA.Common.API.Startup · MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/SignalRExtensions.cs:12 · Level 3 · class (static, extension block)

  • What it is: a one-method helper that maps the NotificationHub SignalR endpoint at the path configured in PushNotificationSettings, and no-ops when push notifications are disabled or their settings were never registered.
  • Depends on: NotificationHub (Infrastructure), PushNotificationSettings, and IOptions<T>.
  • Concept (conditional real-time endpoint mapping). [Rubric §6, CQRS & Event-Driven]: the SignalR hub is the real-time delivery arm of the notification pipeline, so mapping it behind a settings gate means a host that does not push notifications simply never opens the endpoint, and the same Program.cs line is safe in every host.
  • Walkthrough: MapNotificationHub() (SignalRExtensions.cs:22) resolves IOptions<PushNotificationSettings> through GetService<T>(), which returns null when nothing registered it, and takes ?.Value (:24). Only when settings is { Enabled: true } (:25) does it call MapHub<NotificationHub>(settings.HubPath, ...) (:31-33), setting the hub's CloseOnAuthenticationExpiration from settings.CloseConnectionsOnTokenExpiry (PushNotificationSettings, MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Notifications/Push/PushNotificationSettings.cs:100). It returns app either way (:36). The doc comment (:16-21) notes it must run after UseCommonMiddlewarePipeline() so authentication and routing are already in place.
  • Why it's built this way: GetService rather than GetRequiredService, plus the property-pattern guard, is what makes the call unconditionally safe; it matches the same "always call, no-op if not applicable" convention as the JWKS and OIDC mappers. The expiry option is opt-in, and the comment (:27-30) gives its purpose: a connection ends with the token it was authenticated with, so a locked or revoked user is cut off within one token lifetime, and because each replica enforces it on its own connections it needs neither negotiation nor a sticky ingress. The hub path is also why the JWT bearer options carry an access_token query-string fallback for /hubs on both authentication paths (HubAccessTokenEvents, WebApplicationBuilderExtensions.Authentication.cs:192-207, assigned at :114 and :157): a WebSocket cannot send an Authorization header.
  • Where it's used: the ADC Notification service maps it after the shared pipeline (MMCA.ADC/Source/Services/MMCA.ADC.Notification.Service/Program.cs:157, with the pipeline itself at :244); that host reads the hub path from configuration rather than hard-coding it, which the comment there records (:257-260).
  • Caveats / not-in-source: CloseConnectionsOnTokenExpiry is a plain bool with no initializer (PushNotificationSettings.cs:100), so it is off unless configuration sets it; whether any deployment does is not determinable from source.

ModuleHostExtensions

MMCA.Common.API · MMCA.Common.API.Startup · MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/ModuleHostExtensions.cs:22 · Level 4 · class (static, extension block)

  • What it is: a single extension(WebApplicationBuilder builder) member, AddModuleHost, that collapses the settings-bind plus ModuleLoader construction every module-hosting service used to repeat verbatim in its Program.cs. It returns a ModuleHostContext.
  • Depends on: ModuleHostContext (which it constructs), ModuleLoader, ApplicationSettings, ModulesSettings and IModule (the interface discovery looks for); Microsoft.Extensions.Options validation, IConfiguration, ILogger<T> and System.Reflection.Assembly.
  • Concept (a deliberately narrow composition helper). The interesting design property is what this helper refuses to do. It binds two settings sections (validating ApplicationSettings on start), builds the loader, and registers it: it does not run discovery, add the module health checks, or touch the surrounding registration order, because discovery has to sit at a host-chosen position inside the ADR-014 pipeline and the health checks can only enumerate what discovery has already found (ModuleHostExtensions.cs:11-20). [Rubric §3, Clean Architecture] assesses whether composition-root concerns stay in the composition root; hoisting the mechanical part into the framework while leaving the ordering decisions visible in each Program.cs is that line drawn on purpose. [Rubric §15, Best Practices & Code Quality] also applies: ValidateDataAnnotations().ValidateOnStart() on the ApplicationSettings section turns a misconfigured section into a startup failure rather than a null that surfaces on the first request, and the helper registers options only where something resolves them.
  • Walkthrough: AddModuleHost(IEnumerable<Assembly> moduleAssemblies, ILogger<ModuleLoader>? moduleLoaderLogger = null) (ModuleHostExtensions.cs:51).
    • Null-guards the builder and the assembly list (:55-56), then takes local aliases for builder.Services and builder.Configuration (:58-59).
    • Registers ApplicationSettings as options bound to its SectionName, with data-annotation validation on start (:61-64), then also reads the section eagerly and throws InvalidOperationException when it is absent (:66-67). The two are not redundant: ValidateOnStart fires when the host starts, while the eager Get<T>() is what lets the returned context hand the bound settings back to the caller immediately, before builder.Build().
    • Reads ModulesSettings eagerly only, falling back to an empty instance rather than throwing when the section is missing (:71-73): a host with no per-module enable/disable configuration is legal, a host with no ApplicationSettings is not. It is deliberately not registered as IOptions<ModulesSettings>; the comment (:69-70) gives the reason: the bound value is handed to the loader and to AddAPI directly, nothing resolves the options form, and the type carries no data annotations to validate.
    • Builds the ModuleLoader, attaching the caller's logger through an object initializer only when one was supplied so the loader keeps its own NullLogger default otherwise (:75-77), and registers it as a singleton (:79).
    • Returns a ModuleHostContext carrying the configuration, both settings objects, the loader and the assembly list (:81-86).
  • Why it's built this way: the moduleAssemblies parameter is required rather than defaulted to an AppDomain scan, and the doc comment shows the intended call shape (one marker type per module, :31-35). Naming the assemblies explicitly means discovery looks nowhere else, which is what makes a single-module extracted service provably single-module: the ADC Conference host says exactly that in its comment (MMCA.ADC/Source/Services/MMCA.ADC.Conference.Service/Program.cs:378-380), and the Store Sales host uses the same property to explain why Catalog and Identity reach it only as Contracts projects (MMCA.Store/Source/Services/MMCA.Store.Sales.Service/Program.cs:125-129). The optional logger exists because module discovery runs before the host's real logging pipeline is available, so a host that has bootstrapped a Serilog logger passes one in (:36-42).
  • Where it's used: every ADC service host (MMCA.ADC/Source/Services/MMCA.ADC.Conference.Service/Program.cs:382-384, plus Identity :248, Engagement :209 and Notification :187 in their own files) and the Store Sales and Catalog hosts (MMCA.Store/Source/Services/MMCA.Store.Sales.Service/Program.cs:131-133), each passing SerilogHostExtensions.CreateBootstrapLoggerFactory().CreateLogger<ModuleLoader>(). ModuleHostExtensionsTests (MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/Startup/ModuleHostExtensionsTests.cs:45-149) covers the bind, the missing-section throw, the empty ModulesSettings fallback (:81), the singleton registration and the optional logger.
  • Caveats / not-in-source: MMCA.Helpdesk does not use this helper. Its single-module host still constructs the ModuleLoader inline and calls DiscoverAndRegister directly (MMCA.Helpdesk/Source/Hosts/MMCA.Helpdesk.Web/Program.cs:97 and :104), which is the longhand this extension collapses.

JwksKeyStrengthValidator

MMCA.Common.API · MMCA.Common.API.Startup.Auth · MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/Auth/JwksKeyStrengthValidator.cs:20 · Level 6 · class (internal, sealed)

  • What it is: the JWKS-side twin of JwtKeyStrengthValidator: an IValidateOptions<JwksSettings> that holds the published current key and every Jwks:AdditionalKeys entry to the same strength floor (RSA at least Jwt:MinimumRsaKeySizeBits bits, EC on P-384), failing startup outside Development and warning once in Development.
  • Depends on: JwksSettings (the keys it measures) and IOptions<JwtSettings> (the floor and the current signing algorithm); JwtAlgorithms and JwtSigningAlgorithm; JwtKeyStrengthValidator.AddShortfall and .Outcome, which it reuses; System.IO.File.
  • Concept (one floor for every key a validator might trust). [Rubric §11, Security]: a strong signing key does not help if a weak key sits in the published set, because every key in /.well-known/jwks.json is one a validator accepts. Measuring the JWKS keys with the floor and wording of the signing-key validator means a rotation cannot quietly re-admit a short key through the AdditionalKeys list. See ADR-149.
  • Walkthrough: one public member and two private helpers.
    • The primary constructor takes IOptions<JwtSettings>, the logger and an optional IHostEnvironment (JwksKeyStrengthValidator.cs:20-23).
    • Validate(string?, JwksSettings) (:26) null-guards the options (:28) and reads the floor from JwtSettings.MinimumRsaKeySizeBits (:30-31). When options.Enabled it measures the current published key under the configured signing algorithm, or under RS256 when the configured algorithm is HS256 (:34-42). It then walks AdditionalKeys by index, skipping any whose algorithm is not asymmetric (:44-50) and measuring the rest under a Jwks:AdditionalKeys:{i}: prefix built with the invariant culture (:52-58). Each measurement goes through JwtKeyStrengthValidator.AddShortfall, and the result through JwtKeyStrengthValidator.Outcome (:61), so the messages and the Development relaxation are identical to the signing-key check.
    • Material(...) (:68, private) picks the setting name and PEM a key's algorithm reads: the EC PEM for ES384 (:75-78), otherwise the inline RSA PEM when set, else the contents of the RSA key file, because an inline PEM wins, as the loader rules (:80-82).
    • ReadIfPresent(string?) (:89, private) reads a key file for measuring and returns null for a blank path or on an IOException, UnauthorizedAccessException, ArgumentException or NotSupportedException (:100-103). The doc comment (:85-88) gives the reason: a file that cannot be read is left to the loader, which fails on it with its own message.
  • Why it's built this way: reusing the two internal static helpers of JwtKeyStrengthValidator is what keeps the two checks from drifting apart in wording or in their Development rule. Keying the reported setting on the actual configuration path (Jwks:RsaPublicKeyPath, Jwks:AdditionalKeys:2:EcPublicKeyPem) points the operator at the exact entry to replace.
  • Where it's used: registered only by AddCommonAuthentication on WebApplicationBuilderExtensions via TryAddEnumerable (WebApplicationBuilderExtensions.Authentication.cs:150-151). It runs when JwksSettings options are validated; Infrastructure registers those with ValidateDataAnnotations().ValidateOnStart() (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:252-255), so in a host that has both registrations the check fires at startup.
  • Caveats / not-in-source: the validator reads the key file a second time, separately from the loader, so a path that becomes unreadable between the two reads passes here and fails in the loader. A host that calls AddCommonAuthentication without the Infrastructure JwksSettings registration has no ValidateOnStart for that options type, and the check would then run only when something first resolves IOptions<JwksSettings>; whether any host is composed that way is not determinable from this file.

WebApplicationBuilderExtensions

MMCA.Common.API · MMCA.Common.API.Startup · MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/WebApplicationBuilderExtensions.Authentication.cs:17 · Level 7 · class (static, extension block; split across three partials: WebApplicationBuilderExtensions.cs, .RateLimiting.cs and .Authentication.cs)

  • What it is: the consolidated builder-side registration surface shared by every MMCA host: API versioning, rate limiting, response compression, OpenAPI, CORS, and the two JWT authentication modes (in-process validation and JWKS-forwarded validation). It is the sibling of WebApplicationExtensions, which owns the runtime pipeline; this one owns what goes into the DI container.
  • Depends on: JwtSettings and its JwtSigningAlgorithm; JwksSettings (the rotation keys accepted in process); JwtAlgorithms (the pinned algorithm lists and clock skew) and JwtKeyMaterial (the public validation key); JwtKeyStrengthValidator and JwksKeyStrengthValidator; AddAuthorizationPolicies from MMCA.Common.API.Authorization; ApiParameterDescriptorBackfillProvider; RateLimitingSettings, RateLimitAlgorithm, RedisFixedWindowRateLimiter and RemainingWindowFixedWindowRateLimiter; RetryAfterRejection (the 429's Retry-After header); ClientAddressKey and McpCallerKey (partition keys); CacheKeyPrefixOptions and ApplicationNamespace (the Redis counter key namespace); InsecureJwtMetadataWarningStartupFilter; PushNotificationSettings (for the configured hub path); ASP.NET rate-limiting, compression, CORS and Asp.Versioning primitives; Microsoft.IdentityModel.Tokens and StackExchange.Redis.
  • Concept introduced (per-user global rate limiting, a pluggable counter location, algorithm-pinned JWT validation, and endpoint-metadata-verified exemptions). [Rubric §12, Performance & Scalability] (a global limiter protects finite capacity, and a distributed counter makes the configured number mean the same thing behind a load balancer), [Rubric §11, Security] (algorithm pinning, a key-strength floor, HTTPS metadata resolution, per-IP anonymous auth throttling, a gRPC bypass keyed on routed endpoint metadata rather than a spoofable Content-Type header, and an anonymous hub request metered per IP instead of exempted outright) and [Rubric §9, API & Contract Design] (versioning, OpenAPI and compression handled identically across hosts rather than per host).
  • Walkthrough: the load-bearing members, grouped by the partial file that now holds them.
    • CorsPolicyAllowSpecificOrigins / CorsPolicyAllowAll (WebApplicationBuilderExtensions.cs:27, :30): the two policy names the pipeline chooses between by environment.
    • AddCommonApiVersioning() (WebApplicationBuilderExtensions.cs:39): header-based versioning through the api-version reader with AssumeDefaultVersionWhenUnspecified and ReportApiVersions (:44-46), the API explorer group format 'v'VVV and SubstituteApiVersionInUrl (:48-51), then the backfill guard (:54). The comment (:39-41) records that DefaultApiVersion is deliberately not set because 1.0 is already the framework default and restating it trips AV0011/AV0024. See ADR-046.
    • AddCommonResponseCompression() (WebApplicationBuilderExtensions.cs:70): Brotli plus Gzip, enabled for HTTPS, both at CompressionLevel.Fastest (:64-76); the comment (:72-74) justifies Fastest for gzip too on fractional-vCPU hosts serving dynamic payloads.
    • AddCommonOpenApi() (WebApplicationBuilderExtensions.cs:109) registers no OpenAPI document of its own: it installs the backfill guard (:97) and registers StronglyTypedIdSchemaTransformer and StronglyTypedIdParameterTransformer through services.ConfigureAll<OpenApiOptions> (ADR-115, :102-106), rather than on a named document, so whatever document names the host registers are all covered; the comment (:99-101) notes this is inert in a host that declares no strongly typed identifier wrappers. The host must make the services.AddOpenApi() call in its own project (either order relative to this one), because the OpenAPI XML-comment source generator attaches the host's controller summaries by intercepting the AddOpenApi call sites of the project being compiled, and a registration made inside this assembly would carry none of them (doc comment :82-87). Pair it with MapCommonOpenApi() on OpenApiEndpointExtensions, which the same doc comment says fails at startup outside Production when no v1 document was registered (:87-89).
    • AddApiParameterDescriptorBackfill() (WebApplicationBuilderExtensions.cs:132, private) registers ApiParameterDescriptorBackfillProvider via TryAddEnumerable (:119-120), which de-duplicates on implementation type, so calling both AddCommonApiVersioning and AddCommonOpenApi installs the guard exactly once (:111-117).
    • AddCommonCors(IConfiguration) (WebApplicationBuilderExtensions.cs:140): the restrictive production policy takes its origins from Cors:AllowedOrigins and allowlists four headers and five methods with AllowCredentials (:130-136); the development any-origin policy sits under a justified #pragma warning disable S5122 explaining it is only ever selected when the environment is Development (:138-143). See ADR-082.
    • RetryAfterRejection.WithRetryAfterHeader(previous) (MMCA.Common/Source/Build/RateLimiting/RetryAfterRejection.cs:42, on the internal RetryAfterRejection, one linked source file compiled into API, Aspire, UI.Web and Gateway, :12-18) wraps the rate limiter's OnRejected callback so every 429 carries a Retry-After header whenever the rejecting lease reports a MetadataName.RetryAfter hint (:46-49), formatted by its Format in whole seconds, rounded up and never negative (:27-31). Format is a copy of RetryAfterHeader.Format because the Gateway package references no MMCA project, and a test pins the two together (:15-17). A callback the host set before this registration still runs afterwards, so it can read or override the header (:51).
    • RateLimitPolicyAuthIp (WebApplicationBuilderExtensions.RateLimiting.cs:28): the named "auth-ip" policy for anonymous authentication attempts. Its doc comment (:21-27) states why it exists: the global limiter deliberately no-ops for anonymous traffic and per-account lockout is per-email, which would leave a password spray (one password, many emails) from a single source unthrottled.
    • RateLimitPolicyMcp (:37, "mcp"): the policy MapCommonMcp in MMCA.Common.Mcp applies to the MCP endpoint, partitioned by user id, else identity name, else client IP, else one shared bucket, so an anonymous caller of a public tool is metered too, at RateLimitingSettings.McpPermitLimit (:30-36).
    • RateLimitPolicyWellKnown (:51, "wellknown"): one fixed window per client IP for the public discovery documents, RateLimitingSettings.WellKnownPermitLimit requests per minute (default 60 per the doc comment, :41). MapJwksEndpoint and MapOidcDiscoveryEndpoint apply it, so a host that maps either behind UseRateLimiter must register it through AddCommonRateLimiting; MMCA.Common.Gateway does not register it, and a YARP gateway instead declares a policy of the same name under MmcaGateway:RateLimiterPolicies:wellknown (:42-48). The global limiter still exempts these paths; this policy is what bounds them (:48-49).
    • IsRateLimitBypassed(HttpContext) (:70) exempts /health, /alive and /.well-known/* (:71-73), then a mapped gRPC endpoint through IsGrpcEndpoint (:74), all legitimately high-frequency. The remark (:57-63, SEC-Common-44) records why the gRPC arm keys on the routed endpoint rather than the request's Content-Type header: a caller-supplied Content-Type: application/grpc header is unverifiable and used to hand any authenticated account the no-limiter partition, switching off its 300/min cap entirely, while routed endpoint metadata comes from the server's own MapGrpcService registrations and cannot be forged; the predicate runs from the rate-limiting middleware, after UseRouting, so the endpoint is already resolved. It is internal rather than private specifically so the exemption logic is unit-testable through InternalsVisibleTo instead of only under a request flood (:66-67).
    • AnonymousPartition(HttpContext, RateLimitingSettings) (:86, private) is the partition an unauthenticated request counts against: RateLimitPartition.GetNoLimiter("__anonymous") everywhere except a real-time hub path (:96), where IsAnonymousHubRequest routes it through CreateLimitedPartition keyed on ClientAddressKey.For(...) of the client IP (or "anonymous-hub" when there is none) with redisScope: "hub", settings.AnonymousHubPermitLimit, queueLimit: 0 and countLocallyOnRedisFault: false (:87-95). The remark (SEC-ADC-25, :80-85) is the reason: a gateway that bypasses /hubs at the edge (ADR-024 requires it, because the hub authenticates from a query-string token the edge cannot read) left an anonymous negotiate flood metered nowhere at all.
    • IsAnonymousHubRequest(HttpContext, RateLimitingSettings) (:106) null-guards both arguments (:108-109) and matches the request path against the non-blank entries of settings.HubPathPrefixes (:113-115); internal for the same InternalsVisibleTo reason.
    • GrpcServerMetadataNamespace (:123, the literal "Grpc.AspNetCore.Server") and IsGrpcEndpoint(HttpContext) (:131) together are the routed-metadata check: matched by namespace name so MMCA.Common.API needs no package reference on the gRPC server stack, which only the extracted service hosts take (:118-122), returning true only when the resolved endpoint carries metadata from that namespace (:133-149).
    • GlobalRateLimitPartition has two overloads. The permit-count one (:158-159) simply wraps its argument in a RateLimitingSettings and delegates; the settings one (:166) holds the logic: a NoLimiter for bypassed infrastructure (:168-171) and, for unauthenticated callers, a delegate to AnonymousPartition rather than an unconditional NoLimiter (:173-176), otherwise a partition keyed by the user-id (subject) claim, then Identity.Name, then the ClientAddressKey of the remote IP, then the literal "authenticated" (:178-181), built through CreateLimitedPartition with redisScope: "global", queueLimit: 0 and countLocallyOnRedisFault: false (:183-190). The subject claim leads because it is unique per account, while the name claim carries the full name, which two users can share and would then pool into one bucket (:152-155).
    • McpRateLimitPartition (:203) is the selector for the "mcp" policy: one bucket per caller as McpCallerKey.For(user, remote IP) keys it, with redisScope: "mcp", settings.McpPermitLimit and queueLimit: 0 (:204-211). The remark (:198-202) explains why an unattributable caller is limited in one shared bucket rather than waved through: the endpoint and the per-tool limit in MMCA.Common.Mcp then agree on who a caller is and neither fails open.
    • RateLimitKeyNamespace(IServiceProvider) (:219, private) is the namespace that qualifies a distributed counter key: the configured CacheKeyPrefixOptions.KeyPrefix without its trailing colon when one is set, else ApplicationNamespace.Resolve(...), exactly as the distributed cache resolves its own prefix (:213-225).
    • CreateLimitedPartition (:246) is the single place a partition is built, and reading it is the fastest way to understand the whole limiter. When settings.Distributed is set (:255) it resolves IConnectionMultiplexer through a nullable local, because HttpContext.RequestServices is declared non-nullable but is genuinely null outside a request pipeline such as a bare DefaultHttpContext in a unit test (:257-261). With a connection it returns a partition whose factory builds a RedisFixedWindowRateLimiter over $"{RateLimitKeyNamespace(requestServices!)}:{redisScope}:{key}", passing the caller's countLocallyOnRedisFault (:271-279) and falling back to a null logger when none is registered (:265-266); the namespace keeps two MMCA apps on one Redis from sharing counters (SEC-Common-53) and is resolved in the factory, which runs once per partition rather than per request (:268-270). countLocallyOnRedisFault decides what a Redis fault does: false fails open (capacity protection never rejects a healthy request), true counts in this process for the outage (:240-245). Without a connection it deliberately falls through to the in-memory limiters rather than failing startup, so a host that turns the flag on before wiring Redis degrades to per-instance limits instead of losing rate limiting altogether (:282-284). The in-memory branch honours RateLimitAlgorithm: a sliding window with SegmentsPerWindow segments (:287-297) or the default fixed window, built as a RemainingWindowFixedWindowRateLimiter rather than RateLimitPartition.GetFixedWindowLimiter because the framework limiter's Retry-After is always the whole window, while the wrapper reports the time actually left (:299-307). Both run over TimeSpan.FromMinutes(1) with QueueProcessingOrder.OldestFirst.
    • AuthIpRateLimitPartition (:321 permit-count overload, :333 settings overload) partitions the "auth-ip" policy on the ClientAddressKey of the client IP (an IPv6 /64, with IPv4-mapped addresses unmapped, so rotating inside one /64 is one client, :335-336) and returns no limiter at all when the IP is unattributable (:338-339). The remark (:314-320) explains the choice: failing open on a null IP beats collapsing every such request into one shared bucket, which would throttle the in-process TestServer and the integration tier to a standstill. It passes redisScope: "auth-ip" and countLocallyOnRedisFault: true (:340-347), so with Distributed and a registered Redis client every instance counts one IP against one shared allowance, and a Redis fault falls back to a per-instance count rather than failing open (doc :324-331).
    • WellKnownRateLimitPartition (:356) is the same per-IP shape for the "wellknown" policy: no limiter for an unattributable IP, otherwise redisScope: "wellknown" at settings.WellKnownPermitLimit, failing open on a Redis fault (:358-369).
    • AddCommonRateLimiting has three overloads (all WebApplicationBuilderExtensions.RateLimiting.cs). The permit-count one (:403) keeps the defaults globalPermitLimit: 300, authIpPermitLimit: 30 and simply builds a RateLimitingSettings from them (:403-408). The IConfiguration one (:418) null-guards the configuration (:420), registers RateLimitingSettings as options bound to the RateLimiting section with data-annotation validation on start, so a [Range] violation fails at startup rather than building a limiter that throws on every authenticated request (:422-425), and then reads the same section into the settings it passes on, falling back to a default instance when the section is absent (:427). The settings one (:441) does the work: rejection status 429 (:447), OnRejected wrapped by RetryAfterRejection.WithRetryAfterHeader so a refused caller learns when its window resets, while a lease without the hint (a concurrency rejection) sends no header (:449-451), the always-on GlobalLimiter (:453-454), the "mcp" policy, inert until an endpoint names it (:456-458), "auth-ip" (:468-470) and "wellknown" (:474-476). Two comments carry the reasoning: the auth-ip policy takes the client IP from Connection.RemoteIpAddress, which the shared pipeline has already resolved from X-Forwarded-For because UseForwardedHeaders runs before UseRateLimiter (:460-467); and the wellknown policy applies even though the global limiter bypasses /.well-known, because the endpoints name it themselves (:472-473). The doc comment on the permit-count overload (:374-402) explains why anonymous traffic is deliberately unlimited and why authIpPermitLimit is 30 rather than a tighter 10: Blazor Server circuits issue the login call server-side, so every Server-circuit user shares the UI host's IP. See ADR-019.
    • AddForwardedJwtBearer(authority, audience, configuration, environment, requireHttpsMetadata = null) (WebApplicationBuilderExtensions.Authentication.cs:52) is the extracted-service mode. It validates all four required arguments (:59-62), then resolves the metadata posture in three steps: the explicit argument when it is not null, then RequireHttpsMetadataConfigKey, then true everywhere except Development (:64-66). When the resolved value is false outside Development it registers InsecureJwtMetadataWarningStartupFilter so the deviation is logged once at startup (:68-72), and finally delegates to the private AddForwardedJwtBearerCore, passing the hub path read by ResolveHubPath(configuration) along with the resolved posture (:74). Its authority argument is normally the result of JwtAuthorityExtensions.GetRequiredJwtAuthority().
    • RequireHttpsMetadataConfigKey (:25, value "Authentication:JwtBearer:RequireHttpsMetadata"): the one configuration key that can override the secure-by-default metadata posture. Its comment (:19-24) narrows the legitimate use to an authority that is genuinely plain HTTP (an internal-ingress h2c service URL) and asks for the justification to be recorded beside the setting.
    • AddForwardedJwtBearerCore (:77, private, taking a fourth hubPath parameter) does the JWT wiring: Authority, Audience and RequireHttpsMetadata (:86-88), validation parameters that deliberately leave ValidIssuer unset so the middleware takes the issuer from the discovery document, because the authority is whatever URL the AppHost or deployment injects (the gateway's https endpoint locally, the internal Identity app URL in Azure) and need not equal the token's iss claim, the public gateway URL (:96-102), ValidAlgorithms = JwtAlgorithms.Asymmetric (RS256, PS256 and ES384, MMCA.Common/Source/Build/Auth/JwtAlgorithms.cs:25-30) and ClockSkew = JwtAlgorithms.ClockSkew, 30 seconds (JwtAlgorithms.cs:22; :104-111). The comment (:104-109) gives the reason for the list: each published key carries its own alg, so a rotation that changes the algorithm keeps validating, while HS256 is never accepted here, so a token signed with HMAC under a public key as the secret is refused. It installs the SignalR access_token query-string fallback by assigning options.Events = HubAccessTokenEvents(hubPath) (:115) and then calls AddAuthorizationPolicies() (:118).
    • AddCommonAuthentication(IConfiguration) (:142) is the in-process mode: it binds JwtSettings with data-annotation validation on start (:144-147), registers JwtKeyStrengthValidator and JwksKeyStrengthValidator through TryAddEnumerable (:148-151), so outside Development an RSA key below Jwt:MinimumRsaKeySizeBits (default 3072) or an EC key not on P-384 fails startup while Development logs one warning (doc :135-140), reads the hub path once through ResolveHubPath(configuration) (:153), reads the optional Jwks section into a nullable JwksSettings so a token signed with the previous key keeps validating in process across a signing-key rotation (:161-163), builds validation parameters through BuildValidationParameters(jwtSettings, jwksSettings) (:165), wires the same access-token fallback through HubAccessTokenEvents(hubPath) (:169), and adds the authorization policies (:172).
    • ResolveHubPath(IConfiguration) (:182, private static, outside the extension block) reads the PushNotifications section (PushNotificationSettings.SectionName, MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Notifications/Push/PushNotificationSettings.cs:11) and returns its HubPath, falling back to a default instance's value, /hubs/notifications (PushNotificationSettings.cs:25). It is read once per registration, not per request.
    • HubAccessTokenEvents(string hubPath) (:192, private static) is the one JwtBearerEvents both modes share. OnMessageReceived takes the token from the access_token query parameter only when it is non-empty and the request path is under the configured hubPath or under the literal /hubs floor (:194-206), so a host that moves its notification hub still authenticates, and a host mapping further hubs under /hubs keeps working. A WebSocket upgrade cannot carry an Authorization header, which is why the token travels in the query string at all.
    • BuildValidationParameters(JwtSettings, JwksSettings? jwksSettings = null) (:224, internal static, outside the extension block) branches on JwtAlgorithms.IsAsymmetric of the configured JwtSigningAlgorithm (:226-227). The asymmetric branch picks EcPublicKeyPem for ES384 and RsaPublicKeyPem for RS256 and PS256, and throws a message naming the missing setting and the algorithm that points at AddForwardedJwtBearer when it is blank (:229-235). It builds the current key through JwtKeyMaterial.CreatePublicKey(algorithm, publicKeyPem, keyId: null) (:245; MMCA.Common/Source/Build/Auth/JwtKeyMaterial.cs:74), sets IssuerSigningKeys to jwksSettings?.CreateAdditionalValidationKeys() ?? [] (:246; CreateAdditionalValidationKeys at MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/JwksSettings.cs:183, one RSA or ECDSA key per additional key by its algorithm) beside it, and pins ValidAlgorithms = JwtAlgorithms.Asymmetric with the 30-second ClockSkew (:247-248). The doc comment (:209-223) states that the pin is the asymmetric list or HS256, never both, so a token is only ever checked under its key's algorithm family, and that the accepted set is the same one /.well-known/jwks.json publishes, so a signing-key rotation, including one that changes the algorithm, does not reject tokens the previous key signed. The HS256 path builds a SymmetricSecurityKey from JwtSettings.DecodeHmacSigningKey(jwtSettings.SecretForKey) and pins JwtAlgorithms.Symmetric (HS256 only) with the same clock skew (:252-263); it takes no additional keys, because HS256 has no published keys. The key check is not local to this file: DecodeHmacSigningKey (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/JwtSettings.cs:144) throws InvalidOperationException when the secret is not Base64 or decodes to fewer than 32 bytes, and its doc comment (JwtSettings.cs:136-140) names it the one check every HS256 reader applies: the startup validation, the token issuer and this in-process validator. A too-short secret therefore fails host startup rather than weakening every token.
  • Why it's built this way: two authentication entry points are the framework's monolith-to-microservice hinge (ADR-004): the monolith or the issuing Identity service validates in process against a local key, while an extracted service validates against the issuer's published JWKS with no shared secret. The explicit ValidAlgorithms pin on both paths is deliberate defense in depth rather than trust in the token header. Taking IConfiguration and IHostEnvironment as required arguments on AddForwardedJwtBearer is what makes "HTTPS metadata unless you say otherwise" the default a host cannot forget: the insecure value stays reachable for the deployments that need it, but only through a named key and never silently. On the limiter side, factoring every partition through CreateLimitedPartition is what let the Redis counter and the sliding window arrive without touching a single partition-key rule: the policy names, the bypass list and every key are identical whatever the settings say, and only the permit counts, the algorithm and the counter's location change (WebApplicationBuilderExtensions.RateLimiting.cs:432-437). The one per-call difference left is what a Redis fault does, and it is a named argument (countLocallyOnRedisFault) rather than a hidden branch: only the login throttle counts locally through an outage. The key-strength validators extend the same posture to key material: the algorithm pin stops a token from choosing its own verification family, and the floor stops a weak key from being trusted at all. Keying the gRPC exemption and the hub exemption on server-controlled state (routed endpoint metadata, configured hub path prefixes) rather than caller-supplied headers is the same defense-in-depth posture applied to the exemption list itself, not just to the authenticated-caller partitions.
  • Where it's used: every ADC and Store service host reaches the builder-side registrations through builder.AddMmcaServiceHost(...) (MMCA.ADC/Source/Services/MMCA.ADC.Conference.Service/Program.cs:88, MMCA.Store/Source/Services/MMCA.Store.Sales.Service/Program.cs:51), which calls AddCommonCors, AddCommonApiVersioning, AddCommonRateLimiting and AddCommonResponseCompression (MMCA.Common/Source/Hosting/MMCA.Common.ServiceHost/ServiceHostBuilderExtensions.cs:108-110, :118). Identity hosts select the in-process mode (ServiceHostAuthentication.TokenIssuer) while the other services take the forwarded mode, which the composed host calls with the host's configuration and builder.Environment so the framework resolves the metadata posture (ServiceHostBuilderExtensions.cs:132-143). Each ADC service host keeps its own builder.Services.AddOpenApi() line (MMCA.ADC/Source/Services/MMCA.ADC.Conference.Service/Program.cs:86) and the composed host adds AddCommonOpenApi() (ServiceHostBuilderExtensions.cs:130). The "auth-ip" policy is applied by attribute on the login and register actions of AuthControllerBase (AuthControllerBase.cs:78 and :96), so every consumer inheriting that base gets it without opting in. The internal partition helpers are exercised directly by WebApplicationBuilderExtensionsTests, RateLimitPartitionTests and RateLimitAlgorithmSelectionTests; the metadata resolution by ForwardedJwtBearerSecurityTests.
  • Caveats / not-in-source: the two permit-limit defaults on the permit-count overload, and the other counts that come from RateLimitingSettings, are framework defaults only. What a given deployment actually enforces is whatever the host passes or configures under RateLimiting, and that configuration value is not determinable from this file. Likewise Distributed only takes effect when the host also registers an IConnectionMultiplexer; whether it does is host composition, not this file. The forwarded mode registers neither key-strength validator, because it holds no key of its own; the floor there is whatever the issuing Identity host enforced when it published its JWKS.

InsecureJwtMetadataWarningStartupFilter

MMCA.Common.API · MMCA.Common.API.Startup.Auth · MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/Auth/InsecureJwtMetadataWarningStartupFilter.cs:15 · Level 2 · class (internal, sealed, partial)

  • What it is: a one-purpose IStartupFilter that writes a single warning at host startup when AddForwardedJwtBearer resolved RequireHttpsMetadata to false outside Development. It changes no behavior; it only makes a deliberate weakening visible in the logs.
  • Depends on: Microsoft.AspNetCore.Hosting.IStartupFilter, ILogger<T>, the source-generated [LoggerMessage] attribute, and WebApplicationBuilderExtensions.RequireHttpsMetadataConfigKey for the key name it echoes.
  • Concept introduced (IStartupFilter as a "log after the logging providers exist" hook). Registration-time code runs while the IServiceCollection is still being built, so the logging providers are not configured yet and anything written there is dropped. IStartupFilter.Configure runs later, once the provider is built and the application pipeline is being assembled, which is the first moment a warning is guaranteed to reach a sink. The doc comment states exactly that reasoning (InsecureJwtMetadataWarningStartupFilter.cs:7-13). [Rubric §11, Security] assesses whether a security-relevant deviation is deliberate, narrow, and visible; the code permits the deviation (an internal-ingress cleartext authority is a real deployment) but refuses to let it be silent. [Rubric §13, Observability & Operability] assesses whether an operator can see the posture a deployment is actually running: this warning is the only place the resolved value surfaces at runtime.
  • Walkthrough: two members.
    • Configure(Action<IApplicationBuilder> next) (:19) logs once (:21) and returns next unchanged (:23). It inserts nothing into the request pipeline, so the filter costs nothing per request; the whole type is a startup-time side effect wearing a pipeline interface.
    • LogInsecureJwtMetadata (:29) is a [LoggerMessage] source-generated partial at LogLevel.Warning (:26-28). The message names the config key that produced the value and tells the operator what makes it safe (an internal-ingress cleartext h2c authority) and what to do (record that justification beside the setting in the deployment template).
  • Why it's built this way: the filter is registered through TryAddEnumerable(ServiceDescriptor.Singleton<IStartupFilter, ...>) (WebApplicationBuilderExtensions.Authentication.cs:70-71), which de-duplicates on implementation type, so a host that calls AddForwardedJwtBearer more than once still gets exactly one warning. Registration is itself conditional (:67): the filter is only added when the resolved value is false and the environment is not Development, so a developer's normal loop stays quiet. Source-generated logging avoids boxing and string formatting on a path that runs once, which is the framework's convention rather than a hot-path optimization here.
  • Where it's used: registered only from AddForwardedJwtBearer (WebApplicationBuilderExtensions.Authentication.cs:68-72). Its registration conditions are asserted by ForwardedJwtBearerSecurityTests (MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/Startup/ForwardedJwtBearerSecurityTests.cs). In the deployed apps the ADC service hosts document the override explicitly: Azure sets Authentication:JwtBearer:RequireHttpsMetadata to false because the authority is the internal-ingress h2c URL (MMCA.ADC/Source/Services/MMCA.ADC.Conference.Service/Program.cs:326-337), which is precisely the case this filter exists to annotate.
  • Caveats / not-in-source: nothing in the framework fails a build or a deployment on this warning. Whether an operator acts on it is a process concern, and there is no ADR for this decision in Website/docs-src/adr/ at the time of writing.

WebApplicationExtensions

MMCA.Common.API · MMCA.Common.API.Startup · MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/WebApplicationExtensions.cs:15 · Level 11 · class (static, extension block)

  • What it is: the extension(WebApplication app) type every downstream host calls to wire its HTTP edge: the two UseCommonMiddlewarePipeline overloads, the request-localization member, and the culture-switch endpoint. It is the runtime-side sibling of WebApplicationBuilderExtensions.
  • Depends on: MiddlewarePipelineBuilder (which owns the step list) and SupportedCultures; ASP.NET localization and cookie primitives.
  • Concept (one canonical, ordered pipeline, applied through one private helper). [Rubric §13, Observability & Operability]: middleware order is behavior, not taste. Correlation must be established before anything downstream logs, and authentication must run before the rate limiter so the per-user partition sees a principal at all. Centralizing the order means a host cannot get it wrong (ADR-079). [Rubric §27, i18n] applies through the localization wiring (ADR-027).
  • Walkthrough
    • UseCommonMiddlewarePipeline() (WebApplicationExtensions.cs:28) is a one-liner: ApplyPipeline(app, configure: null). Its doc comment (:19-27) states the contract in one sentence worth keeping: the order is data, not prose, named by MiddlewarePipelineStepNames and frozen by the MiddlewarePipelineOrderTestsBase fitness function.
    • UseCommonMiddlewarePipeline(Action<MiddlewarePipelineBuilder> configure) (:40) is the scoped escape hatch: it null-guards the delegate (:42) and routes through the same helper (:43). The XML doc declares both failure modes, ArgumentNullException and the InvalidOperationException an invariant violation raises (:38-39).
    • UseCommonRequestLocalization() (:53) builds the supported list from SupportedCultures.All (:55), appends the pseudo-locale in Development only (:60-63), and sets the default plus both supported and supported-UI culture lists (:66-69). It is itself the RequestLocalization step of the default pipeline, and Blazor UI hosts call it explicitly before MapRazorComponents so SSR prerender runs under the right culture (:46-52).
    • MapCultureEndpoint() (:83) is a one-line default that calls the MapCultureEndpoint(bool httpOnly) overload with httpOnly: false. MapCultureEndpoint(bool httpOnly) (:96) does the real work: it maps the anonymous GET /culture/set?culture=&redirectUri= that the culture switcher calls (:101, .AllowAnonymous() at :130), honors only allowlisted cultures and the pseudo-locale only in Development (:100, :107), and writes the cookie only when the request is not cross-site (!IsCrossSiteRequest(context.Request), :106). The comment (:103-105) gives the reason: a navigation another site started must not pin the visitor's language for a year, since the switch itself is same-origin, and the endpoint still redirects, so a cross-site link degrades to a plain visit instead of an error. When the checks pass it writes the standard ASP.NET culture cookie with the caller-chosen HttpOnly (:110-121, with Secure = !app.Environment.IsDevelopment() || context.Request.IsHttps and a one-year expiry), then local-redirects (:128-129) to force a full reload. Both Sonar deviations are justified inline at :109: S3330 because the cookie is non-HttpOnly by default for the WASM client, and S2092 because Secure follows the SessionCookieJar.BuildOptions rule (always set outside Development, and in Development whenever the request is HTTPS), so only a plain-HTTP Development host writes the cookie without Secure. The redirect target passes through IsLocalRedirectTarget first and falls back to / when the requested target is missing or not local (:125-128): Results.LocalRedirect throws at execution for a non-local URL, which on this anonymous endpoint would surface as a 500 rather than a redirect. The httpOnly parameter (:89-94) exists so a Server-only host that never runs WASM can pass true and keep the cookie out of script reach; a host that serves a WebAssembly client must keep the parameterless overload's false, because the WASM runtime reads the cookie directly on startup (MmcaCultureBootstrap.SetBrowserCultureAsync).
    • IsLocalRedirectTarget(string?) (:144, private) applies the rule LocalRedirect itself enforces, ahead of it (:136-143): a non-blank value with a single leading / that is not followed by a second / or a \, since browsers treat either of those as a protocol-relative URL to another host, and that contains **no control character anywhere** (!url.Any(char.IsControl), :145-148). The control-character clause matches what LocalRedirect rejects when it executes, and the doc comment notes why checking it first matters: by execution time the culture cookie has already been written.
    • IsCrossSiteRequest(HttpRequest) (:156, private) is true only when the Sec-Fetch-Site header equals cross-site, compared case-insensitively. A request without the header (an older browser, a non-browser client) is not treated as cross-site (:150-155), so the check narrows the cookie write for browsers that send fetch metadata without breaking clients that do not.
    • ApplyPipeline (:164, private) is the whole application step: seed the defaults (:166), let the host's delegate adjust them if there is one (:167), then foreach over builder.Build() invoking each step's Configure in order (:169-172). Because both public overloads route through here, the zero-argument path is exactly the validated default pipeline (:159-163).
  • Why it's built this way: pushing the step list out into MiddlewarePipelineBuilder and keeping only ApplyPipeline here is what lets the order be inspected and asserted while the entry point stays a single line in a host's Program.cs. The configure-then-Build sequence is deliberate: the host mutates first and the invariants are checked last, so a customization is judged on its result rather than on the order the host happened to make its edits.
  • Where it's used: called once per service host after app.Build(). The ADC and Store service hosts reach UseCommonMiddlewarePipeline through await app.UseMmcaServiceHostAsync(host) (MMCA.Common/Source/Hosting/MMCA.Common.ServiceHost/ServiceHostApplicationExtensions.cs:59 and :63), for example MMCA.ADC/Source/Services/MMCA.ADC.Conference.Service/Program.cs:379, MMCA.ADC/Source/Services/MMCA.ADC.Notification.Service/Program.cs:152 and MMCA.Store/Source/Services/MMCA.Store.Sales.Service/Program.cs:154; Helpdesk calls it directly (MMCA.Helpdesk/Source/Hosts/MMCA.Helpdesk.Web/Program.cs:170). The Blazor UI hosts instead get the localization and culture-endpoint members through the shared Blazor Web pipeline (MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/Hosting/BlazorWebHostExtensions.cs:201 and :211), which the ADC UI host invokes with app.UseMmcaBlazorWebPipeline(...) (MMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI.Web/Program.cs:120).
  • Caveats / not-in-source: a host that maps additional endpoints (SignalR hubs, minimal-API endpoints, app-association documents) does so after this call; the framework cannot enforce that ordering, it only documents it on the members that require it (for example SignalRExtensions.MapNotificationHub, MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/SignalRExtensions.cs:16-21). Note also that this is the only WebApplicationExtensions in MMCA.Common (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/WebApplicationExtensions.cs:15): the server-rendered UI pipeline is UseMmcaBlazorWebPipeline (MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/Hosting/BlazorWebHostExtensions.cs:181), which reuses this class's localization and culture members rather than shipping its own.

DatabaseInitializationExtensions

MMCA.Common.API · MMCA.Common.API.Startup · MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/DatabaseInitializationExtensions.cs:28 · Level 12 · class (static, two extension blocks)

  • What it is: the shared startup routine every downstream host calls once after app.Build(), either directly or through a WebApplication wrapper that skips it during build-time OpenAPI generation. It walks each physical data source the host actually uses, creates or migrates that schema according to the configured strategy, repeats the pass for every tenant that keeps its own copy of a source, and finally runs each enabled module's seeder.
  • Depends on: IEntityDataSourceRegistry, IDataSourceResolver, IDbContextFactory, DataSourceKey and its DataSource engine enum, PhysicalDataSource, TenantDataSourceTargets / TenantDataSourceTarget, ITenantContext, TenancySettings, ApplicationSettings, ModuleLoader, and ModuleHostContext for the WebApplication wrapper. Externally it uses only IServiceProvider scoping, IOptions<T>, the host's environment and configuration, and EF Core's DatabaseFacade (MigrateAsync, EnsureCreatedAsync, GetPendingMigrationsAsync).
  • Concept (strategy-driven, per-source database initialization). [Rubric §8, Data Architecture] assesses deliberate persistence decisions including migrations: because of database-per-service (ADR-006) a host may own several physical databases at once, so "initialize the database" is really a loop over sources, and polyglot persistence (ADR-018) means those sources do not all have a migrations pipeline. [Rubric §17, DevOps] assesses how schema reaches an environment: the single DatabaseInitStrategy string is the switch between a host that self-migrates on boot ("Migrate", the default in every environment, made multi-replica-safe by the migrations lock and the raised timeout below) and a host whose migrations are applied out of band and which must therefore refuse to start if it finds itself behind ("None"). [Rubric §13, Observability & Operability]: every failure path here throws a message that names the offending value or the exact pending migrations plus the command to run, so a bad boot is diagnosable from the startup log alone.
  • Walkthrough: the public surface is two extension members in two extension(T) blocks, one on IServiceProvider (DatabaseInitializationExtensions.cs:39) and one on WebApplication (:151), declared with C# extension(T) syntax like the rest of the framework's DI and startup helpers. The class carries a justified CA1708 suppression because multiple extension blocks in one static class trip that rule on compiler-generated grouping members (:24-27).
    • InitializeDatabaseAsync(applicationSettings, moduleLoader, cancellationToken) (:51-54) starts by null-guarding all three inputs (:56-58).
    • Strategy is validated first (:63). EnsureKnownStrategy (:292) accepts only the ordinal strings "Migrate" and "None" (:294-295) and otherwise throws UnknownStrategy (:297), whose message names the valid values (:304-305). The comment (:60-62) gives the reason for doing it up front: a misspelled strategy is a configuration mistake, and the host must stop before the code below has already created the migrationless sources.
    • It then opens a scope (:65) and warms the entity data-source registry: resolving IEntityDataSourceRegistry and calling GetPhysicalSourcesInUse() (:70-72) scans the configuration assemblies once so entity-to-database routing is deterministic before the first repository call, replacing a lazy model-building side effect (:67-69).
    • The migrationless pass (:90-106) walks every source in use with no engine filter (:90). A source with an empty connection string is skipped (:94-97), since integration tests may omit one; a source where PhysicalDataSource.UsesMigrations is true is also skipped (:99-102); everything left is created outright with EnsureCreatedAsync (:104-105). The comments carry the load here. The first (:76-82) says this is the only path that creates such a source (without it the first repository call fails) and that the per-tenant pass repeats it for a tenant's own copy under either strategy. The second (:84-86) explains the UsesMigrations exclusion: running EnsureCreated against a PostgreSQL or SQLite source that does have a migrations assembly writes the tables with no __EFMigrationsHistory row, after which every migration is both pending and un-appliable because its CREATE TABLE hits an existing table. The third (:88-89) is why no engine filter is needed: a SQL Server source always answers UsesMigrations and is skipped, so only a migration-less source reaches EnsureCreated. UsesMigrations itself is the per-engine rule on the source record, read from the engine's MigrationPolicy capability (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/PhysicalDataSource.cs:42-48): Always (SQL Server), WhenAssemblyConfigured (PostgreSQL and SQLite, true only with a configured migrations assembly), Never (Cosmos), per the doc comment above it (PhysicalDataSource.cs:36-39).
    • A long command timeout wraps migration and seeding. InitializationCommandTimeout (:37) is five minutes. Before the strategy switch, RaiseCommandTimeouts (:259, called at :112) walks the sources in use, skips any with no connection string (:267-270) or a non-relational provider (:273-276), and raises each context's command timeout to that value, recording the previous one (:278-279). The comment (:108-111) gives the reason: with several replicas starting together, every replica but one waits on EF's migrations lock (__EFMigrationsLock), and a wait past the 30-second default would kill that replica's startup. The seeders resolve the same scoped context factory, so the raised timeout covers them too. The switch, the tenant pass and the seeding all sit inside a try (:113), and a finally restores every recorded timeout (:141-147). The tenant pass applies the same timeout to each tenant context (:221-224) but restores nothing, because that scope and its context end with the loop iteration (:219-220).
    • The strategy switch (:120-130) has exactly two live branches, and the comment above it (:115-119) describes both: "Migrate" auto-applies pending migrations per migrated source in every environment, as the multi-replica-safe default, while "None" is for migrations applied out of band. "Migrate" delegates to IDbContextFactory.MigrateAsync (:123), which applies pending migrations for every migration-owned source in use (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/Factory/IDbContextFactory.cs:74-82). "None" calls ThrowIfPendingMigrationsAsync (:126). The default arm rethrows UnknownStrategy (:129), unreachable in practice because of the guard at :63 but kept so the switch is total.
    • The tenant pass runs next (:132-133) and module seeding last (:139). Seeding deliberately runs on the default scope only; the comment (:135-138) states the rationale: a seeder writes reference data the application needs to boot, no module declares which of its seeders are tenant-scoped, and running one twice against a shared database is worse than not running it per tenant at all.
    • InitializeDatabaseUnlessDesignTimeAsync(moduleHost, cancellationToken) (:169) is the WebApplication wrapper the service hosts call. It null-guards both the app and the ModuleHostContext (:173-174), returns a completed task without touching any database when the environment is Development and the MmcaOpenApiDesignTime configuration switch (OpenApiDesignTimeKey, :31) is true (:176-179), and otherwise forwards to InitializeDatabaseAsync with moduleHost.ApplicationSettings and moduleHost.ModuleLoader (:181-184). The remarks (:157-164) give the reason: build-time OpenAPI generation (MmcaGenerateOpenApiDocument) starts the host with no database reachable, and the schema step is the one startup action that throws rather than logs when it cannot connect. Honouring the switch only in Development means a host in any other environment can never be talked out of initializing its schema (ADR-122).
    • InitializeTenantDatabasesAsync (:198) resolves IOptions<TenancySettings> with GetService rather than GetRequiredService (:205) and returns immediately when tenancy was never registered or no tenants are configured (:206-209). Otherwise it expands the sources into targets via TenantDataSourceTargets.Expand and keeps only the ones with a tenant id (:211-212), because Expand also emits the shared, tenant-less target for each source, which the pass above already handled. For each target it opens a fresh scope through IServiceScopeFactory.CreateTenantScope(target) (:214), the shared helper (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/TenantDataSourceTargets.cs:100) every other per-tenant background pass (the outbox processor, the internal-command processor, the audit-trail and outbox cleanup jobs) also calls; it creates the scope and, when the target carries a tenant id, calls ITenantContext.SetTenant on it before returning (TenantDataSourceTargets.cs:109), so the tenant is always set before anything asks that scope for a context. The remark (:193-197) is still the reason a fresh scope is required at all: the scoped context factory binds one physical database per source for the life of a scope, so reusing the outer scope would keep handing back the shared database.
    • Per tenant it reads UsesMigrations off the shared resolved source (:229), on the grounds stated at :226-228: a tenant's copy is the same schema on a different connection, the migrations assembly is declared once on the source, and a per-tenant override only replaces the connection string. It then applies the same strategy (:231-250): under "Migrate" a migrated source gets MigrateAsync and anything else gets EnsureCreatedAsync (:233-243), under "None" it defers to ApplyNoneStrategyToTenantAsync (:245).
    • ApplyNoneStrategyToTenantAsync (:312, private) is the tenant-side "None" branch. A migration-less tenant copy (Cosmos, or PostgreSQL/SQLite with no migrations assembly) is created with EnsureCreatedAsync (:318-322), mirroring the shared migrationless pass, because nothing else ever creates it (:307-311); every other copy goes to ThrowIfTenantPendingMigrationsAsync (:324).
    • The two out-of-band rails. ThrowIfTenantPendingMigrationsAsync (:332) no-ops for a non-migrated source (:338-341), otherwise queries GetPendingMigrationsAsync (:343) and, when anything is pending, throws naming the tenant target, the migrations, and the dotnet ef database update remedy (:349-352). ThrowIfPendingMigrationsAsync (:361) short-circuits on IDbContextFactory.HasPendingMigrationsAsync (:367-370), then builds a per-source breakdown by re-querying each key whose resolved source answers PhysicalDataSource.IsMigrationTarget (:372-381) before throwing (:383-385). IsMigrationTarget now lives on the source record (PhysicalDataSource.cs:57-60): a source that UsesMigrations and either belongs to an engine whose sources require a connection string (SQL Server, so a missing one fails loudly at startup) or has one configured. Its doc comment (PhysicalDataSource.cs:50-56) states that the context factory and this initializer share that one rule, so the breakdown names exactly the sources the factory checked rather than an empty list (:355-360).
  • Why it's built this way: one shared init path keeps every service host consistent, so adding a database engine or a tenant changes this file rather than five Program.cs files. PostgreSQL joining the migrationless pass alongside Cosmos and SQLite (ADR-113) is exactly that: a host that names no PostgreSQLMigrationsAssembly gets the same EnsureCreatedAsync treatment a migrations-less SQLite source already got, with no change to the strategy switch below it. The "None" strategy is the deploy-time guarantee that an app never serves traffic against an un-migrated database when migrations are applied out of band, and validating the strategy string before any side effect keeps a typo from silently degrading into "schema untouched, first query fails". The tenant pass exists because nothing else ever opens a per-tenant database (ADR-073), so without it such a database is never created and never migrated (:188-192). The "None" tenant branch creating a migration-less copy keeps that true under either strategy, matching what the shared pass already did. Skipping initialization for build-time OpenAPI generation through a Development-only switch, rather than a flag any environment can set, keeps the one exemption from becoming a way to boot production against an untouched schema.
  • Where it's used: called once per host after app.Build(), before the middleware pipeline is wired. The ADC and Store service hosts reach the wrapper, InitializeDatabaseUnlessDesignTimeAsync(host.ModuleHost, ...), through await app.UseMmcaServiceHostAsync(host) (MMCA.Common/Source/Hosting/MMCA.Common.ServiceHost/ServiceHostApplicationExtensions.cs:54; call sites MMCA.ADC/Source/Services/MMCA.ADC.Conference.Service/Program.cs:379, MMCA.Store/Source/Services/MMCA.Store.Sales.Service/Program.cs:154), which reads ApplicationSettings and ModuleLoader off ModuleHostContext (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/ModuleHostContext.cs:41, :51); Helpdesk calls InitializeDatabaseAsync directly with its own settings and loader (MMCA.Helpdesk/Source/Hosts/MMCA.Helpdesk.Web/Program.cs:167). The migrationless-engine loop and the strategy contract are covered by DatabaseInitializationExtensionsTests (MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/Startup/DatabaseInitializationExtensionsTests.cs:43, :97, :145, :183, :233), which exercise SQLite create, SQLite migrate, the "None" failure message, the "None" creation of a migration-less tenant copy, and the unknown-strategy guard.
  • Caveats / not-in-source: which strategy a given deployment runs is configuration, not code. The framework default is "Migrate" (MMCA.Common/Source/Core/MMCA.Common.Application/Settings/ApplicationSettings.cs:46); what any environment overrides it to lives in that app's settings and cannot be read here. The tenant pass is also only as complete as TenancySettings: Expand emits a tenant target only when the tenant declares an override connection string for that source, so a tenant that shares the default database is initialized by the shared pass and never appears in the per-tenant loop.

AppAssociationOptions

MMCA.Common.API · MMCA.Common.API.Startup.Endpoints · MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/Endpoints/AppAssociationOptions.cs:9 · Level 0 · class (sealed)

  • What it is: the strongly-typed options bag carrying the identifiers a mobile OS needs in order to verify that an installed native app may claim this host's https links. It feeds AppAssociationEndpointExtensions, which serializes it into the two well-known documents (Android Digital Asset Links and the Apple App Site Association).
  • Depends on: nothing first-party. BCL only (IReadOnlyList<string>).
  • Concept introduced (deep-link / universal-link association). For a Blazor Hybrid app to open a shared web URL directly in the installed native app rather than the browser, the operating system fetches an association document from the URL's host and checks that the installed app's signing identity matches what the document names. This options type is the single source of those identities, so a certificate rotation is a config change and not a code change (the doc comment says exactly that at AppAssociationOptions.cs:3-8). [Rubric §9, API & Contract Design] assesses whether public contracts are typed and pinned rather than hand-built inline; here the "public contract" is the exact JSON payload Google and Apple parse, and binding its inputs from an AppAssociation configuration section is that discipline. [Rubric §11, Security] also applies: the fingerprints in this bag are what stop an unrelated app from claiming the host's links.
  • Walkthrough: four members, all init-only.
    • AndroidPackageName (AppAssociationOptions.cs:12, required): the Android application id declared in assetlinks.json.
    • AndroidCertFingerprints (AppAssociationOptions.cs:18, defaults to []): the SHA-256 signing-certificate fingerprints; the doc comment (:14-17) warns that for Play-distributed builds this is the Play App Signing certificate, not the local upload keystore.
    • AppleAppId (AppAssociationOptions.cs:21, required): the TeamID.BundleID value used by both the webcredentials and the applinks sections.
    • AppleAppLinkComponents (AppAssociationOptions.cs:28, defaults to []): the URL patterns (for example "/conference/*") that each become a { "/": pattern } component; the comment (:23-27) notes these should mirror the app's shared Blazor routes, because identical URLs on web and device is the Blazor Hybrid payoff (no route-translation table).
  • Why it's built this way: required init gives compile-checked construction plus immutability once bound (see the primer on required/init immutability), which matches the lifetime: a host builds one instance at startup and the endpoint reads it for the process lifetime. Defaulting the two collections to [] means a host that ships only one platform still constructs a valid document for the other. See ADR-043 for the deep-link decision this serves.
  • Where it's used: constructed inline by the ADC Blazor web host and passed straight to the mapper, with the Android and Apple identifiers read from the AppAssociation configuration section (with in-code fallbacks) and the applinks patterns hard-coded to the app's routes (MMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI.Web/Program.cs:135-146). The comment there (:180-183) records a trap worth reading: the Release Android head overrides ApplicationId to ivanball.AtlDevCon, so that is the package Digital Asset Links must name, not the Debug-only id.
  • Caveats / not-in-source: the type performs no validation. Whether a fingerprint or bundle id is the correct one for the shipped app is only observable at install time on the device.

Entry

MMCA.Common.API · MMCA.Common.API.Startup.Endpoints · MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/Endpoints/JwksEndpointExtensions.cs:84 · Level 0 · record (private sealed, nested)

  • What it is: the single slot SerializedKeySetCache holds: the JsonWebKeySet instance it last served beside that set's serialized JSON, as the positional pair (KeySet, Json) (JwksEndpointExtensions.cs:84).
  • Depends on: Microsoft.IdentityModel.Tokens.JsonWebKeySet and BCL string. Nested in, and only constructed by, SerializedKeySetCache.
  • Concept: the serialize-once memo is introduced at SerializedKeySetCache; this record is its payload. [Rubric §12, Performance & Scalability] applies through that type.
  • Walkthrough: two members. KeySet is the cache key, and the cache compares it by object identity with ReferenceEquals, never by value (JwksEndpointExtensions.cs:72). Json is the document the endpoint writes on a hit (:74) and after a rebuild (:81).
  • Why it's built this way: keeping the key set and its JSON in one immutable object lets the cache publish both with a single Volatile.Write (:80) and read both with a single Volatile.Read (:71), so a request can never pair the identity of one key set with the JSON of another, and no lock is needed.
  • Where it's used: created only in SerializedKeySetCache.Serialize (JwksEndpointExtensions.cs:79) and held in the cache's _entry field (:67).
  • Caveats / not-in-source: the simple name is shared with other nested records that have nothing to do with this one: SerializedDocumentCache.Entry on the OIDC discovery path (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/Endpoints/OidcDiscoveryEndpointExtensions.cs:153, the pair (Issuer, Json), covered under SerializedDocumentCache), the inbox consume marker nested in InboxConsumeScope (G04), and the health-report cache slot in CachedHealthReportProvider (G16). The Entry anchor in this group resolves to this section.

MiddlewarePipelineStep

MMCA.Common.API · MMCA.Common.API.Startup.Pipeline · MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/Pipeline/MiddlewarePipelineStep.cs:21 · Level 0 · record (sealed, positional)

  • What it is: one named step of the shared HTTP edge pipeline: a stable string identifier plus the delegate that registers that step's middleware on a WebApplication. It is the atom that makes the edge order data rather than a hand-written sequence of app.UseX() calls.
  • Depends on: ASP.NET Core's WebApplication (through the Action<WebApplication> payload) and nothing else first-party. Its names normally come from MiddlewarePipelineStepNames; its container is MiddlewarePipelineBuilder.
  • Concept introduced (the pipeline as an inspectable list, not an imperative script). A conventional ASP.NET composition root is its own ordering: the order exists only as the sequence of statements in Program.cs, so nothing can read it, assert on it, or edit it. Modelling each step as a value with a name means the whole order can be enumerated (StepNames on the builder), rewritten by name, validated, and frozen by a unit test with no host running at all. The doc comment states the payoff directly: steps are pure data until UseCommonMiddlewarePipeline runs them in order, which is what makes the pipeline order testable without a running host (MiddlewarePipelineStep.cs:5-10). [Rubric §2, Design Patterns] assesses whether a recognizable pattern is applied where it earns its keep; this is the classic "reify the plan, then execute it" split, and it is what unlocks the fitness function. [Rubric §14, Testability] assesses whether behavior can be asserted cheaply: because a step never touches a host until Configure is invoked, the entire order runs in the fast unit tier.
  • Walkthrough: a positional record with two components, each re-declared as a validated property.
    • Name (MiddlewarePipelineStep.cs:27) shadows the positional parameter with Validated(Name), which calls ArgumentException.ThrowIfNullOrWhiteSpace (:32-36). Null, empty, and whitespace names are rejected at construction, so an anchor lookup can never match a meaningless key.
    • Configure (:30) is validated the same way through the second Validated overload, which null-guards the delegate (:38-42).
    • The init accessors keep both immutable after construction, so a step handed to the builder cannot be mutated behind the builder's back.
    • The parameter doc records the runtime contract: Configure is invoked exactly once, in pipeline order, at the point UseCommonMiddlewarePipeline is called, so anything the delegate reads from the host (configuration, environment) is evaluated at configure time and not per request (:16-20).
  • Why it's built this way: the validation-in-the-property-initializer idiom is how a positional record enforces invariants without giving up the concise declaration or the value semantics. Value equality also matters here: two steps with the same name and delegate compare equal, which keeps assertions in MiddlewarePipelineBuilder tests simple. See ADR-079, which records the move from an inline sequence to named steps.
  • Where it's used: MiddlewarePipelineBuilder.CreateDefault() constructs eighteen of them (MiddlewarePipelineBuilder.cs:31-151), and a host customizing the pipeline constructs its own to pass to InsertBefore / InsertAfter / Replace.
  • Caveats / not-in-source: name uniqueness is not enforced here; it is enforced by the builder's RequireUniqueName at insertion time (MiddlewarePipelineBuilder.cs:313-321). Constructing two steps with the same name in isolation is legal.

MiddlewarePipelineStepNames

MMCA.Common.API · MMCA.Common.API.Startup.Pipeline · MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/Pipeline/MiddlewarePipelineStepNames.cs:14 · Level 0 · class (static, constants)

  • What it is: the nineteen well-known step names of the default edge pipeline, as const string fields declared in runtime order. A host customizing the pipeline addresses steps by these constants.
  • Depends on: nothing. It is referenced by MiddlewarePipelineBuilder (which seeds the defaults with these names and re-checks adjacencies by them) and by MiddlewarePipelineOrderTestsBase.
  • Concept (names as a published contract). Because a host inserts, replaces, and removes steps by name, the names are part of the framework's public API surface: the doc comment says so outright and adds that renaming one is a breaking change (MiddlewarePipelineStepNames.cs:3-7). [Rubric §9, API & Contract Design] assesses whether the surface a consumer binds to is explicit and stable; hoisting each name into a const is what turns a magic string into that surface, and what lets the compiler find every caller when the list changes. [Rubric §34, Architecture Governance & Documentation] also applies: the declaration order below the summary is the documented runtime order, so the code and the documentation cannot drift apart.
  • Walkthrough: the constants in declaration order, which is application order (outermost first).
    • ExceptionHandler (:17), CorrelationId (:20), RequestLocalization (:23).
    • ForwardedHeaders (:26), HttpsRedirection (:29), ResponseCompression (:32), Routing (:35).
    • JsonBodySizeLimit (:42), the JSON request body ceiling (Api:MaxJsonBodyBytes, default 1 MiB) for endpoints that carry no request size metadata of their own, wired as JsonRequestBodyLimitMiddleware. Its comment (:37-41) records why it sits after Routing: it reads the selected endpoint's metadata.
    • Cors (:45), Authentication (:48).
    • TenantResolution (:54), whose comment (:50-53) records that it must run immediately after Authentication because the claim strategy reads HttpContext.User.
    • RateLimiting (:57), documented as needing to run after Authentication per ADR-019.
    • SoftDeletedUserFilter (:60).
    • ViewAsGuard (:66), the read-only view-as guard of ADR-137 wired as ViewAsGuardMiddleware. Its comment (:62-65) records that the step is always present: with ViewAs:Enabled false it refuses every view-as token.
    • Authorization (:69), OutputCache (:72).
    • JwksEndpoint (:75), OidcDiscoveryEndpoint (:78), and Controllers (:81), the innermost step.
    • The class summary (:8-12) flags that several of these adjacencies are load-bearing and are re-checked by MiddlewarePipelineBuilder.Build.
  • Why it's built this way: const rather than static readonly so the values are usable in attribute arguments and switch patterns, and one file rather than a nested enum so the XML doc on each field can carry the ordering rationale next to the name it explains. See ADR-079.
  • Where it's used: MiddlewarePipelineBuilder.CreateDefault() names every seeded step with these constants; Build() names them again in its six invariant checks; and MiddlewarePipelineOrderTestsBase.ExpectedStepNames (MMCA.Common/Source/Hosting/MMCA.Common.Testing/Conformance/MiddlewarePipelineOrderTestsBase.cs:40-61) lists all nineteen as the frozen expected order, which each app's MiddlewarePipelineOrderTests subclasses.

OpenApiEndpointExtensions

MMCA.Common.API · MMCA.Common.API.Startup.Endpoints · MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/Endpoints/OpenApiEndpointExtensions.cs:26 · Level 0 · class (static, extension block)

  • What it is: one extension(WebApplication app) mapping helper, MapCommonOpenApi(), that exposes the generated OpenAPI document in Development only, or in any environment where the OpenApi:ExposeOutsideDevelopment switch is true (default false).
  • Depends on: Microsoft.AspNetCore.OpenApi for MapOpenApi() and the keyed IOpenApiDocumentProvider it probes; IConfiguration for the exposure switch. It pairs with the host's own services.AddOpenApi(), which registers the v1 document, plus AddCommonOpenApi() on WebApplicationBuilderExtensions, which only configures the registered documents and registers none of its own (doc comment OpenApiEndpointExtensions.cs:13-14, :46-47).
  • Concept introduced (the OpenAPI document as a dev/CI artifact, not a public surface). [Rubric §9, API & Contract Design] assesses whether an API has a machine-readable contract and whether that contract is guarded against silent drift. The doc comment (OpenApiEndpointExtensions.cs:10-25) is explicit that the guarding happens at two levels: the framework-owned part of the generated document (the unbound-route-token backfill, the generated ProblemDetails error schema) is diffed against a committed baseline in-repo by OpenApiBaselineTests (MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/OpenApi/OpenApiBaselineTests.cs), which fails on any change until the baseline is regenerated deliberately in the same pull request, while each consumer's concrete API surface stays the concern of that host's committed document and its contract-snapshot tests. Mapping in Development only is the security posture [Rubric §11, Security]: the spec is a dev/CI artifact, not a surface for a Staging, UAT or Production environment the internet can reach (:21-24), so those environments answer 404 unless the switch is set (:41-44).
  • Walkthrough
    • DefaultDocumentName (OpenApiEndpointExtensions.cs:29) is the private constant "v1": the document name plain AddOpenApi() registers and this endpoint serves.
    • ExposeOutsideDevelopmentConfigKey (OpenApiEndpointExtensions.cs:36) is the internal constant "OpenApi:ExposeOutsideDevelopment"; its doc comment (:31-35) names the intended setter: a test or tooling host that reads the live document under another environment name.
    • MapCommonOpenApi() (OpenApiEndpointExtensions.cs:69) maps only when the environment is Development or GetValue<bool> reads the switch as true (:71-72); everywhere else it does nothing and returns app for chaining (:87). Where it maps, it first resolves IServiceProviderIsKeyedService and checks that a keyed IOpenApiDocumentProvider exists for "v1" (:74-75); if not, it throws InvalidOperationException telling the host to call services.AddOpenApi() in the host project itself, because that is the call the OpenAPI XML-comment generator intercepts to attach the host's summaries (:77-81). A host that calls only the framework method therefore fails at startup (and at build-time document generation) instead of silently serving no document (doc comment :46-50). It then maps the document with app.MapOpenApi().AllowAnonymous() (:84). The anonymous declaration is load-bearing: the framework's fallback authorization policy gates every endpoint that states nothing and /openapi is not one of its exempt prefixes, so an undeclared mapping would answer 401 to the contract-snapshot tests and API tooling (doc comment :52-58).
    • The method carries a [SuppressMessage("Usage", "AV0030:Missing WithDocumentPerVersion")] (:65-68). The justification records why: the analyzer fires because AddCommonApiVersioning's AddApiExplorer call lives in this assembly, but no versioned OpenAPI registration exists (Asp.Versioning.OpenApi is not referenced, so WithDocumentPerVersion() is not available). The host serves the single plain v1 document.
    • There is no interactive reference UI in the framework: the class exposes only the JSON document.
  • Why it's built this way: one shared helper keeps every service's OpenAPI story identical and enforces the "internal spec, not public surface" convention in one place instead of per host. Keying on Development rather than "not Production" means a Staging or UAT slot stays closed by default (ADR-122), and the explicit switch is the one way to open it, so a test host can read the live document under a non-Development environment without the framework guessing. The registration guard turns a missing host AddOpenApi() call (which would otherwise lose the XML-comment summaries or serve nothing) into a startup failure, and the explicit AllowAnonymous() keeps the contract reachable before a client holds a token without widening the fallback policy's exempt list. API versioning itself is ADR-046.
  • Where it's used: service hosts reach it through the shared service-host composition, which calls app.MapCommonOpenApi() right after UseCommonMiddlewarePipeline (ServiceHostApplicationExtensions, MMCA.Common/Source/Hosting/MMCA.Common.ServiceHost/ServiceHostApplicationExtensions.cs:66). The ADC integration tiers subclass OpenApiContractTestsBase (MMCA.Common/Source/Hosting/MMCA.Common.Testing/Conformance/OpenApiContractTestsBase.cs:32), for example MMCA.ADC/Tests/Integration/MMCA.ADC.Conference.IntegrationTests/Contract/OpenApiContractTests.cs:15; the shared ServiceHostTestFactory turns the switch on for them (MMCA.Common/Source/Hosting/MMCA.Common.Testing/Fixtures/ServiceHostTestFactory.cs:89). In the framework, OpenApiProbeHost (MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/OpenApi/OpenApiProbeHost.cs:44-45 registers, :65 maps) is what OpenApiBaselineTests boots; MapCommonOpenApiAuthorizationTests (MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/OpenApi/MapCommonOpenApiAuthorizationTests.cs) pins the anonymous declaration; and MapCommonOpenApiExposureTests pins the environment gate: 404 outside Development without the switch or with it false, the document in Development, and the document outside Development with the switch on (MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/OpenApi/MapCommonOpenApiExposureTests.cs:26-55).

OversizeFormResourceFilter

MMCA.Common.API · MMCA.Common.API.Uploads · MMCA.Common/Source/Presentation/MMCA.Common.API/Uploads/OversizeFormResourceFilter.cs:22 · Level 0 · class (internal sealed, MVC resource filter)

  • What it is: a global IAsyncResourceFilter that reads the request form before model binding for any action that binds a form or a form file, so a body over the endpoint's size limit answers 413 Payload Too Large instead of 400 (doc comment OversizeFormResourceFilter.cs:8-14).
  • Depends on: ASP.NET Core MVC filter and model-binding abstractions (IAsyncResourceFilter, ActionDescriptor, BindingSource) and BadHttpRequestException. Its 413 reaches GlobalExceptionHandler, which answers it as "Payload Too Large".
  • Concept (the right status code for a refused body). [Rubric §9, API & Contract Design] assesses whether an API reports failures with accurate, consistent status codes. Without this filter, model binding catches the server's "request body too large" refusal and turns it into a model-state error, which [ApiController] answers as 400: a client cannot tell "your form is malformed" from "your file is too big". Reading the form one step earlier lets the same refusal surface as a BadHttpRequestException carrying 413 (:8-14).
  • Walkthrough
    • FilterOrder (OversizeFormResourceFilter.cs:29) is 1000: after [RequestSizeLimit] and [RequestFormLimits] (both order 900), so the endpoint's own limits are applied before the body is read (:24-28).
    • OnResourceExecutionAsync (:32) null-guards both arguments (:34-35), then only when the request has a form content type and the action binds a form (:38) calls ReadFormAsync with the request-aborted token (:42). A BadHttpRequestException whose status is not 413 is swallowed (:44), as is InvalidDataException (:48), so a malformed form or one over a form limit is still reported by model binding as before. A 413 propagates. It always calls next() (:54).
    • BindsForm (:57-60) is true when any action parameter's binding source is Form or FormFile.
  • Why it's built this way: the change is narrow on purpose (:15-20). Only the oversize refusal changes; an action that binds no form (a streaming upload that reads the body itself) is never touched, so its body is not buffered here; and the form read is cached on the request, so binding does not read the body twice.
  • Where it's used: registered globally by AddAPI on DependencyInjection as options.Filters.Add<OversizeFormResourceFilter>(OversizeFormResourceFilter.FilterOrder) (MMCA.Common/Source/Presentation/MMCA.Common.API/DependencyInjection.cs:53), so every MVC host gets it.

UploadedFileContent

MMCA.Common.API · MMCA.Common.API.Uploads · MMCA.Common/Source/Presentation/MMCA.Common.API/Uploads/FormFileUploadExtensions.cs:16 · Level 0 · record (sealed, positional)

  • What it is: an uploaded file read into memory by ReadBoundedAsync: the bytes, plus the file name and content type exactly as the client declared them (doc comment FormFileUploadExtensions.cs:8-14).
  • Depends on: nothing first-party.
  • Concept: the result shape of the bounded upload read taught on FormFileUploadExtensions.
  • Walkthrough: Content (byte[]), FileName (not normalized) and ContentType (:16). The class-level [SuppressMessage("Performance", "CA1819")] (:15) records why the record exposes an array: the bytes go to a command unchanged, and a defensive copy would double the upload in memory.
  • Why it's built this way: the declared name and type travel beside the bytes untouched, so any normalization or content sniffing is the receiving command's decision, not the edge's. [Rubric §12, Performance & Scalability]: one buffer of the declared length, never copied again.
  • Where it's used: returned by ReadBoundedAsync and carried inside CsvUpload; ADC upload actions consume it (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.API/Controllers/SessionAssets/SessionAssetsController.cs:202, MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/Controllers/UsersController.cs:171). Covered by FormFileUploadExtensionsTests (MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/Uploads/FormFileUploadExtensionsTests.cs).

AppAssociationEndpointExtensions

MMCA.Common.API · MMCA.Common.API.Startup.Endpoints · MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/Endpoints/AppAssociationEndpointExtensions.cs:15 · Level 1 · class (static, extension block)

  • What it is: a mapping helper that serves the two well-known app-association documents from an AppAssociationOptions: Android Digital Asset Links at /.well-known/assetlinks.json and the Apple App Site Association at /.well-known/apple-app-site-association.
  • Depends on: AppAssociationOptions (Level 0) for every value; ASP.NET IEndpointRouteBuilder and Results.Json.
  • Concept (anonymous, machine-verified association documents). Both endpoints are anonymous by design because the OS and Apple's CDN fetch them without credentials, which the doc comment states (AppAssociationEndpointExtensions.cs:12-13). [Rubric §9, API & Contract Design]: the exact JSON shape is a contract a third party parses, so the code builds it structurally out of dictionaries rather than formatting strings by hand.
  • Walkthrough
    • Two path constants: AssetLinksPath (AppAssociationEndpointExtensions.cs:18) and AppleAppSiteAssociationPath (:24). The comment on the Apple constant (:20-23) records that the path deliberately has no file extension because Apple requires that exact path, while the content type must still be JSON.
    • MapAppAssociationEndpoints(AppAssociationOptions options) (:35) null-guards the options (:37), builds both documents once at map time because they are static for the process lifetime (:39-40), then maps two GETs that each return Results.Json(...), are .AllowAnonymous() and are .ExcludeFromDescription() so they never leak into the OpenAPI document (:42-48).
    • BuildAssetLinks (:54) emits the delegate_permission/common.handle_all_urls relation with the Android package name and the fingerprint list (:56-65).
    • BuildAppleAppSiteAssociation (:68) emits the applinks details block, projecting each configured URL pattern into a { "/": pattern } component (:78-80), plus the webcredentials apps list naming the same app id (:84-87).
  • Why it's built this way: building the payload once at map time avoids a per-request allocation for a document that never changes [Rubric §12, Performance & Scalability], and holding the RFC 8615 well-known paths as public constants keeps them from drifting between hosts or between the endpoint and any gateway forwarding rule.
  • Where it's used: the ADC Blazor web host maps them once at startup (MMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI.Web/Program.cs:136), which is the host that ships a companion MAUI Hybrid app. Both documents' exact shapes are asserted by AppAssociationEndpointTests (MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/Startup/AppAssociationEndpointTests.cs).

SerializedKeySetCache

MMCA.Common.API · MMCA.Common.API.Startup.Endpoints · MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/Endpoints/JwksEndpointExtensions.cs:65 · Level 1 · class (private sealed, nested)

  • What it is: the memo behind the JWKS endpoint: it serializes a JsonWebKeySet once and returns the same JSON for as long as the provider hands back the same key set instance. A different instance (a provider that rebuilt its keys) is serialized again (doc comment JwksEndpointExtensions.cs:61-64).
  • Depends on: Entry (its one cached slot), Microsoft.IdentityModel.Tokens.JsonWebKeySet, System.Text.Json.JsonSerializer and System.Threading.Volatile.
  • Concept introduced (a lock-free serialize-once memo keyed on reference identity). [Rubric §12, Performance & Scalability] assesses whether repeated work on a hot path is avoided cheaply. Every validator and ingress fetches the JWKS document, and its content changes only when the provider's keys do, so serializing it per request is pure waste. The cache keys on the key set object, not its content: comparing references costs nothing, and a provider that changes its keys signals the change by returning a new instance (:62-63).
  • Walkthrough
    • One field, _entry (JwksEndpointExtensions.cs:67), null until the first request.
    • Serialize(JsonWebKeySet) (:69) reads the field with Volatile.Read (:71); when an entry exists and its KeySet is ReferenceEquals to the argument, it returns the cached JSON (:72-75).
    • Otherwise it builds a new Entry holding the key set and JsonSerializer.Serialize(keySet) (:79), publishes it with Volatile.Write (:80), and returns its JSON (:81).
  • Why it's built this way: there is no lock because the only race is benign, and the comment says so: two first requests may both serialize and either write wins, because both produce the same document (:77-78). Publishing one immutable Entry through a volatile write is what keeps a reader from ever seeing a half-updated pair. Holding one entry rather than a dictionary matches the provider's shape: one current key set at a time.
  • Where it's used: MapJwksEndpoint() creates one instance per mapping (JwksEndpointExtensions.cs:45), captured by the handler, which calls cache.Serialize(provider.GetJsonWebKeySet()) per request (:49). The swap case is pinned by WellKnownEndpointHardeningTests.GetJwks_AfterTheProviderSwapsItsKeySet_ServesTheNewKeys (MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/Startup/Endpoints/WellKnownEndpointHardeningTests.cs:116).
  • Caveats / not-in-source: correctness rests on the provider's contract stated in the doc comment (:62-63): new keys arrive as a new instance. A provider that mutated one JsonWebKeySet in place would keep being served its first serialization, because identity, not content, is compared.

CsvUpload

MMCA.Common.API · MMCA.Common.API.Uploads · MMCA.Common/Source/Presentation/MMCA.Common.API/Uploads/FormFileUploadExtensions.cs:24 · Level 2 · record (sealed, positional)

  • What it is: the result of ReadCsvAsync: the raw upload beside the parsed table, so one read serves both the edge's own validation and dry run and a command that stores or re-parses the file (doc comment FormFileUploadExtensions.cs:18-23).
  • Depends on: UploadedFileContent (Level 0) for File, and CsvTable for Table.
  • Concept: the CSV flavor of the bounded upload read taught on FormFileUploadExtensions.
  • Walkthrough: two positional components (:24). File is the raw upload, bytes unchanged (:22); Table is the parsed table (:23).
  • Why it's built this way: keeping the bytes next to the parsed rows means an action never has to choose between validating the table at the edge and handing the original file on: the CSV is read from the request once, and parsed once from the same buffer. [Rubric §12, Performance & Scalability]: no second read of the request body and no second copy of the bytes.
  • Where it's used: built only by ReadCsvCoreAsync on success (FormFileUploadExtensions.cs:128). The ADC ticket roster import consumes it (MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.API/Controllers/TicketRosterImportController.cs:77). Covered by FormFileCsvUploadTests (MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/Uploads/FormFileCsvUploadTests.cs).

FormFileUploadExtensions

MMCA.Common.API · MMCA.Common.API.Uploads · MMCA.Common/Source/Presentation/MMCA.Common.API/Uploads/FormFileUploadExtensions.cs:31 · Level 4 · class (static, extension block)

  • What it is: bounded upload reads for a controller action that takes an IFormFile: the size check, the single exact read and the refusal error in one call, instead of a hand-written check plus a MemoryStream copy per action (doc comment FormFileUploadExtensions.cs:26-30).
  • Depends on: UploadedFileContent and CsvUpload (the two result shapes); Result and Error; CsvReader for the CSV parse; ASP.NET Core IFormFile.
  • Concept introduced (bound the file, not only the request). [Rubric §11, Security] and [Rubric §12, Performance & Scalability] assess whether untrusted input is bounded before it costs memory. An action's [RequestSizeLimit] bounds the request body; this bounds the file itself, and a declared length over the limit is refused before any byte is read (remarks at FormFileUploadExtensions.cs:45-48). [Rubric §9, API & Contract Design]: every refused file returns the caller's own Error unchanged, so each action keeps its documented error code.
  • Walkthrough
    • One extension(IFormFile? file) block (FormFileUploadExtensions.cs:33), so the methods also accept a missing file.
    • ReadBoundedAsync(maxBytes, invalidUpload) (:49) throws ArgumentOutOfRangeException for maxBytes below 1 or above Array.MaxLength and ArgumentNullException for a null error (:51-53), then delegates to ReadBoundedCoreAsync.
    • ReadCsvAsync(maxBytes, invalidUpload) (:72) applies the same argument guards (:74-76) and delegates to ReadCsvCoreAsync.
    • ReadBoundedCoreAsync (:82) refuses a null, empty or oversize file with invalidUpload (:88-89), checks cancellation, allocates one byte[] of the declared length (:93) and fills it with ReadExactlyAsync (:99). A stream shorter than its declared length raises EndOfStreamException, which is answered with the same invalidUpload (:101-104). Success carries the declared file name and content type (:107).
    • ReadCsvCoreAsync (:110) reuses the bounded read, passing its errors through (:117-118), then parses the buffer through a read-only MemoryStream with CsvReader.ReadTableAsync (:121-125). A parse failure returns the reader's own errors unchanged (MalformedCode with the line in Target, or EmptyCode, per the doc comment :65-69); success returns a CsvUpload (:127-129).
  • Why it's built this way: the public methods validate their arguments synchronously and hand off to private async cores, so a programming error throws at the call rather than inside a faulted task. One buffer of the declared length, read exactly once, is the cheapest correct read; a truncated stream is treated like any other bad upload rather than surfacing as an exception. Every await uses ConfigureAwait(false) (:99, :116, :124), as packaged non-UI code requires.
  • Where it's used: ADC actions call it directly: ReadBoundedAsync for session assets and user photos (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.API/Controllers/SessionAssets/SessionAssetsController.cs:202, MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/Controllers/UsersController.cs:171) and ReadCsvAsync for the ticket roster import (MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.API/Controllers/TicketRosterImportController.cs:77). Covered by FormFileUploadExtensionsTests and FormFileCsvUploadTests (MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/Uploads/). A body over the endpoint limit never reaches it: OversizeFormResourceFilter answers 413 first.

JwksEndpointExtensions

MMCA.Common.API · MMCA.Common.API.Startup.Endpoints · MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/Endpoints/JwksEndpointExtensions.cs:15 · Level 8 · class (static, extension block)

  • What it is: maps /.well-known/jwks.json, serializing the active JsonWebKeySet of the Identity service so other services can validate its asymmetric tokens (the bearer path pins RS256, PS256 and ES384, WebApplicationBuilderExtensions.Authentication.cs:104-106). It also owns the Cache-Control value both discovery documents are served with.
  • Depends on: IJwksProvider, resolved from DI per request, whose implementation is RsaJwksProvider; the nested SerializedKeySetCache; WebApplicationBuilderExtensions for the wellknown rate-limit policy name; plus Microsoft.IdentityModel.Tokens.JsonWebKeySet and System.Text.Json.
  • Concept (the public-key distribution endpoint of cross-service auth). [Rubric §11, Security] and [Rubric §7, Microservices Readiness]: with asymmetric signing only the Identity service holds the private key, and every other service fetches the public keys from here, so no shared secret ever crosses a service boundary (ADR-004, ADR-149). The endpoint is .AllowAnonymous() (JwksEndpointExtensions.cs:54) because clients fetch it before they have a token, which is what JWKS means (RFC 7517; the doc comment says so at :36-37). Anonymous does not mean unbounded: the endpoint names its own per-IP rate-limit policy, covered below.
  • Walkthrough
    • DefaultJwksPath (JwksEndpointExtensions.cs:20) pins the RFC 8615 path.
    • DiscoveryCacheControl (:28) is the internal constant "public, max-age=300". Its doc comment (:22-27) gives the reasoning: five minutes, publicly cacheable, so an ingress or a validator absorbs repeats; keys change only when the process restarts with new configuration, and a rotation keeps the previous key published as an additional key, so a five-minute-old copy still validates. OidcDiscoveryEndpointExtensions reuses the same constant.
    • MapJwksEndpoint() (:43) creates one SerializedKeySetCache (:45) and maps a single GET whose handler takes HttpContext and IJwksProvider as parameters (:47). Per request it serializes through the cache (:49), sets application/json; charset=utf-8 explicitly (:50) and the Cache-Control header (:51), and writes the body (:52).
    • The mapping is chained with .AllowAnonymous() (:54) and .RequireRateLimiting(WebApplicationBuilderExtensions.RateLimitPolicyWellKnown) (:55).
  • Why it's built this way: non-Identity hosts still map it (the JwksEndpoint step is unconditional in the default pipeline, MiddlewarePipelineBuilder.cs:135-142); their provider returns an empty key set rather than erroring, so the wiring is uniform across every host and a single gateway forwarder rule for /.well-known/* covers JWKS discovery for the whole platform. That same prefix is one of the paths the global rate limiter bypasses (WebApplicationBuilderExtensions.RateLimiting.cs:73), which is why the endpoint names the wellknown policy itself: one fixed window per client IP, WellKnownPermitLimit requests per minute (default 60), registered by AddCommonRateLimiting (WebApplicationBuilderExtensions.RateLimiting.cs:39-51, :472-476). The doc comment draws the consequence: a host that runs UseRateLimiter must call AddCommonRateLimiting (JwksEndpointExtensions.cs:38-40). The serialize-once cache and the five-minute header attack the same cost from both ends, [Rubric §12, Performance & Scalability]: fewer requests arrive, and those that do skip serialization.
  • Where it's used: applied as the JwksEndpoint step of the default pipeline seeded by MiddlewarePipelineBuilder (MiddlewarePipelineBuilder.cs:142), so every host that adopts the shared pipeline serves it; the path it owns is the jwks_uri value that OidcDiscoveryEndpointExtensions advertises, which is in turn what AddForwardedJwtBearer (on WebApplicationBuilderExtensions) reaches through OIDC discovery. Its behavior is covered by JwksEndpointTests and JwksMixedKeyTypeTests, and the hardening by WellKnownEndpointHardeningTests, which pins the five-minute header (:42), a 429 on the 61st request from one IP inside a minute (:62), the default of 60 (:111) and a provider key-set swap (:116) (all under MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/Startup/Endpoints/).

SerializedDocumentCache

MMCA.Common.API · MMCA.Common.API.Startup.Endpoints · MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/Endpoints/OidcDiscoveryEndpointExtensions.cs:89 · Level 9 · class (private sealed, nested)

  • What it is: the memo behind the OIDC discovery endpoint: it builds and serializes the discovery document once per configured issuer and returns the same JSON until that value changes (doc comment OidcDiscoveryEndpointExtensions.cs:85-88). It is also where the document's fields, including the advertised signing algorithms, are composed.
  • Depends on: its own nested Entry record, the pair (Issuer, Json) (:153); IJwksProvider (optional) for the algorithm list; JwksEndpointExtensions.DefaultJwksPath for jwks_uri (:124); the outer class's three supported-value arrays and OidcJsonOptions (:31-33, :42-45); System.Text.Json and System.Threading.Volatile.
  • Concept: the lock-free serialize-once memo introduced at SerializedKeySetCache, keyed here on the issuer string (compared ordinally) rather than on object identity. [Rubric §12, Performance & Scalability] for the memo; [Rubric §11, Security] for the algorithm advertisement, which is how a signing-algorithm rotation (ADR-149) becomes visible to OIDC clients.
  • Walkthrough
    • One field, _entry (OidcDiscoveryEndpointExtensions.cs:91). Serialize(issuer, jwksProvider) (:93) reads it with Volatile.Read (:95) and returns the cached JSON when the stored issuer equals the argument under StringComparison.Ordinal (:96-98). Otherwise it builds new Entry(issuer, BuildDocument(issuer, SigningAlgorithms(jwksProvider))) (:103), publishes it with Volatile.Write (:104), and returns its JSON (:105).
    • BuildDocument (:114) derives jwks_uri as the issuer with any trailing / trimmed plus DefaultJwksPath (:124), then serializes an anonymous object carrying issuer, jwks_uri, response_types_supported, subject_types_supported and id_token_signing_alg_values_supported under OidcJsonOptions (:126-133).
    • SigningAlgorithms (:142) takes the alg of every key the provider publishes, drops blanks, keeps distinct values ordinally in key order (:144-148; the doc comment, :137-138, says current key first), and falls back to DefaultSigningAlgsSupported, ["RS256"] (:33), when there is no provider or no key carries an alg (:150).
  • Why it's built this way: the issuer comes from configuration, so the document only needs rebuilding if that value changes (:86-87). The race comment (:101-102) accepts the same benign double-build as the JWKS cache. The comment in BuildDocument (:116-123) records why jwks_uri comes from the configured issuer and not the inbound request: Aspire/DCP fronts the Identity service on per-launchSettings ports and rewrites Host via X-Forwarded-Host to canonical ports that internal callers cannot always reach, so reusing the issuer keeps issuer and jwks_uri origin-aligned (a common OIDC client requirement) and routes both through the same gateway that fronts /Auth, which means one forwarder rule for /.well-known/* covers everything. Deriving the algorithm list from the published keys, rather than hard-coding RS256, means a rotation to PS256 or ES384 is advertised (:137-138).
  • Where it's used: MapOidcDiscoveryEndpoint() creates one instance per mapping (OidcDiscoveryEndpointExtensions.cs:63); the handler calls cache.Serialize(issuer, context.RequestServices.GetService<IJwksProvider>()) per request (:75). Covered through OidcDiscoveryEndpointTests (MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/Startup/Endpoints/OidcDiscoveryEndpointTests.cs).
  • Caveats / not-in-source: the cache key is the issuer alone. The algorithm list is computed when an entry is built (:103) and a matching issuer returns before SigningAlgorithms runs (:96-98), so if a provider's key algorithms changed while the issuer stayed the same, the document would keep advertising the first build's list until the process restarts. That matches the stated key lifetime (keys change only on a restart with new configuration, JwksEndpointExtensions.cs:25-26).

MiddlewarePipelineBuilder

MMCA.Common.API · MMCA.Common.API.Startup.Pipeline · MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/Pipeline/MiddlewarePipelineBuilder.cs:15 · Level 10 · class (sealed)

  • What it is: the mutable, ordered list of MiddlewarePipelineStep values behind UseCommonMiddlewarePipeline. CreateDefault() seeds the framework's nineteen-step edge pipeline; a host may then insert, replace, or remove steps by name; and Build() re-checks six load-bearing ordering invariants before anything is applied.
  • Depends on: MiddlewarePipelineStep and MiddlewarePipelineStepNames; CorrelationIdMiddleware, JsonRequestBodyLimitMiddleware, TenantResolutionMiddleware, SoftDeletedUserMiddleware and ViewAsGuardMiddleware (the five custom middlewares it wires); WebApplicationBuilderExtensions for the two CORS policy names; JwksEndpointExtensions and OidcDiscoveryEndpointExtensions for the two always-mapped well-known endpoints; WebApplicationExtensions for UseCommonRequestLocalization; CommonForwardedHeaders for the shared forwarded-headers options; ASP.NET forwarded-headers primitives.
  • Concept introduced (a customization point that validates itself, not a free-for-all). The tension a shared pipeline has to resolve: one fixed order is safe but blocks any host with a legitimate extra step, while an open Action<WebApplication> hook gives the order back to every host and re-opens exactly the bugs the shared pipeline closed. The resolution here is a scoped escape hatch with startup-enforced invariants: the host may edit the list, but six ordering invariants are re-asserted afterwards and a violation throws while the host is starting, naming the invariant it broke and printing the current order. [Rubric §15, Best Practices & Code Quality] assesses whether a change can be made locally without breaking distant behavior; encoding the rationale as an executable check rather than a comment is what makes that true here. [Rubric §13, Observability & Operability] also applies: the failure modes these invariants prevent (a tenant that never resolves, a per-user rate cap that never engages, a deleted user's live token or a view-as token slipping past a check that saw an anonymous request) all look like configuration bugs at runtime, so converting them into a startup exception with a named cause is a large operability win. See ADR-079.
  • Walkthrough
    • One field, _steps (MiddlewarePipelineBuilder.cs:17), and a private constructor (:19), so the only way in is CreateDefault(). StepNames (:24) projects the current names in application order, which is what the fitness function asserts on and what error messages print.
    • CreateDefault() (:31-151) seeds the nineteen steps. Reading it top to bottom is the fastest way to learn the edge: exception handler (:34-36), correlation id (:38-40), request localization (:42-47, with the ADR-027 note that this runs early so edge error localization uses the caller's culture), forwarded headers via CommonForwardedHeaders.Create() clearing KnownProxies/KnownIPNetworks for cloud reverse proxies (:49-54; UI hosts take the same options through UseCommonUiForwardedHeaders), an HTTPS redirect wrapped in UseWhen that skips negotiated-h2c requests via IsCleartextHttp2 (:56-72) so gRPC-over-cleartext calls are not 307-redirected, response compression (:74-76), routing (:78-80), the JSON body-size ceiling (:82-86, after routing because it applies only to an endpoint that states no request size of its own, and ahead of everything that reads the body), CORS choosing the development or production policy by environment (:88-92), authentication (:94-96), tenant resolution (:98-104), the rate limiter (:106-112), the soft-deleted-user filter (:114-116), the view-as guard (:118-125, after authentication so act_sub is on the principal and after routing so the end-view-as action's metadata is readable), authorization (:127-129), output cache (:131-133), the always-mapped JWKS (:135-142) and OIDC discovery (:144-146) endpoints, and finally MapControllers() (:148-150). Each Configure delegate is static, so no closure is allocated per step.
    • IsCleartextHttp2(HttpContext) (:364-370, public static) is the HTTPS-redirect exemption predicate, defined at the bottom of the class and pulled out to its own method under SEC-Common-44: it null-checks the context (:366) and returns true only when !Request.IsHttps and HttpProtocol.IsHttp2(Request.Protocol) (:368-369), i.e. the connection negotiated HTTP/2 without TLS. It replaced a Content-Type: application/grpc string check, which any caller could forge in a header; the negotiated protocol is settled by Kestrel at connection setup and cannot be faked by a request header. The method is public specifically so a host that rebuilds the HttpsRedirection step reuses the same predicate instead of reintroducing the forgeable check.
    • Four mutators, all returning this for chaining and all validating first: InsertBefore (:161), InsertAfter (:178), Replace (:198) and Remove (:219). Replace keeps the replaced step's position and permits a different name, but rejects a name another step already carries (:203-209).
    • Build() (:256) runs six checks and returns a defensive copy (:288). One adjacency check: Authentication immediately before TenantResolution (:258-261). Five precedence checks: Authentication before RateLimiting (:263-266, ADR-019), ForwardedHeaders before HttpsRedirection (:268-271), Authentication before SoftDeletedUserFilter (:273-276, the check reads the authenticated subject, so ahead of authentication a deleted user's live token passes), Authentication before ViewAsGuard (:278-281, the guard reads the act_sub claim of ADR-137), and Routing before ViewAsGuard (:283-286, the guard reads the selected endpoint's metadata to let the end-view-as action through). Every check carries its rationale string, which is what the exception message prints.
    • The private helpers hold the guard semantics. RequireIndexOf (:294) rejects a blank name and, for an unknown one, throws listing every known step (:305-307), which turns a typo into a self-answering error. RequireUniqueName (:313) enforces name uniqueness across the list. RequireImmediatelyBefore (:323) and RequirePrecedes (:338) share one subtle rule: an invariant binds only when both of its steps are still present (:329, :344), so a host that removes a whole capability (both members of a pair) stays legal, while a host that removes only one half is not constrained by a rule that no longer has anything to say.
  • Why it's built this way: the "both present or the rule is silent" clause is the design decision worth internalizing. Without it, Remove(MiddlewarePipelineStepNames.TenantResolution) on a single-tenant host would fail the authentication adjacency check for no reason, and the escape hatch would be unusable. With it, the invariants constrain reordering rather than composition, which is what they were written to protect. Constructing the defaults as data rather than as calls also means the whole order can be asserted with no WebApplication built at all, which is what puts the fitness function in the fast unit tier. The IsCleartextHttp2 extraction is the same "encode the invariant, don't comment it" instinct the class applies to step ordering: SEC-Common-44 turned a header the caller controls into a protocol fact Kestrel controls, closing a path where a forged Content-Type could have served plaintext gRPC traffic that should have been redirected.
  • Where it's used: only through WebApplicationExtensions.ApplyPipeline (WebApplicationExtensions.cs:164-175), which both UseCommonMiddlewarePipeline overloads route through, so the zero-argument path is exactly the validated default pipeline. MiddlewarePipelineOrderTestsBase (MMCA.Common/Source/Hosting/MMCA.Common.Testing/Conformance/MiddlewarePipelineOrderTestsBase.cs:31) subclasses into each app's architecture tier (ADC, Store, Helpdesk, and Common's own testing tier) and freezes the nineteen-name order (:40-61); MiddlewarePipelineBuilderTests covers the mutators and the invariants directly, and JsonBodySizeLimitStepTests covers the body-size step.
  • Caveats / not-in-source: the builder validates order, not semantics. A Replace that keeps a step's name but swaps in an unrelated middleware passes every check, because nothing inspects the Configure delegate.

OidcDiscoveryEndpointExtensions

MMCA.Common.API · MMCA.Common.API.Startup.Endpoints · MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/Endpoints/OidcDiscoveryEndpointExtensions.cs:24 · Level 10 · class (static, extension block)

  • What it is: maps a minimal OpenID Connect discovery document at /.well-known/openid-configuration. It returns just enough for token validation (the issuer and jwks_uri fields, plus three supported-value arrays, the signing-algorithm one derived from the published keys), so a downstream service that points its JWT authority here can discover the signing keys automatically. When no issuer is configured it returns 404.
  • Depends on: the nested SerializedDocumentCache, which composes and caches the document; JwksEndpointExtensions for DefaultJwksPath (OidcDiscoveryEndpointExtensions.cs:124) and DiscoveryCacheControl (:73); IJwksProvider, resolved optionally from the request services (:75); WebApplicationBuilderExtensions for the wellknown rate-limit policy name (:79); IConfiguration for Jwt:Issuer; System.Text.Json.
  • Concept (OIDC discovery as the bootstrap for JWKS-based validation). [Rubric §7, Microservices Readiness] and [Rubric §11, Security]: AddForwardedJwtBearer sets an Authority, and the JWT bearer middleware fetches {authority}/.well-known/openid-configuration to learn the issuer and the JWKS URL. This endpoint answers that fetch, which is the other half of ADR-004 alongside JwksEndpointExtensions.
  • Walkthrough
    • DefaultOidcDiscoveryPath constant (OidcDiscoveryEndpointExtensions.cs:29).
    • Three static arrays: ResponseTypesSupported (["token"]), SubjectTypesSupported (["public"]) and DefaultSigningAlgsSupported (["RS256"], the fallback when no key advertises an algorithm) (:31-33). OidcJsonOptions sets PropertyNamingPolicy = null (:42-45). Disabling the naming policy is load-bearing: the field names are already OIDC snake_case per RFC 8414, and camelCasing jwks_uri to jwksUri would leave OpenIdConnectConfigurationRetriever unable to recognise the document (:35-41; the comment names Results.Json, while the document is now serialized by JsonSerializer.Serialize under the same options, :126-133).
    • MapOidcDiscoveryEndpoint() (:61) creates one SerializedDocumentCache (:63) and maps a GET that reads Jwt:Issuer (:67); a blank issuer returns Results.NotFound() (:68-71), safe because no downstream points its authority at a non-Identity host. Otherwise it sets the shared five-minute Cache-Control header (:73) and returns the cached document as Results.Text(..., "application/json; charset=utf-8") (:74-76).
    • The mapping is chained with .AllowAnonymous() (:78) and .RequireRateLimiting(WebApplicationBuilderExtensions.RateLimitPolicyWellKnown) (:79), the same per-IP policy the JWKS endpoint names, since the global limiter bypasses /.well-known (WebApplicationBuilderExtensions.RateLimiting.cs:73).
  • Why it's built this way: the reason jwks_uri is built from the configured issuer and not from the request lives in the comment inside SerializedDocumentCache.BuildDocument (:116-123): reusing the issuer keeps issuer and jwks_uri origin-aligned and routes both through the same gateway that fronts /Auth, so one forwarder rule for /.well-known/* covers everything. Returning a prebuilt string through Results.Text means a request pays a configuration read and a cache lookup, not a serialization. The doc comment (:49-59) states the full contract: serialized once per configured issuer, algorithms taken from the registered provider (RS256 when none), five-minute caching, and the wellknown policy as on MapJwksEndpoint.
  • Where it's used: applied unconditionally as the OidcDiscoveryEndpoint step of the default pipeline (MiddlewarePipelineBuilder.cs:144-146); consumed by the bearer middleware that AddForwardedJwtBearer configures on WebApplicationBuilderExtensions, which deliberately leaves ValidIssuer unset so the issuer comes from this document (WebApplicationBuilderExtensions.Authentication.cs:90-103). Covered by OidcDiscoveryEndpointTests and, for the header and rate limit, WellKnownEndpointHardeningTests (both under MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/Startup/Endpoints/).
  • Caveats / not-in-source: the document carries only the five fields token validation needs (:128-132); there is no authorization_endpoint or token_endpoint, so it is a discovery shim for JWT bearer validation, not full OpenID provider metadata.

ClientAddressKey

Linked source (compiled into MMCA.Common.API, Infrastructure, Aspire, UI.Web and Gateway) · MMCA.Common.RateLimiting · MMCA.Common/Source/Build/RateLimiting/ClientAddressKey.cs:31 · Level 0 · class (internal, static)

  • What it is: the one client-address key every per-IP rate-limit partition uses: the API's auth-ip throttle, its anonymous-hub partition, global and MCP fallbacks, the registration cap, the Blazor host's edge limiter, and the gateway's per-IP, per-visitor and named route-policy windows (ClientAddressKey.cs:6-9).
  • Depends on: BCL only (System.Net.IPAddress, System.Net.Sockets.AddressFamily).
  • Concept introduced (normalizing the partition key before counting). [Rubric §11, Security] assesses whether abuse bounds hold against a client that controls its own identifiers. Keying a limiter on the raw IPAddress.ToString() has two holes the remarks name (ClientAddressKey.cs:12-17): an IPv6 subscriber normally holds a whole /64, so rotating the low 64 bits buys a fresh window per request and defeats every per-IP bound (the credential-submission throttles included); and an IPv4-mapped address (::ffff:a.b.c.d) and the plain IPv4 address are two spellings of one client, so a dual-stack hop could give one visitor two windows. The key collapses both to one partition. [Rubric §15, Best Practices & Code Quality]: one definition shared by every limiter, so the API, the gateway and the Blazor host cannot disagree on what "one client" means.
  • Walkthrough
    • IPv6PrefixLength (:34) is the constant 64, the prefix one client is assumed to hold.
    • For(IPAddress?) (:42) returns null for no address (:44-47); an IPv4-mapped IPv6 address becomes its IPv4 text (:49-52); any non-IPv6 address is its own text (:54-57). An IPv6 address is written to a 16-byte stack buffer (:59-60), every byte past the /64 is cleared (:61), and the result is rendered as a fresh IPAddress plus "/64" in CIDR form (:64). Building a new address also drops the scope id, so a link-local zone index cannot split a client either (:63).
    • For(string) (:73) is the overload for an address already read as text: it trims (:75) and returns the normalized key when the text parses, or the trimmed text itself when it does not (:76).
  • Why it's built this way: one source file is compiled as an internal type into each package that partitions by client address through a Compile Include ... Link, because the Gateway package references no MMCA project (:23-28); this is the same linked-source arrangement as RemainingWindowFixedWindowRateLimiter. The remarks also draw the boundary of its use: the idempotency filter's anonymous subject is not a limiter but a key that keeps users' cached replays apart, and masking it to /64 would let neighbours share each other's replays, so it does not use this key (:19-22). ADR-019 and ADR-088 cover the limiters it serves.
  • Where it's used: AddCommonRateLimiting in WebApplicationBuilderExtensions keys its per-IP partitions on it (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/WebApplicationBuilderExtensions.RateLimiting.cs:90, with "anonymous-hub" as the no-address fallback, and :180, :336, :358); McpCallerKey falls back to it (MMCA.Common/Source/Presentation/MMCA.Common.API/RateLimiting/McpCallerKey.cs:35); LoginProtectionService hashes the text overload's key into its registration-cap cache key, applying it there rather than where the controller reads the address because the stored session record must keep the real address (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/LoginProtectionService.cs:278-287). At the edge: GatewayRateLimitingExtensions (MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Gateway/GatewayRateLimitingExtensions.cs:249, :258), GatewaySettings (MMCA.Common/Source/Hosting/MMCA.Common.Gateway/GatewaySettings.cs:276) and UiRateLimitingExtensions (MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/Hardening/UiRateLimitingExtensions.cs:135). Covered by ClientAddressKeyTests (MMCA.Common/Tests/Hosting/MMCA.Common.Gateway.Tests/RateLimiting/ClientAddressKeyTests.cs:17-47).

FeatureFlagAssembly

MMCA.Common.Infrastructure · MMCA.Common.Infrastructure.FeatureFlags · MMCA.Common/Source/Core/MMCA.Common.Infrastructure/FeatureFlags/FeatureFlagCatalog.cs:9 · Level 0 · record (internal, sealed)

  • What it is: a one-property DI carrier: "this assembly's *Features classes declare flags this host may override" (doc comment, FeatureFlagCatalog.cs:7-8).
  • Depends on: System.Reflection.Assembly only.
  • Concept introduced: none of its own; it is the multi-registration input of FeatureFlagCatalog, which teaches the declared-flag catalog. Wrapping a bare Assembly in a named record is what lets several modules each contribute one with AddSingleton and the catalog take them all as IEnumerable<FeatureFlagAssembly>, without colliding with any other Assembly registration in the container.
  • Walkthrough: a positional record, FeatureFlagAssembly(Assembly Assembly) (FeatureFlagCatalog.cs:9). No members beyond the generated ones.
  • Where it's used: AddReloadableFeatureFlags registers one per assembly passed to it (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.FeatureFlags.cs:54-57), before its already-registered check, so a second call (one per module) still adds its assemblies. FeatureFlagCatalog consumes the set (FeatureFlagCatalog.cs:17).

FeatureFlagOverrideSettings

MMCA.Common.Application · MMCA.Common.Application.FeatureFlags · MMCA.Common/Source/Core/MMCA.Common.Application/FeatureFlags/FeatureFlagOverrideSettings.cs:9 · Level 0 · class (sealed, options)

  • What it is: the options bag for the reloadable feature flags (stored overrides, ADR-031), bound from the FeatureFlags configuration section by AddReloadableFeatureFlags (doc comment FeatureFlagOverrideSettings.cs:5-8).
  • Depends on: nothing first-party. System.ComponentModel.DataAnnotations for [Range] and [Required].
  • Concept (a bounded cache lifetime as a stated staleness contract). [Rubric §13, Observability & Operability] assesses whether an operator can predict how a runtime change propagates; the remarks on OverrideCacheSeconds (FeatureFlagOverrideSettings.cs:17-22) state that a write invalidates the snapshot at once on the replica that served it, and that this value is the upper bound on how long another replica keeps serving the old snapshot when there is no distributed L2 and shared Redis for the generation tokens. [Rubric §15, Best Practices & Code Quality] also applies: both members carry DataAnnotations and the registration validates them on start, which is the fail-fast configuration contract of ADR-070.
  • Walkthrough
    • SectionName (FeatureFlagOverrideSettings.cs:12) is the constant "FeatureFlags".
    • OverrideCacheSeconds (:24, default 30) is how long the cached override snapshot is served before it is reloaded, constrained to [Range(1, 3600)] (:23).
    • DataSourceName (:31, default "Default", [Required] at :30) names the logical data source that owns the override table: the owning service's own database. The default suits a single-database host (:26-29).
  • Why it's built this way: init-only properties with defaults mean a host that sets nothing still gets a valid 30-second, single-database configuration, while a bad value (zero seconds, a blank source) fails at startup rather than on the first flag read. AddReloadableFeatureFlags binds it with .ValidateDataAnnotations().ValidateOnStart() (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.FeatureFlags.cs:67-70).
  • Where it's used: the shipped FeatureFlagOverrideSnapshot turns OverrideCacheSeconds into its cache lifetime and folds DataSourceName into its cache-key prefix (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/FeatureFlags/FeatureFlagOverrideSnapshot.cs:55, :62); the internal FeatureFlagOverrideModelContributor reads DataSourceName in AppliesTo to decide which database instance maps the override table (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/FeatureFlags/FeatureFlagOverrideModelBuilderExtensions.cs:92-93). The ADC Conference and Engagement services opt in through AddReloadableFeatureFlags (MMCA.ADC/Source/Services/MMCA.ADC.Conference.Service/Program.cs:288, MMCA.ADC/Source/Services/MMCA.ADC.Engagement.Service/Program.cs:137). See IFeatureFlagOverrideSnapshot.

IFeatureFlagOverrideSnapshot

MMCA.Common.Application · MMCA.Common.Application.FeatureFlags · MMCA.Common/Source/Core/MMCA.Common.Application/FeatureFlags/IFeatureFlagOverrideSnapshot.cs:14 · Level 2 · interface

  • What it is: the cached whole-table snapshot of the stored feature-flag overrides that every flag evaluation reads, plus the invalidation every write performs (ADR-031; doc comment IFeatureFlagOverrideSnapshot.cs:5-8).
  • Depends on: FeatureFlagOverrideResponse, the element type it returns.
  • Concept (one snapshot, not a lookup per flag). A flag check sits on the request path, so loading every override in one query on a slow interval, and again right after an edit, keeps that check a cache read; the remarks borrow the reasoning of the permission-grant cache (IFeatureFlagOverrideSnapshot.cs:9-13). [Rubric §12, Performance & Scalability] assesses whether hot-path reads avoid a database round trip; [Rubric §13, Observability & Operability] applies to the staleness bound that FeatureFlagOverrideSettings.OverrideCacheSeconds states.
  • Walkthrough
    • GetAsync (IFeatureFlagOverrideSnapshot.cs:19) returns the active overrides, from the cache when it holds them.
    • InvalidateAsync (:24) drops the cached snapshot so the next read reloads it from the store.
  • Why it's built this way: separating the cached read from the store (IFeatureFlagOverrideStore) keeps the evaluator off the database. The shipped implementation, the internal FeatureFlagOverrideSnapshot, holds the whole table as one entry in the host's ICacheService under a key that carries the host's application name and the data source name, and invalidates by prefix, so on a host with the two-level cache a write on one replica retires the snapshot on every replica (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/FeatureFlags/FeatureFlagOverrideSnapshot.cs:11-37). It is a singleton that opens its own DI scope per load because the store is scoped (:35-36, :104).
  • Where it's used: registered as a singleton by AddReloadableFeatureFlags (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.FeatureFlags.cs:77); read by StoredOverrideFeatureDefinitionProvider (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/FeatureFlags/StoredOverrideFeatureDefinitionProvider.cs:33) and invalidated by the shipped IFeatureFlagAdministrationService after each write (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/FeatureFlags/FeatureFlagAdministrationService.cs:33). Fallback behavior is covered by StoredOverrideFallbackTests (MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/FeatureFlags/StoredOverrideFallbackTests.cs).

IFeatureFlagAdministrationService

MMCA.Common.Application · MMCA.Common.Application.FeatureFlags · MMCA.Common/Source/Core/MMCA.Common.Application/FeatureFlags/IFeatureFlagAdministrationService.cs:17 · Level 3 · interface

  • What it is: the administration surface of the reloadable feature flags (ADR-031): list the flags this service declares, and set or clear their stored overrides. Registered by AddReloadableFeatureFlags and served by FeatureFlagsControllerBase (doc comment IFeatureFlagAdministrationService.cs:6-10).
  • Depends on: Result; FeatureFlagStatusResponse and SetFeatureFlagOverrideRequest.
  • Concept (only a declared flag can be overridden). The declared set is what FeatureFlagRegistry.Describe reports over the assemblies the host passed to AddReloadableFeatureFlags, so an override cannot be written for a name no code reads: a typo is refused with FeatureFlag.Undeclared rather than stored and left silently inert (IFeatureFlagAdministrationService.cs:11-16). [Rubric §9, API & Contract Design]: failures come back as Result values naming the cause, not as exceptions. [Rubric §13, Observability & Operability]: an operator changes a flag at runtime through one audited surface.
  • Walkthrough
    • ListAsync (IFeatureFlagAdministrationService.cs:22) lists every declared flag with its configured value, its override and its effective value, ordered by name.
    • SetOverrideAsync(name, request) (:28) stores the override of one declared flag and invalidates the cached snapshot, returning the flag's state afterwards or a failure (an undeclared name, an invalid override).
    • ClearOverrideAsync(name) (:38) clears the override and invalidates the snapshot; it fails only for an undeclared name.
  • Why it's built this way: the declared-name check, the store write and the invalidation live in one service so a controller cannot skip a step. The shipped internal FeatureFlagAdministrationService also records that the invalidation never fails a committed write: a cache fault after the row is saved is logged and the call still succeeds, and the entry lifetime bounds how long the old snapshot can be served (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/FeatureFlags/FeatureFlagAdministrationService.cs:9-24).
  • Where it's used: registered scoped by AddReloadableFeatureFlags (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.FeatureFlags.cs:78); injected into FeatureFlagsControllerBase (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Administration/FeatureFlagsControllerBase.cs:38), which the ADC Conference and Engagement AdminFeatureFlagsController subclasses receive (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.API/Controllers/FeatureFlags/AdminFeatureFlagsController.cs:23, MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.API/Controllers/AdminFeatureFlagsController.cs:23). Covered by FeatureFlagsControllerBaseTests (MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/Controllers/Administration/FeatureFlagsControllerBaseTests.cs).

IFeatureFlagOverrideStore

MMCA.Common.Application · MMCA.Common.Application.FeatureFlags · MMCA.Common/Source/Core/MMCA.Common.Application/FeatureFlags/IFeatureFlagOverrideStore.cs:15 · Level 3 · interface

  • What it is: the persistence of stored feature-flag overrides (ADR-031). The shipped implementation is the EF store AddReloadableFeatureFlags registers over the owning service's own database (doc comment IFeatureFlagOverrideStore.cs:6-9).
  • Depends on: Result; FeatureFlagOverrideResponse and SetFeatureFlagOverrideRequest.
  • Concept (a dumb store under a smart service). The store does not check that a name is a declared flag, and its writes do not invalidate the cached snapshot: the administration service does both, around each call (IFeatureFlagOverrideStore.cs:10-14). [Rubric §15, Best Practices & Code Quality]: each rule has exactly one owner, so the store stays a plain persistence boundary.
  • Walkthrough
    • GetAllAsync (IFeatureFlagOverrideStore.cs:20) reads every active override, ordered by flag name; cleared ones are not included.
    • SetAsync(name, request) (:26) creates or replaces the override of one flag, returning the stored override or a validation failure.
    • ClearAsync(name) (:36) clears the override; clearing a flag with no override succeeds.
  • Why it's built this way: the overrides live in the owning service's own database (database per service), selected by FeatureFlagOverrideSettings.DataSourceName; keeping the interface in Application lets a host substitute a store without touching the evaluator or the snapshot.
  • Where it's used: registered scoped as the internal EFFeatureFlagOverrideStore by AddReloadableFeatureFlags (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.FeatureFlags.cs:76; implementation at MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/FeatureFlags/EFFeatureFlagOverrideStore.cs:33); read by the snapshot in a fresh scope per load (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/FeatureFlags/FeatureFlagOverrideSnapshot.cs:104) and written by the shipped administration service (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/FeatureFlags/FeatureFlagAdministrationService.cs:32). See IFeatureFlagOverrideSnapshot and IFeatureFlagAdministrationService.

ICorrelationContext

MMCA.Common.Application · MMCA.Common.Application.Interfaces · MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/ICorrelationContext.cs:8 · Level 0 · interface

  • What it is: the Application-layer abstraction for "the correlation ID of the work currently in flight": one reader and one writer, resolved per scope.
  • Depends on: nothing first-party, BCL string only. Implemented by CorrelationContext in Infrastructure.
  • Concept introduced (request correlation as an injected ambient value). [Rubric §13, Observability & Operability] assesses whether one logical request can be reassembled from disjoint logs; a correlation ID is the value that makes that possible. [Rubric §3, Clean Architecture] is the reason this interface exists at all: handlers, decorators and interceptors need the ID, but they must not reach for HttpContext, so the contract sits in Application and the holder sits in Infrastructure, keeping the dependency arrow pointing inward. [Rubric §13, Observability & Operability]: nothing in the business path sets or threads the ID, it is populated once at the edge and read wherever it is needed.
  • Walkthrough: two members. string CorrelationId { get; } (ICorrelationContext.cs:11) is read-only to consumers. void SetCorrelationId(string correlationId) (ICorrelationContext.cs:15) is the single write path, on the same interface, so the edge component that populates the value can do it through the DI-resolved instance without a second, internal interface. The doc comment (ICorrelationContext.cs:3-6) states the intended lifecycle: set by middleware from the X-Correlation-ID header or generated, then carried through the handler pipeline in structured-logging scopes.
  • Why it's built this way: a two-member interface is small enough that a test or a background host can supply its own holder, and putting the setter here (rather than on the concrete class) keeps middleware depending on the abstraction. ITenantContext is deliberately modelled on it, and says so: one scoped instance per request, populated once at the edge (MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/ITenantContext.cs:11).
  • Where it's used: registered as TryAddScoped<ICorrelationContext, CorrelationContext>() (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:389). Populated by CorrelationIdMiddleware, which takes it as a method-injected parameter of InvokeAsync (MMCA.Common/Source/Presentation/MMCA.Common.API/Middleware/CorrelationIdMiddleware.cs:35). Consumed by LoggingCommandDecorator<TCommand, TResult> (MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Decorators/LoggingCommandDecorator.cs:20) and LoggingQueryDecorator<TQuery, TResult> (.../LoggingQueryDecorator.cs:16), which wrap the ID into their log scope for the duration of the pipeline.
  • Caveats / not-in-source: not every component can use it. The audit-trail interceptor is a singleton and records the ambient Activity trace id instead of this scoped value, and says so in its own comment (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/AuditTrail/AuditTrailEntry.cs:94).

OutboundAddressPolicy

MMCA.Common.Infrastructure · MMCA.Common.Infrastructure.Http · MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Http/OutboundAddressPolicy.cs:11 · Level 0 · class (public, static)

  • What it is: the address and target rules an outbound call to an operator-supplied URL is held to, so a stored target cannot reach the host's own network (OutboundAddressPolicy.cs:5-9). Two public predicates: IsPublicAddress and IsAcceptableTargetUri.
  • Depends on: BCL only (System.Net.IPAddress, System.Net.Sockets.AddressFamily, System.Uri).
  • Concept introduced (server-side request forgery defense). [Rubric §11, Security] assesses whether the system refuses attacker-steerable requests to internal resources. SSRF is the attack where a server is talked into calling a URL the attacker chose (a webhook target, say) that resolves into the private network, loopback, or the cloud host's metadata endpoint. This class is the single rule set for that check, applied twice by its callers: once to the URI as written and once to every address the name resolves to at connect time, which is what defeats DNS rebinding.
  • Walkthrough
    • DeniedIPv4 (:18-32) is a deny-list of (network, prefix) pairs: 0/8, 10/8, 100.64/10, 127/8, 169.254/16, 172.16/12, 192.0.0.0/24, 192.168/16, 198.18/15, 224/4, 240/4, plus the single address 168.63.129.16/32 (:31), the cloud platform's host endpoint that is reachable from every VM although it is public space (:13-17).
    • IPv6 is an allow-list instead: only global unicast 2000::/3 (GlobalUnicastIPv6, :40-41), because several formats outside it embed an IPv4 address the stack may still dial (IPv4-compatible ::/96, both NAT64 prefixes) and a range added later is refused without anyone listing it (:34-39). Inside it, DeniedGlobalIPv6 (:48-54) still refuses Teredo 2001::/32, 6to4 2002::/16 and the documentation prefixes 2001:db8::/32 and 3fff::/20.
    • IsPublicAddress (:68) unwraps an IPv4-mapped IPv6 address to its IPv4 form first (:72-75), checks IPv4 against the deny-list (:77-80), returns false for any family that is neither IPv4 nor IPv6 (:82-85), and for IPv6 requires "inside 2000::/3 and in none of the denied ranges" (:87-89).
    • IsAcceptableTargetUri(target, allowInsecure) (:100) always requires the callable shape: absolute, https or http, no user info, a non-empty host (HasCallableShape, :114-118). Unless allowInsecure (Development only, per the parameter doc), it also requires https, a host that is not localhost or *.localhost (IsLocalHostName, :123-125), and, for an IP-literal host only, a public address (IsPublicIfLiteral, :128-130); a host name passes here because its addresses are checked when it is resolved (:127).
    • IsInRange (:135-151) compares the whole prefix bytes with SequenceEqual, then masks the remaining bits of the next byte (:149).
  • Why it's built this way: one public static class means the validation-time and connect-time checks cannot drift apart. ADR-142 covers the outbound-webhook design this serves.
  • Where it's used: DnsWebhookTargetValidator applies IsAcceptableTargetUri and then requires every resolved address to pass IsPublicAddress (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Webhooks/DnsWebhookTargetValidator.cs:31, :52). HttpWebhookSender re-checks the URI before sending (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Webhooks/HttpWebhookSender.cs:46), and WebhookConnectCallback refuses a non-public address at connect time (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Webhooks/WebhookConnectCallback.cs:48).

RejectedLease

Linked source (compiled into each limiter host package) · MMCA.Common.RateLimiting · MMCA.Common/Source/Build/RateLimiting/RemainingWindowFixedWindowRateLimiter.cs:137 · Level 0 · class (private, sealed, nested)

  • What it is: the rejection lease RemainingWindowFixedWindowRateLimiter hands back in place of the framework's: not acquired, carrying only a remaining-window Retry-After hint (RemainingWindowFixedWindowRateLimiter.cs:132-136).
  • Depends on: System.Threading.RateLimiting.RateLimitLease (base), MetadataName.RetryAfter.
  • Concept introduced: none of its own; see the parent type for the honest Retry-After concept.
  • Walkthrough: a primary constructor takes the TimeSpan retryAfter (:137). IsAcquired is constant false (:142). MetadataNames returns a static one-element array holding MetadataName.RetryAfter.Name (:139, :145). TryGetMetadata answers that name, compared ordinally, with the captured retryAfter (:148-154) and every other name with null/false (:156-157).
  • Where it's used: created only by the parent's WithRemainingRetryAfter (:129). The rate-limiter OnRejected callback turns its hint into the 429's Retry-After header (:134-135).

RetryAfterRejection

Linked source (compiled into MMCA.Common.API, Aspire, UI.Web and Gateway) · MMCA.Common.RateLimiting · MMCA.Common/Source/Build/RateLimiting/RetryAfterRejection.cs:19 · Level 0 · class (internal, static)

  • What it is: the OnRejected wrapper every MMCA rate limiter installs, so each 429 carries a Retry-After header whenever the rejecting lease has a MetadataName.RetryAfter hint (RetryAfterRejection.cs:7-11).
  • Depends on: Microsoft.AspNetCore.RateLimiting.OnRejectedContext, System.Threading.RateLimiting.MetadataName, System.Globalization.CultureInfo.
  • Concept introduced (a rejection that tells the client when to come back). [Rubric §9, API & Contract Design] assesses whether an error response gives a client what it needs to behave well: a 429 with a Retry-After lets a well-behaved client wait exactly long enough instead of guessing or hammering. The hint itself comes from the lease: RemainingWindowFixedWindowRateLimiter (through RejectedLease) and RedisFixedWindowRateLimiter supply the time left in the window; this type only turns it into the header. [Rubric §2, Design Patterns]: a decorator over a callback, which writes the header and then defers to whatever was configured before it.
  • Walkthrough
    • Format(TimeSpan) (:27) renders whole seconds, rounded up with Math.Ceiling and clamped at zero with Math.Max (:29), so a client never retries before the window has moved on and never sees a negative value (:22-23); the result is formatted with the invariant culture (:30).
    • WithRetryAfterHeader(previous) (:42) returns a callback that writes Response.Headers.RetryAfter when the lease answers TryGetMetadata(MetadataName.RetryAfter, ...) (:46-49), then invokes previous when there is one, or completes (:51). A fixed-window rejection carries the hint; a concurrency rejection does not, and sends no header (:36-37). Because previous runs after the header is written, it can read or override it (:38-39).
  • Why it's built this way: one source file is compiled as an internal type into the four packages that register a limiter through a Compile Include ... Link (:13-15). Format is a copy of RetryAfterHeader.Format from MMCA.Common.Shared, because the Gateway package references no MMCA project; a test pins the two together so they cannot drift (:15-17). Wrapping the existing callback, rather than replacing it, keeps a host's own OnRejected logic working. ADR-019 and ADR-088 cover the limiters it serves.
  • Where it's used: every limiter registration assigns options.OnRejected = RetryAfterRejection.WithRetryAfterHeader(options.OnRejected): AddCommonRateLimiting in WebApplicationBuilderExtensions (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/WebApplicationBuilderExtensions.RateLimiting.cs:451), GatewayRateLimitingExtensions (MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Gateway/GatewayRateLimitingExtensions.cs:390), GatewayRoutePolicyExtensions (MMCA.Common/Source/Hosting/MMCA.Common.Gateway/RateLimiting/GatewayRoutePolicyExtensions.cs:82) and UiRateLimitingExtensions (MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/Hardening/UiRateLimitingExtensions.cs:215). GatewayRetryAfterTests pins Format to the shared helper and covers the header, the no-hint case and the chained callback (MMCA.Common/Tests/Hosting/MMCA.Common.Gateway.Tests/RateLimiting/GatewayRetryAfterTests.cs:25-74).

RemainingWindowFixedWindowRateLimiter

Linked source (compiled into MMCA.Common.API, Aspire, UI.Web and Gateway) · MMCA.Common.RateLimiting · MMCA.Common/Source/Build/RateLimiting/RemainingWindowFixedWindowRateLimiter.cs:31 · Level 1 · class (internal, sealed)

  • What it is: the in-memory fixed-window limiter with an honest Retry-After hint. The framework's FixedWindowRateLimiter stamps every rejection with the whole window length, so a 429 always said Retry-After: 60 however much of the minute was left; this wraps it, tracks when the current window opened, and rewrites the hint to the time remaining (RemainingWindowFixedWindowRateLimiter.cs:5-12).
  • Depends on: System.Threading.RateLimiting (ReplenishingRateLimiter base, an inner FixedWindowRateLimiter), TimeProvider. Nested RejectedLease. Its distributed counterpart is RedisFixedWindowRateLimiter, whose figure this one now matches (:10-11).
  • Concept introduced (decorating a BCL limiter to correct its metadata). [Rubric §9, API & Contract Design] assesses whether responses tell clients the truth they need to behave well: a Retry-After that overstates the wait makes well-behaved clients back off longer than necessary. [Rubric §2, Design Patterns]: a decorator over FixedWindowRateLimiter that forwards every permit decision unchanged and rewrites only the rejection metadata.
  • Walkthrough
    • The constructor (:45) copies the options into a new inner FixedWindowRateLimiter with AutoReplenishment = false forced (:49-56), because the owning partitioned limiter drives replenishment. It sets ReplenishmentPeriod to the window (:57), takes TimeProvider.System when none is injected (:58), and stamps the window start (:59).
    • IsAutoReplenishing is false (:63); IdleDuration and GetStatistics forward to the inner limiter (:69, :72).
    • TryReplenish (:75) resets its own window start when at least one period has elapsed (:77-80), then delegates (:82). The remarks explain why this agrees with the inner limiter's own window to within one timer tick (:23-28).
    • TimeUntilNextWindow (:87-91) is period minus elapsed, clamped at zero.
    • AttemptAcquireCore and AcquireAsyncCore (:94, :98) both pass the inner lease through WithRemainingRetryAfter (:121): an acquired lease, or a rejection with no RetryAfter hint (a request larger than the whole allowance, :119-120), is returned untouched (:123-126); any other rejection is disposed and replaced by a RejectedLease carrying TimeUntilNextWindow() (:128-129).
    • Dispose(bool) and DisposeAsyncCore dispose the inner limiter before the base (:102-117).
  • Why it's built this way: one source file is linked as an internal type into each package that runs an in-memory fixed window, keeping the Gateway package free of any MMCA reference; it cannot sit in MMCA.Common.Shared because System.Threading.RateLimiting ships in the ASP.NET Core shared framework, which Shared (also loaded by Blazor WebAssembly) does not reference (:13-22). ADR-088 covers the gateway edge limiter it serves.
  • Where it's used: every in-memory fixed-window partition: RateLimitPartitions (MMCA.Common/Source/Presentation/MMCA.Common.API/RateLimiting/RateLimitPartitions.cs:48), AddCommonRateLimiting in WebApplicationBuilderExtensions (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/WebApplicationBuilderExtensions.RateLimiting.cs:301), the gateway edge limiter (MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Gateway/GatewayRateLimitingExtensions.cs:307), the gateway route policies (MMCA.Common/Source/Hosting/MMCA.Common.Gateway/RateLimiting/GatewayRoutePolicyExtensions.cs:145) and the Blazor host's edge limiter (MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/Hardening/UiRateLimitingExtensions.cs:146).
  • Caveats / not-in-source: the class doc cites a Store local test run ("X-18", :9) as the trigger; that run is not in source.

FeatureFlagDefinitions

MMCA.Common.Infrastructure · MMCA.Common.Infrastructure.FeatureFlags · MMCA.Common/Source/Core/MMCA.Common.Infrastructure/FeatureFlags/FeatureFlagDefinitions.cs:19 · Level 2 · class (internal, static)

  • What it is: the two-way translation between a stored override and the Microsoft.FeatureManagement FeatureDefinition the feature manager evaluates, plus the summary of a definition into the coarse state the administration surface reports.
  • Depends on: FeatureFlagOverrideResponse, FeatureFlagOverrideMode, FeatureFlagValueKind; Microsoft.FeatureManagement (FeatureDefinition, FeatureFilterConfiguration, RequirementType, FeatureStatus), Microsoft.Extensions.Configuration in-memory builder.
  • Concept introduced (stored overrides expressed as ordinary filter definitions). [Rubric §2, Design Patterns]: rather than a second evaluation path, an override is turned into the same FeatureDefinition configuration would have produced, so the feature manager and every FeatureGate decorator stay unaware overrides exist. See ADR-031.
  • Walkthrough
    • Constants: AlwaysOnFilter = "AlwaysOn" (:22), TargetingFilter = "Microsoft.Targeting" (:25), private WholeGroup = "100" (:28).
    • ToDefinition (:33) switches on the mode: On becomes one AlwaysOn filter with empty parameters (:35-39); Percentage a targeting filter with no users or groups and the stored percentage (:40); Targeting a targeting filter with the stored users, groups and percentage (:41); Off a definition with no filters (:42); an unknown mode also evaluates to off (:44-45). A null percentage becomes 0.
    • Targeting (:89) builds the filter's parameters as the configuration section the targeting filter binds from: Audience:DefaultRolloutPercentage (:96), Audience:Users:{i} (:101), and per group Audience:Groups:{i}:Name with a RolloutPercentage of WholeGroup (:106-107). The doc comment's point (:84-88): the binding is the filter's own, not a copy of its settings shape.
    • Describe (:51) returns Off for a null or Disabled definition (:53-56) or one with no named filters (:58-65); On when every filter is always-on, or any is and the requirement type is Any (:68-71); otherwise Conditional with the filter names (:74). IsAlwaysOn accepts AlwaysOn or On, case-insensitively (:77-79).
  • Where it's used: StoredOverrideFeatureDefinitionProvider calls ToDefinition for every overridden flag; FeatureFlagAdministrationService calls both methods to report configured and effective state.

FeatureFlagCatalog

MMCA.Common.Infrastructure · MMCA.Common.Infrastructure.FeatureFlags · MMCA.Common/Source/Core/MMCA.Common.Infrastructure/FeatureFlags/FeatureFlagCatalog.cs:17 · Level 3 · class (internal, sealed)

  • What it is: the set of flags this host declares, computed once from every registered FeatureFlagAssembly. Only these names can carry a stored override (FeatureFlagCatalog.cs:11-15).
  • Depends on: FeatureFlagAssembly, FeatureFlagRegistry, FeatureFlagDescriptor.
  • Concept introduced (declared flags as the override allow-list). [Rubric §34, Architecture Governance & Documentation]: flags are declared by [FeatureFlag] constants on *Features classes, and this catalog makes that declaration the boundary for runtime overrides, so an operator cannot create an override for a name no code reads.
  • Walkthrough: _flags is a Lazy (:19-22) over FeatureFlagRegistry.Describe on the distinct assemblies (:20), de-duplicated by flag name case-insensitively (:21). Flags exposes it, ordered by name per the doc (:24-25). TryFind (:31) trims the input (:33) and matches case-insensitively, returning the declared spelling (:34-35).
  • Where it's used: registered with TryAddSingleton by AddReloadableFeatureFlags (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.FeatureFlags.cs:75); consumed by FeatureFlagAdministrationService for listing and for rejecting undeclared names.

StoredOverrideFeatureDefinitionProvider

MMCA.Common.Infrastructure · MMCA.Common.Infrastructure.FeatureFlags · MMCA.Common/Source/Core/MMCA.Common.Infrastructure/FeatureFlags/StoredOverrideFeatureDefinitionProvider.cs:31 · Level 3 · class (internal, sealed, partial)

  • What it is: the IFeatureDefinitionProvider that AddReloadableFeatureFlags layers over the configured one: a flag with a stored override answers with the override's definition, every other flag is answered by configuration unchanged (StoredOverrideFeatureDefinitionProvider.cs:8-13).
  • Depends on: Microsoft.FeatureManagement.IFeatureDefinitionProvider (implemented and wrapped), IFeatureFlagOverrideSnapshot, FeatureFlagDefinitions, FeatureFlagOverrideResponse, ILogger.
  • Concept introduced (runtime flag changes with no restart). [Rubric §2, Design Patterns]: a decorator on the definition provider; the FeatureGate decorators keep calling IFeatureManager, which asks this provider on every evaluation, so a stored override takes effect on the next evaluation after the snapshot is invalidated (:15-18). [Rubric §29, Resilience, Reliability & Business Continuity]: the override layer is never more fragile than the configuration under it.
  • Walkthrough
    • Configured (:40) exposes the wrapped provider, which is what "the configured value" means on the administration surface.
    • GetFeatureDefinitionAsync (:43) looks the name up in the loaded overrides (:45) and returns either the configured definition or FeatureFlagDefinitions.ToDefinition(stored) (:47-49).
    • GetAllFeatureDefinitionsAsync (:53) streams the configured definitions, substituting overridden ones (:58-63), then yields any override for a name configuration never mentions (:65-69).
    • Find (:72) compares names case-insensitively, like the configuration keys.
    • OverridesOrNoneAsync (:81) catches any non-cancellation exception from the snapshot (:87), logs one Warning (:89, message at :94) and returns an empty list (:90), so a transient database error or an unapplied migration degrades to configuration instead of failing every feature-gated command and query (:75-80).
  • Where it's used: installed by services.TryDecorateWith<IFeatureDefinitionProvider> in AddReloadableFeatureFlags, which throws if no provider is registered yet ("Call it after AddAPI() (or AddFeatureManagement())") (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.FeatureFlags.cs:80-89). FeatureFlagAdministrationService unwraps it through Configured.

FeatureFlagAdministrationService

MMCA.Common.Infrastructure · MMCA.Common.Infrastructure.FeatureFlags · MMCA.Common/Source/Core/MMCA.Common.Infrastructure/FeatureFlags/FeatureFlagAdministrationService.cs:30 · Level 4 · class (internal, sealed, partial)

  • What it is: the implementation of IFeatureFlagAdministrationService: list every declared flag with its configured and effective state, set an override, clear one.
  • Depends on: FeatureFlagCatalog, IFeatureFlagOverrideStore, IFeatureFlagOverrideSnapshot, IFeatureDefinitionProvider, FeatureFlagDefinitions, FeatureFlagStatusResponse, SetFeatureFlagOverrideRequest, Result, Error.
  • Concept introduced: none new; it composes the catalog, store and snapshot taught in their own sections. [Rubric §13, Observability & Operability]: the operator view shows both what configuration says and what actually applies.
  • Walkthrough
    • ConfiguredProvider (:41-42) is the layered provider's Configured when the registered provider is a StoredOverrideFeatureDefinitionProvider, else the registered provider itself.
    • ListAsync (:45) reads overrides from the store, not the snapshot, so the operator sees the rows as they are rather than one replica's cache (:47-49), then describes every catalog flag (:52-56).
    • SetOverrideAsync (:62) returns a not-found Error FeatureFlag.Undeclared for an undeclared name (:69-72, :103-106), writes through the store under the declared spelling (:74), propagates a store failure (:75-78), invalidates the snapshot (:80) and returns the new status (:82).
    • ClearOverrideAsync (:86) follows the same shape (:88-99).
    • InvalidateAsync (:111) swallows a non-cancellation failure with a Warning (:117, message at :108): the write is already committed, and other evaluations may serve the previous snapshot until it expires.
    • DescribeAsync (:123) computes the configured state from ConfiguredProvider (:125-126) and the effective kind from the override when there is one (:128-130), returning a FeatureFlagStatusResponse with the descriptor's lifetime, owner and remove-by date (:132-140).
  • Where it's used: registered with TryAddScoped<IFeatureFlagAdministrationService, FeatureFlagAdministrationService>() (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.FeatureFlags.cs:78); the HTTP surface is FeatureFlagsControllerBase.

FeatureFlagOverrideSnapshot

MMCA.Common.Infrastructure · MMCA.Common.Infrastructure.FeatureFlags · MMCA.Common/Source/Core/MMCA.Common.Infrastructure/FeatureFlags/FeatureFlagOverrideSnapshot.cs:46 · Level 5 · class (internal, sealed)

  • What it is: the cached, whole-table copy of the stored overrides that every flag evaluation reads, implementing IFeatureFlagOverrideSnapshot.
  • Depends on: ICacheService, IServiceScopeFactory, IOptions<FeatureFlagOverrideSettings>, optional IHostEnvironment, IFeatureFlagOverrideStore (resolved per load).
  • Concept introduced (cross-replica invalidation by key prefix). [Rubric §12, Performance & Scalability]: evaluation must not hit the database each time, so the table is read once per lifetime and shared. [Rubric §29, Resilience, Reliability & Business Continuity]: a write invalidates by prefix through ICacheService.RemoveByPrefixAsync, which on a Redis-backed host replaces one generation token so every replica stops addressing the old snapshot; on a memory-only host FeatureFlags:OverrideCacheSeconds is the staleness bound for other replicas (FeatureFlagOverrideSnapshot.cs:20-24).
  • Walkthrough
    • KeyRoot = "featureflags:overrides:" (:53); _lifetime is OverrideCacheSeconds (:55).
    • Prefix (:62) is KeyRoot + service name + : + data-source name + : (BuildPrefix, :77-78). Both parts are needed: services sharing one Redis on the default data-source name would otherwise share one snapshot (:27-33). ResolveServiceName (:85) uses IHostEnvironment.ApplicationName, else the entry assembly name, else "host" (:93).
    • GetAsync (:65) is GetOrCreateAsync on Prefix + "all" (:66) with LoadAsync as the factory, so the key and the invalidated prefix cannot disagree. InvalidateAsync (:70-71) removes by Prefix.
    • LoadAsync (:99) opens its own async scope (:101) because the store is scoped while this class is a singleton (:35-37), and returns an array so the two-level cache can serialize it (:104-105).
  • Where it's used: registered with TryAddSingleton<IFeatureFlagOverrideSnapshot, FeatureFlagOverrideSnapshot>() (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.FeatureFlags.cs:77); read by StoredOverrideFeatureDefinitionProvider, invalidated by FeatureFlagAdministrationService. The singleton-plus-scope shape follows PermissionGrantCache (:36-37).

IBaseDTO<TIdentifierType>

MMCA.Common.Shared · MMCA.Common.Shared.DTOs · MMCA.Common/Source/Core/MMCA.Common.Shared/DTOs/IBaseDTO.cs:9 · Level 0 · interface

  • What it is: a one-property marker interface. Every DTO that carries an entity identifier exposes TIdentifierType Id { get; init; } (MMCA.Common/Source/Core/MMCA.Common.Shared/DTOs/IBaseDTO.cs:13).
  • Depends on: nothing first-party, and nothing external beyond the generic constraint. It lives in MMCA.Common.Shared, the bottom layer, so a Blazor WebAssembly client and an EF-backed service can both reference it.
  • Concept introduced (the DTO and the marker/role interface). [Rubric §9, API & Contract Design] assesses DTOs decoupled from domain entities and stable wire contracts: a DTO (Data Transfer Object) is the shape that crosses the wire, deliberately separate from the domain entity. IBaseDTO lets generic machinery treat any DTO uniformly through its Id, which is what makes a single generic read service, a single generic controller base, and a single generic UI service possible instead of one hand-written trio per entity. This is also [Rubric §1, SOLID]: a textbook Interface Segregation interface, with one member (the only thing a generic consumer needs), so clients never depend on more than they use.
  • Walkthrough: generic over TIdentifierType with a where TIdentifierType : notnull constraint (IBaseDTO.cs:10); the single Id is get; init; (IBaseDTO.cs:13), settable at construction and immutable after. The init-not-set choice recurs across these contracts (see the primer on immutability with required/init). The doc comment (IBaseDTO.cs:3-6) names the two consumers it exists for: the generic query service and the controller bases.
  • Why it's built this way: making the identifier type a generic parameter, rather than hard-coding int, lets a DTO match its entity's strongly-typed id alias (see identifier aliases), so a Guid-keyed aggregate and an int-keyed one share the same generic pipeline; the notnull constraint forbids Id being a nullable type, which keeps the generic code free of null checks on the one value it always needs.
  • Where it's used: it is the constraint on every generic read/write pipeline in the framework, each declaring the same where TEntityDTO : IBaseDTO<TIdentifierType> line: IEntityQueryService<TEntity, TEntityDTO, TIdentifierType> (MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Mapping/IEntityQueryService.cs:21), IEntityDTOMapper<TEntity, TEntityDTO, TIdentifierType> (MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Mapping/IEntityDTOMapper.cs:16), the generic create handler CreateEntityHandlerBase<TCreateRequest, TEntity, TIdentifierType, TEntityDTO> (MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Crud/CreateEntityHandlerBase.cs:50), the controller hierarchy (EntityControllerBase<TEntity, TEntityDTO, TIdentifierType> at MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/EntityControllerBase.cs:41), and the UI's EntityServiceBase<TEntityDTO, TIdentifierType> (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Api/EntityServiceBase.cs:39). Implemented directly by BaseLookup<TIdentifierType> and by every module DTO in ADC, Store, and Helpdesk (for example MMCA.Helpdesk/Source/Modules/Tickets/MMCA.Helpdesk.Tickets.Shared/Tickets/TicketDTO.cs:10).

IConcurrencyAware

MMCA.Common.Shared · MMCA.Common.Shared.DTOs · MMCA.Common/Source/Core/MMCA.Common.Shared/DTOs/IConcurrencyAware.cs:15 · Level 0 · interface

  • What it is: the contract for read DTOs that expose the current optimistic-concurrency token (byte[] RowVersion). The API renders that token as the response ETag, and the client echoes it back in the If-Match header of its next write.
  • Depends on: nothing first-party. It is the wire-side half of a pair whose persistence-side half is IWriteRepository<TEntity, TIdentifierType>.SetOriginalRowVersion; the header encoding of the same bytes is ConcurrencyETag, which names this interface as the byte-array side of the translation (MMCA.Common/Source/Core/MMCA.Common.Shared/Http/ConcurrencyETag.cs:7).
  • Concept introduced (optimistic concurrency, header-only). [Rubric §8, Data Architecture] assesses deliberate persistence: transactions, migrations, soft-delete, audit, and concurrency control. The token is a version stamp that changes on every save of a row: on SQL Server it is a server-generated rowversion, and on PostgreSQL and SQLite it is stamped on every save instead (IConcurrencyAware.cs:17). A read DTO carries the current RowVersion so the client can state a precondition on the next write, and the persistence layer can then refuse a conflicting concurrent edit instead of silently overwriting it. The doc comment (IConcurrencyAware.cs:3-7) spells out the full round trip: DTO to ETag to If-Match to SetOriginalRowVersion. [Rubric §9, API & Contract Design] applies too, because the precondition is expressed in HTTP's own vocabulary rather than in a body field.
  • Walkthrough: one property, byte[] RowVersion { get; init; } (IConcurrencyAware.cs:19), and it is not nullable. The remark (IConcurrencyAware.cs:9-13) is the reason: the token is the If-Match header's whole content, so it is never optional. A DTO read from a persisted aggregate always has one (AuditableBaseEntity.RowVersion is non-null), and a write that states no precondition is refused with 428 Precondition Required rather than falling back to last-write-wins. The same remark states the other half of the current design: update requests carry no token, because the precondition travels in the header alone. Note the [SuppressMessage("Performance", "CA1819")] on IConcurrencyAware.cs:18: exposing a byte[] property normally trips the "properties should not return arrays" analyzer rule, but it is required to round-trip the EF token, and the suppression is justified inline ([Rubric §15, Best Practices]: suppressions are tracked and explained, not blanket-disabled).
  • Why it's built this way: ADR-035 puts the precondition on the resource read rather than on each request model, so a module adds conditional writes by making its read DTO concurrency-aware plus tagging the action, and no request record has to loosen its immutability to receive a token. Keeping the contract in Shared means the same interface is visible to the Blazor client that must echo the tag and to the Infrastructure repository that consumes the bytes.
  • Where it's used: implemented by the read DTOs across the apps: ADC's SessionDTO (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Shared/Sessions/SessionDTO.cs:15) and LivePollDTO (MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.Shared/LivePolls/LivePollDTO.cs:8), Store's OrderDTO (MMCA.Store/Source/Modules/Sales/MMCA.Store.Sales.Shared/Orders/OrderDTO.cs:9) and InventoryItemDTO (MMCA.Store/Source/Modules/Sales/MMCA.Store.Sales.Shared/Inventory/InventoryItemDTO.cs:9), and Helpdesk's TicketDTO (MMCA.Helpdesk/Source/Modules/Tickets/MMCA.Helpdesk.Tickets.Shared/Tickets/TicketDTO.cs:10). On the server, ApiControllerBase.SetConcurrencyETag writes the ETag response header (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/ApiControllerBase.cs:136-145), called from EntityControllerBase<TEntity, TEntityDTO, TIdentifierType> (EntityControllerBase.cs:396) and CrudEntityControllerBase<TEntity, TEntityDTO, TIdentifierType, TCreateRequest, TUpdateRequest> (CrudEntityControllerBase.cs:113). It does not test for this interface: it reads a public byte[] RowVersion property off the row's runtime shape (or the rowVersion entry of a field-projected dictionary row), cached per type (ApiControllerBase.cs:26-30, :112-116), so a shaped response keeps its tag. On the client, EntityServiceBase<TEntityDTO, TIdentifierType>.ConcurrencyTagOf pattern-matches the same interface to build the outgoing If-Match value, treating an empty array as no token (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Api/EntityServiceBase.cs:215-219).
  • Caveats / not-in-source: the "update requests carry no token" half is a convention this interface cannot enforce by itself; it is pinned by the shipped fitness rule UpdateRequests_ShouldNotImplement_IConcurrencyAware (MMCA.Common/Source/Hosting/MMCA.Common.Testing.Architecture/Bases/Domain/ConcurrencyConventionTestsBase.cs:16), which each consumer app subclasses.

ServiceHostAuthentication

MMCA.Common.ServiceHost · MMCA.Common.ServiceHost · MMCA.Common/Source/Hosting/MMCA.Common.ServiceHost/ServiceHostAuthentication.cs:6 · Level 0 · enum

  • What it is: the two-value switch that tells the composed service host how it validates bearer tokens: ForwardedJwtBearer = 0 (ServiceHostAuthentication.cs:12) for every service that receives tokens, and TokenIssuer = 1 (ServiceHostAuthentication.cs:18) for the one Identity service that mints them.
  • Depends on: nothing; it is read by ServiceHostBuilderExtensions and carried on MmcaServiceHostOptions.
  • Concept (issuer versus relying party). [Rubric §11, Security] assesses authentication and token handling. A service that only consumes tokens validates them against the issuer's published signing keys (JWKS discovery against Authentication:JwtBearer:Authority, ServiceHostAuthentication.cs:8-11), while the issuer validates in process with its own Jwt settings and reads no authority at all (:14-17). The dual-fetch model itself is taught in the primer under ADR-004; this enum only picks which half a host runs.
  • Walkthrough: the zero value is the forwarded mode, so a default-constructed options object is a relying party, and MmcaServiceHostOptions.Authentication defaults to it explicitly (MmcaServiceHostOptions.cs:52). AddMmcaServiceHost branches on it: TokenIssuer calls AddCommonAuthentication, anything else calls AddForwardedJwtBearer with the authority from GetRequiredJwtAuthority() and an audience from JwtAudience.RequireConfigured (ServiceHostBuilderExtensions.cs:132-143).
  • Why it's built this way: a selector, rather than a callback, keeps the fail-closed audience check inside the package for every relying-party host, and it gives the architecture rule a literal to look for. ArchitectureRules.ForwardedJwtBearerAudienceIsFailClosed exempts a host file only when it names ServiceHostAuthentication.TokenIssuer (MMCA.Common/Source/Hosting/MMCA.Common.Testing.Architecture/Rules/Api/ArchitectureRules.ForwardedJwt.cs:10, :41), surfaced through ForwardedJwtAudienceTestsBase.
  • Where it's used: ADC's Identity service is the one host that selects TokenIssuer (MMCA.ADC/Source/Services/MMCA.ADC.Identity.Service/Program.cs:114); ADC's Conference, Engagement and Notification services keep the default.

ServiceHostOpenApi

MMCA.Common.ServiceHost · MMCA.Common.ServiceHost · MMCA.Common/Source/Hosting/MMCA.Common.ServiceHost/ServiceHostOpenApi.cs:10 · Level 0 · static class (internal)

  • What it is: the internal helper that names the served OpenAPI document (DocumentName = "v1", ServiceHostOpenApi.cs:15) and fails startup when the host never registered it.
  • Depends on: ASP.NET Core's IOpenApiDocumentProvider and IServiceProviderIsKeyedService (external).
  • Concept: cross-reference OpenApiEndpointExtensions for the served document. [Rubric §33, Developer Experience] assesses whether a mistake is caught early with an actionable message; this type turns a silently summary-less document into a startup exception that names the missing line.
  • Walkthrough: EnsureHostRegisteredDocument (ServiceHostOpenApi.cs:24) asks the root provider whether IOpenApiDocumentProvider is registered as a keyed service under "v1" (the registration AddOpenApi makes) and returns if so (:26-30); otherwise it throws InvalidOperationException telling the developer to call builder.Services.AddOpenApi() in the host's own Program.cs (:32).
  • Why it's built this way: the message states the reason. The OpenAPI XML-comment generator attaches controller summaries only at an AddOpenApi call compiled in the host project, so the package cannot register the document on the host's behalf without losing them; it pins the version instead (see ServiceHostBuilderExtensions). Versioned-API context: ADR-046.
  • Where it's used: DocumentName keys the OpenAPI 3.1 pin in AddMmcaServiceHost (ServiceHostBuilderExtensions.cs:127-129), and the check runs first in ServiceHostApplicationExtensions.UseMmcaServiceHostAsync (ServiceHostApplicationExtensions.cs:51).

RedisCounterScript

Linked source (compiled into MMCA.Common.Infrastructure and MMCA.Common.API) · MMCA.Common.Redis · MMCA.Common/Source/Build/Redis/RedisCounterScript.cs:15 · Level 0 · class (internal, static)

  • What it is: the one Lua script both Redis fixed-window counters run: the distributed rate limiter RedisFixedWindowRateLimiter and the counter store RedisCounterStore (RedisCounterScript.cs:3-7). Its only member is the Increment constant (:24-27).
  • Depends on: nothing; a string constant evaluated server-side by Redis.
  • Concept introduced (atomic increment-plus-expiry). [Rubric §29, Resilience, Reliability & Business Continuity] assesses whether a partial failure can leave state behind: running INCRBY and EXPIRE as two client calls could die between them and leave a counter key with no TTL, which would never reset. One script makes the pair a single atomic server-side step (:18-19). [Rubric §12, Performance & Scalability]: the count is shared across replicas without any client-side lock.
  • Walkthrough: KEYS[1] is the counter key, ARGV[1] the amount to add, ARGV[2] the TTL in seconds; the script returns the new count (:19-20). It runs INCRBY (:25), and only when the resulting count is no larger than the amount just added, that is on the increment that created the key, it runs EXPIRE (:26). Re-stamping the TTL on every call would slide the window forward for a caller who keeps hitting it, so the allowance would never reset (:20-22). It uses no command newer than Redis 2.6 (:22).
  • Why it's built this way: one source file is linked as an internal type into both packages with Compile Include ... Link (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/MMCA.Common.Infrastructure.csproj:13, MMCA.Common/Source/Presentation/MMCA.Common.API/MMCA.Common.API.csproj:38), following the precedent of RemainingWindowFixedWindowRateLimiter. A linked source rather than a reference because the two owners sit in different layers (Infrastructure must not reference API), and the script is too small to justify a public type in a shared package (RedisCounterScript.cs:8-14).
  • Where it's used: RedisFixedWindowRateLimiter passes it to ScriptEvaluateAsync with the window key, the permit count and its key TTL (MMCA.Common/Source/Presentation/MMCA.Common.API/RateLimiting/RedisFixedWindowRateLimiter.cs:212-215); RedisCounterStore does the same with an amount of 1 (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Caching/RedisCounterStore.cs:91). RedisFixedWindowRateLimiterTests asserts the script's content (MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/RateLimiting/RedisFixedWindowRateLimiterTests.cs:178).

RedisOutageCircuit

Linked source (compiled into MMCA.Common.Infrastructure and MMCA.Common.API) · MMCA.Common.Redis · MMCA.Common/Source/Build/Redis/RedisOutageCircuit.cs:27 · Level 0 · class (internal, sealed)

  • What it is: a short open-circuit window around one Redis connection, shared by the two fail-soft Redis counters: RedisCounterStore and RedisFixedWindowRateLimiter (RedisOutageCircuit.cs:6-10). After a Redis fault it tells both to skip Redis and use their process-local fallback at once, for OpenDuration (10 seconds, :30).
  • Depends on: nothing first-party; StackExchange.Redis's IConnectionMultiplexer, the BCL ConditionalWeakTable, TimeProvider, Volatile and Interlocked (external).
  • Concept (a minimal circuit breaker). [Rubric §29, Resilience, Reliability & Business Continuity] assesses whether a dependency outage degrades the caller gracefully rather than slowly. Both counters already answer a Redis fault from a fallback, but without a circuit every call still waited for the client to give up first: with the StackExchange.Redis defaults (commands queued while disconnected, a five-second asynchronous timeout) a call against an unreachable server took about six seconds before falling back, on every call (:13-16). The circuit turns that per-call wait into one wait per window: closed (call Redis), open (skip it), and after the window a single probe whose result closes or re-opens it (:17-19). [Rubric §12, Performance & Scalability]: the state is one long read without a lock on the hot path.
  • Walkthrough: OpenDuration is TimeSpan.FromSeconds(10) (:30). The state is _openUntilTicks, the UTC ticks until which the circuit is open, zero while closed (:34-35). For(IConnectionMultiplexer) (:40-41) returns the connection's circuit from a static ConditionalWeakTable, creating it closed on first use (:32), so the table never keeps a disposed connection alive. ShouldAttempt(TimeProvider) (:50) returns true while closed (:52-56); otherwise it returns true only once now >= openUntil and the caller wins an Interlocked.CompareExchange that pushes the window forward by another OpenDuration (:58-60). That compare-and-swap is what makes the probe exactly one caller: concurrent callers see the re-armed window and keep the fallback until the probe reports (:43-47). RecordSuccess() (:64) resets the ticks to zero, writing only when the circuit is not already closed (:66-69); RecordFault(TimeProvider) (:74-75) sets the window to now plus OpenDuration.
  • Why it's built this way: one circuit per connection, because a fault is a property of the connection that every partition and key shares (:22-23), so the limiter's many per-partition instances all trip together. It is a linked source like RedisCounterScript (Compile Include ... Link in MMCA.Common/Source/Core/MMCA.Common.Infrastructure/MMCA.Common.Infrastructure.csproj:18 and MMCA.Common/Source/Presentation/MMCA.Common.API/MMCA.Common.API.csproj:46), so each package holds its own copy of the static table and the store and the limiter open their circuits independently (:23-24). Injecting TimeProvider into each call keeps the window testable without a real clock.
  • Where it's used: both owners take their circuit with RedisOutageCircuit.For(connection) in the constructor (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Caching/RedisCounterStore.cs:70, MMCA.Common/Source/Presentation/MMCA.Common.API/RateLimiting/RedisFixedWindowRateLimiter.cs:143). RedisCounterStore checks ShouldAttempt before each Redis call and goes straight to its fallback counter when it is false (RedisCounterStore.cs:83-86, also :109, :136), records success after each answer (:93, :117, :144), and records a fault in LogFault (:171). RedisFixedWindowRateLimiter answers an open circuit as a fault would, counting locally for the auth-ip policy or failing open otherwise (RedisFixedWindowRateLimiter.cs:202-207), records success after the script returns (:217) and a fault in its catch (:225).
  • Caveats / not-in-source: no test in MMCA.Common/Tests names the type directly; its behavior is exercised only through its two owners. Not determinable from source: the measurement behind the six-second figure, which the remark tags only as (C7) (:16).

BaseLookup<TIdentifierType>

MMCA.Common.Shared · MMCA.Common.Shared.DTOs · MMCA.Common/Source/Core/MMCA.Common.Shared/DTOs/BaseLookup.cs:8 · Level 1 · record class

  • What it is: a minimal DTO for dropdown and autocomplete lookups: just Id and Name.
  • Depends on: IBaseDTO<TIdentifierType> (Level 0), which it implements (BaseLookup.cs:8).
  • Concept (right-sized response shapes). [Rubric §9, API & Contract Design] assesses whether responses are shaped to their consumer rather than dumping full entities. Instead of returning a full entity DTO to populate a <select> element, the system returns BaseLookup<T>, carrying only the id and the display name; this cuts wire size and avoids coupling the UI to full entity shapes it does not need. Both Id (BaseLookup.cs:12) and Name (BaseLookup.cs:15) are required, so hand-written construction is compile-checked, and record equality gives value semantics for free.
  • Walkthrough: the type itself is four lines, but its interesting half lives in the repository that projects into it. EFReadRepository<TEntity, TIdentifierType>.GetAllForLookupAsync (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Repositories/EFReadRepository.cs:222) takes the name of the display property and lets the database do the shaping. The selector is built once per (entity type, property name) pair into a cache (:247-248), binding Id and the named property into a BaseLookup<TIdentifierType> via Expression.MemberInit (:262-268). Note the consequence for required: an expression-tree MemberInit constructs the record without the compiler's required-member check, which is legal because required is a compile-time contract, not a runtime one. Above the repository the shape travels as a CollectionResult<T> through EntityControllerBase<TEntity, TEntityDTO, TIdentifierType>.GetAllForLookupAsync (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/EntityControllerBase.cs:334-353).
  • Why it's built this way: one shared lookup shape means the UI's generic select components bind to a single type regardless of which entity fills them, and projecting inside the SQL query (rather than materializing entities and mapping) keeps a lookup list cheap [Rubric §12, Performance & Scalability]; caching the compiled expression per property name keeps the reflection cost to the first call.
  • Where it's used: returned by the lookup path at every layer: the read repository (EFReadRepository.cs:222), IEntityQueryService<TEntity, TEntityDTO, TIdentifierType>, the controller base (EntityControllerBase.cs:334), and the UI's IEntityService<TEntityDTO, TIdentifierType>.

MmcaServiceHost

MMCA.Common.ServiceHost · MMCA.Common.ServiceHost · MMCA.Common/Source/Hosting/MMCA.Common.ServiceHost/MmcaServiceHost.cs:11 · Level 4 · sealed class

  • What it is: the handle AddMmcaServiceHost returns and UseMmcaServiceHostAsync takes back, carrying state from the registration phase to the application phase of startup.
  • Depends on: ModuleHostContext and ILoggerFactory (external).
  • Walkthrough: the constructor is internal (MmcaServiceHost.cs:13), so only ServiceHostBuilderExtensions can create one. ModuleHost (:23) is public: the same module host the ConfigurePipeline callback received (bound settings, the module loader, the discovery step). BootstrapLoggerFactory (:29) is internal: the factory the module loader's logger came from, kept alive for the life of the host and disposed on ApplicationStopped.
  • Why it's built this way: the module loader keeps the logger it was given, so the factory cannot be disposed at the end of registration; returning it inside an opaque handle lets the application phase own its disposal without exposing it to the host.
  • Where it's used: every ADC service host stores it as var host = builder.AddMmcaServiceHost(...) and passes it to app.UseMmcaServiceHostAsync(host) (for example MMCA.ADC/Source/Services/MMCA.ADC.Conference.Service/Program.cs:88, :376).

MmcaServiceHostOptions

MMCA.Common.ServiceHost · MMCA.Common.ServiceHost · MMCA.Common/Source/Hosting/MMCA.Common.ServiceHost/MmcaServiceHostOptions.cs:16 · Level 4 · sealed class

  • What it is: the values and callbacks that differ between service hosts. Its defaults are the REST plus gRPC service profile: an Http2-only cleartext endpoint, forwarded JWT validation, no Redis-backed output cache (MmcaServiceHostOptions.cs:11-15).
  • Depends on: ServiceHostAuthentication, MmcaApplicationPipelineBuilder, ModuleHostContext; externals HttpProtocols, OutputCacheOptions, WebApplicationBuilder, IServiceCollection, Assembly.
  • Concept (options object plus ordered callbacks). [Rubric §2, Design Patterns] assesses deliberate pattern use: this is a Template Method expressed as data. The package owns the fixed registration order, and each Action property is a hook invoked at one named point in it, so a host supplies only what differs. [Rubric §7, Microservices Readiness] applies too: every extracted service starts the same way, which is what lets a module move out of the monolith without a hand-written startup (ADR-059).
  • Walkthrough: three required members. LogFilePath (:22) is the rolling Serilog file, skipped in Production; ModuleAssemblies (:28) lists only the host's own module assemblies so peer modules are never loaded; ConfigurePipeline (:35) is the application-pipeline body (ADR-014), typically pipeline.Register(moduleHost.RegisterModules) plus gRPC clients and AddBrokerMessaging. Defaulted values: Protocols is HttpProtocols.Http2 (:42; Http1AndHttp2 for the ADR-012 mixed profile), RedeclareCleartextEndpoint is true (:49; false for a host that declares endpoints under Kestrel:Endpoints), Authentication is ForwardedJwtBearer (:52), UseRedisOutputCaching is false (:55). The optional callbacks, by the point they run: ConfigureConfigurationSources first of all, before any configuration is read (:66); AfterServiceDefaults right after AddServiceDefaults(), the place for vendor exporters and the shared DataProtection key ring (:72); ConfigureOutputCache after the always-present no-cache base policy (:60); ConfigureServices after AddAPI (:78); RegisterBrokerTransports immediately before the pipeline, because AddBrokerMessaging picks its transport while it registers (:84).
  • Why it's built this way: vendor calls (Key Vault, the Azure Monitor exporter, a cloud broker transport) arrive only as callbacks, so the package stays cloud-neutral (ADR-134); the options type is sealed with init-only members, so a host cannot change it after the call.
  • Where it's used: passed as new() { ... } to AddMmcaServiceHost by each ADC service host (MMCA.ADC/Source/Services/MMCA.ADC.Engagement.Service/Program.cs:59, MMCA.ADC/Source/Services/MMCA.ADC.Notification.Service/Program.cs:58, MMCA.ADC/Source/Services/MMCA.ADC.Identity.Service/Program.cs:76).

ServiceHostBuilderExtensions

MMCA.Common.ServiceHost · MMCA.Common.ServiceHost · MMCA.Common/Source/Hosting/MMCA.Common.ServiceHost/ServiceHostBuilderExtensions.cs:30 · Level 5 · static class

  • What it is: the composed service-host registration, one extension(WebApplicationBuilder) method, AddMmcaServiceHost(MmcaServiceHostOptions) (ServiceHostBuilderExtensions.cs:65), that holds the start-up list every extracted service host would otherwise repeat, in the one order that is correct for all of them (:20-25).
  • Depends on: MmcaServiceHostOptions, ServiceHostAuthentication, ServiceHostOpenApi, MmcaServiceHost, ModuleHostExtensions, ModuleLoader, SerilogHostExtensions, JwtAudience, JwtAuthorityExtensions, MiniProfilerExtensions; it spans the API, Aspire, Grpc and Infrastructure packages (:6-16).
  • Concept: C# extension(T) blocks are taught in the primer. [Rubric §3, Clean Architecture] assesses composition at the edge: this is the composition root for a service host, and the only place that knows the order. The CA1708 suppression (:26-29) is justified inline as an extension(T) false positive [Rubric §15, Best Practices].
  • Walkthrough: guards first: null builder or options, and an empty ModuleAssemblies throws ArgumentException (:67-74). Then, in order: ConfigureConfigurationSources (:79) so a vault value is seen by every eager bind below; Kestrel endpoints with the health-probe listener (:81); AddCommonSerilog then AddServiceDefaults() then AfterServiceDefaults (:84-86); AddRedisCaching, the Redis output cache when asked for, and the hybrid cache when Redis is configured (:91-97); a bootstrap logger factory and AddModuleHost (:101-104); infrastructure health checks with requireDatabase: true (:106); CORS, API versioning and rate limiting (:108-110); the output cache with a no-cache base policy then the host's policies (:112-116); response compression (:118); the OpenAPI 3.1 pin as named options on the "v1" document, then AddCommonOpenApi() (:127-130), so a bare AddOpenApi() made before or after still emits 3.1 on both framework lines (ADR-141); token validation by Authentication (:132-143); exception handlers, AddInfrastructure, AddAPI (:145-147); AddMiniProfilerIfEnabled (:151); ConfigureServices (:153); RegisterBrokerTransports (:156); AddMmcaApplicationPipeline with the host's ConfigurePipeline as its body (:158); AddApplicationProfiling only when ApplicationSettings:UseMiniProfiler is true, after the pipeline because TryDecorate wraps only what is registered (:162-165); AddGrpcServiceDefaults (:167); and last the per-module health checks, which can only see modules discovery found (:170). It returns a new MmcaServiceHost (:172).
  • Why it's built this way: the doc comment (:49-59) records two contracts. The host keeps its own builder.Services.AddOpenApi() line, because XML-comment summaries attach only at a call site compiled in the host project (enforced at startup by ServiceHostOpenApi). And after the call the application pipeline is sealed, so anything registered afterwards (gRPC endpoint services, a service-token client, MCP) must not register command or query handlers. Composition order and module contract: ADR-059.
  • Where it's used: every ADC service host (MMCA.ADC/Source/Services/MMCA.ADC.Conference.Service/Program.cs:88, MMCA.ADC/Source/Services/MMCA.ADC.Identity.Service/Program.cs:76, and the Engagement and Notification hosts at Program.cs:55); its layer placement is pinned by Common's LayerDependencyTests and CloudVendorIsolationTests.

ServiceHostProfiling

MMCA.Common.ServiceHost · MMCA.Common.ServiceHost · MMCA.Common/Source/Hosting/MMCA.Common.ServiceHost/ServiceHostProfiling.cs:11 · Level 11 · static class (internal)

  • What it is: the internal helper that inserts a "MiniProfiler" step (StepName, ServiceHostProfiling.cs:14) into the shared middleware pipeline.
  • Depends on: MiddlewarePipelineBuilder, MiddlewarePipelineStep, MiddlewarePipelineStepNames; MiniProfiler's UseMiniProfiler (external).
  • Walkthrough: InsertMiddleware (:24) calls pipeline.InsertAfter(MiddlewarePipelineStepNames.TenantResolution, ...) with a step that runs app.UseMiniProfiler() (:25-27). Placing it right after tenant resolution means HttpContext.User is populated when the profiler answers its own result routes, and the controllers, the CQRS pipeline and EF Core all run inside the profiled request (:16-22).
  • Why it's built this way: the named-step builder (ADR-079) lets the host add an optional step at a stable position without restating the whole pipeline. Who may read the results is decided by MiniProfilerOptions.ResultsAuthorize, which AddMiniProfilerIfEnabled limits to Development (:20-21) [Rubric §13, Observability & Operability].
  • Where it's used: only by ServiceHostApplicationExtensions when ApplicationSettings:UseMiniProfiler is true (ServiceHostApplicationExtensions.cs:57-60).

ServiceHostApplicationExtensions

MMCA.Common.ServiceHost · MMCA.Common.ServiceHost · MMCA.Common/Source/Hosting/MMCA.Common.ServiceHost/ServiceHostApplicationExtensions.cs:19 · Level 12 · static class

  • What it is: the application-phase half of the composed service host: one extension(WebApplication) method, UseMmcaServiceHostAsync(MmcaServiceHost, CancellationToken) (ServiceHostApplicationExtensions.cs:44).
  • Depends on: MmcaServiceHost, ServiceHostOpenApi, ServiceHostProfiling, DatabaseInitializationExtensions, WebApplicationExtensions, OpenApiEndpointExtensions.
  • Walkthrough: after null guards (:46-47), in order: the OpenAPI registration check, before the database is touched or anything mapped (:51); database initialization (migrate and seed, skipped only for the Development design-time OpenAPI run) so nothing is mapped against an unmigrated schema (:54, ADR-030); MapDefaultEndpoints (:56); the shared middleware pipeline, with the MiniProfiler step inserted when UseMiniProfiler is true (:57-64); MapCommonOpenApi (:66); in Development only, the gRPC reflection service marked AllowAnonymous for the fallback authorization policy (:68-73, ADR-122); and finally registering disposal of the bootstrap logger factory on ApplicationStopped (:77).
  • Why it's built this way: it mirrors ServiceHostBuilderExtensions so the two halves of startup are each one call, and every fail-fast check runs before side effects [Rubric §29, Resilience & Business Continuity]: a misconfigured host refuses to start rather than serving a degraded document or an unmigrated database.
  • Where it's used: every ADC service host ends with await app.UseMmcaServiceHostAsync(host) (MMCA.ADC/Source/Services/MMCA.ADC.Conference.Service/Program.cs:379, MMCA.ADC/Source/Services/MMCA.ADC.Identity.Service/Program.cs:300, MMCA.ADC/Source/Services/MMCA.ADC.Engagement.Service/Program.cs:255, MMCA.ADC/Source/Services/MMCA.ADC.Notification.Service/Program.cs:152).

FeatureFlagLifetime

MMCA.Common.Shared · MMCA.Common.Shared.FeatureFlags · MMCA.Common/Source/Core/MMCA.Common.Shared/FeatureFlags/FeatureFlagLifetime.cs:9 · Level 0 · enum

  • What it is: the two-value lifetime a feature flag declares itself as, Permanent or Temporary (MMCA.Common/Source/Core/MMCA.Common.Shared/FeatureFlags/FeatureFlagLifetime.cs:9-22).
  • Depends on: nothing; consumed by FeatureFlagAttribute, FeatureFlagDescriptor and FeatureFlagStatusResponse.
  • Concept introduced (the flag with a stated exit). [Rubric §34, Architecture Governance & Documentation] assesses whether architectural decisions are enforced by checks rather than by memory. Permanent is "a capability a host chooses to run with or without (push notifications, a data-subject export endpoint)" and must NOT carry a removal date (FeatureFlagLifetime.cs:11-15); Temporary "exists only until a migration, rollout or experiment finishes", must carry a removal date, and the build fails once that date has passed (:17-21). The enforcement itself lives on FeatureFlagAttribute and the governance architecture rule that reads it.
  • Walkthrough: two members, Permanent (FeatureFlagLifetime.cs:15) and Temporary (:21), each documented inline with the consequence it carries.
  • Why it's built this way: ADR-031 is the feature-flag management scheme this lifetime enforces.
  • Where it's used: the Lifetime argument every [FeatureFlag] attribute application supplies, across MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.Shared/EngagementFeatures.cs, MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Shared/ConferenceFeatures.cs, MMCA.Common/Source/Core/MMCA.Common.Shared/Notifications/NotificationFeatures.cs, and MMCA.Common/Source/Core/MMCA.Common.Shared/Privacy/PrivacyFeatures.cs; read back by FeatureFlagRegistry.Describe into each FeatureFlagDescriptor.Lifetime, surfaced to operators as FeatureFlagStatusResponse.Lifetime, and checked by the governance architecture rule that fails a Temporary flag past its RemoveBy date (MMCA.Common/Source/Hosting/MMCA.Common.Testing.Architecture/Rules/Governance/ArchitectureRules.FeatureFlags.cs:70). That rule compares the lifetime by its name string (ArchitectureRules.FeatureFlags.cs:13-14), not through this enum, because the architecture-testing package takes no framework reference (:7-9).

FeatureFlagOverrideMode

MMCA.Common.Shared · MMCA.Common.Shared.FeatureFlags · MMCA.Common/Source/Core/MMCA.Common.Shared/FeatureFlags/FeatureFlagOverrideMode.cs:10 · Level 0 · enum

  • What it is: what a stored, operator-set override does to a declared flag: Off, On, Percentage, or Targeting (MMCA.Common/Source/Core/MMCA.Common.Shared/FeatureFlags/FeatureFlagOverrideMode.cs:10-29).
  • Depends on: System.Text.Json.Serialization.JsonStringEnumConverter<T> (BCL), applied at :9.
  • Concept: the runtime half of ADR-031. Where FeatureFlagLifetime describes a flag's declared life cycle, this enum describes what an operator has set it to without a new revision. [Rubric §9, API & Contract Design] assesses whether a wire contract can evolve without breaking clients: the type doc says it is "Serialized by name, so a client reads a newer mode as an unknown string rather than a bare number" (:6-7), and the explicit numeric values (= 0 to = 3) pin the stored column against a reorder.
  • Walkthrough: Off = 0 is the kill switch (:13); On = 1 is on for everyone (:16); Percentage = 2 is on for a stable percentage of users through the targeting filter's default rollout, "so one user keeps the same answer from request to request" (:18-22); Targeting = 3 is on for named users and groups plus an optional percentage of everyone else, and groups are how a tenant-wide override is expressed (:24-28).
  • Why it's built this way: each mode maps one-to-one onto a Microsoft.FeatureManagement definition in FeatureFlagDefinitions.ToDefinition (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/FeatureFlags/FeatureFlagDefinitions.cs:33-46): On becomes an always-on filter, Percentage and Targeting become a targeting filter, Off becomes a definition with no filter, and an unknown mode also evaluates to off (:44-45), which fails closed.
  • Where it's used: carried by SetFeatureFlagOverrideRequest.Mode, FeatureFlagOverrideResponse.Mode, and stored on FeatureFlagOverride.Mode, which also decides which modes carry a percentage or an audience; the admin page MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Administration/FeatureFlagAdmin.razor.cs offers the four modes to the operator.

FeatureFlagValueKind

MMCA.Common.Shared · MMCA.Common.Shared.FeatureFlags · MMCA.Common/Source/Core/MMCA.Common.Shared/FeatureFlags/FeatureFlagValueKind.cs:10 · Level 0 · enum

  • What it is: the coarse state a flag definition puts a flag in, as the administration surface reports it: Off, On, or Conditional (MMCA.Common/Source/Core/MMCA.Common.Shared/FeatureFlags/FeatureFlagValueKind.cs:5-20).
  • Depends on: JsonStringEnumConverter<T> (BCL), applied at :9; serialized by name like FeatureFlagOverrideMode.
  • Concept: a summary, not an evaluation. A conditional flag's answer depends on the caller, so the admin surface cannot say "on" or "off" for it; this enum names that third state honestly instead of guessing. The concept of a stored override is introduced at FeatureFlagOverrideMode.
  • Walkthrough: Off = 0 covers "everyone, including a flag the configuration never mentions" (:12-13); On = 1 is on for everyone (:15-16); Conditional = 2 is "decided per evaluation by one or more feature filters" (:18-19).
  • Why it's built this way: FeatureFlagDefinitions.Describe is the one place that collapses a definition into this enum (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/FeatureFlags/FeatureFlagDefinitions.cs:51-75): a missing or disabled definition is Off (:53-56), a definition with no named filter is Off (:63-66), a definition whose filters are all always-on (or any always-on under RequirementType.Any) is On (:68-72), and anything else is Conditional with its filter names (:74).
  • Where it's used: the Configured and Effective fields of FeatureFlagStatusResponse, filled by FeatureFlagAdministrationService (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/FeatureFlags/FeatureFlagAdministrationService.cs:125-130), and rendered by FeatureFlagAdmin.razor.cs.

SupportedCultures

MMCA.Common.Shared · MMCA.Common.Shared.Globalization · MMCA.Common/Source/Core/MMCA.Common.Shared/Globalization/SupportedCultures.cs:9 · Level 0 · class (static)

  • What it is: the framework-wide allowlist of supported UI cultures (ADR-027). A static class holding the default culture, the full supported set, the Development-only pseudo-localization locale, a closest-match resolver, and two membership tests.
  • Depends on: nothing first-party. Uses only BCL types (IReadOnlyList<string>, StringComparison).
  • Concept introduced (internationalization allowlist as one source of truth). [Rubric §27, i18n] assesses whether locale support is centralized, discoverable, and drift-resistant rather than scattered string checks. Every consumer that decides "is this a language we support" reads this one list: the host request-localization setup, the culture switcher, the MAUI head's culture resolution, and the domain guard on a user's preferred culture. Adding a locale means adding a .<culture>.resx sibling set plus one entry here, with no other infrastructure change (SupportedCultures.cs:3-8).
  • Walkthrough
    • Default = "en-US" (SupportedCultures.cs:12) is the fallback used when no cookie, profile, or Accept-Language preference resolves.
    • All (SupportedCultures.cs:18) is the supported set, default first, and today it is exactly [Default, "es"]: English and Spanish. Both the request-localization options and the culture switcher iterate it.
    • PseudoLocale = "qps-Ploc" (SupportedCultures.cs:28) is the Windows-standard pseudo-localization locale, deliberately not part of All so the translation-completeness fitness gate does not demand a .qps-Ploc.resx sibling (:21-23). It is wired into request localization, the culture-switch endpoint, and the culture switcher in Development only, where it runtime-transforms every resolved resource string (accents, padding, bracket sentinel) to surface hard-coded strings, truncation, and string concatenation without translating anything (:23-26).
    • IsSupported(string?) (SupportedCultures.cs:35-37) returns true for a non-empty culture matched case-insensitively against All; IsPseudoLocale(string?) (SupportedCultures.cs:76-77) tests case-insensitively against PseudoLocale. Both take a nullable string so callers can pass an unvalidated cookie, query value, or profile field straight in.
    • ResolveClosest(string?) (SupportedCultures.cs:51) is the fallback ladder: blank returns Default (:53-56), an exact case-insensitive All match wins (:58-62), otherwise the language subtag is matched, so "es-MX" resolves to "es" (:64-66), and anything left over falls to Default (:68). The subtag split is done by the private LanguageOf (:83-87), which returns the input unchanged when there is no -, avoiding an allocation for an already-neutral culture. Because PseudoLocale is not in All, this method can never return it (stated at :42).
  • Why it's built this way: a single const plus IReadOnlyList allowlist keeps the localization middleware, the switcher UI, the fitness gate, and the domain guard from drifting apart; separating PseudoLocale from All lets a diagnostic locale ship in Development without polluting the production culture set or the resx-completeness gate. ResolveClosest exists because web heads get language-level fallback for free from request localization's Accept-Language matching, while a head with no request pipeline (the MAUI Blazor Hybrid, which resolves against the device locale) has to do it itself, and the doc comment (SupportedCultures.cs:43-48) says explicitly that the point is to keep the two paths from diverging.
  • Where it's used: WebApplicationExtensions.UseCommonRequestLocalization builds the supported list from All (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/WebApplicationExtensions.cs:55), appends PseudoLocale only in Development (:80), and sets Default as the default culture (:85); the culture-switch endpoint validates the incoming value with IsSupported or, when pseudo is allowed, IsPseudoLocale (:107). MmcaCultureBootstrap falls back to Default when the stored culture is not supported (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Culture/MmcaCultureBootstrap.cs:46), and PseudoStringLocalizer activates only under IsPseudoLocale (MMCA.Common/Source/Presentation/MMCA.Common.UI/Globalization/PseudoStringLocalizer.cs:17). The MAUI head is the ResolveClosest caller: MauiCultureStore resolves the device culture when nothing is stored (MMCA.Common/Source/Presentation/MMCA.Common.UI.Maui/Globalization/MauiCultureStore.cs:41-43), and MauiCultureApplier refuses an unsupported culture outright (.../MauiCultureApplier.cs:32). The domain guard is CommonInvariants.EnsurePreferredCultureIsValid, which allows null or an IsSupported culture (MMCA.Common/Source/Core/MMCA.Common.Domain/Invariants/CommonInvariants.cs:144).

FeatureFlagAttribute

MMCA.Common.Shared · MMCA.Common.Shared.FeatureFlags · MMCA.Common/Source/Core/MMCA.Common.Shared/FeatureFlags/FeatureFlagAttribute.cs:32 · Level 1 · class (sealed)

  • What it is: the attribute a *Features constant class applies to each flag field, carrying a FeatureFlagLifetime, an optional RemoveBy date, and an optional Owner (MMCA.Common/Source/Core/MMCA.Common.Shared/FeatureFlags/FeatureFlagAttribute.cs:32-67).
  • Depends on: FeatureFlagLifetime; System.Attribute, System.DateOnly, System.Globalization.CultureInfo (BCL).
  • Concept introduced (self-describing metadata a reflection scan can enforce). [Rubric §34, Architecture Governance & Documentation] assesses whether a "temporary" label is actually checkable. RemoveBy is a string? rather than a DateOnly? because "an attribute argument must be a compile-time constant" (FeatureFlagAttribute.cs:44), so TryParseRemoveBy (:60-66) is what turns the constant string back into a real date for the check, parsed strictly against RemoveByFormat = "yyyy-MM-dd" (:35,63). Owner exists purely for the failure message: "Carried into the failure message, so an expired flag names someone" (:50), which lets the governance architecture rule point at a person rather than an anonymous build break.
  • Walkthrough: a primary constructor takes lifetime (:32), stored read-only as Lifetime (:38). RemoveBy and Owner are init-only properties (:46,52), settable only as named attribute arguments. TryParseRemoveBy is the one static method: a thin wrapper over DateOnly.TryParseExact with DateTimeStyles.None (:60-66), so a malformed date fails to parse rather than being silently coerced.
  • Why it's built this way: ADR-031 is the flag life cycle this attribute encodes: pairing every flag with an explicit permanent or temporary choice and, for temporary ones, a checkable expiry.
  • Where it's used: applied to every flag field in the *Features constant classes; read by FeatureFlagRegistry.Describe via GetCustomAttribute<FeatureFlagAttribute> (MMCA.Common/Source/Core/MMCA.Common.Shared/FeatureFlags/FeatureFlagRegistry.cs:102). The governance architecture rules FeatureFlagsDeclareLifetime and TemporaryFeatureFlagsAreNotPastRemoveBy (MMCA.Common/Source/Hosting/MMCA.Common.Testing.Architecture/Rules/Governance/ArchitectureRules.FeatureFlags.cs:28,70) do not reference this type: they match it by its full name string (:10) and read its properties reflectively (:95-98), keeping their own copy of RemoveByFormat (:12).
  • Caveats / not-in-source: because the governance rule duplicates the format and lifetime names as strings (ArchitectureRules.FeatureFlags.cs:12-14), a rename here is not a compile error there.

FeatureFlagDescriptor

MMCA.Common.Shared · MMCA.Common.Shared.FeatureFlags · MMCA.Common/Source/Core/MMCA.Common.Shared/FeatureFlags/FeatureFlagRegistry.cs:17 · Level 1 · record (sealed)

  • What it is: one row of FeatureFlagRegistry.Describe's output: a flag's field name, wire name, and the FeatureFlagLifetime, RemoveBy and Owner its [FeatureFlag] attribute carries, if any (MMCA.Common/Source/Core/MMCA.Common.Shared/FeatureFlags/FeatureFlagRegistry.cs:17-22).
  • Depends on: FeatureFlagLifetime.
  • Concept: Lifetime, RemoveBy, and Owner are all nullable (:20-22) because a flag field compiles without the [FeatureFlag] attribute at all: the descriptor still reports the field and its constant value, just with no life-cycle metadata attached. The governance rule is what turns a missing attribute into a build failure; the descriptor itself stays uniform either way.
  • Walkthrough: five positional parameters and no body (FeatureFlagRegistry.cs:17-22): FieldName (the CLR field), FlagName (the constant's string value), then the three attribute-sourced, nullable fields.
  • Why it's built this way: ADR-031 is the scheme this record inventories.
  • Where it's used: produced by FeatureFlagRegistry.Describe, one per flag field; cached by FeatureFlagCatalog as the host's declared flag list, de-duplicated case-insensitively by FlagName (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/FeatureFlags/FeatureFlagCatalog.cs:19-25) and looked up by TryFind (:31); projected into a FeatureFlagStatusResponse by FeatureFlagAdministrationService (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/FeatureFlags/FeatureFlagAdministrationService.cs:123-140).

FeatureFlagOverrideResponse

MMCA.Common.Shared · MMCA.Common.Shared.FeatureFlags · MMCA.Common/Source/Core/MMCA.Common.Shared/FeatureFlags/FeatureFlagOverrideResponse.cs:14 · Level 1 · record (sealed)

  • What it is: one stored feature-flag override "as the administration surface reports it" (MMCA.Common/Source/Core/MMCA.Common.Shared/FeatureFlags/FeatureFlagOverrideResponse.cs:3-5): the read-side shape of a FeatureFlagOverride.
  • Depends on: FeatureFlagOverrideMode; the UserIdentifierType alias for ChangedBy (:22).
  • Concept: a contract DTO in the Shared layer, so the API, the Blazor admin page and the infrastructure snapshot share one shape (manual mapping per ADR-001). It doubles as the in-memory form the flag evaluator reads: FeatureFlagDefinitions.ToDefinition takes this record, not the entity (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/FeatureFlags/FeatureFlagDefinitions.cs:33).
  • Walkthrough: eight positional parameters (:14-22): Name, Mode, Percentage (only when the mode carries one, :8), Users and Groups (empty unless the mode is targeting, :9-10), Reason, then the audit pair ChangedOn (UTC instant of the last write, :12) and ChangedBy (the last writer or the system sentinel, :13).
  • Why it's built this way: the audit pair is flattened from the entity's audit stamps by EFFeatureFlagOverrideStore.ToResponse, taking the last-modified stamp and falling back to the created one (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/FeatureFlags/EFFeatureFlagOverrideStore.cs:128-137), so a client sees who last touched the override without reading audit history.
  • Where it's used: returned by IFeatureFlagOverrideStore and EFFeatureFlagOverrideStore, held by IFeatureFlagOverrideSnapshot / FeatureFlagOverrideSnapshot, turned into a feature definition by StoredOverrideFeatureDefinitionProvider, and nested as FeatureFlagStatusResponse.Override.

SetFeatureFlagOverrideRequest

MMCA.Common.Shared · MMCA.Common.Shared.FeatureFlags · MMCA.Common/Source/Core/MMCA.Common.Shared/FeatureFlags/SetFeatureFlagOverrideRequest.cs:18 · Level 1 · record (sealed)

  • What it is: the body of PUT {flags}/{name}, the override to store for one declared flag (MMCA.Common/Source/Core/MMCA.Common.Shared/FeatureFlags/SetFeatureFlagOverrideRequest.cs:3-5,18-23).
  • Depends on: FeatureFlagOverrideMode.
  • Concept: the required Reason is the design point. "An override is deliberately not time-boxed, so its reason is what tells the next operator whether it can be cleared" (:7-10): where a FeatureFlagLifetime.Temporary flag gets a build-enforced expiry, a runtime override gets a mandatory explanation instead.
  • Walkthrough: Mode and Reason are required positional parameters (:19-20); Percentage (:21), Users (:22) and Groups (:23) default to null. Percentage is 0 to 100, required for Percentage mode, the share of everyone outside the named audience for Targeting, and ignored otherwise (:11-15). The record itself validates nothing: the rules are enforced by FeatureFlagOverride.Create and .Change.
  • Where it's used: bound from the body of FeatureFlagsControllerBase.SetOverrideAsync (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Administration/FeatureFlagsControllerBase.cs:68-76), passed through IFeatureFlagAdministrationService to EFFeatureFlagOverrideStore, which spreads its fields into FeatureFlagOverride.Create or existing.Change (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/FeatureFlags/EFFeatureFlagOverrideStore.cs:77-78,89); the Blazor admin page sends it through FeatureFlagAdminService.

FeatureFlagRegistry

MMCA.Common.Shared · MMCA.Common.Shared.FeatureFlags · MMCA.Common/Source/Core/MMCA.Common.Shared/FeatureFlags/FeatureFlagRegistry.cs:35 · Level 2 · class (static)

  • What it is: the reflection scanner that turns a set of *Features constant classes into a flat, ordered list of FeatureFlagDescriptor rows, given the assemblies to scan (MMCA.Common/Source/Core/MMCA.Common.Shared/FeatureFlags/FeatureFlagRegistry.cs:35-124).
  • Depends on: FeatureFlagDescriptor, FeatureFlagAttribute; System.Reflection (BCL).
  • Concept introduced (the flag inventory built entirely by convention). [Rubric §34, Architecture Governance & Documentation] assesses whether the set of flags in play is discoverable rather than tribal knowledge. A *Features class is recognized purely by shape: IsFeatureClass requires a static, abstract, sealed type (the C# pattern for a static class) whose name ends in FeatureClassSuffix = "Features" (:38,77,81-82); FlagFields then takes only its public const string fields (:91,95-97). No registration call, no central list to keep in sync: adding a flag is adding a const string field to the module's *Features class.
  • Walkthrough:
    • Describe(IEnumerable<Assembly>) (:46) scans every loadable type across the given assemblies, filters to feature classes, flattens to their flag fields, maps each to a descriptor, and orders the result by FlagName with StringComparer.Ordinal (:50-55) so the inventory is deterministic regardless of assembly load order.
    • Describe(Assembly) (:64) is the single-assembly overload, delegating to the collection one (:68).
    • LoadableTypes (:112) guards Assembly.GetTypes() against ReflectionTypeLoadException, falling back to the subset of types that did load via ex.Types.OfType<Type>() (:118-121), so one broken type in an assembly does not blank out every flag in it.
    • The private Describe(FieldInfo) (:100) reads the optional FeatureFlagAttribute with inherit: false (:102) and the field's raw constant value via GetRawConstantValue(), defaulting to an empty string (:106).
  • Why it's built this way: ADR-031 is the convention this registry executes; scanning by name suffix rather than a marker interface keeps a *Features class a plain constant holder with no base type or registration boilerplate.
  • Where it's used: FeatureFlagCatalog calls Describe lazily over every assembly the host passed to AddReloadableFeatureFlags (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/FeatureFlags/FeatureFlagCatalog.cs:11-22), which is what limits stored overrides to declared flags; MMCA.Common/Tests/Core/MMCA.Common.Shared.Tests/FeatureFlags/FeatureFlagRegistryTests.cs exercises Describe, IsFeatureClass, and FlagFields directly.
  • Caveats / not-in-source: the governance architecture rule does not call this registry. It re-implements the same shape test and field filter over the Shared layer of the architecture map (MMCA.Common/Source/Hosting/MMCA.Common.Testing.Architecture/Rules/Governance/ArchitectureRules.FeatureFlags.cs:87-93) with its own FeatureClassSuffix constant (:11), because that package takes no framework reference (:7-9); the two copies must be kept in step by hand. FeatureClassSuffix is a public constant ("Features"), but nothing enforces that every constant class ending in that suffix is meant to hold flags: a coincidentally named class would be scanned as one.

FeatureFlagStatusResponse

MMCA.Common.Shared · MMCA.Common.Shared.FeatureFlags · MMCA.Common/Source/Core/MMCA.Common.Shared/FeatureFlags/FeatureFlagStatusResponse.cs:15 · Level 2 · record (sealed)

  • What it is: one declared flag as the administration surface lists it: "what it is, what configuration says, what (if anything) a stored override says, and which of the two is in force" (MMCA.Common/Source/Core/MMCA.Common.Shared/FeatureFlags/FeatureFlagStatusResponse.cs:3-6).
  • Depends on: FeatureFlagLifetime, FeatureFlagValueKind, FeatureFlagOverrideResponse.
  • Concept: [Rubric §13, Observability & Operability] assesses whether an operator can see the state a system is actually in. Reporting Configured and Effective side by side, with the Override between them, answers "why is this flag on" in one row instead of leaving the operator to diff configuration against the database.
  • Walkthrough: eight positional parameters (:15-23). Name, Lifetime, Owner and RemoveBy (:16-19) are the declared metadata, null when undeclared (:8-10); Configured and ConfiguredFilters (:20-21) are configuration's state and, when conditional, its filter names; Override (:22) is null when configuration is in force; Effective (:23) is the override's state when there is one, otherwise configuration's (:14).
  • Why it's built this way: FeatureFlagAdministrationService.DescribeAsync builds it from a FeatureFlagDescriptor plus the stored override: Configured comes from the configuration provider's definition, and Effective reuses the same FeatureFlagDefinitions.Describe over the override's definition, so both columns are summarized by one rule (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/FeatureFlags/FeatureFlagAdministrationService.cs:123-140).
  • Where it's used: returned by FeatureFlagsControllerBase.GetAllAsync and .SetOverrideAsync (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Administration/FeatureFlagsControllerBase.cs:53,74), declared on IFeatureFlagAdministrationService, and consumed by the Blazor FeatureFlagAdminService and FeatureFlagAdmin.razor.cs page in MMCA.Common.UI.

CorrelationContext

MMCA.Common.Infrastructure · MMCA.Common.Infrastructure.Context · MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Context/CorrelationContext.cs:10 · Level 6 · class (sealed)

  • What it is: the scoped service that holds the correlation ID for the current request, defaulting to the enclosing background hop's correlation ID when one is being delivered, and otherwise to a fresh GUID, until middleware or a restore sets it.
  • Depends on: ICorrelationContext (Level 0, MMCA.Common.Application.Interfaces), the abstraction it implements (CorrelationContext.cs:1, :9), and AmbientOrigin (same namespace), whose Current?.CorrelationId seeds the default (CorrelationContext.cs:13). Uses BCL Guid.
  • Concept (where the correlation value actually lives). The pattern itself is introduced at ICorrelationContext; this is its one shipped implementation. [Rubric §13, Observability & Operability]: the eager default is what makes correlation always-on, so a log line emitted from a path with no HTTP request still carries an ID, and a handler delivered from the outbox or a consumer inherits the originating request's ID instead of minting a disconnected one. [Rubric §3, Clean Architecture]: the concrete holder sits in Infrastructure while every consumer depends on the Application interface.
  • Walkthrough: CorrelationId (CorrelationContext.cs:13) is { get; private set; }, initialized eagerly to AmbientOrigin.Current?.CorrelationId ?? Guid.NewGuid().ToString("N") so a value always exists even if no middleware runs (a background processor, a test path, a gRPC call). SetCorrelationId(string) (CorrelationContext.cs:16-20) overwrites it, guarding the input with ArgumentException.ThrowIfNullOrWhiteSpace (:18) so a blank header can never wipe the ID. The private setter means the only write path is that one guarded method.
  • Why it's built this way: a scoped holder with an eager default keeps correlation cheap and unconditional: every code path has an ID without a null check, and inbound requests still adopt the caller's ID for cross-service tracing. The ambient-origin default lets a restored background hop continue the trace it came from. The "N" GUID format (32 hex digits, no hyphens) keeps the fallback compact in log lines and headers. Registration is TryAddScoped (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:389): scoped, so one instance lives per request, and TryAdd, so a host that wants its own implementation can register it first and win.
  • Where it's used: CorrelationIdMiddleware resolves it per request and calls SetCorrelationId with the inbound X-Correlation-ID header, falling back to the current Activity trace ID and then to HttpContext.TraceIdentifier (MMCA.Common/Source/Presentation/MMCA.Common.API/Middleware/CorrelationIdMiddleware.cs:34-38), then echoes the value back on the response through OnStarting (:37-41). Downstream, LoggingCommandDecorator<TCommand, TResult> and LoggingQueryDecorator<TQuery, TResult> take it as a constructor dependency and wrap the ID into their log scope for the full pipeline duration. The outbox and consumer restore paths read and set it through AmbientOrigin (AmbientOrigin.cs:288, :184).

FeatureFlagOverride

MMCA.Common.Domain · MMCA.Common.Domain.FeatureFlags · MMCA.Common/Source/Core/MMCA.Common.Domain/FeatureFlags/FeatureFlagOverride.cs:24 · Level 4 · class (sealed)

  • What it is: one stored override of a declared feature flag, "the data half of a reloadable flag", laid over configuration so an operator can flip a kill switch without a new revision (MMCA.Common/Source/Core/MMCA.Common.Domain/FeatureFlags/FeatureFlagOverride.cs:7-10).
  • Depends on: AuditableBaseEntity<TIdentifierType> keyed by string (:24), Result and Error, FeatureFlagOverrideMode.
  • Concept introduced (the flag name is the identity, and clearing is a soft delete). [Rubric §4, DDD] assesses whether an entity guards its own invariants. There is at most one override per flag in the owning service's database, so Name => Id (:49); clearing soft-deletes the row so the audit stamps keep who cleared it, and setting the flag again revives the same row (:12-15). Deriving from the auditable base means every write is stamped and carries the row-version token; the required Reason "is the half of the audit no interceptor can supply" (:17-21). [Rubric §13, Observability & Operability]: the kill switch is data, so it moves without a deployment.
  • Walkthrough:
    • Limits: NameMaxLength = 128 (:27), ReasonMaxLength = 500 (:30), TargetMaxLength = 128 (:33), TargetListMaxLength = 4000 (:36), MaxPercentage = 100 (:39), and TargetSeparator = ',' (:42), which is also refused inside a name.
    • State: Mode, Percentage, TargetUsers, TargetGroups and Reason have private setters (:52-64); the target lists are stored as one joined string, and Users / Groups split them back on read (:67,70, Split at :136-137).
    • Create (:82) refuses a blank or over-long trimmed name (:90-96), constructs the entity with the trimmed name as Id (:98), and runs Apply (:99), returning its failure or the entity.
    • Change (:116) runs the same Apply, then revives a cleared override with Undelete() (:124-129). Clear (:134) is Delete().
    • Refusal (:152) checks the scalar half in order: an undefined mode (:154), a blank or over-long reason (:162), then PercentageFits (:146-149), which requires 0 to 100 for Percentage, allows a null or 0 to 100 for Targeting, and ignores it otherwise.
    • Audience (:179) applies only to Targeting and requires at least one user or group (:193-198); NormalizeTargets (:205) drops blanks, trims, de-duplicates ordinally (:210), and refuses an over-long list, an over-long name, or a name containing the separator (:214-215).
    • Apply (:230) validates everything first (:237-248) and only then writes (:250-254), so "a refused change never leaves the override half-updated" (:226-228); a percentage is kept only for a mode that carries one (:251).
  • Why it's built this way: keeping the override as an ordinary auditable entity (rather than a configuration file write) gives it the database-per-service home, the audit trail, and the concurrency token every aggregate already has. ADR-031 is the feature-flag scheme it extends.
  • Where it's used: mapped by FeatureFlagOverrideModelBuilderExtensions into each owning service's database (ADC ships an AddFeatureFlagOverrides migration in both its Conference and Engagement migration projects, for example MMCA.ADC/Source/Hosting/MMCA.ADC.Migrations.SqlServer.Conference/Migrations/20261108145459_AddFeatureFlagOverrides.Designer.cs); created, changed and cleared by EFFeatureFlagOverrideStore (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/FeatureFlags/EFFeatureFlagOverrideStore.cs:77,89,118) and projected to FeatureFlagOverrideResponse there (:126). Unit coverage is MMCA.Common/Tests/Core/MMCA.Common.Domain.Tests/FeatureFlags/FeatureFlagOverrideTests.cs.

IEntityDTOMapper<TEntity, TEntityDTO, TIdentifierType>

MMCA.Common.Application · MMCA.Common.Application.Interfaces.Mapping · MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Mapping/IEntityDTOMapper.cs:14 · Level 4 · interface

  • What it is: the contract for mapping a domain entity to its DTO. One required method, MapToDTO(entity), plus a default MapToDTOs(collection) that fans the single map over a collection.
  • Depends on: AuditableBaseEntity<TIdentifierType> and IBaseDTO<TIdentifierType> as generic constraints (IEntityDTOMapper.cs:15-17), and the file's usings pull in the Domain entities and the Shared DTO namespace (:1-3).
  • Concept introduced (manual DTO mapping as a first-class contract). [Rubric §15, Best Practices & Code Quality] assesses whether a change is caught where it happens: ADR-001 chose hand-written mappers over a convention-based mapping library precisely so that adding a DTO property that nobody maps is a compile error, not a silently null field at runtime, and so that "where is this field filled in" is a single go-to-definition. [Rubric §1, SOLID] shows up twice: the interface has one job (ISP), and every generic read path depends on this abstraction rather than on any concrete mapper (DIP). [Rubric §2, Design Patterns]: the C# interface default method at :27-32 is the code-sharing mechanism, so a concrete mapper inherits collection mapping for free and overrides it only when batch mapping needs something smarter.
  • Walkthrough
    • Three generic parameters with matched constraints (:15-17): TEntity : AuditableBaseEntity<TIdentifierType>, TEntityDTO : IBaseDTO<TIdentifierType>, TIdentifierType : notnull. The shared TIdentifierType is what makes a mismatched entity/DTO pair fail to compile.
    • TEntityDTO MapToDTO(TEntity entity) (:22) is the single member an implementer must write; it is synchronous, because mapping is a pure in-memory shape change.
    • IReadOnlyCollection<TEntityDTO> MapToDTOs(IReadOnlyCollection<TEntity> entityCollection) (:27) is the default implementation: guard (:29), then [.. entityCollection.Select(MapToDTO)] (:31), a collection expression that materializes once into a read-only collection.
  • Why it's built this way: see ADR-001. The default method is what keeps the hand-written cost to one method per entity: without it, every mapper would repeat the same Select. Registration is by convention rather than by hand: the module registration scans each module assembly for implementations and registers them ScanRegistration.SelfWithInterfaces with a scoped lifetime (MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.ModuleScanning.cs:58), so a new mapper class is wired by existing.
  • Where it's used: it is a constructor dependency of the whole generic write and read stack: EntityQueryService<TEntity, TEntityDTO, TIdentifierType> takes one and re-exposes it as its DTOMapper property (MMCA.Common/Source/Core/MMCA.Common.Application/Services/Query/EntityQueryService.cs:39, :94, declared on the interface at Interfaces/Mapping/IEntityQueryService.cs:37), and it is injected into CreateEntityHandlerBase<TCreateRequest, TEntity, TIdentifierType, TEntityDTO> (UseCases/CreateEntityHandlerBase.cs:44), UpdateEntityHandler<TEntity, TEntityDTO, TIdentifierType, TUpdateRequest> (UseCases/UpdateEntityHandler.cs:51), and MutateEntityHandlerBase<TCommand, TEntity, TIdentifierType> (UseCases/MutateEntityHandlerBase.cs:344). Implementations are one per entity in every app (for example MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Application/Sponsors/DTOs/SponsorDTOMapper.cs:14), plus the framework's own PushNotificationDTOMapper (MMCA.Common/Source/Core/MMCA.Common.Application/Notifications/PushNotifications/DTOs/PushNotificationDTOMapper.cs:13).
  • Caveats / not-in-source: mapping is not always the read path. An entity may also have an opt-in IEntityDTOProjector<TEntity, TEntityDTO, TIdentifierType>, scanned beside the mappers (DependencyInjection.ModuleScanning.cs:60-63), which pushes the same shaping into SQL for list reads; an entity with no projector keeps materialize-then-map through this interface.

IEntityRequestMapper<TEntity, TCreateRequest, TIdentifierType>

MMCA.Common.Application · MMCA.Common.Application.Interfaces.Mapping · MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Mapping/IEntityDTOMapper.cs:42 · Level 4 · interface

  • What it is: the create-side mapper. It turns an incoming create request into a new domain entity by calling that entity's factory method, and returns a Result so a refused invariant travels back as a failure rather than an exception.
  • Depends on: AuditableBaseEntity<TIdentifierType>, the ICreateRequest marker, and Result (IEntityDTOMapper.cs:43-45, :54). It shares a file with IEntityDTOMapper<TEntity, TEntityDTO, TIdentifierType>, because the file covers both mapping directions.
  • Concept (the entity factory is the only construction path). The manual-mapping rationale is introduced at IEntityDTOMapper; what this interface adds is a boundary rule. [Rubric §4, DDD] assesses whether aggregates are constructed through guarded factories that enforce invariants: the mapper does not new an entity, it calls Entity.Create(...) and hands the resulting Result<TEntity> straight back, so no code path can produce an invalid aggregate. [Rubric §1, SOLID]: separating request-to-entity creation from entity-to-DTO reading keeps each mapper single-purpose. The signature is Task<Result<TEntity>> (:54) even though most implementations are synchronous, because creation may need a database round trip first (a uniqueness check, for example, as the doc says at :37).
  • Walkthrough: three constrained generic parameters (:43-45), with TCreateRequest : ICreateRequest as the type-system guard that stops an update request being passed to the create path. The single member is Task<Result<TEntity>> CreateEntityAsync(TCreateRequest request, CancellationToken cancellationToken = default) (:54). A representative implementation is one method: guard the request, then Task.FromResult(Sponsor.Create(...)) with the request's fields spread into the factory (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Application/Sponsors/UseCases/Create/SponsorCreateRequestMapper.cs:15-31).
  • Why it's built this way: ADR-001 again. Because the mapper is a named contract rather than inline handler code, the framework can ship one generic create handler for every aggregate: CreateEntityHandlerBase injects it (UseCases/CreateEntityHandlerBase.cs:43) and awaits requestMapper.CreateEntityAsync(request, cancellationToken), short-circuiting on failure (:89-90), while the module supplies only the per-entity mapping. Registration is the same AddAssignableTypes assembly scan as the DTO mappers, ScanRegistration.SelfWithInterfaces and scoped (MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.ModuleScanning.cs:65).
  • Where it's used: implemented once per creatable aggregate across the apps (for example SponsorCreateRequestMapper.cs:11, MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Application/Questions/UseCases/Create/QuestionCreateRequestMapper.cs:12), and consumed by the generic create handlers (UseCases/CreateEntityHandlerBase.cs:43, UseCases/CreateEntityHandler.cs:30).
  • Caveats / not-in-source: this interface has a write-side twin declared in the same file, IEntityUpdateApplier<TEntity, TUpdateRequest, TIdentifierType> (IEntityDTOMapper.cs:79-91), which applies a request onto an already-loaded aggregate and returns a bare Result because the instance handed in is the tracked one (:70-74). Do not reach for the create mapper on the update path.

FeatureFlagOverrideModelBuilderExtensions

MMCA.Common.Infrastructure · MMCA.Common.Infrastructure.Persistence.FeatureFlags · MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/FeatureFlags/FeatureFlagOverrideModelBuilderExtensions.cs:20 · Level 5 · class (public, static)

  • What it is: the EF Core mapping of FeatureFlagOverride to the FeatureFlagOverrides table, as a ModelBuilder extension method.
  • Depends on: FeatureFlagOverride (its length constants), Microsoft.EntityFrameworkCore.ModelBuilder.
  • Concept introduced: none new; gated table mapping is taught at FeatureFlagOverrideModelContributor. [Rubric §8, Data Architecture]: the mapping pins storage choices that keep a row's meaning stable.
  • Walkthrough
    • Public constants TableName = "FeatureFlagOverrides" (:18) and NameColumn = "Name" (:21); private ModeMaxLength = 16 (:24).
    • ApplyFeatureFlagOverrideConfiguration(schema = "dbo") (:34) maps to the table (:40) keyed on Id (:41), which is stored in the Name column, non-unicode, at FeatureFlagOverride.NameMaxLength, never generated (:43-48). Mode is stored as its string name so a reordered enum cannot silently change what a row means (:50-54). TargetUsers, TargetGroups and the required Reason take the entity's max lengths (:56-58); the computed Name, Users and Groups are ignored (:60-62).
  • Why it's built this way: the doc requires calling it BEFORE the soft-delete, tenant and concurrency-token passes so the override is treated like any other auditable entity (:26-30); ApplicationDbContext does so, first in OnModelCreating (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/ApplicationDbContext.cs:750-756).
  • Where it's used: ApplicationDbContext.OnModelCreating when the gate is open (above); EFFeatureFlagOverrideStore references it.

MachineClientsControllerBase

MMCA.Common.API · MMCA.Common.API.Controllers.MachineClients · MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/MachineClients/MachineClientsControllerBase.cs:42 · Level 8 · class (abstract)

  • What it is: the shipped base controller for administering machine clients (OAuth client-credentials callers): list them, create one with its secret, rotate and promote a secondary secret, and revoke a client. A subclass mounts the route and API version; the base owns the actions (MachineClientsControllerBase.cs:19-26).
  • Depends on: ApiControllerBase (its base, for HandleFailure), IMachineClientService resolved per request (:45-46), CreateMachineClientRequest, MachineClientResponse and MachineClientSecretResponse on the wire, IdempotentAttribute and NonIdempotentAttribute on the write actions, HasPermissionAttribute with AdministrationPermissions.ManageClients on the class (:41), IPermissionRegistry and PermissionAuthorizationHandler.Holds for the privilege ceiling (:180, :186), and AdminActionMetrics for the success counter (:94, :122).
  • Concept (a secret is never a cacheable response). [Rubric §11, Security] assesses how credentials and sensitive data are handled end to end: CreateAsync and RotateAsync return the only copy of a client secret, so both are marked [NonIdempotent] (:72, :103) with reasons stating that a replay would leave the secret at rest in the idempotency replay cache, while PromoteAsync and RevokeAsync, whose responses carry no secret and whose effect is the same on a retry, are [Idempotent] (:131, :156). The same two secret-issuing actions also run under a privilege ceiling: CallerHoldsPermission() (:178-187) hands the service a predicate that asks whether the caller holds a given permission, evaluated exactly as the permission authorization handler evaluates it (:186), so an admin cannot mint a client whose role grants more than the admin holds; the class remarks name the refusal, UserAdministration.PrivilegeCeiling (403), alongside MachineClients.RoleNotAllowed (400), MachineClients.NotFound (404), MachineClients.Revoked and MachineClients.NoSecondarySecret (409) (:33-38). [Rubric §9, API & Contract Design]: the controller takes no constructor dependency; the private EnabledMachineClients property (:45-46) resolves the service with GetService and keeps it only when IsEnabled is true, so on a host where the feature is off every action answers a plain 404 rather than failing to construct (:28-30).
  • Walkthrough
    • GetAllAsync(cancellationToken) ([HttpGet] at :51, method at :56-65) lists every client, revoked ones included, via ListAsync.
    • CreateAsync(request, cancellationToken) ([HttpPost] at :71, method at :78-96) null-guards the body (:82) and calls CreateAsync(request, CallerHoldsPermission(), cancellationToken) (:88), creating the client and its service account; on success it records AdminActionMetrics.MachineClientCreate (:94) and the MachineClientSecretResponse carries the secret once.
    • RotateAsync(id, cancellationToken) ([HttpPost("{id:guid}/rotate")] at :102, method at :109-124) issues a secondary secret under the same ceiling (:116); both secrets work until it is promoted, and a second rotation replaces the waiting secret (:103). 409 is declared (:108). Success records AdminActionMetrics.MachineClientRotate (:122).
    • PromoteAsync(id, cancellationToken) ([HttpPost("{id:guid}/promote")] at :130, method at :137-146) makes the secondary secret primary; the old primary stops working.
    • RevokeAsync(id, cancellationToken) ([HttpPost("{id:guid}/revoke")] at :155, method at :161-170) stops the secrets working and, per the summary, makes every service reject the tokens the client holds; revoking a revoked client succeeds (:149-150).
    • CallerHoldsPermission() (:178-187) returns null, meaning no ceiling, only when the host registers no IPermissionRegistry (:180-183); otherwise it captures User and returns permission => PermissionAuthorizationHandler.Holds(caller, registry, permission) (:185-186).
    • Every action opens with the same EnabledMachineClients is not { } machineClients guard returning NotFound(). List, promote and revoke close with result.IsFailure ? HandleFailure(result.Errors) : Ok(result.Value); create and rotate branch on IsFailure first so the metric is recorded only for a success.
  • Why it's built this way: ADR-140 introduces machine clients as an opt-in capability; resolving the service per action keeps the controller mountable on a host that has not opted in. The rotate-then-promote pair gives a zero-downtime secret rollover: the caller deploys the new secret while the old one still works, then promotes. The ceiling is passed as a predicate rather than evaluated in the controller so the service decides which permissions the client's role grants, while the controller supplies the caller's view; the null case mirrors the users-admin rule for a host with no permission registry (:174-175). The idempotency split follows ADR-017.
  • Where it's used: ADC's AdminMachineClientsController (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/Controllers/MachineClients/AdminMachineClientsController.cs); the UI client is IMachineClientAdminUIService (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Administration/IMachineClientAdminUIService.cs). The framework tests mount it through MachineClientTestHost.

MachineTokenControllerBase

MMCA.Common.API · MMCA.Common.API.Controllers.MachineClients · MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/MachineClients/MachineTokenControllerBase.cs:40 · Level 6 · class (abstract)

  • What it is: the shipped base controller for the OAuth 2.0 client-credentials token endpoint: one anonymous, form-encoded POST that issues an access token to a machine client and speaks RFC 6749's response and error format rather than Problem Details.
  • Depends on: ApiControllerBase (its base), IMachineClientService resolved per request (MachineTokenControllerBase.cs:57), MachineTokenResponse and MachineTokenErrorResponse on the wire, MachineClientErrors for the error-code mapping, Error, NonIdempotentAttribute, and the RateLimitPolicyAuthIp policy name on WebApplicationBuilderExtensions (:48). Externals: System.Net.Http.Headers.AuthenticationHeaderValue, Convert.FromBase64String, Uri.UnescapeDataString.
  • Concept (the one endpoint that does not answer in Problem Details). [Rubric §9, API & Contract Design]: a token endpoint is consumed by generic OAuth client libraries, so it answers in the protocol's own shape: RFC 6749 error bodies (invalid_client, unsupported_grant_type, invalid_request) through MachineTokenErrorResponse (:120-121), 401 with a WWW-Authenticate: Basic realm="token" header (:129), and Cache-Control: no-store plus Pragma: no-cache on every response, success or refusal (:62-64). [Rubric §11, Security]: the endpoint is [AllowAnonymous] (:47) because the credentials are the request, so it is bounded instead by [EnableRateLimiting(RateLimitPolicyAuthIp)] (:48), and it is [NonIdempotent] (:46) so no bearer token is ever held at rest in the replay cache or handed to a retry minted for an earlier request.
  • Walkthrough
    • IssueTokenAsync(cancellationToken) ([HttpPost] at :45, [Consumes("application/x-www-form-urlencoded")] at :49, method at :55-76) answers 404 when the service is missing or disabled (:57-60), sets the no-store headers (:63-64), reads the form when the request has form content and otherwise uses FormCollection.Empty (:66-68), extracts the credentials, and calls IssueTokenAsync(form["grant_type"], clientId, clientSecret, ...) (:71-73). Success is Ok(result.Value); a failure goes to TokenError (:75).
    • ReadClientCredentials(form) (:85-108) prefers HTTP Basic (RFC 6749 section 2.3.1): it base64-decodes the parameter, returns (null, null) on a FormatException (:96-99) or when there is no : separator, and otherwise form-decodes each half through FormDecode (:110, + to space, then Uri.UnescapeDataString). Without a Basic header it reads the client_id and client_secret form fields (:107).
    • TokenError(errors) (:115-124) switches on the first error's code: MachineClientErrors.UnsupportedGrantTypeCode becomes 400 unsupported_grant_type, InvalidRequestCode becomes 400 invalid_request, and anything else (including an empty list, which defaults to InvalidClientCode) becomes InvalidClient() (:126-131), a 401 invalid_client.
  • Why it's built this way: ADR-140 adopts the standard client-credentials grant so callers can use stock OAuth clients; speaking the RFC's wire format is what makes that work. The per-IP limit follows ADR-019 and the brute-force posture of ADR-029.
  • Where it's used: ADC's MachineTokenController (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/Controllers/MachineClients/MachineTokenController.cs). AnonymousEndpointTests (MMCA.Common/Tests/Architecture/MMCA.Common.Architecture.Tests/Api/AnonymousEndpointTests.cs) lists it among the framework's anonymous endpoints, and MachineClientTestHost exercises it.

SignInLinkControllerBase<TSendCommand, TRedeemCommand>

MMCA.Common.API · MMCA.Common.API.Controllers.SignInLinks · MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/SignInLinks/SignInLinkControllerBase.cs:35 · Level 6 · class (abstract)

  • What it is: the shipped base controller for passwordless email sign-in: one anonymous POST that emails a single-use sign-in link, and one that redeems it for a token pair. A subclass supplies the two app command types, their factories, and the route.
  • Depends on: ApiControllerBase (its base, for HandleFailure), two ICommandHandler<in TCommand, TResult> instances taken as primary-constructor parameters (SignInLinkControllerBase.cs:35-37) and re-exposed as SendHandler (:42) and RedeemHandler (:45), the constraints ICommandWithRequest<out TRequest> over SendSignInLinkRequest (:38) and IRedeemSignInLinkCommand (:39), RedeemSignInLinkRequest and AuthenticationResponse on the wire, and IdempotentAttribute / NonIdempotentAttribute.
  • Concept (an anonymous credential endpoint that reveals nothing). [Rubric §11, Security]: the send action answers 202 Accepted on any well-formed request "whether or not the address holds an account" (:74-75, Accepted() at :97), so it cannot be used to enumerate accounts; both actions are [AllowAnonymous] and bounded by [EnableRateLimiting(RateLimitPolicyAuthIp)] (:82-83, :110-111); and the link carries the address and token in the URI fragment, which the page reads client-side and posts, so neither reaches a server log or a Referer header (:101-103). The controller follows the same generic command-factory shape as EmailConfirmationControllerBase<TSendCommand, TConfirmCommand>: the app owns its command types, the base dispatches them through the decorator pipeline.
  • Walkthrough
    • ClientIpAddress (:51) reads Connection.RemoteIpAddress, which behind a proxy is the forwarded value only when the host configured UseForwardedHeaders (:48-50); ClientUserAgent (:54) reads the User-Agent header. Both are recorded on the session the redeem opens.
    • CreateSendCommand(request) (:61) and CreateRedeemCommand(request, ipAddress, userAgent) (:71) are the abstract factories; the XML docs give the expected one-line => new(...) bodies.
    • SendSignInLinkAsync(request, cancellationToken) ([HttpPost("sign-in-link")] at :80, [Idempotent] at :81, method at :87-98) dispatches the send command and answers Accepted() or a Problem Details failure for a malformed payload.
    • RedeemSignInLinkAsync(request, cancellationToken) ([HttpPost("sign-in-link/redeem")] at :108, method at :116-127) dispatches the redeem command with the caller's IP and user agent and returns the AuthenticationResponse. It is [NonIdempotent] (:109): a replay would hand a retrying client tokens minted for an earlier call, while the single-use token makes a genuine retry fail, which is the correct answer.
  • Why it's built this way: ADR-116 makes the identity completions opt-in; shipping them as abstract bases lets an app adopt the HTTP shape without its commands leaving its own Application assembly. The per-IP limiting follows ADR-019 and ADR-029.
  • Where it's used: ADC's SignInLinkController (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/Controllers/SignInLinkController.cs); AnonymousEndpointTests lists both actions among the framework's anonymous endpoints.

EntityCsvExporter<TEntityDTO>

MMCA.Common.API · MMCA.Common.API.Export · MMCA.Common/Source/Presentation/MMCA.Common.API/Export/EntityCsvExporter.cs:18 · Level 6 · class (internal static)

  • What it is: the page-looping CSV export engine EntityControllerBase<TEntity, TEntityDTO, TIdentifierType>.ExportAsync delegates to: it validates a fields= request, walks the paged query service page by page, and streams RFC 4180 CSV to a caller-supplied stream. Closed over the DTO type alone (EntityCsvExporter.cs:18), so its exclusion lists and column resolution are computed once per DTO shape without needing the entity or identifier type at all.
  • Depends on: CsvWriter (byte order mark, header, rows), Error, PagedCollectionResult<T>, PaginationMetadata (TotalItemCount, the last-page and cap-boundary arbiter), QueryFieldService (ShapeData, the shaped-row fallback), System.Reflection, System.Text.Json (JsonNamingPolicy.CamelCase), and System.Globalization.
  • Concept introduced: extracting a generic algorithm out of the controller that only invokes it. [Rubric §1, SOLID] covers Single Responsibility: the page loop, the column resolution, and the exclusion lists are export mechanics independent of HTTP, so hoisting them out of EntityControllerBase<TEntity, TEntityDTO, TIdentifierType> lets ExportAsync shrink to validate, delegate, and translate the result (class doc, EntityCsvExporter.cs:11-16). [Rubric §15, Best Practices & Code Quality]: WriteAsync takes the fetch as a delegate (Func<int, CancellationToken, Task<Result<PagedCollectionResult<object>>>>) rather than the query service itself, so the exporter carries no dependency on IEntityQueryService<TEntity, TEntityDTO, TIdentifierType> and could stream any paged source a caller adapts to that shape.
  • Walkthrough
    • The three exclusion sets, UnexportablePropertyNames (EntityCsvExporter.cs:32-38), UnexportableColumns (:44-45), and UnexportableFields (:51-52), are static readonly fields computed once per closed EntityCsvExporter<TEntityDTO>, since a DTO's shape cannot change at runtime: the property names that cannot render a faithful scalar CSV cell (binary concurrency tokens and every collection type except string, IsExportableType at :239), their camelCase column-name form, and a case-insensitive lookup set for fields= matching. Value objects and other class-typed properties are deliberately not dropped: CsvWriter renders Money as amount plus code, Currency as its code, and any other record as compact JSON (remarks, :26-29).
    • ValidateFields(fields) (:62) rejects a fields= request naming one of those properties as an Error.InvalidEntityField failure (:71), before a single byte of the body is written; an empty exclusion set short-circuits to null.
    • WriteAsync(body, fetchPageAsync, pageSize, maxExportRows, fields, beginResponse, onFailureAfterStart, cancellationToken) (:117) is the page loop. The CSV writer is synchronous, so it never writes to body directly: it renders into an in-memory MemoryStream (:133) through a StreamWriter (:136), and DrainAsync (:210) copies each page to the body with awaited WriteAsync/FlushAsync and empties the buffer. The type doc gives the reason: a StreamWriter over the body itself would flush synchronously whenever its buffer filled, which Kestrel rejects, and any export over about 1 KB aborted. Each fetched page is unwrapped with result.TryGetValue(out var page) (:143), so the failure branch and the page variable come from one test. Nothing reaches the body before the first page succeeds, so a first-page failure still returns Result.Failure with nothing written (:145-146) for the caller to turn into Problem Details. On the first successful page it resolves columns, calls beginResponse() (:161), and writes the BOM and header (:162-163); each page is written by WritePage (:167) and drained (:170). Three termination conditions follow: a page that stopped mid-page marks the export truncated (:173-177), IsLastPage ends it on the last page (:179-180), and a cap landing exactly on a page boundary consults PaginationMetadata.TotalItemCount rather than issuing a wasted page (:184-188). A mid-stream failure after the header started calls onFailureAfterStart and writes the incomplete marker instead of returning failure (:151-152). A final drain follows the optional truncation marker (:193-198).
    • IsLastPage(itemCount, pageSize, rowsWritten, metadata) (:230) does not trust a short page on its own: an empty page ends the export, but a short non-empty page ends it only when rowsWritten has reached TotalItemCount. The query pipeline clamps every page to its own ceiling (EntityQueryPipeline.MaxUnboundedResultLimit, MMCA.Common/Source/Core/MMCA.Common.Application/Services/Query/EntityQueryPipeline.cs:25, defined as KeysetPageRequest.MaxPageSize, which is 1000 at MMCA.Common/Source/Core/MMCA.Common.Shared/Abstractions/KeysetPagination.cs:27), so a full clamped page can come back shorter than a larger requested page size, and ending there would cut the export short with no marker line.
    • ResolveColumns (:294) takes the shaped keys of the first row when there is one, or falls back to the DTO's own properties in declaration order, filtered by fields, for an empty result, so an export of nothing still owes a header row.
    • ShapeRow (:324) and BuildCells (:335) normalize a row (typed DTO or already-shaped dynamic object) to a camelCase-keyed dictionary and then project it onto the resolved column order, substituting null for a column a row does not carry.
    • TruncationMarker (:357) and IncompleteMarker (:363) format the two trailing marker lines with CultureInfo.InvariantCulture. ParseFields (:349) splits a fields= value into a case-insensitive set.
  • Why it's built this way: generic over TEntityDTO alone, because export needs only the DTO shape to compute its exclusion lists and resolve columns; the fetch delegate carries everything else the caller's specific entity/query pipeline needs. internal static keeps it a framework implementation detail behind ExportAsync, not a public surface a consumer can bind to. The last-page test reads the total rather than the page length because the page length is a property of the pipeline's clamp, not of the data. Buffering a page in memory before an awaited copy trades one page of memory for compatibility with default Kestrel synchronous-I/O rules.
  • Caveats / not-in-source: this type has no HTTP awareness of its own; the authorization symmetry, the fail-closed row scoping, and the no-output-caching caveats belong to EntityControllerBase<TEntity, TEntityDTO, TIdentifierType>, which is the only caller.
  • Where it's used: only by EntityControllerBase<TEntity, TEntityDTO, TIdentifierType>.ExportAsync, which calls ValidateFields (EntityControllerBase.cs:279) and WriteAsync (EntityControllerBase.cs:293). Unit coverage is EntityCsvExporterTests and EntityCsvExporterValueObjectTests (MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/Export/).

QueryFilterModelBinder

MMCA.Common.API · MMCA.Common.API.ModelBinders · MMCA.Common/Source/Presentation/MMCA.Common.API/ModelBinders/QueryFilterModelBinder.cs:25 · Level 7 · class (sealed)

  • What it is: a custom IModelBinder that parses the structured filter query string (?filters[Name].operator=contains&filters[Name].value=shirt) into a Dictionary<string, (string Operator, string Value)> that list endpoints hand to the query layer.
  • Depends on: Microsoft.AspNetCore.Mvc.ModelBinding.IModelBinder, and QueryFilterService for its cap: MaxFilters is defined as QueryFilterService.MaxFilters (QueryFilterModelBinder.cs:34, using at :2). Its output is consumed by QueryFilterService via the list actions on EntityControllerBase<TEntity, TEntityDTO, TIdentifierType>.
  • Concept introduced: model binding as the parsing boundary for a bespoke query grammar. ASP.NET's default binders cannot express "a bag of per-property operator/value pairs", so the grammar is defined once here rather than re-parsed in each controller. [Rubric §9, API & Contract Design] assesses whether the request contract is explicit and uniform: every list endpoint in both apps accepts the identical filter syntax because they share this binder, and the expected format is documented on the class itself (QueryFilterModelBinder.cs:10-24). [Rubric §12, Performance & Scalability] applies through MaxFilters: the binder shares the cap that bounds attacker-controlled work, while the refusal itself happens in the query layer.
  • Walkthrough
    • MaxFilters = QueryFilterService.MaxFilters (QueryFilterModelBinder.cs:34), which is 50 (MMCA.Common/Source/Core/MMCA.Common.Application/Services/Filtering/QueryFilterService.cs:34). The binder does not enforce it: per the comment (QueryFilterModelBinder.cs:27-32) it keeps every complete entry, and a request over the cap is refused by QueryFilterService.ValidateFilters with a 400 validation error Filter.TooMany before any name is resolved (QueryFilterService.cs:192-197). Dropping the surplus in the binder instead would silently widen the result set past what the caller asked for.
    • BindModelAsync (QueryFilterModelBinder.cs:37): null-guards the binding context (:39), then builds the dictionary with StringComparer.OrdinalIgnoreCase (:42) so client capitalization does not matter.
    • It iterates Request.Query.Keys (:46), skipping anything that fails IsFilterKey (:112-115, prefix filters[ plus suffix ].operator or ].value), extracts the bracketed property name with GetFilterPropertyName (:122-130, which finds the closing ] with key.AsSpan(startIndex).IndexOf(']') and slices key[startIndex..(startIndex + length)], :125-129, returning null when there is no ]) and the suffix with GetFilterSuffix (:137-146).
    • The two halves of one filter can arrive in either order, so it accumulates into a tuple and merges (:59-65, with the ordering comment at :44-45). No count check runs here: every distinct property is added.
    • A second pass removes every entry that IsIncomplete flags (:71-77, comment at :68-70): incomplete filters are silently discarded, never a 400. IsIncomplete (:89-91) is true when the operator is empty, or when the value is empty and the operator is not value-less. IsValueLessOperator (:99-105) trims the operator and matches IS EMPTY or IS NOT EMPTY case-insensitively (so MudBlazor's lower-case "is empty" counts), because those presence checks take no value and a grid sends the operator alone.
    • Finally ModelBindingResult.Success(filters) (:79) and Task.CompletedTask (:80): the binder is synchronous work behind an async signature, so it allocates no task machinery.
  • Why it's built this way: silent discard (with the value-less carve-out for IS EMPTY / IS NOT EMPTY) plus case-insensitive matching makes the grammar forgiving for hand-built UI query strings. The cap is defined once, on QueryFilterService, and enforced there as a whole-request refusal, so a malicious caller cannot turn the query string into a reflection amplifier and an honest caller never gets a silently partial filter.
  • Where it's used: applied per parameter with [ModelBinder(typeof(QueryFilterModelBinder))] on the list actions of IEntityControllerBase<TEntityDTO, TIdentifierType> (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/IEntityControllerBase.cs:51) and EntityControllerBase<TEntity, TEntityDTO, TIdentifierType> (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/EntityControllerBase.cs:165 for the paged read and :263 for the CSV export). QueryFilterModelBinderMaxFiltersTests (MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/ModelBinders/QueryFilterModelBinderMaxFiltersTests.cs) covers the cap behavior.

PasskeysControllerBase

MMCA.Common.API · MMCA.Common.API.Controllers.Passkeys · MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Passkeys/PasskeysControllerBase.cs:41 · Level 8 · class (abstract)

  • What it is: the shipped base controller for WebAuthn passkeys: the signed-in user registers, lists, renames and deletes their passkeys, and an anonymous caller signs in with one. A subclass mounts the route; the base owns all seven actions.
  • Depends on: ApiControllerBase (its base, for HandleFailure), IPasskeyService resolved per request (PasskeysControllerBase.cs:53-54), PasskeyStepUp and PasskeyErrors for the recent-sign-in rule, PasskeyOptionsResponse and AuthenticationResponse on the wire, NonIdempotentAttribute, and BCL TimeProvider (falling back to TimeProvider.System, :56-57).
  • Concept (two-step ceremonies over single-use challenges). A WebAuthn registration or sign-in is two requests: an options call that stores a fresh challenge and returns it, and a completion that proves possession by signing that challenge, which burns it. [Rubric §11, Security] shows in three places: every ceremony action is [NonIdempotent] (:63, :111, :230, :255) because a replayed response would hand back a challenge or tokens that are already spent; registration additionally requires a recent sign-in through PasskeyStepUp.IsSatisfiedBy(User, UtcNow) (:81, :132), refused with PasskeyErrors.StepUpRequired; and the anonymous sign-in pair is bounded by [EnableRateLimiting(RateLimitPolicyAuthIp)] (:232, :257). The controller has no constructor dependency: EnabledPasskeys keeps the service only when IsEnabled is true, so on a host that has not opted in every action answers 404.
  • Walkthrough
    • BeginRegistrationAsync ([HttpPost("register/options")] at :62, [Authorize] at :64, method at :69-89) checks enabled (404), caller id (401), and step-up, then names the account through DescribeCaller (:86) and returns the creation options.
    • DescribeCaller(userId) (:97-104) takes the account name from ClaimTypes.Email or the raw email claim, falling back to the user id, and the display name from ClaimTypes.Name or name, falling back to the account name, so it works with mapped and unmapped JWT claims.
    • CompleteRegistrationAsync(request, ...) ([HttpPost("register")] at :110, method at :118-139) repeats the three checks and stores the passkey.
    • ListAsync ([HttpGet] at :144, method at :149-163) returns the caller's passkeys, oldest first. RenameAsync(id, request, ...) ([HttpPatch("{id:guid}")] at :170, method at :176-194) and DeleteAsync(id, ...) ([HttpDelete("{id:guid}")] at :204, method at :210-224) answer 404 for another account's passkey; the last passkey can be deleted only while the account still has a password or an external login, otherwise 409 Passkeys.LastPasskey (:197-199).
    • BeginSignInAsync ([HttpPost("signin/options")] at :229, [AllowAnonymous] at :231, method at :236-245) returns the request options. CompleteSignInAsync(request, ...) ([HttpPost("signin")] at :254, method at :263-276) passes ClientIpAddress (:47) and ClientUserAgent (:50) to the service (:273) and returns a token pair whose access token carries mfa=passkey (:248-249).
  • Why it's built this way: ADR-139 makes passkeys an opt-in sign-in method; resolving the service per request is what lets the controller ship in the framework and stay inert until a host opts in. Rate limiting follows ADR-019 and ADR-029.
  • Where it's used: ADC's PasskeysController (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/Controllers/Passkeys/PasskeysController.cs) with PasskeysControllerTests; registration support in PasskeysServiceCollectionExtensions (MMCA.Common/Source/Core/MMCA.Common.Passkeys/PasskeysServiceCollectionExtensions.cs); framework coverage in PasskeysControllerBaseTests and PasskeyTestHost; AnonymousEndpointTests lists the two sign-in actions.

TwoFactorControllerBase<TBeginCommand, TConfirmCommand, TDisableCommand, TRegenerateCommand>

MMCA.Common.API · MMCA.Common.API.Controllers.TwoFactor · MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/TwoFactor/TwoFactorControllerBase.cs:60 · Level 8 · class (abstract, partial)

  • What it is: the shipped base controller for authenticator-app (TOTP) two-factor authentication on the signed-in account: read the status, begin and confirm an enrollment, regenerate recovery codes, and turn the factor off. A subclass supplies the four app command types, their factories, and the route.
  • Depends on: ApiControllerBase (its base, for HandleFailure), four ICommandHandler<in TCommand, TResult> instances and an ITwoFactorStore, all primary-constructor parameters (TwoFactorControllerBase.cs:60-65) re-exposed as BeginHandler, ConfirmHandler, DisableHandler, RegenerateHandler and Store (:72-84); the constraints IUserScopedRequest and IUserScopedCommand<out TRequest> over TwoFactorCodeRequest (:66-69); PasskeyStepUp and TwoFactorErrors; IAuthenticationService, resolved optionally to end sessions; and RefuseMachineClientsAttribute on the class (:59).
  • Concept (a factor change invalidates every session signed in under the old state). [Rubric §11, Security]: after a confirmed enrollment (:181) and after a disable (:244), EndSessionsAsync revokes every refresh session of the account (:285-308), so a session opened before the change cannot keep refreshing. The change is already saved at that point, so a failed revocation is caught (any exception except OperationCanceledException, :299) and logged rather than failing the request. The secret-bearing responses (enrollment, confirm, recovery codes) carry [ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)] (:122, :153, :193) and every write is [NonIdempotent] (:121, :152, :192, :221), so neither an HTTP cache nor the replay cache holds a secret or a set of recovery codes. Beginning and confirming an enrollment require a recent sign-in through PasskeyStepUp.IsSatisfiedBy(User, UtcNow) (:134, :168), refused with TwoFactorErrors.RecentSignInRequired. [Rubric §13, Observability & Operability]: the failure line is a source-generated [LoggerMessage] at Warning (:272-273) that names the user id, the change and the error codes or exception type, and no address.
  • Walkthrough
    • GetStatusAsync ([HttpGet] at :92, method at :98-114) answers 401 without a caller id, 404 when the store holds no state for the account (:106-109), and otherwise whether the factor is on and how many recovery codes remain, reported as 0 while the factor is off (:111-113).
    • BeginEnrollmentAsync ([HttpPost("enrollment")] at :119, method at :127-144) checks the caller and the step-up, then dispatches CreateBeginEnrollmentCommand(userId) and returns the shared secret as a key and a provisioning URI.
    • ConfirmEnrollmentAsync(request, ...) ([HttpPost("enrollment/confirm")] at :150, method at :159-184) checks the caller and the step-up, dispatches the confirm command, ends the sessions, and returns the single-use recovery codes once.
    • RegenerateRecoveryCodesAsync(request, ...) ([HttpPost("recovery-codes")] at :190, method at :199-213) replaces the recovery codes after a code verifies; it applies no step-up check and ends no sessions.
    • DisableAsync(request, ...) ([HttpPost("disable")] at :219, method at :227-247) dispatches the disable command, ends the sessions, and answers 204.
    • The four abstract factories CreateBeginEnrollmentCommand, CreateConfirmEnrollmentCommand, CreateDisableCommand and CreateRegenerateRecoveryCodesCommand (:252, :258, :264, :270) each take the authenticated user id (and the presented code), so the account a command targets always comes from the token, never the body.
    • EndSessionsAsync (:285-308) returns early on a host without the framework's IAuthenticationService (:288), otherwise calls RevokeAllSessionsAsync (:296) and logs any failure (:304-307).
  • Why it's built this way: the same generic command-factory shape as SignInLinkControllerBase<TSendCommand, TRedeemCommand>: the app owns its commands and their handlers run through the decorator pipeline, while the HTTP shape, the step-up rule and the session revocation ship once in the framework.
  • Where it's used: in the usage sites read here only by the framework's tests, TwoFactorControllerBaseTests and TwoFactorControllerTestHost (MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/Controllers/TwoFactor/). UsersAdminControllerBase<TUserDto> reads the same ITwoFactorStore to require enrollment before a listed role is granted.
  • Caveats / not-in-source: no ADR mentions this type; no ADC subclass appears among its usage sites, so whether an app mounts it is not determinable from source read here.

FeatureFlagOverrideModelContributor

MMCA.Common.Infrastructure · MMCA.Common.Infrastructure.Persistence.FeatureFlags · MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/FeatureFlags/FeatureFlagOverrideModelBuilderExtensions.cs:86 · Level 9 · class (internal, sealed)

  • What it is: the IModelContributor that adds the FeatureFlagOverrides table mapping to exactly one database's EF model: the source named by FeatureFlags:DataSourceName, the owning service's own database (FeatureFlagOverrideModelBuilderExtensions.cs:74-79).
  • Depends on: IModelContributor (the contract it implements), ModelContributorPhase, PhysicalDataSource, DataSource, IOptions<FeatureFlagOverrideSettings> taken as its primary-constructor parameter (:86), and FeatureFlagOverrideModelBuilderExtensions, whose ApplyFeatureFlagOverrideConfiguration it calls (:97). External: Microsoft.EntityFrameworkCore.ModelBuilder.
  • Concept (registration as the opt-in). [Rubric §8, Data Architecture] assesses whether each service owns its schema and whether optional storage stays out of databases that do not need it: the contributor's registration is itself the opt-in, so a host that never calls AddReloadableFeatureFlags keeps a byte-identical model and sees no migration, and a host that does gets the table only in the one named source (:75-79). The remarks call out why a second configuration flag was not added: it would be a second way to say the same thing (:76-77).
  • Walkthrough
    • Phase (:89) is ModelContributorPhase.BeforeEntityPasses. Unlike most optional tables, the mapping runs before the entity passes because an override is an auditable entity, so the soft-delete filter and the concurrency token must see it (:81-82).
    • AppliesTo(source) (:92-93) is an ordinal comparison of source.Key.Name against settings.Value.DataSourceName, so every other physical source is left untouched.
    • Configure(modelBuilder, engine) (:96-97) calls modelBuilder.ApplyFeatureFlagOverrideConfiguration() with its default schema; it does not branch on the engine.
  • Why it's built this way: the remarks tie it to ADR-148 and to the shape the stored permission grants already use (:75-76): moving the mapping out of a hand call and into a registered contributor means no consumer wires the table by hand, while a host with its own context class can still call the extension directly (FeatureFlagOverrideModelBuilderExtensions.cs:14-17).
  • Where it's used: registered as a singleton IModelContributor by AddReloadableFeatureFlags (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.FeatureFlags.cs:73), after the settings are bound with ValidateDataAnnotations and ValidateOnStart (:67-70). The same registration doubles as the "already registered" marker: a second call finds it and returns early, because decorating twice would layer the stored overrides over themselves (:59-65). DesignTimeDbContextHelper constructs one directly when EnableFeatureFlagOverrides is set, so migrations can be generated for the table (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/Design/DesignTimeDbContextHelper.cs:202-203). Test coverage: FeatureFlagOverrideModelGateTests, ReloadableFlagsHost and ModelCacheKeyGateTests under MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/.
  • Caveats / not-in-source: no ADR file in the brief mentions this type; the ADR-148 reference comes from the XML remarks (:75) and its content was not read here.

LegalAcceptanceControllerBase

MMCA.Common.API · MMCA.Common.API.Controllers.Legal · MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Legal/LegalAcceptanceControllerBase.cs:45 · Level 10 · class (abstract)

  • What it is: the shipped base controller for the signed-in user's Terms of Service standing: one GET that reads whether the user has accepted the configured current version, and one POST that records the acceptance. An app subclass supplies only the route prefix.
  • Depends on: ApiControllerBase (its base, for HandleFailure), ILegalAcceptanceService, ICurrentUserService (re-exposed as the protected CurrentUserService, LegalAcceptanceControllerBase.cs:51), and IOptions<LegalAcceptanceOptions> (LegalAcceptanceOptions), all taken as primary-constructor parameters (:45-48). It maps through LegalAcceptancePolicy and exchanges LegalAcceptanceDTO and AcceptLegalTermsRequest on the wire, at the route constant LegalAcceptanceRoutes.Action (me/legal-acceptance, LegalAcceptanceRoutes.cs:13).
  • Concept (the configured version is the only truth the controller trusts). [Rubric §11, Security]: the POST does not store what the client sent. LegalAcceptancePolicy.EnsureAcceptsCurrentVersion (:110-111) proves the request names the configured current version, and then the service is called with the configured value (:119-120), with a comment recording that this keeps the stored version byte-identical to configuration (:117-118). [Rubric §1, SOLID]: like the other admin and account bases, the controller holds no rule of its own, only translation to the service and policy (DIP).
  • Walkthrough
    • CurrentTermsVersion (:54) is LegalAcceptancePolicy.ResolveCurrentVersion(options.Value), null when no version is configured.
    • GetLegalAcceptanceAsync(cancellationToken) ([HttpGet(LegalAcceptanceRoutes.Action)] at :59, method at :63) returns Ok(LegalAcceptanceDTO.Evaluate(null, null, null)) when no version is configured (:66-69), a 401 Problem Details failure (Legal.Unauthorized) when UserId is null, (:71-75), and otherwise asks GetForCurrentUserAsync (:77), unwraps the result with result.TryGetValue(out var acceptance) (:81), and returns the standing normalized against the current version through LegalAcceptancePolicy.Normalize (:83).
    • AcceptLegalTermsAsync(request, cancellationToken) ([HttpPost] plus [Idempotent] at :93-94, method at :99) applies the same 401 guard, then the version check described above, then AcceptForCurrentUserAsync with the configured version (:119-121), and returns the normalized standing through the same TryGetValue unwrap (:123-125). A version mismatch comes back as a failure through HandleFailure, surfaced as a 400 per the declared ProducesResponseType.
  • Why it's built this way: the HTTP shape ships once in the framework and an app contributes its ILegalAcceptanceService implementation, the same pattern as the other base controllers in this group. [Idempotent] on the POST (IdempotentAttribute) makes a retried acceptance replay the first response rather than run twice (see ADR-017). Both actions are virtual, so an app can override one without re-declaring routing.
  • Where it's used: ADC's LegalAcceptanceController is the current subclass and supplies only the route (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/Controllers/LegalAcceptanceController.cs:24-28); the Common coverage is LegalAcceptanceControllerBaseTests. ADR-116 mentions the surface.
  • Caveats / not-in-source: how the opt-in registration of this controller is wired is outside the cited span and not determinable from the lines read here.

DataExportControllerBase<TQuery>

MMCA.Common.API · MMCA.Common.API.Controllers.Privacy · MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Privacy/DataExportControllerBase.cs:61 · Level 10 · class (abstract)

  • What it is: the shipped base controller for the data-subject export endpoint (GET {route}/{userId}/export, the GDPR/CCPA access and portability request). A subclass supplies its app's query type and a route; the base owns the action, the authorization posture, the feature gate, and the file-download delivery.
  • Depends on: ApiControllerBase (its base, for HandleFailure at MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/ApiControllerBase.cs:50), IQueryHandler<in TQuery, TResult> closed over UserDataExportDTO, ICurrentUserService, Result and Error, PrivacyFeatures, and the constraint IUserOwnedRequest on TQuery (DataExportControllerBase.cs:61-64). Externals: ASP.NET Core MVC (including its IOptions<JsonOptions>), System.Text.Json, Microsoft.Extensions.DependencyInjection and Microsoft.Extensions.Options (:6-7), and Microsoft.FeatureManagement.Mvc's [FeatureGate].
  • Concept (a privacy endpoint shipped as a base class, not a registered controller). [Rubric §30, Compliance/Privacy/Data Governance] assesses whether legal obligations such as subject access, portability, and erasure are first-class code rather than manual operations: the access/portability half of a DSAR is framework code here, so an app gets it by subclassing rather than by re-implementing the dispatch, the ownership posture, and the delivery format. [Rubric §11, Security] shows up as defence in depth: the class-level [Authorize] (:59) demands an authenticated caller, while the handler independently enforces owner-or-privileged-role, so the endpoint cannot leak another subject's data even if a subclass is mounted without its own [Authorize] (:52-55). [Rubric §6, CQRS & Event-Driven Design] covers the [FeatureGate(PrivacyFeatures.DataExport)] (:60, the flag string is "Privacy.DataExport" at MMCA.Common/Source/Core/MMCA.Common.Shared/Privacy/PrivacyFeatures.cs:12): the whole surface stays off, answered by DisabledFeatureHandler's 404, until a host deliberately turns the flag on.
  • Walkthrough
    • The primary constructor takes the app's query handler and ICurrentUserService (:61-63); the latter is re-exposed as the protected CurrentUserService property (:70) so a subclass can reuse it. ExportContentType = "application/json" (:67) is the one media type the package is served as.
    • ExportAsync(UserIdentifierType userId, CancellationToken) (:84-86) is routed by the action-level [HttpGet("{userId}/export")] (:79) only: the route prefix lives on the subclass, so a controller routed at Users serves /Users/{userId}/export (:41-43). The declared responses are 200 with a UserDataExportDTO, plus 401/403/404 as ProblemDetails (:80-83).
    • It reads CurrentUserService.UserId first and, when there is none, short-circuits through HandleFailure with Error.Unauthorized("Privacy.Unauthorized", ...) (:88-92), so even the unauthenticated case comes back as RFC 9457 Problem Details rather than a bare status.
    • It then builds the app's query through the abstract CreateQuery(userId, currentUserId, CurrentUserService.Role) factory (:94, declared at :126-129), awaits the handler (:95-96), and unwraps the Result with result.TryGetValue(out var export), mapping a failure through HandleFailure(result.Errors) (:98-101), which is what turns the handler's own ownership refusal into a 403.
    • The role passed to CreateQuery is the caller's FIRST role claim (ICurrentUserService.Role), which the parameter doc notes is the only one on the single-role tokens TokenService mints; a host issuing multi-role tokens overrides CreateQuery to pass its privileged role when CurrentUserService.IsInRole holds, as OwnershipHelper.IsAdmin does (:119-124).
    • On success it serializes the package itself with JsonSerializer.SerializeToUtf8Bytes(export, json) (:109) and returns File(payload, ExportContentType, BuildFileName(...)) (:111). The options are the host's MVC JSON options, resolved per request as HttpContext.RequestServices?.GetService<IOptions<JsonOptions>>()?.Value.JsonSerializerOptions, with JsonSerializerOptions.Web only as the fallback when none resolve (:107-108). The inline comment (:103-106) is explicit about why: Ok(export) would content-negotiate and render inline, and this document exists to be saved, while reusing the MVC options (the host's converters included) keeps the payload byte-shape identical to every other response the API produces.
    • BuildFileName (:140-141) composes user-data-{userId}-{yyyyMMdd}.json with CultureInfo.InvariantCulture, taking the date from the package's own UserDataExportDTO.GeneratedOn so the file name and the document always agree, and so a saved file sorts and parses the same in every locale (:131-136).
  • Why it's built this way: ADR-076 hoists the export idiom that ADC and Store each wrote by hand. It ships as an abstract base with a CreateQuery factory rather than as a concrete controller added through an application part because the query type is app-owned (each app's ExportUserDataQuery lives in its own Application assembly), and a concrete controller could not construct a type it cannot see (DataExportControllerBase.cs:46-49). The route staying on the subclass follows the AuthControllerBase precedent: the app owns its URL space (:41-43).
  • Where it's used: both full apps now derive from it, and each subclass is nothing but a route plus a query factory: ADC's UsersDataExportController (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/Controllers/UsersDataExportController.cs:26-35) and Store's (MMCA.Store/Source/Modules/Identity/MMCA.Store.Identity.API/Controllers/UsersDataExportController.cs:19-29). Both are routed at the literal Users rather than [controller], and both say why: [Route("[controller]")] would resolve to UsersDataExport and move the published path (ADC :19-22, Store :9-13). The framework's own coverage is DataExportControllerBaseTests, whose TestDataExportController is the third subclass in source (MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/Controllers/Privacy/DataExportControllerBaseTests.cs:267).

EFFeatureFlagOverrideStore

MMCA.Common.Infrastructure · MMCA.Common.Infrastructure.Persistence.FeatureFlags · MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/FeatureFlags/EFFeatureFlagOverrideStore.cs:33 · Level 13 · class (internal, sealed)

  • What it is: the EF Core implementation of IFeatureFlagOverrideStore: read all active overrides, upsert one, soft-clear one, in the owning service's own database.
  • Depends on: IDbContextFactory, IEntityDataSourceRegistry, IDataSourceResolver, DataSourceKey, ApplicationDbContext, FeatureFlagOverride, FeatureFlagOverrideResponse, FeatureFlagOverrideSettings, FrameworkTableTargets, Result.
  • Concept introduced: none new; soft delete, audit stamping and data-source resolution are taught in the primer and in G07. [Rubric §4, DDD]: every write goes through the aggregate's Create, Change and Clear, which return Result. [Rubric §11, Security]: the revive-on-set path drops only the named soft-delete filter, never the tenant filter (:67-70).
  • Walkthrough
    • Context (:39) resolves the context for ResolveDataSourceKey() on each access; Overrides is its Set<FeatureFlagOverride>() (:41).
    • ResolveDataSourceKey (:140-141) delegates to FrameworkTableTargets.ResolveHome<FeatureFlagOverride> with the configured DataSourceName, the one resolution every store and sweep over this table shares (:139): the registry's mapping for the entity when present, else the configured name verbatim with only the engine taken from the resolver's default logical source (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DataSources/FrameworkTableTargets.cs:105-113).
    • GetAllAsync (:44) is a no-tracking query with an explicit !IsDeleted predicate, ordered by Id (:48-53); the predicate is redundant with the soft-delete filter but keeps a hand-mapped table correct (:46-47).
    • SetAsync (:59) loads the row with IgnoreQueryFilters([ApplicationDbContext.SoftDeleteFilterName]) (:69-72), so a soft-cleared row is revived rather than duplicated while the Tenant filter still applies; the comment notes that EF's parameterless IgnoreQueryFilters() would drop both (:67-68). The filter names are "SoftDelete" and "Tenant" (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/ApplicationDbContext.cs:712, :715). A new name goes through FeatureFlagOverride.Create and AddAsync (:77-85); an existing row through Change (:89). Domain failures return as Result.Failure; success saves through the factory (:98) and maps the entity (:100).
    • ClearAsync (:104) finds an active row (:108-110); none is success, the idempotent-clear promise (:112-116); otherwise Clear() and save (:118-125).
    • ToResponse (:128) reports LastModifiedOn ?? CreatedOn and LastModifiedBy ?? CreatedBy (:136-137).
  • Where it's used: registered with TryAddScoped<IFeatureFlagOverrideStore, EFFeatureFlagOverrideStore>() (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.FeatureFlags.cs:76); called by FeatureFlagAdministrationService directly and by FeatureFlagOverrideSnapshot on each load. ADR-073 mentions it.
  • Caveats / not-in-source: GetAllAsync and ClearAsync keep every model filter, and SetAsync keeps the Tenant one; whether the Tenant filter is actually configured for FeatureFlagOverride on a given host is decided by the model ApplicationDbContext builds, not determinable from this file alone.

⬅ Navigation Metadata & Populators (EF-decoupled eager loading) • Index • gRPC & Inter-Service Contracts ➡