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.APIassembly 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 dedicatedAssemblyReferencemakes 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 readonlyfields.Assembly(AssemblyReference.cs:11) istypeof(AssemblyReference).Assembly, resolved once at type initialization.AssemblyName(AssemblyReference.cs:14) isAssembly.GetName().Namewith a?? string.Emptyfallback 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.APIassembly, used where a generic constraint or atypeof(...)needs a concrete reference type from this layer rather than anAssemblyinstance. - Depends on: nothing. See AssemblyReference for the full concept;
ClassReferenceis its type-shaped sibling. - Concept: covered under AssemblyReference. Where
AssemblyReference.Assemblyanswers "which assembly",ClassReferenceanswers "give me aclasstoken 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.GivenNameandClaimTypes.Surnameclaims. - Depends on: the ASP.NET Core OAuth ticket context (
OAuthCreatingTicketContext),System.Security.Claims, andSystem.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
userfield, 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 theOnCreatingTickethandler. 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 toAddFromUserFieldwith the scheme'sClaimsIssuer(:36).AddFromUserField(ClaimsIdentity, string?, string?)(:47) returns on a blank value, parses the JSON, requires an object with anameobject, and readsfirstNameandlastName(:54-68). AJsonExceptionis 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
OnCreatingTicketrather than the controller. - Where it's used: only by the Apple branch of ExternalAuthExtensions (
ExternalAuthExtensions.cs:241); covered byMMCA.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.Claimsonly (OidcClaimNormalizer.cs:1). It is called from theOnTokenValidatedevent 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), andemail_verifiedpasses through only when the operator configured the provider withTrustEmailand 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), addsClaimTypes.NameIdentifierfromProviderKeywhen one can be built (:35-39), then copies email, given name, surname, and name, each from the raw OIDC claim name with the mappedClaimTypesname as a fallback (:41-44). It addsemail_verified=trueonly whentrustEmailis set and the token's value parses astrue(: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 IDsubis pairwise per application whileoidis the stable user id inside the tenant (:10-12). Otherwise it usessub(orNameIdentifier) and returnsnullwhen there is none (:65-69), qualifies it with theissclaim, falling back to the subject claim'sIssuerwhenisswas not kept and the issuer is not the default (:71-78), and returns{iss}|{sub}, ornullwhen no issuer is known (:80).First(:83-86) returns the first non-blank value across a list of claim types, andAddIfPresent(: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 baresubkeeps 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, andTrustEmail(OidcProviderSettings.cs:20-28), plus the static reader that builds the list from configuration. - Depends on:
IConfigurationand a source-generatedRegex(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 anInvalidOperationExceptionthat names the offending key at startup rather than producing a half-working scheme, and a section withoutClientIdstays 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 whoseClientIdis 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 throughOidcReservedProviderNames.IsReserved(:74-78):google,github, andapple(the built-in providers) andcomplete,exchange, anddiscover(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).AuthorityandClientSecretare required throughRequired(:86-87,:123-129). Scopes default toopenid profile emailwhen none are configured, andopenidis inserted first when a configured list omits it (:33,:89-101). Domains are normalized, blanks dropped, and de-duplicated ignoring case (:103-107).DisplayNamefalls back to the name (:109,:118), andTrustEmailistrueonly 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
NormalizeDomainrule (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
Domainsclaim that address's domain, rather than showing one button per provider.[Rubric §9, API & Contract Design]is relevant: both lookups returnnullinstead 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, ornullfor a blank name or no match.FindByEmail(string? email)(:26) takes the domain after the last@and returnsnullfor a missing@, an empty local part, or an empty domain (:28-32). It then normalizes the domain and returns the provider whoseDomainscontains 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 callsFindfor the generic challenge route (:160) andFindByEmailfor 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 thatAddCommonAuthentication(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 throughAddGoogle,AddGitHub,AddApple, andAddOpenIdConnect(:178,:195,:211,:127). First-party, it partners with the app's OAuth controller subclassing OAuthControllerBase, whoseExtractClaimsconsumes 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 itsEmailVerifiedClaimType(: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:AddCommonAuthenticationregisters only the JWT bearer scheme, so without this call the OAuth controller wouldChallengeand read schemes that are not in the authentication pipeline and the flow would fail at runtime (:14-16), yet a host with noOAuthconfiguration 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 itsClientIdbeing 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 oneemail_verifiedclaim that the controller passes toExternalLoginAsync, GitHub asserts nothing so its logins read as unverified, and an OIDC provider's assertion passes only underTrustEmail(:28-35).[Rubric §9, API & Contract Design]is relevant because the opt-in posture mirrorsAddPermissions(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 theOAuthsection (:66), pullsGoogle:ClientId,GitHub:ClientId, andApple:ClientId(:67-69), and reads every OIDC provider eagerly throughOidcProviderSettings.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 asAddCommonAuthenticationleft 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 byAddCommonAuthentication, it just yields a builder to append schemes onto. - It then adds the
ExternalLogincookie (: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 returningservicesfor 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 intoExternalLoginScheme(:134) with callback/auth/callback/<Name>(:135) andOnRemoteFailurebound toOAuthReturnUrls.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, andGetClaimsFromUserInfoEndpoint = 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), andOnTokenValidatedswaps the principal for OidcClaimNormalizer's output (:155-159).AddExternalLoginCookie(:166-175) configures the bridge cookie: namemmca_external_login(:169),HttpOnly(:170),SameSite=Lax(:173, sufficient because the OAuth round trip returns as a top-level GET navigation, which avoids theSecureplus cross-site cost thatSameSite=Noneimposes,:171-172), and a 10-minute expiry (:174).AddGoogleProvider(:177-192) andAddGitHubProvider(:194-208) each set the client id, require the matchingClientSecretor throw (:181-183,:198-200), setSignInScheme = ExternalLoginScheme, pin a fixedCallbackPath(/auth/callback/googleat:185,/auth/callback/githubat:202), bindOnRemoteFailuretoOAuthReturnUrls.RedirectRemoteFailureAsync(:186,:203), and setSaveTokens = true(:187,:207). Google also maps both the v3 userinfo keyemail_verifiedand the legacy v2 keyverified_emailontoOidcClaimNormalizer.EmailVerifiedClaimTypethroughClaimActions.MapJsonKey(:189-191). GitHub additionally requests theuser:emailscope (:206) because it does not return the email on the default scope and the controller'sClaimTypes.Emaillookup would otherwise fail (:204-205); it maps no verified claim.AddAppleProvider(:210-242) is the one that differs structurally among the built-in providers. ItsClientIdis 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, soGenerateClientSecret = true(:219) andTeamId(:220),KeyId(:223), andPrivateKeyPem(:226) are each required-or-throw. The PEM is handed over as a callback returning aReadOnlyMemory<char>(:229). Scheme, callback path (/auth/callback/apple,:232), theOnRemoteFailurebinding (:233), andSaveTokens(:234) match the other two. The ID token'semail_verified(asserted for relay and real addresses alike) is mapped ontoOidcClaimNormalizer.EmailVerifiedClaimType(:236-237). It also wiresoptions.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'suserform field, on the first authorization (:239-240). See AppleUserNameClaims.
- The public surface is one C#
- 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 fromAddCommonAuthenticationkeeps 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 byMMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/Authentication/ExternalAuthExtensionsTests.cs,ExternalAuthOidcTests.cs,ExternalAuthRemoteFailureTests.cs, andExternalLoginEmailVerifiedTests.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 itsUIBaseUrlConfigKey(: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 inOAuth:AllowedReturnUrlSchemes, never http or https, so web destinations always flow through the config-pinnedOAuth:UIBaseUrland 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), andReturnUrlItemKey = "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 toOnRemoteFailure. 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 toErrorRedirectUrl(..., FailedErrorCode)and callsHandleResponse()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 witherror=<code>appended (so the WebAuthenticator window closes) when one is in play.GetAllowedMobileReturnUrl(IConfiguration configuration, string returnUrl)(:68) returnsnullfor anything that is not an absolute URI or is http/https (:70-75), then matches the scheme againstOAuth:AllowedReturnUrlSchemesignoring case (:80-81). The read is null-tolerant on purpose: a missing section, an empty one, or a test double whoseGetSectionreturns null all mean "no allowlist", never a throw from the binder (:77-79).AppendQuery(Uri target, string queryFragment)(:88) appends with?or&ontoOriginalString, notToString(), because URI normalization adds a trailing slash to authority-only URIs and native authenticator callback matching can be exact (:90-94).
- Two constants:
- 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 bindsRedirectRemoteFailureAsyncfor every provider (ExternalAuthExtensions.cs:136,:178,:191,:221). Covered byMMCA.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), plusSystem.Reflectionfor theTypeInfoit inspects (:1). - Concept introduced (module-aware controller discovery). MVC discovers controllers by scanning referenced assemblies. When a host references a module's
APIassembly 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 byIsDisabledModuleController(:46-53). The private static matcher (:60) reads the controller's assembly simple name and namespace, each with a?? string.Emptyfallback (: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.insideMMCA.Store.Catalog.APIor its.Controllersnamespace while avoiding false positives from substrings like "Catalogue" (:69-71). The comparison isOrdinalIgnoreCaseon both the assembly name and the namespace (:74-75), and the loop falls through tofalsewhen nothing matches (:81). - Why it's built this way: matching on the dotted token handles both the
MMCA.{Repo}.{Module}.APIconvention 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)viaConfigureApplicationPartManager(DependencyInjection.cs:72-73), but only when a non-nullModulesSettingsis 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.APIlayer. Using a C#extension(IServiceCollection services)block (DependencyInjection.cs:28) it adds six methods toIServiceCollection:AddAPI,AddErrorLocalization,AddErrorResources<TResource>,AddCommonExceptionHandlers,AddServerAuthSessionCookie, andAddModuleHealthChecks. - 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), andStronglyTypedIdJsonConverterFactory(ADR-115 strongly typed identifiers, serializing wrapper types as their bare primitive), UnhandledResultFailureFilter, OversizeFormResourceFilter (fromMMCA.Common.API.Uploads,:15), IdempotencyFilter and IdempotencySettings, OwnerOrAdminFilter and itsOwnerOrAdminFilterOptions, 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, fromMMCA.Common.API.SessionCookies,:14), and ModuleLoader/ModulesSettings. Externals:Microsoft.FeatureManagement(including itsIDisabledFeaturesHandlercontract),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 forModulesSettings/ModuleLoader(:16-17).[Rubric §13, Observability & Operability]and[Rubric §17, DevOps]both apply throughAddModuleHealthChecks(:230), which projects module state into/healthchecks taggedmoduleso/health?tag=modulereports 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 withReturnHttpNotAcceptable = false, the UnhandledResultFailureFilter global filter, and the OversizeFormResourceFilter at its ownFilterOrder, 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);Currencyis 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 becauseSystem.Text.Jsonresolves it withinherit: false, so the factory is registered once here and everyEnumeration<T>serializes byNameacross 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 whenmodulesSettingsis 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 byOwnerOrAdminFilter, which takes the scoped ICurrentUserService;IdempotencyFiltertakes only a logger and reads the singleton ICacheService from the request's services (:84-86). Right after that it bindsOwnerOrAdminFilterOptionswith data-annotation validation but deliberately notValidateOnStart(:90-95):BypassRoleis 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 isTryAdd-based and therefore safe to repeat, thenAddFeatureManagement().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 readsIHttpContextAccessorrather than the scopedICurrentUserService. Finally the singleton DisabledFeatureHandler is bound toIDisabledFeaturesHandler(:110) andAddErrorLocalization()is called (:113).AddErrorLocalization()(:125) registers ASP.NET localization (:127), the singleton IErrorLocalizer viaTryAddSingletonso 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 withIsFramework = true(:132) rather than throughAddErrorResources<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 anIStringLocalizerFactory(:146-147). This is the ADR-027 edge error-localization extension point, keyed byError.Code, and modules add their translations additively (:119-122).AddCommonExceptionHandlers()(:157) registers ProblemDetails (adding arequestIdextension fromTraceIdentifier,:159-161) then fourIExceptionHandlers 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 addsHttpContextAccessor, memory cache, the scoped CookieTokenReader (:186-188), a namedHttpClientpointed 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 viaTryAddSingleton(: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 anonymousauth/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 inMMCA.Common.UI.Webtightens SameSite on opt-in (ADR-131) (:200-202). Next it callsAddDataProtection()(: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 (AddAzureDataProtectionand 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 viaTryAddSingleton(:209). Last it registersTimeProvider.SystemviaTryAddSingleton(:211-214): the refresher judges access-token expiry against the injected clock, and a Blazor Web host that calls only this method has noAddServicesregistration to supply one, whileTryAddnever 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,Healthyfor each enabled module (:234-240) andDegradedfor each disabled one (:242-249), namedmodule-{Name}and taggedmodule. It must run after ModuleLoader'sDiscoverAndRegister(: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 nullmodulesSettings; a host with no idempotency configuration passes a nullconfigurationand keeps the defaults). The exception-handler ordering, the oversize-form filter's 413, the enumeration and strongly-typed-id converter factories, theOwnerOrAdminFilterOptionsvalidate-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 theTryAddfallback clock for hosts that call onlyAddServerAuthSessionCookieare the non-obvious, correctness-critical choices, and each carries an inline comment. Error localization is registered automatically byAddAPIso modules only add their own resources additively (ADR-027). - Where it's used: called from every service host's composition (
Program.csof 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 (seeMMCA.Common/CLAUDE.mdDI ordering note). - Caveats / not-in-source: the relative ordering of
AddAPIagainstAddInfrastructure/AddApplicationin a given host is not fixed by this file; onlyAddApplicationDecorators()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
IResultFilterthat 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, andMicrosoft.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.OnStartingcallback, 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 readsApiVersionMetadatafrom the matched endpoint (:36) and the host'sIReportApiVersionsfromRequestServices(:37); if either is missing it returns (:38-41), else it callsreporter.Report(response, metadata.Map(reporter.Mapping))(:43).OnResultExecutedis 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
OnStartingcallback then finds them present and adds nothing (:17-18). ResolvingIReportApiVersionsfrom DI, rather than writing the headers directly, means a host withReportApiVersionsoff 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 afterAddApiParameterDescriptorBackfill()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>) andMicrosoft.EntityFrameworkCoreforDbUpdateConcurrencyException(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 explicitIf-Matchand 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.
- Counted once, at the two places a conflict becomes a response (
- Walkthrough
MeterName = "MMCA.Common.Persistence"(:27) and a single staticMeterbuilt 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 aCounter<long>namedpersistence.concurrency.conflictwith unit{conflict}.RecordConflict(DbUpdateConcurrencyException)(:46-47) adds one, tagged withEntityTypeName(exception).EntityTypeName(:55-56) returnsUnknownEntityTypewhenexception.Entriesis 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 statickeeps 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 inMMCA.Common.Aspirebecause that package has no reference toMMCA.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 theDbUpdateConcurrencyExceptionkind, 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,IStatusCodeActionResultfor the result's own status,IOutputCacheStore, andILoggerwith aNullLoggerfallback (EvictOutputCacheAttribute.cs:1-7). The eviction itself is the best-effortTryEvictTagsAsyncverb 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 noIOutputCacheStoreregistered 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 inHttpContext.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.
- When it evicts (
- Walkthrough
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)](:35).EvictedTagsItemKey(:42) is theHttpContext.Itemsslot holding the per-request set of evicted tags.- The constructor takes
params string[] tags(:52), throwsArgumentNullExceptionon null (:54),ArgumentExceptionwhen 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 whenShouldEvictsays so (:80-83), then always awaitsnext()(: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 ownIStatusCodeActionResult.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 thoseHashSet.Addaccepts (:102-103), returns when none are pending, returns when noIOutputCacheStoreresolves (:107-109), resolvesILogger<EvictOutputCacheAttribute>or the null logger (:111-112), and callsstore.TryEvictTagsAsync(logger, pending)(:114).EvictedTagsOf(:118) returns the set already stored underEvictedTagsItemKey(:120-121) or creates an ordinalHashSet<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
RequestServicesinstead 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 exampleActivitiesController(MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.API/Controllers/Activities/ActivitiesController.cs:42) andSessionAssetsController(MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.API/Controllers/SessionAssets/SessionAssetsController.cs:63), and at method level with several tags, for exampleEventsController(MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.API/Controllers/Events/EventsController.cs:180) and the lifecycle transitions ofEventLifecycleController(MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.API/Controllers/Events/EventLifecycleController.cs:61). Framework coverage isEvictOutputCacheAttributeTests(MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/Caching/EvictOutputCacheAttributeTests.cs), and consumers assert their declarations throughEvictOutputCacheAssertionsin 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: thecache_tagtag 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 staticMeterbuilt from it (:21). The type doc carries a warning worth reading once and remembering (:10-14): never create a secondMeterwith 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 aCounter<long>namedcache.eviction.failedwith unit{tag}.RecordEvictionFailure(string cacheTag)(:36-37) adds one with acache_tagtag, so the instrument name and the tag name are spelled in exactly one place.
- Why it's built this way:
internal statickeeps 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 inMMCA.Common.Aspirebecause that package has no reference toMMCA.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
IOutputCachePolicyfor public, user-independent GET/HEAD endpoints that must stay cacheable even when the request carries anAuthorizationheader. 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) andMicrosoft.Extensions.Primitives(StringValues),Asp.Versioning(IApiVersionReader,ApiVersion,ApiVersioningOptions,AmbiguousApiVersionException) for the version-vary key, andMicrosoft.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 thebypassRolesmechanism 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, andbypassPermissionsdoes 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,1and1.0share 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 thet:{tenantId}prefix the caching CQRS decorators use, anApiVersionVaryByKey = "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: theparams string[] tagsoverload 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 throughIOutputCachePolicy.CacheRequestAsync(:118) first resolves the version key (:124), then computesattemptOutputCachingas "is a GET/HEAD request" AND "the version is readable" AND "is not a bypassed caller" (:125-127), enables output caching, setsAllowCacheLookup/AllowCacheStorageto that flag, deliberately turns request coalescing off withAllowLocking = false(:136), sets the expiration (:137), and (matching the built-in default) varies the cache key by every query-string parameter viaCacheVaryByRules.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'sRequestAbortedtoken: one client disconnecting would cancel the shared query and every waiter would answer 500 with aTaskCanceledException; the cost is that simultaneous misses each run the query once (:132-135). It then resolves the tenant fromcontext.HttpContext.RequestServicesand, when one is present, stamps it intoCacheVaryByRules.VaryByValues[TenantVaryByKey](:147-151), an unresolved tenant, single-tenant host or background call, adds nothing; stamps a non-null version key intoVaryByValues[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 returningValueTask.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 noIApiVersionReaderis registered, so a host that does not version keeps its key unchanged (:199-202); otherwise it readshttpContext.ApiVersioningFeature(:204), returns false when a version was named but did not parse (RequestedApiVersionnull whileRawRequestedApiVersionis not,:208-213) or when versioning throwsAmbiguousApiVersionException(:215-218), falls back to the configuredApiVersioningOptions.DefaultApiVersion(orApiVersion.Default) for an absent version (:220), and normalizes it (:221).NormalizeApiVersion(:229-232) formats one invariant-culture spelling, group date,major.minorwith a missing part read as 0 (so1and1.0agree) and status.IsCacheableRequest(:234-235) accepts GET or HEAD.IsBypassedCaller(HttpContext)(:241) first returns true whenArray.Exists(_bypassRoles, user.HasRole)(:244), returns false when no bypass permissions are configured (:249-252), and otherwise resolves the optionalIPermissionRegistryfromRequestServices(:256) and asksPermissionAuthorizationHandler.Holds(user, registry, permission)for each bypass permission (:257), the same evaluation the permission handler grants the elevated payload by (:254-255).HasRoleis deliberate, notClaimsPrincipal.IsInRole:IsInRoleonly matches the identity's own role claim type, so against a provider that emits barerole/rolesclaims 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 rawIOutputCachePolicyimplementation 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) andBookmarkCountsPolicy(:214). Its sessions policy is the one that constructs the policy directly with a bypass permission,ConferencePermissions.SessionAssetsManage, becauseSessionAssetsController's read answers a holder of that permission with materials the public cannot see (:179-190). Framework coverage isPublicEndpointOutputCachePolicyTestsandPublicEndpointOutputCachePermissionBypassTests(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) takesname,expiration, andparams string[] tagsand registersnew PublicEndpointOutputCachePolicy(expiration, tags). The second (:34-35) adds astring[] bypassRolesparameter before theparams string[] tagsand 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 returnvoid, 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-16and:23-29) instead of being re-derived at each registration. - Where it's used: called during host composition where the app configures
AddOutputCache(...); the registerednameis 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'sIOutputCacheStore,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): anOperationCanceledExceptionfrom host shutdown propagates, so the broker receive pipeline sees the shutdown rather than a completed message. This is the samewhen (ex is not OperationCanceledException)discipline used across the framework's cache-touching code.
- Per-tag best effort (
- Walkthrough: the primary constructor takes
IOutputCacheStore outputCacheStoreandILogger<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 throughoutputCacheStore.EvictByTagAsync(tag, cancellationToken)inside its owntry(:51-53) followed by a Debug log (:54). The catch (:56-63) is deliberately broad, filtered only bywhen (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:
partialplus 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 isRegisterOutputCacheEvictionConsumer()inside the host'sAddBrokerMessagingconfiguration, which wires the genericIntegrationEventConsumer<OutputCacheEvictionRequested>onto this handler; ADC's Conference service calls both (MMCA.ADC/Source/Services/MMCA.ADC.Conference.Service/Program.cs:259andMMCA.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 theOutputCacheEvictionRequestedit 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 isOutputCacheEvictionHandlerTests(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-Matchheader, the header is mandatory, and a conflict outcome is answered with412 Precondition Failedrather than409 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, andMicrosoft.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 inHttpContext.ItemsunderTokenItemKey, 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 with428 Precondition Requiredand the action never runs. A malformed tag is a400 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 whatIf-Matchis, 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 implementsIAsyncActionFilterdirectly 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 Details412and428response 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 everyIApiResponseMetadataProviderfilter on the action and its controller (:100-104) and adds aProducesResponseTypeAttribute(typeof(ProblemDetails), status)for each missing one ofPreconditionStatusCodes(: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.
- The token never touches the request model (
- Walkthrough
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)](:48);TokenItemKey(:57) is theHttpContext.Itemsslot.RequiredToken(HttpContext)(:68-76) is the action-side accessor: it returns the decodedbyte[], or throwsInvalidOperationExceptionnaming 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), callsTryApplyIfMatch(: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 awaitsnext()(:90) and passes the outcome to the rewrite (:92).TryApplyIfMatch(:104) reads the header (:106-107), then refuses withPreconditionRequiredResultwhen the value is blank or is the wildcard (:109-114), refuses withMalformedIfMatchResultwhenConcurrencyETag.TryParsecannot decode it (:116-120), and otherwise stores the bytes inHttpContext.Itemsand returns true (:122-123).RewriteConflictToPreconditionFailed(:130) handles two shapes. ADbUpdateConcurrencyExceptionis first recorded on ConcurrencyConflictMetrics (:137), then replaced with the 412 result and markedExceptionHandled = true(:132-141). Marking it handled is what stops DbUpdateExceptionHandler from mapping it to a 409 like any otherDbUpdateException, and it is also why the conflict is counted here: the global handler never sees it (:134-136). AnObjectResultalready carrying 409 has both its ownStatusCodeand itsProblemDetails.Statusmoved to 412, leaving the body otherwise intact (:145-152); a bareStatusCodeResult409 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 registeredProblemDetailsFactoryfor the body so the response carries the same diagnostic extensions (traceId) as the rest of the API, falls back to a hand-builtProblemDetailswhen no factory is registered, and attaches the framework's standarderrorsextension through ErrorHttpMapping.BuildErrorsExtensionwith the optional IErrorLocalizer (:218-219). The three call sites differ only in status, title, detail and error: 428Concurrency.PreconditionRequired(:164-173), 400Concurrency.MalformedIfMatch(:176-185), and 412Concurrency.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.Itemsinstead of through the bound model is what removed reflection from the request path entirely: there is no per-type property lookup, and request records stayinit-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 ofEventsController(.../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'sSessionQuestionsController(MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.API/Controllers/SessionQuestionsController.cs:137,:160,:186) andLivePollsController(.../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) andInventoryItemsController(.../InventoryItemsController.cs:96,:129) in Sales, the Catalog controllers (for exampleMMCA.Store/Source/Modules/Catalog/MMCA.Store.Catalog.API/Controllers/ProductVariantsController.cs:100), and Identity'sCustomersController(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 withConditionalWriteConventionTestsfitness 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 atMMCA.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
IOutputCacheStoreevicts one tag per call, but a single write usually invalidates several (a speaker edit drops bothconference:speakersandconference). Rather than a private per-controller helper wrapping a run ofEvictByTagAsynccalls (: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.EvictTagsAsyncpropagates the failure. A caller that considers a failed eviction part of its own success uses this one.TryEvictTagsAsyncis 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
TryEvictTagsAsyncis easy to miss and load-bearing: eviction runs underCancellationToken.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
AddOutputCacheEvictionHandlerand 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 throughTryAddEnumerablerather thanAddSingleton, 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 plainAddhere 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 multipleextension(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-guardsstoreandtags(:51-52) and awaitsEvictByTagAsyncfor each tag in the order given (:54-57).TryEvictTagsAsync(ILogger logger, params string[] tags)(:78) adds aloggerguard (:80-82) and routes each eviction throughBestEffort.ExecuteAsyncwith the prefixed operation name, the caller's logger, the eviction as the action, andCancellationToken.None(:86-90).extension(IServiceCollection services)(:95) holdsAddOutputCacheEvictionHandler()(:111). It null-guardsservices(:113), callsservices.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 singletonIOutputCacheStorethe handler evicts through.
- A class-level
- 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'sIBrokerConsumerBuilderis the broker half (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Consumers/IntegrationEventConsumerExtensions.cs:28, shorthand forRegisterIntegrationEventConsumer<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 exampleSpeakerCategoryItemsController(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) andCategoriesController(MMCA.Store/Source/Modules/Catalog/MMCA.Store.Catalog.API/Controllers/CategoriesController.cs:33). Framework coverage:OutputCacheEvictTagsTestspins both verbs, including theCancellationToken.Nonerule and the swallow-versus-throw split (MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/Caching/OutputCacheEvictTagsTests.cs:59-113), andOutputCacheEvictionHandlerTestspins 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
GetAllAsyncoverloads,GetAllForLookupAsyncandGetByIdAsync) 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) andMicrosoft.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.
- What it adds (
- Walkthrough
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)](:41).ReadActionNames(:45-50) holds the three base read names vianameofon the openEntityControllerBase<,,>; bothGetAllAsyncoverloads share one name.- The constructor takes
policyName(:57) and rejects null, empty or whitespace withArgumentException.ThrowIfNullOrWhiteSpace(:59).PolicyName(:64) exposes it.ByIdRouteName(:71) is an optionalinitproperty: null derivesGet{EntityName}ById, and empty or whitespace is rejected when the convention runs. Apply(ControllerModel)(:83) null-guards the model, finds the closedEntityControllerBase<,,>in the controller's base chain or throwsInvalidOperationExceptionnaming the controller (:87-89), throws whenByIdRouteNameis set but blank (:91-95), and derives the route name from the first generic argument, the entity type (:97). For every actionIsBaseReadaccepts (:99) it runsEnsureNoDeclaredAuthorization(:101), notes whether the action isGetByIdAsync(:103), and marks each selector, passing the route name only for the by-id read (:105-108).MarkSelector(:118) addsAllowAnonymousAttributewhen noIAllowAnonymousis present (:120-123), addsOutputCacheAttribute { PolicyName = PolicyName }when noOutputCacheAttributeis 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 anIAuthorizeDataand noIAllowAnonymous(:148); authorization declared on the controller class is deliberately left alone, the usual shape of gated writes beside public reads (:136-141).FindEntityControllerBase(:156) walksBaseTypeuntil it meets a generic type whose definition isEntityControllerBase<,,>(:158-161).IsBaseRead(:171) takes the method'sGetBaseDefinition().DeclaringType(:173), so an override still counts as a base read, and requires that declaring type to be a closedEntityControllerBase<,,>and the method name to be one ofReadActionNames(: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
EndpointMetadatarather 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) andSponsorsController(MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.API/Controllers/Sponsors/SponsorsController.cs:39). Framework coverage isPublicCachedReadsAttributeTests(MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/Caching/PublicCachedReadsAttributeTests.cs), and ADC asserts its declarations throughPublicCachedReadAssertions(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
recordinside 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 byGetV1()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
recordinside 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 theSupported/Deprecatedarrays the controller holds (ServiceInfoControllerBase.cs:32-33), so the body itself documents the version landscape, the same facts theapi-supported-versions/api-deprecated-versionsheaders 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
/ServiceInforoute is served by v1.0 (deprecated) and v2.0, selected via theapi-versionheader. - 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, andReportApiVersions = true(set inAddCommonApiVersioningon WebApplicationBuilderExtensions,WebApplicationBuilderExtensions.cs:47, inside the extension member declared atWebApplicationBuilderExtensions.cs:39) so responses carryapi-supported-versions/api-deprecated-versionsheaders (class doc,ServiceInfoControllerBase.cs:6-14). ADR-046 makes the point that a versioning claim which only ever shipsv1.0is untestable; this endpoint is what makes it testable. - Walkthrough
Supported = ["1.0", "2.0"]andDeprecated = ["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
ServiceNameso 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>andTIdentifierType : notnull(IEntityControllerBase.cs:17-18). The members:GetAllAsyncunpaged (IEntityControllerBase.cs:26), withfieldsprojection ([FromQuery]) and the two eager-load flags (IEntityControllerBase.cs:27-30).- the paged
GetAllAsyncoverload (IEntityControllerBase.cs:43), addingsortColumn/sortDirection,[Range(1, int.MaxValue)]-guardedpageNumber/pageSize(IEntityControllerBase.cs:49-50), and aDictionary<string, (string Operator, string Value)>of filters bound by QueryFilterModelBinder (IEntityControllerBase.cs:51). GetAllForLookupAsyncfor id/label dropdown data (IEntityControllerBase.cs:58).GetByIdAsync(IEntityControllerBase.cs:69), whoseincludeFKsdefaults totruefor the single-entity case (IEntityControllerBase.cs:71) while the collection endpoints default it tofalse(IEntityControllerBase.cs:28andIEntityControllerBase.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
ExportAsyncaction 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
- What it is: the read-write extension of IEntityControllerBase<TEntityDTO, TIdentifierType>: it adds
CreateAsyncandDeleteAsyncfor aggregate-root entities. - Depends on: IEntityControllerBase<TEntityDTO, TIdentifierType> (base interface), IBaseDTO<TIdentifierType> and ICreateRequest (constraints).
- Concept: the write half of the segregated controller contract introduced by IEntityControllerBase<TEntityDTO, TIdentifierType>.
[Rubric §1, SOLID]: only aggregate roots get a create/delete surface (TCreateRequest : ICreateRequest,IAggregateRootEntityControllerBase.cs:22), so child-collection controllers that implement only the read interface never expose mutation they should not own.[Rubric §9, API & Contract Design]: create returns the created DTO with a 201, delete returns 204, a consistent verb-to-status contract. - Walkthrough: extends the read interface (
IAggregateRootEntityControllerBase.cs:19) and adds two members:CreateAsync([Required] TCreateRequest request, ...)returning the created DTO with 201 (IAggregateRootEntityControllerBase.cs:28-30), andDeleteAsync(TIdentifierType id, ...)returning 204 No Content (IAggregateRootEntityControllerBase.cs:36-38). Like its base interface it declares no update member: PUT is added one rung higher by CrudEntityControllerBase<TEntity, TEntityDTO, TIdentifierType, TCreateRequest, TUpdateRequest> as a class member only, for the same "changing a shipped interface breaks every explicit implementer" reason. - Where it's used: implemented by AggregateRootEntityControllerBase<TEntity, TEntityDTO, TIdentifierType, TCreateRequest>.
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
ControllerBasedirectly, as the class doc atApiControllerBase.cs:16-21states). It carries the[ApiController]behavior, the sharedHandleFailurethat turns domain errors into RFC 9457 Problem Details responses (adding aRetry-Afterheader to a 429 or 503 that knows its wait), and the concurrency-token plumbing every controller that serves or conditionally writes a row reuses:SetConcurrencyETagand the twoHandleConditionalCommand*Asynchelpers. - 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.Reflectionplus aConcurrentDictionaryfor 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, andProblemDetailsserialization. - 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 byResult.Combinecarries several errors at once, and if the response status came fromerrors[0]then the order in which handlers appended errors would decide whether a caller saw 403 or 400.HandleFailuretherefore hands the whole list toErrorHttpMapping.GetStatusCode(IReadOnlyList<Error>)(ApiControllerBase.cs:63, mapping atMMCA.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), thenUnavailable(503),Unauthorized(401),Forbidden(403),TooManyRequests(429),Conflict(409),NotFound(404),UnprocessableEntity(422), and finallyInvariant/Validation(400). The 503 comes from the[ErrorType.Unavailable] = StatusCodes.Status503ServiceUnavailableentry 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 inMMCA.Common.Sharedon 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 onError.RetryAfter.SetRetryAfter(ApiControllerBase.cs:89) picks the error type whose hint it honours from the ranked status:TooManyRequestsfor a 429 (:92-95),Unavailablefor a 503 (:96-99), and for any other status it returns without a header (:100-103). It then takes the longestRetryAfteramong the errors of that type (:105-107, because retrying before the longest would only be refused again), and writesResponse.Headers.RetryAfterthroughRetryAfterHeader.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 weakETagon a read and hands it back asIf-Matchon the next write (see SupportsIfMatchAttribute); this base owns both halves so they cannot drift apart.SetConcurrencyETag(object? dto)(:136) isprotected, 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 writesConcurrencyETag.Format(rowVersion)underConcurrencyETag.ETagHeaderName(:144).ReadRowVersion(:250) reads the token off the row's RUNTIME shape: a shaped dictionary (afields=projection) is probed underrowVersion, thenRowVersion(:252-257); a typed value goes throughRowVersionProperties.GetOrAdd(dto.GetType(), FindRowVersionProperty)(:259). That staticConcurrentDictionary<Type, PropertyInfo?>(:30) resolves each runtime type once, since a type's shape cannot change at runtime (:25-29), andFindRowVersionProperty(:266-271) accepts only a public instance, readable, non-indexerbyte[]property named exactlyRowVersion. 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 : Resultat:169) andHandleConditionalCommandWithResponseAsync<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 tokenSupportsIfMatchAttribute.RequiredToken(HttpContext)decoded (:174,:204; an action without[SupportsIfMatch]throwsInvalidOperationExceptionand 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 throughHandleFailure(:217-218), awaits the optionalonSuccessfollow-up such as a cache eviction (:220-221), and answers 204 (:223).RunConditionalCommandWithResponseAsync(:227) unwraps the value withTryGetValue(:234-235), awaitsonSuccesswith it (:237-238), emits the refreshed token throughSetConcurrencyETag(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) isprotected 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 atApiControllerBase.cs:62). - Builds a
ProblemDetailswith that status and a fixed title/detail (ApiControllerBase.cs:65-70), attachesExtensions["errors"]viaErrorHttpMapping.BuildErrorsExtension(ApiControllerBase.cs:73), optionally localized through an IErrorLocalizer resolved withGetService(ApiControllerBase.cs:72, so a host without localization simply passesnull), sets theRetry-Afterheader when it applies (ApiControllerBase.cs:75), then returnsStatusCode(statusCode, problemDetails)(ApiControllerBase.cs:77).
- Null/empty guard (
- Why it's built this way: one
virtualmethod instead of aswitchin 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 itvirtuallets a subclass (EntityControllerBase<TEntity, TEntityDTO, TIdentifierType>) wrap it with logging without reimplementing the mapping. TheErrorHttpMappingmembers areinternal static(ErrorHttpMapping.cs:41,:54,:65), which is what lets UnhandledResultFailureFilter reuse the same ranked status mapping and the sameerrorsextension array for a failedResultthat an action returned without callingHandleFailure(UnhandledResultFailureFilter.cs:36and:47). The two bodies are deliberately not identical: the filter labels itsProblemDetailsTitle/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 byError.Codeand leavingCode/Type/Source/Targetverbatim so clients can still branch on them (ErrorHttpMapping.cs:60-63for the contract,ErrorHttpMapping.cs:65-74for 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 rawControllerBaseunless it is listed as exempt. The conditional-write helpers are used by ADC'sEventLifecycleController(MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.API/Controllers/Events/EventLifecycleController.cs:72,HandleConditionalCommandAsync) andQuestionsController(MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.API/Controllers/Questions/QuestionsController.cs:67,HandleConditionalCommandWithResponseAsync) among others, andSetConcurrencyETagdirectly by ADC'sSpeakersController(MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.API/Controllers/Speakers/SpeakersController.cs:301). Framework coverage isApiControllerBaseTests(MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/Controllers/ApiControllerBaseTests.cs) andApiControllerBaseConditionalCommandTests(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-confirmationandPOST confirm-email(ADR-116 is the identity-completions decision it implements; the route names are atEmailConfirmationControllerBase.cs:78and: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 theRateLimitPolicyAuthIpconstant 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 ownAuthControlleralready occupies the single-inheritance chain (AuthControllerBase to UserAccountAuthControllerBase<TChangePasswordCommand, TChangePreferencesCommand>), so confirmation ships as a separate controller routed to the sameAuthprefix, which reaches the gateway through the existing/Authroute (:13-20). The commands stay app-side, the same split PasswordResetAuthControllerBase<TForgotPasswordCommand, TResetPasswordCommand> uses: the derived controller supplies each throughCreateSendCommand(:61) andCreateConfirmCommand(:69), and the base reads the request back only throughICommandWithRequest<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 asprotectedSendHandler(:50) andConfirmHandler(:53). SendEmailConfirmationAsync(:85):[HttpPost("send-email-confirmation")],[Idempotent],[AllowAnonymous](:78-80); dispatchesCreateSendCommand(request)(:89-91) and returnsAccepted()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 aRefererheader (:98-101). It returnsNoContent()on success (:122-124) and declares 400, 401 and 429 (:111-113).
- Primary constructor (
- 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 arevirtualso an app can wrap them. Errors go through the sharedHandleFailure, 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 isEmailConfirmationControllerBaseTests(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 fromRequestServices), OidcClaimNormalizer (EmailVerifiedClaimType), OidcDiscoveryResponse, WebApplicationBuilderExtensions (RateLimitPolicyAuthIp), NonIdempotentAttribute, AuthenticationResponse, OAuthCodeExchangeRequest (Code,CodeVerifier), and Error; the Google, GitHub, and Apple OAuth packages,System.Security.Cryptography(RandomNumberGenerator,SHA256), andBase64Url. - 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, theRefererheader, 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 anIDistributedLockto 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).AddCachingalways registers a lock, Redis-backed when anIConnectionMultiplexeris 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 optionalcode_challengeandcode_challenge_methodfrom the query throughReadCodeChallenge(:496-514), so no action declares them as parameters, andChallengeProviderstashes the result underCodeChallengeItemKey = "codeChallenge"(:78, set at:485). OnlyS256with a well-formed challenge is kept: 43 base64url characters (CodeChallengeLength,:90;IsWellFormedCodeChallenge,:393-395). Any other challenge that was sent becomesInvalidCodeChallengeMarker = "!"(:87), which can never equal a computed challenge (:85-86), andCompleteAsyncrefuses such a flow before minting anything, redirecting withinvalid_code_challenge(InvalidCodeChallengeErrorCode,:83; check at:228-233). A bound flow's token pair waits underExchangeCacheKey(:380-383):oauth-exchange-pkce:{challenge}:{code}(ProofKeyExchangeCodePrefix,:82) instead ofoauth-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 sentCodeVerifiermust 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 byComputeCodeChallenge, 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 underOAuth:Oidc:<Name>(registered byExternalAuthExtensions.AddExternalAuthProviders,:146-147) is reachable through one parameterized route.OidcLogin(:160,[HttpGet("{provider}")]and[AllowAnonymous]at:156-157) looks the name up ignoring case throughOidcProviders?.Find(provider)and either challenges with the provider's registered name or answers 404 (:162-163). The literalgoogle,github, andappleroutes take precedence and those names are reserved, so an OIDC provider can never shadow them, and MAUI heads reach it through the sameauth/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 whoseDomainslist claims it throughFindByEmail(:183) and answers anOidcDiscoveryResponse(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 fromOidcProviders(:190), an optionalGetServicelookup, becauseAddExternalAuthProvidersregisters 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-minuteOAuthExchangeCodeLifetime(: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 separateAuthenticationProperties.Itemsslot 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 isOAuthReturnUrls.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 throughWithUiLinksasOAuth__UIBaseUrl(:58-61).GoogleLogin(:119),GitHubLogin(:129), andAppleLogin(:142) each take an optionalstatequery parameter alongsidereturnUrland carry[AllowAnonymous]directly (:118,:128,:141); all three, likeOidcLogin, callChallengeProvider(:469), which stashesreturnUrlunderOAuthReturnUrls.ReturnUrlItemKey(:476), the client'sstateunderClientStateItemKey(:481), and the proof-key challenge (:485) inAuthenticationProperties.Itemsand setsRedirectUri = "/auth/oauth/complete"(:471-488). Apple needs no special action here: its callback arrives as a cross-site form POST (response_mode=form_postis forced by the name/email scopes) that the middleware handles at/auth/callback/applelike any other provider (:133-136).CompleteAsync(:209) carries[AllowAnonymous](:207). It reads the UI base URL throughUIBaseUrlConfigKey(:211), and after the middleware handles the provider callback it reads the external cookie (:212), redirects to/login?error=oauth_failedwhen the ticket did not survive (:214-219, throughOAuthReturnUrls.ErrorRedirectUrlwith no native callback andFailedErrorCode = "oauth_failed",OAuthReturnUrls.cs:18), reads both the stashedreturnUrlandclientStateviaReadChallengeState(: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 withmissing_claimswhen the provider key or email is absent (:237-240), callsExternalLoginAsyncwith 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 hexexchangeCode(:260), stashes the token pair in the cache underExchangeCacheKey(exchangeCode, codeChallenge)(:261-262), and redirects with the code and, when the client sent one, the echoedstate(:264, URL built byBuildSuccessRedirectUrlat:273-287).ExtractClaims(:405-417) returns the provider name, key, email, both name parts, and anEmailVerifiedflag read fromOidcClaimNormalizer.EmailVerifiedClaimType. The flag fails closed: an absent or unparseable assertion reads as unverified (:413-415).ReadChallengeState(:270-271) is a safe-lookup helper (GetStringisTryGetValueunder the hood): the challenge normally stashes bothreturnUrlandclientState, but a ticket minted without them (custom challenge, provider round-trip edge) falls back to"/"andnullinstead of throwing on theItemsindexer.BuildSuccessRedirectUrl(:273-287) appends&state=(URL-escaped) only whenclientStateis non-empty (:280-282), for both the web redirect and the nativeOAuthReturnUrls.AppendQuerybranch (:284-286), so callers that never sent astatesee 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) usesGivenName/Surnameonly when both are non-blank (:424-427); otherwise it takes the full name from the GitHub display-name claimurn:github:name(GitHubDisplayNameClaimType,:97), because the GitHub handler mapsClaimTypes.Nameto the login handle, and falls back toClaimTypes.Namewhen that claim is blank (:429-435). It then splits throughSplitFullName(: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):
CompleteAsyncasksOAuthReturnUrls.GetAllowedMobileReturnUrl(configuration, returnUrl)(:225; defined atOAuthReturnUrls.cs:68), which returns the stashedreturnUrlas the redirect target only when it is an absolute URI whose custom scheme is listed inOAuth: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 returningnullfromGetSection) means "no allowlist", the exact pre-ADR-043 behavior (OAuthReturnUrls.cs:77-81). Failures route to the same surface throughOAuthReturnUrls.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,RedirectRemoteFailureAsyncat:31-43), so a round trip that fails before reachingCompleteAsynclands 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 takeslock:{cacheKey}throughTryAcquireAsync(:343-345), answers an invalid code if the lock cannot be taken within the wait (:346-349), and redeems insideawait usingon 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 throughICacheService.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 thannull, so the miss is detected via an emptyAccessToken(: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 onExchangeAsync(: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. ItsAppendQuery(OAuthReturnUrls.cs:88) deliberately usesOriginalStringrather thanToString(), becauseUrinormalization 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-suppliedstateis 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
ExternalLoginAsyncimplementation live outside this base (ExternalAuthExtensions, OidcProviderRegistry, and the app's IAuthenticationService); this file assumes they are wired, and what the service does with theemailVerifiedflag is decided there, not here. HowGetFromSharedStoreAsyncbypasses a local tier is the cache implementation's concern (ICacheService), not this file's. The proof key is optional: a client that sends nocode_challengegets 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;OidcLoginandDiscoverOidcProvidercarry no such attribute and declare their responses (:158-159,:179-180). TheExchangeAsyncdoc 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 derivesControllerBasedirectly (: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 injectedIDistributedLockto the base (OAuthController.cs:25).ExchangeAsyncis 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, andDiscoverOidcProvideractions are listed there too (AnonymousEndpointTests.cs:62-69), so each[AllowAnonymous]is an approved exception rather than an oversight. The Aspire hosting side writesUIBaseUrlConfigKeythroughIdentityLinkExtensions(MMCA.Common/Source/Hosting/MMCA.Common.Aspire.Hosting/IdentityLinkExtensions.cs). Framework coverage isOAuthControllerBaseTestsandOAuthControllerBaseOidcTests(MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/Controllers/Auth/), and ADC exercises the exchange end to end inOAuthExchangeTests(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 /cursorfor keyset paging,GET /changesfor a change feed), with filtering, sorting, pagination, field projection, one shared row-scoping hook, a fail-closed export behind an overridable caller gate, and anETagon 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 (throughIOptions<T>), CollectionResult<T>, PagedCollectionResult<T>, KeysetCollectionResult<T>, KeysetPageRequest, EntityChange<TEntityDTO, TIdentifierType>, BaseLookup<TIdentifierType>, QueryFilterModelBinder, OptInActionAttribute, SupportsCursorPagingAttribute, SupportsChangeFeedAttribute, Error andResult(the export caller gate), EntityCsvExporter<TEntityDTO>, QueryFieldService, and Specification<TEntity, TIdentifierType>;EntityQueryPipeline.MaxUnboundedResultLimitfor the page-size clamp; ASP.NET Core MVC,Asp.Versioning,TimeProvider, andILogger. - 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 anILogger, both null-guarded into theQueryService(:44) andLogger(:49) protected properties. MaxPageSize(:58-65) resolvesIOptions<ApplicationSettings>per-request fromHttpContext.RequestServices, falling back to 500, and clamps the result to the range 1 toEntityQueryPipeline.MaxUnboundedResultLimit(:63; the ceiling is defined asKeysetPageRequest.MaxPageSizeatMMCA.Common/Source/Core/MMCA.Common.Application/Services/Query/EntityQueryPipeline.cs:25, which is 1000 atMMCA.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) istypeof(TEntity).Name, used in log messages and in the export refusals.GetAllAsyncunpaged (:109,[HttpGet]at:106): resolves the read specification (:115), then delegates to the query service withpageNumber: 1andpageSize: MaxPageSize(:122-123), so even the "all" endpoint is capped, then eitherHandleFailureorOk.GetAllAsyncpaged (:157,[HttpGet("paged")]at:153): clamps withMath.Min(pageSize, MaxPageSize)(:168), unwraps the page withresult.TryGetValue(out var page)(:184, the miss routes toHandleFailureat:185) so the success branch reads a non-nullpagewith no!suppression, and on success writes PaginationMetadata into theX-Paginationresponse 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): returnsCollectionResult<BaseLookup<TIdentifierType>>, a lightweight id/label pair, with a[Required]nameProperty(:335) choosing the label. The sameTryGetValueunwrap (:346) feeds the lookups into theCollectionResultitems (:348-352).GetByIdAsync(:375,[HttpGet("{id}")]at:370):includeFKsdefaults totruefor the single-entity case (:377), and on success it calls the inheritedSetConcurrencyETag(result.Value)before returning (:396-397).GetCursorPageAsync(:421) andGetChangesAsync(:474) are covered as their own concept below.HandleFailureoverride (:498-512): logs the first error at Warning, guarded byLogger.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 throughSingleLine(: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: falseto the query service (for example:124), because a read endpoint never mutates what it loaded.
- Primary constructor (
- 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: bothGetAllAsyncoverloads,GetAllForLookupAsync,GetByIdAsync,ExportAsync,GetCursorPageAsync, andGetChangesAsync(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 anawaitin before the query. An override with nothing to await returnsValueTask.FromResult(...)and allocates nothing. - It narrows, it never replaces (
:664-668). The query service ANDs the specification with the caller'sfiltersdictionary andfieldsprojection, 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 onGetByIdAsyncat: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).GetAllForLookupAsynchas no specification parameter, so the scope travels asspecification?.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 returnsnullby default and is whatGetReadSpecificationAsyncreturns 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 anawaitoverrides 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/exportrather than handing every caller the whole table (:699-702). See ADR-033 for the ownership model this hook reproduces in the query.
- It is asynchronous because row scoping usually is (
- 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.ExportAsyncis 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 tonullandAllowUnscopedExportisfalse, it returns before any query runs (:287-288) with theError.Forbiddenbuilt byUnscopedExportRefused(:717-722), whichHandleFailureturns into a 403 Problem Details carrying the codeExportRowScopeRequiredErrorCode = "Export.RowScopeRequired"(:541; the 403 is declared on the action at:264). The error message names the three ways out: overrideGetReadSpecificationAsync, overrideGetExportSpecification, or opt in.- A caller gate runs before the scope.
AuthorizeExport()(protected virtual Result, defaultResult.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), typicallyIsPrivileged ? Result.Success() : ExportNotPermitted(), or returning an existing gate's ownResultso that gate's error code survives.ExportNotPermitted()(:576-581) builds the standardError.ForbiddenwithExportNotPermittedErrorCode = "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 andAllowUnscopedExport(:563-565). AllowUnscopedExport(protected virtual bool, defaultfalse,: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: returnnullfrom 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).
- A caller gate runs before the scope.
- 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:GetCursorPageAsyncneeds SupportsCursorPagingAttribute (:416-417) andGetChangesAsyncneeds SupportsChangeFeedAttribute (:469-470). Both clamp the page size toMaxPageSize(:432,:480), read the same row-scoping hook, and unwrap withTryGetValueintoOkorHandleFailure(:442-444,:487-489).GET /cursor([HttpGet("cursor")],:416) returns one seek page after an opaquecursor, ordered bysortColumnwithIdas the tie-break, plus the next page's cursor (null on the last page). It validates the sort direction first (:428-430) and callsQueryService.GetPageByCursorAsyncwith 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 aftersince, ordered by(LastModifiedOn, Id), each an upsert carrying the DTO or a tombstone for a soft-deleted row (:448-451), throughQueryService.GetChangesSinceAsync(:484-485). The bound is inclusive, so a client pages with the samesinceuntil the cursor is null, then keeps the largestchangedOnas its nextsince, 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.ExportAsyncanswers 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 anAccept: text/csvformatter wrong here (:198-203): the public output-cache policy varies by query string but not byAccept, so a cached JSON body could be replayed to a CSV request, andAddAPIsetsReturnHttpNotAcceptable = 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>.ValidateFieldsrejects afields=request naming a property the CSV cannot render, as anError.InvalidEntityFieldfailure, 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:
ExportAsyncbuilds a fetch delegate that callsQueryService.GetAllAsync(:295-306) atpageSize = Math.Max(1, MaxPageSize)(:291) and hands it,beginResponse, andonFailureAfterStarttoEntityCsvExporter<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
includeChildrenparameter, but the fetch delegate loads children whenExportIncludeChildrenis overridden totrueand foreign keys when either the request'sincludeFKsorExportIncludeFKsis set (:296-297). Both areprotected virtual booldefaulting tofalse(: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 typetext/csv; charset=utf-8(CsvContentType,:529, set at:732), aContent-Dispositionattachment whose file name is{controller}-{yyyyMMdd'T'HHmmss'Z'}.csvbuilt invariantly from an injectedTimeProvider(:730,:733,BuildExportFileNameat:744-747, prefixExportFileNamePrefixat:619-642), andX-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 rowsrecord (marker built by EntityCsvExporter<TEntityDTO>.TruncationMarker; the remarks at:220-226name the same line) and a mid-stream query failure ends with an incomplete marker plus a Warning log (LogExportPageFailure,:755-767, wired asonFailureAfterStartat:311), whose error code and message pass through the sameSingleLineasHandleFailure's (:765-766). A failure on the FIRST page, before anything was written, still returns Problem Details throughHandleFailure(:315), which is exactly what "constructing the writer sends nothing" protects on the exporter side. - Column resolution is derived, not invented:
EntityCsvExporter<TEntityDTO>.ResolveColumnstakes the shaped keys of the first row, so the CSV columns for a givenfields=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.UnexportablePropertyNameson that type drops the properties that cannot render a faithful scalar cell,byte[]/ReadOnlyMemory<byte>concurrency tokens and every collection type exceptstring, 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 invariantToString. See EntityCsvExporter<TEntityDTO> for the full walkthrough.
- A dedicated route, not content negotiation (
- 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
ETagemission 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, matchingApplicationSettings.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 exposespagedanonymously exposesexportanonymously once it scopes the rows or opts in, unless it narrows the audience throughAuthorizeExport; the symmetry is deliberate and documented (:206-210). The fail-closed rule applies toExportAsynconly: 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) andCategoryItemsController(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 asyncGetReadSpecificationAsyncby ADC'sSpeakersController(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-scopedShoppingCartsController(MMCA.Store/Source/Modules/Sales/MMCA.Store.Sales.API/Controllers/ShoppingCartsController.cs:200); the synchronousGetExportSpecificationby ADC'sEventsController(EventsController.cs:72) andSessionQuestionAnswersController(SessionQuestionAnswersController.cs:111) and by Store'sOrdersController(MMCA.Store/Source/Modules/Sales/MMCA.Store.Sales.API/Controllers/OrdersController.cs:241).AllowUnscopedExportis overridden two ways. Unconditionaltrueon reference and catalog data: ADC'sConferenceCategoriesController(ConferenceCategoriesController.cs:44),QuestionsController(QuestionsController.cs:43) andCategoryItemsController(CategoryItemsController.cs:74), and Store'sProductsController(MMCA.Store/Source/Modules/Catalog/MMCA.Store.Catalog.API/Controllers/ProductsController.cs:51),CategoriesController(CategoriesController.cs:48),InventoryItemsController(InventoryItemsController.cs:43) andCustomersController(MMCA.Store/Source/Modules/Identity/MMCA.Store.Identity.API/Controllers/CustomersController.cs:48), whose export sits behindCustomersManageand whose list endpoints are Admin-only rather than row-scoped (:90-104). Per principal, where the read hook returnsnullto a privileged caller: ADC'sSpeakersController(SpeakersController.cs:126),SessionsController(SessionsController.cs:96),RoomsController(RoomsController.cs:149),EventsController(EventsController.cs:80),SessionQuestionAnswersController(SessionQuestionAnswersController.cs:123) and their siblings, and Store'sOrdersController(OrdersController.cs:249) andShoppingCartsController(ShoppingCartsController.cs:209). No ADC or Store controller overridesAuthorizeExporttoday. Framework coverage lives inEntityControllerBaseTests,EntityControllerBaseExportTests(opt-in doubles atEntityControllerBaseExportTests.cs:692and:672),EntityControllerBaseETagTests, andEntityControllerBaseReadSpecificationTests(MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/Controllers/), the last of which drives both hooks through purpose-built doubles (EntityControllerBaseReadSpecificationTests.cs:358and: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 aDeleteAsync(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;CreateAsynccarries[Idempotent](AggregateRootEntityControllerBase.cs:76, beside[HttpPost]at:75), which wires IdempotencyFilter so a retried POST carrying the sameIdempotency-Keyreplays the original 201 (flaggedX-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-secondLockWait(IdempotencyFilter.cs:107, awaited atIdempotencyFilter.cs:269) is answered with 409 Conflict rather than a replay (IdempotencyFilter.cs:323-328). Because the fitness rule reads attributes withinherit: 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, notablyTEntity : AuditableAggregateRootEntity<TIdentifierType>) enforce at compile time that only aggregate roots reach this create/delete surface. - Walkthrough
- Primary constructor (
AggregateRootEntityControllerBase.cs:29-40): four parameters, wherequeryServiceandloggerare forwarded to the EntityControllerBase<TEntity, TEntityDTO, TIdentifierType> base (:40), pluscreateHandleranddeleteHandler. Theloggeris typedILogger<EntityControllerBase<...>>, not of this class, becauseILogger<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]). CreateHandlerproperty (:50):protected, so a derived controller that overridesCreateAsyncto build a more specific command can still reach the handler.deleteHandlerstays a captured constructor parameter, used directly at:115, because nothing overrides delete today.GetByIdRouteName(:57): aprotected virtual stringdefaulting to$"Get{EntityName}ById", the route nameCreateAsynclinks 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 withresult.TryGetValue(out var created)(:86), returningHandleFailureon a miss (:86-89), so the success path reads a non-nullcreatedwith no!suppression. On success it resolves theLocationitself, before returning (:93-95), and returnsCreated(location, created)(:97). The remarks (:67-74) give the reason: aCreatedAtRoutenaming 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); otherwiseCollectionMemberPath(:126-131) appends the escaped id to the request's own path (PathBase + Path, trailing slash trimmed), a host-relativeLocationthat RFC 9110 permits and where the inheritedGET {id}answers. Each branch is parsed with its ownUriKind, becauseRelativeOrAbsolutereads/x/1as a file URI on Unix (:91-92).DeleteAsync(:111-120):[HttpDelete("{id}")](:106); builds a DeleteEntityCommand<TEntity, TIdentifierType>, dispatches it, and returnsNoContent()on success. Delete here means soft-delete: the handler loads the aggregate and calls itsDelete()method, so the domain, not the controller, decides whether the removal is allowed.
- Primary constructor (
- 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) andSessionsController(SessionsController.cs:58), and Store'sCustomersController(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 inAggregateRootEntityControllerBaseTests(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 andAsp.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 noUpdateAsyncmember, 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'sIf-Matchheader into the command'sRowVersion, 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 anETagon the read, back asIf-Matchon the write. On success the refreshed token is emitted through the inheritedSetConcurrencyETag(: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 whichqueryService,createHandler,deleteHandler, andloggerare forwarded straight to the aggregate-root base (:66-67); onlyupdateHandleris new. The same narrowly-scoped#pragma warning disable S6672covers the non-covariantILogger<T>category (:63-65). UpdateHandlerproperty (:77):protected, for a derived controller that overridesUpdateAsyncentirely rather than wrapping it.UpdateAsync(:97-113):[HttpPut("{id}")],[Idempotent],[SupportsIfMatch](:87-89), body bound[FromBody, Required](:99). It reads the decoded token withSupportsIfMatchAttribute.RequiredToken(HttpContext)(:102), dispatches an UpdateEntityCommand<TEntity, TUpdateRequest, TIdentifierType> carrying id, request, and row version (:104-106), and on success sets the freshETagand returnsOk(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.
- Class attributes (
- 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
CachePrefixthrough the caching decorator (:38-43). An app that also uses ASP.NET output caching overridesUpdateAsync, awaitsbase.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 aTestCrudControllerdouble (: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 theRateLimitPolicyAuthIpconstant on WebApplicationBuilderExtensions;Microsoft.AspNetCore.RateLimitingfor[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 providesvirtualendpoints, a derived controller overrides only what differs), but the load-bearing idea here is[Rubric §11, Security]: anti-spray throttling is on by default.LoginAsyncandRegisterAsynccarry[EnableRateLimiting(WebApplicationBuilderExtensions.RateLimitPolicyAuthIp)](AuthControllerBase.cs:78and: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, checkresult.IsFailure, returnHandleFailure(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) exposesAuthenticationServiceandCurrentUserServiceasprotectedproperties (:54and:57) so derived controllers can reach them for extra endpoints. ClientIpAddress(:64) andClientUserAgent(: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 configuredUseForwardedHeaders(: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); callsLoginAsync(request, ClientIpAddress, ClientUserAgent, ...)(:86-88) and returnsOkorHandleFailure. 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 returnsRegistrationResult(result, request.Email)(:117). It isvirtualso a module can override it to pass further context (:96-98). Its declared responses are 201 with the token pair, 202 with aRegistrationPendingResponse(:105), 429, 400 and 409 (:104-108), matching every statusRegistrationResultcan answer.RegistrationResult(:132) is theprotectedmapping a derivedRegisterAsyncoverride returns instead of writing the201itself, so the pending case never answers a token-less201(:121-127). After argument guards (:134-135) a failure goes toHandleFailure(:137-140); a value for whichIsConfirmationPending()holds (the account exists but the host requires a confirmed address first) setsCache-Control: no-store(:142-147) and answers202 Acceptedwith aRegistrationPendingResponsecarrying the trimmed email (:149); otherwise it answers201 Createdwith 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 thanRefreshSessions:ReuseGraceSecondsago is answered409 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 anEndSessionRequestand anIAuthSessionIssuerinjected with[FromServices](:206-208), guards both (:210-211), callsSignOutByRefreshTokenAsync(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); readsCurrentUserService.UserId, returnsUnauthorized()if null (:230-232) as a defensive guard even though[Authorize]should already prevent a null id, then callsRevokeAllSessionsAsyncand returnsNoContent()(: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 ownsidclaim throughRevokeSessionByIdAsync, so the account stays signed in on its other devices, and falls back toRevokeAllSessionsAsyncfor a token minted beforesidshipped (:264-266). A failure made only ofNotFounderrors 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 ownsidclaim, read withUser.FindSessionId()(:296), so no client state is involved and nothing has to send a refresh token to a read endpoint; a token minted beforesidshipped 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 anIAuthSessionIssuerinjected 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 nosidanswers 404Auth.SessionNotFound(:337-344); otherwise it callsRecordDeviceAsync(: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 throughGetSignInsAsyncwith the currentsid(: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 underusers: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 whileViewAs:Enabledis false or this host does not hold the grant store (:420-423), 400ViewAs.NotViewingwhen the token carries no parsable grant and actor claim (:425-429), maps anEndAsyncfailure throughHandleFailure(:431-435), and on success writes the grant-ended marker to the shared cache throughViewAsEndedMarker.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 (codeAuth.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).
- Primary constructor (
- 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 methodsvirtual(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 callingAddCommonRateLimiting()(MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/WebApplicationBuilderExtensions.RateLimiting.cs:403, whoseauthIpPermitLimitdefaults 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, andEndSessionAsyncgives 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-processTestServer, integration tests):AuthIpRateLimitPartitionreturnsRateLimitPartition.GetNoLimiter("__unknown-ip")in that case (WebApplicationBuilderExtensions.RateLimiting.cs:338-339), a fail-open posture matching the global limiter and documented atWebApplicationBuilderExtensions.RateLimiting.cs:460-467. WithRateLimitingSettings.Distributedand 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).EndSessionAsyncis 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>.RegisterAsyncandEndSessionAsyncare among the anonymous endpoints the framework's architecture gate lists by name (MMCA.Common/Tests/Architecture/MMCA.Common.Architecture.Tests/Api/AnonymousEndpointTests.cs:27and: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 inAuthControllerBaseRateLimitTests.
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-passwordandPOST 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 theRateLimitPolicyAuthIpconstant on WebApplicationBuilderExtensions; ASP.NET Core MVC,Microsoft.AspNetCore.Authorization, andMicrosoft.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
AuthControlleralready spends it on UserAccountAuthControllerBase<TChangePasswordCommand, TChangePreferencesCommand>. Recovery therefore ships as its own base that the app routes to the sameAuthprefix ([Route("Auth")]on the concrete controller), soPOST /Auth/forgot-passwordrides the gateway's existing/Authroute with no gateway change (class doc,PasswordResetAuthControllerBase.cs:13-18; the ADC subclass records the same reasoning atMMCA.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.
- Why a sibling controller and not two more actions on the auth base. C# gives a class one base, and each app's
- Walkthrough
- Type parameters and constraints (
:43-47):TForgotPasswordCommand : ICommandWithRequest<ForgotPasswordRequest>andTResetPasswordCommand : 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 areIUserScopedCommand<TRequest>: recovery has no authenticated user to scope to. - The two handlers become
protectedproperties (:50and:53), the same convention the other auth bases follow, so a derived controller can dispatch them itself for an extra endpoint. CreateForgotPasswordCommand(request)(:61) andCreateResetPasswordCommand(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:36and: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 returnsAccepted()on success orHandleFailure(:86-92).ResetPasswordAsync(:107) mirrors it at[HttpPost("reset-password")](:99-102), declaring 204/400/401/429 (:103-106) and returningNoContent()on success (:111-117).
- Type parameters and constraints (
- 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'sResetPasswordCommandimplements onlyICommandWithRequest<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 isPasswordResetAuthControllerBaseTests(MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/Controllers/Auth/PasswordResetAuthControllerBaseTests.cs:23), which drives aTestPasswordResetControllerdouble (: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, andGET 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 andMicrosoft.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
Usertype while Store's do not (remarks,UserAccountAuthControllerBase.cs:22-31), but today ADC'sChangePasswordCommandimplements onlyICommandWithRequest<ChangePasswordRequest>andIUserScopedCommand<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 implementsICacheInvalidating, 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 theIUserScopedCommand<TRequest>abstraction and never on either app's concrete record.[Rubric §2, Design Patterns]: the twoCreate*Commandoverrides are the pattern's primitive operations, and their implementations really are one line each. - Walkthrough
- Type parameters and constraints (
:41-49):TChangePasswordCommand : IUserScopedCommand<ChangePasswordRequest>andTChangePreferencesCommand : 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
protectedproperties (: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) andCreateChangePreferencesCommand(userId, request)(:78-80) are the two abstract factories. Both take aUserIdentifierType, the solution-wide identifier alias, so the base never has to know whether an app's user key is anintor aGuid.ChangePasswordAsync(:92):[HttpPut("password")]plus[Authorize](:87-88). It readsCurrentUserService.UserId, returnsUnauthorized()when null (:96-98), then dispatchesCreateChangePasswordCommand(userId.Value, request)through the handler (:100-102) and returnsNoContent()orHandleFailure. 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.RevokeAsynctakes.
- Type parameters and constraints (
- 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 overrideRegisterAsyncor 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 byUserAccountAuthControllerBaseTests(MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/Controllers/Auth/UserAccountAuthControllerBaseTests.cs:17), which drives the base through aTestUserAccountAuthControllerdouble (: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-cardinalityaction, 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) andViewAsStart = "view_as_start"(:41).- One static
Meterbuilt from the name (AdminActionMetrics.cs:43) and oneCounter<long>namedmmca.auth.admin_actionwith 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 aKeyValuePairtag.
- 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 statickeeps 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
ViewAsStartafter a successfulStartViewAsAsync(UsersAdminControllerBase.cs:196) and passesLock,UnlockandRoleChangeinto itsCompletedhelper, which records on success (UsersAdminControllerBase.cs:496); MachineClientsControllerBase recordsMachineClientCreate(MachineClientsControllerBase.cs:94) andMachineClientRotate(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.degradedis 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;Meteris 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), andidempotency.degraded(IdempotencyMetrics.cs:51-54). - The three conflict shapes are separated by a tag rather than by separate counters:
ConflictKindTag = "kind"(IdempotencyMetrics.cs:37) carriesConflictKindBodyMismatch = "body_mismatch"(IdempotencyMetrics.cs:24),ConflictKindTargetMismatch = "target_mismatch"for a key reused against a different concrete path or query (IdempotencyMetrics.cs:29), orConflictKindInFlight = "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 aKeyValuePair(IdempotencyMetrics.cs:67-68), andRecordDegraded()(IdempotencyMetrics.cs:74).
- Why it's built this way:
internal statickeeps 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, becauseMMCA.Common.Aspirehas no reference toMMCA.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:
RecordDegradedon a faulted lock acquisition (IdempotencyFilter.cs:274), a failed cache read (IdempotencyFilter.cs:403) and a failed cache write (IdempotencyFilter.cs:503);RecordConflictfor an in-flight duplicate (IdempotencyFilter.cs:286), a body mismatch (IdempotencyFilter.cs:413) and a target mismatch (IdempotencyFilter.cs:424);RecordReplayedon 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 (
LocationandETag), 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
recordwhose 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:
Locationso a replayed201 Createdstill says where the resource is, andETagso a replayed response still carries its concurrency token (parameter docs,IdempotencyRecord.cs:14-20; replay atIdempotencyFilter.cs:435-441). The replay path addsX-Idempotent-Replayitself (IdempotencyFilter.cs:433). Second,RequestBodyHashis 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,RequestTargetHashbinds the record to the concrete resource: the cache key holds only the route template, soPUT /orders/1andPUT /orders/2share 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).StatusCodeis the original response's code, defaulting to 200 when anObjectResultcarried none (IdempotencyFilter.cs:525).ResponseBodyis non-nullable: anObjectResultstoresobjectResult.Valueserialized with the host's MVC JSON options (falling back toJsonSerializerOptions.Web), and storesstring.Emptywhen the value is null (IdempotencyFilter.cs:484-485and:530), while a body-less 2xx such as the 204 fromNoContent()also storesstring.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.RequestBodyHashis the lowercase hex SHA-256 of the request body (IdempotencyFilter.cs:637-648).Locationis resolved only for anObjectResult(IdempotencyFilter.cs:535) and isnullwhen the response carried none;ETagis whatever the action wrote to the response headers,nullwhen empty (IdempotencyFilter.cs:517-518).RequestTargetHashis the lowercase hex SHA-256 of the request'sPathvalue concatenated with itsQueryStringvalue, exactly as received (IdempotencyFilter.cs:658-662), and both cacheable result shapes store it (IdempotencyFilter.cs:537and:549). The parameter docs note thatLocationandRequestTargetHasharenullfor records written before each field existed (IdempotencyRecord.cs:16andIdempotencyRecord.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 atIdempotencyFilter.cs:539-541names 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 itsBuildRecord(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
Idempotencyconfiguration section. It carries exactly one knob: how long a cached idempotent response is retained. - Depends on:
System.ComponentModel.DataAnnotationsfor the[Range]attribute; bound throughMicrosoft.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:
SectionNameis apublic static readonly stringequal to"Idempotency"(IdempotencySettings.cs:12), so the binding key is a symbol rather than a magic string at the call site.CacheExpirationHoursdefaults to 24 (IdempotencySettings.cs:16) and is constrained by[Range(1, 168)](IdempotencySettings.cs:15), one hour to one week. The property isinit-only, so the value is fixed once bound. - Why it's built this way:
AddAPIbinds the section only when the caller passes anIConfiguration, and when it does it chains.ValidateDataAnnotations().ValidateOnStart()(MMCA.Common/Source/Presentation/MMCA.Common.API/DependencyInjection.cs:78-81), so an out-of-rangeCacheExpirationHoursfails 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 deliberateGetService, notGetRequiredService: when the options are absent (theAddAPIoverload called with no configuration) the filter falls back to its hard-coded 24-hourDefaultExpiration(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-Keycontract, 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 thePostActionsDeclareIdempotencyIntentfitness 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 theNonIdempotentAttributeNameconstant atArchitectureRules.Idempotency.cs:9so 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), exposingpublic 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:
IDisabledFeaturesHandlerandFeatureGateAttributefromMicrosoft.FeatureManagement.Mvc(NuGet);ProblemDetails,ObjectResult, andStatusCodesfrom 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.HandleFailureshape 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) setscontext.Resultto anObjectResultwrapping aProblemDetailswithStatus = 404and a fixed title/detail ("Feature not available",DisabledFeatureHandler.cs:19-24), and also sets the outerStatusCode = 404(DisabledFeatureHandler.cs:26) so the response code and the body agree. It returnsTask.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
featuresparameter is available but unused for that reason. - Where it's used: registered as the app's
IDisabledFeaturesHandlersingleton insideAddAPI(MMCA.Common/Source/Presentation/MMCA.Common.API/DependencyInjection.cs:110, immediately afterservices.AddFeatureManagement().WithTargeting<CurrentUserTargetingContextAccessor>()onDependencyInjection.cs:108-109); invoked byMicrosoft.FeatureManagement.Mvcwhenever a[FeatureGate]action is hit with its flag disabled. In the framework itself that covers DataExportControllerBase<TQuery> whilePrivacyFeatures.DataExportis off (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Privacy/DataExportControllerBase.cs:60) and the three notification controllers gated onNotificationFeatures.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, andTargetHash, 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 inOnActionExecutionAsyncfromComputeRequestBodyHashAsyncandComputeRequestTargetHash(IdempotencyFilter.cs:142-144), then passed unchanged intoExecuteUnderProcessLockAsync(:223),ExecuteUnderDistributedLockAsync(:262),ExecuteAndStoreAsync(:310),TryReplayAsync(:394),TryStoreAsync(:479) andBuildRecord(:514).TryReplayAsynccomparesBodyHashfirst (:411) andTargetHashsecond, only when the stored record carries one (:421-422);BuildRecordwrites both halves into the record (:534and:537for anObjectResult,:547and:549for 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 structadds 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-Keyheader; 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 bothIAsyncActionFilterandIAsyncResourceFilter(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:145andIdempotencyFilter.cs:153); IdempotencyRecord; RequestFingerprint; IdempotencySettings viaIOptions<>; 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 MVCIOptions<JsonOptions>resolved per request when present),IUrlHelperFactoryfor reconstructing a created result'sLocation, andILoggerwith 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.- 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. - 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 atIdempotencyFilter.cs:239-242), so the primary path uses an IDistributedLock and the stripe is only the fallback for a host that registers none. - 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/1thenPUT /orders/2), which the cache key alone cannot tell apart because it holds only the template (IdempotencyFilter.cs:44-54).
- Double-check locking (doc comment,
- Walkthrough
- Constants and shared state:
IdempotencyKeyHeaderdelegates toIdempotencyHeaders.IdempotencyKey(IdempotencyFilter.cs:76, defined atMMCA.Common/Source/Core/MMCA.Common.Shared/Http/IdempotencyHeaders.cs:19as"Idempotency-Key");CacheKeyPrefixreturns"idempotency:"(IdempotencyFilter.cs:78);DefaultExpirationof 24 hours (IdempotencyFilter.cs:83);LockTimeToLiveof 30 seconds andLockWaitof 5 seconds (IdempotencyFilter.cs:100andIdempotencyFilter.cs:107), sized so a slow action finishes under its own lock while a dead replica does not block a retry for long; andEmptyBodyHash, 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 callsRequest.EnableBuffering()only when the header is present (IdempotencyFilter.cs:124-125), so ordinary traffic on an[Idempotent]action pays nothing, then awaitsnext()(IdempotencyFilter.cs:127). - Action stage.
OnActionExecutionAsync(IdempotencyFilter.cs:131): no header means straight through tonext()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-152states 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 takesEmptyBodyHashrather than throwing (:190-191), which leaves such a request deduplicated on its key alone. Otherwise it rewinds to 0, hashes withSHA256.HashDataAsync, and rewinds again (:193-195) because model binding still has to read the whole body.ComputeRequestTargetHash(IdempotencyFilter.cs:208-212) hashesPath.Valueconcatenated withQueryString.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 honoringRequestAbortedinside ausingso 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_flightconflict and answer withInFlightDuplicateResult()(:280-292). That helper (:320-329) is a 409ProblemDetailstitled "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 usingon the handle (:294), double-check (:297), then execute and store (:300).
- The lock backend faults: counted on
ExecuteAndStoreAsync(IdempotencyFilter.cs:305-314) is the two-line shared tail of all three paths: awaitnext(), thenTryStoreAsyncthe 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 whoseRequestBodyHashdiffers from the fingerprint'sBodyHash(an ordinal comparison,:411) yields abody_mismatchconflict andBodyMismatchResult()(: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 aRequestTargetHashdifferent from the fingerprint'sTargetHashyields atarget_mismatchconflict andTargetMismatchResult()(: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), appendsX-Idempotent-Replay: true(:433, name fromIdempotencyHeaders.cs:25), restores the storedLocationandETagheaders 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 bareStatusCodeResultwhen the stored body is empty or aContentResultwithapplication/jsonotherwise (: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 MVCJsonOptionsand falls back toJsonSerializerOptions.Webonly 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 andDefaultExpirationotherwise (:491-495), and swallows a failingSetAsyncafter 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 anyETagthe action wrote to the response, storingnullwhen it is empty (:517-518). AnObjectResultwith a non-2xx status returnsnull(:525-527); a 2xx one stores its value serialized with the resolved options, or the empty string when the value is null so anAccepted()with no payload replays as a body-less status rather than a JSONnull(:522-523and:530; a plain comment at:529records that serializing to a string is correctly synchronous, with no analyzer suppression around the call), together with the body hash, the resolvedLocation, theETagand the target hash (:531-537). AStatusCodeResultwith a 2xx status, which is whatNoContent(),OkResultandStatusCode(int)produce, stores the empty string plus the body hash, theETagand the target hash (:542-550). Everything else, including every redirect or file result, returnsnulland is not stored (:552-553);IsSuccessis the>= 200 and < 300test (:584).ResolveLocation(IdempotencyFilter.cs:561-582) exists because a created result writes itsLocationwhen the RESULT executes, after this filter has already run, so the filter computes it the same way the result will (:557-560): aCreatedResultgives itsLocationdirectly (:565-566), aCreatedAtRouteResultgoes throughIUrlHelperFactoryandLink(:568-571), aCreatedAtActionResultthroughIUrlHelperFactoryandActionwith the request's scheme and host (:573-577), and any otherObjectResultyieldsnull(:579-580).BuildCacheKey(IdempotencyFilter.cs:598-612) is the security-relevant part: the subject is the caller's user-id claim viaFindUserIdValue()(:600,MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/ClaimsPrincipalExtensions.cs:26, which readssuband falls back to the mappedNameIdentifier) 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 asidempotency:{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.
- Constants and shared state:
- 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 answeringNoContent()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
LocationandETagheaders stored on IdempotencyRecord (IdempotencyFilter.cs:435-441); any other header the original action set is not captured and is therefore not reproduced, andX-Idempotent-Replayis added.Locationis reconstructed only forCreatedResult,CreatedAtRouteResultandCreatedAtActionResult, and for the two URL-helper cases only when anIUrlHelperFactoryis registered (IdempotencyFilter.cs:569and:575); aLocationthe 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:76and: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 theIdempotency-Keyreplay behavior; leaving it off means the action is never deduplicated. - Depends on:
ServiceFilterAttributefrom 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 registeredAddScopedand 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, whichAddAPIdoes (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 noIdempotency-Keyheader 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, whosePostActionsDeclareIdempotencyIntentrule 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 withinherit: 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 protectedReaderproperty (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.ViewAuditTrailon the class (:47). Externals: ASP.NET Core MVC andSystem.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 codeAuditHistory.UnknownEntity(:51, returned at:106-113) and a blank key answers 400 withAuditHistory.KeyRequired(:54, returned at:115-122), both as Problem Details throughHandleFailure.[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 aparams Type[]of served types, null-guards both, and buildsAuditedEntityTypes(:82), a dictionary keyed by simple type name withStringComparer.OrdinalIgnoreCase(:136). BuildAliasMap(:131-150) fails construction fast: it throwsArgumentExceptionfor an empty list (:134), a null entry (:140), a type that does not implementIAuditedEntity(: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) takespageas[Range(1, int.MaxValue)]defaulting to 1 (:102) andpageSizeas[Range(1, 500)]defaulting to 50 (:103). After the two refusals it callsReader.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 withOk(entries)(:127), declared asIReadOnlyList<AuditHistoryEntryDTO>(:94).
- The constructor (
- 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 throughIAuditHistoryUIService(MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auditing/IAuditHistoryUIService.cs); the framework's coverage isAuditHistoryControllerBaseTests. - Caveats / not-in-source: the
[Range]bounds are enforced by MVC model validation; whetherIAuditTrailReaderclamps 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 protectedAdministrationproperty (:41), FeatureFlagStatusResponse and SetFeatureFlagOverrideRequest on the wire, and HasPermissionAttribute with AdministrationPermissions.ManageFeatureson 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 toIFeatureFlagAdministrationService(DIP), mapping a failedResultthroughHandleFailureand 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) returnsIReadOnlyList<FeatureFlagStatusResponse>fromAdministration.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 callsAdministration.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 isIFeatureFlagAdminUIService(MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Administration/IFeatureFlagAdminUIService.cs); the framework's coverage isFeatureFlagsControllerBaseTests.
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 BCLTimeProvider, 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.ManageUserson 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 byg.StatusAt(now)(:90) against anowtaken from the injectedTimeProvider(: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 onManageUsers(:39) and dark (404) unless bothViewAs:EnabledandHostsGrantStoreare 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 callsgrants.ListAsync(request, now, cancellationToken)for a(items, total)pair (:76).- It projects each grant to a
ViewAsGrantSummaryResponsecarrying 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)andMath.Max(request.PageNumber, 1)(:94-97), with a comment noting the store clamps the same way (:93). It returnsOk(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 isIViewAsGrantsUIService(MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Administration/IViewAsGrantsUIService.cs); coverage isViewAsGrantsAdminEndpointTests. 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
ITargetingContextAccessorthat supplies the audience (a user id plus that user's groups, including atenant:<tenantId>group when the request resolved a tenant) which the feature-managementTargetingfilter evaluates, read from the current HTTP request. - Depends on:
Microsoft.FeatureManagement.FeatureFilters.ITargetingContextAccessorandTargetingContext,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 byAddAPI; a sibling of DisabledFeatureHandler in the same folder. - Concept introduced: a percentage rollout that is sticky per user rather than random per request. A
Percentagefeature 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. TheTargetingfilter 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 standardsubclaimTokenServiceemits, read through ClaimsPrincipalExtensions so theClaimTypes.NameIdentifierform the bearer handler maps it to resolves identically, the same readCurrentUserServiceand 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 lifetimeWithTargetinggives it), so it cannot take the scopedICurrentUserService; it readsIHttpContextAccessorinstead and takes the roles straight off the principal, which the doc calls out explicitly (:25-26). That role read isClaimsPrincipalExtensions.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'sITenantContexthas resolved a tenant (ADR-073), the groups also carrytenant:<tenantId>, so an audience group such astenant:acmeturns a flag on for every request of that tenant (:29-34). The prefix is the public constantTenantGroupPrefix = "tenant:"(:75), and the publicTenantGroup(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.ITenantContextis scoped, soResolveTenantGroups(:123) reads it fromHttpContext.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 currentHttpContext(:97), its principal (:98), and the tenant groups (:99) up front. An unauthenticated or absent principal yields a context withUserId = nulland only the tenant groups (:101-108,Groups = tenantGroupsat: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 throughuser.GetRoleValues()(:110), which accepts each claim type the JWT middleware may produce: the standardClaimTypes.RoleURI when inbound claim mapping is on, or the rawrole/rolesclaim when it is off (ClaimsPrincipalExtensions.cs:47-49), and appends the tenant groups (:111-112). Finally it builds theTargetingContextwithuser.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.Rolewould 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 sharedGetRoleValuesrather than a local claim filter keeps this accessor,ICurrentUserServiceand the permission handler reading roles one way. Folding the tenant into the existingGroupslist, rather than adding a custom filter, keeps the stockTargetingfilter and its configuration shape unchanged. The class doc carries a workedFeatureManagementconfiguration example (:41-65) showing a rollout that always includes one role (Reviewers) and every request of tenantacme, 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
AddAPIasservices.AddFeatureManagement().WithTargeting<CurrentUserTargetingContextAccessor>()(MMCA.Common/Source/Presentation/MMCA.Common.API/DependencyInjection.cs:108-109), immediately afterAddHttpContextAccessor()(:107, which isTryAdd-based and therefore safe to call here as well as elsewhere, the reasoning recorded at:101-106). From there it is consumed only by theTargetingfeature filter, whose verdicts reach the HTTP edge through[FeatureGate]and DisabledFeatureHandler, and the CQRS layer through FeatureGateCommandDecorator<TCommand, TResult>. Framework coverage isCurrentUserTargetingContextAccessorTestsand, 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
TUserDtoand 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 protectedAdministrationproperty (:72),UserIdentifierType, the per-action-resolved IUserSessionsAdministrationService with its RefreshSessionSummaryResponse and SignInSummaryResponse items, the per-action-resolved IViewAsService andIOptions<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) andIOptions<MultiFactorAuthorizationSettings>(:472). The ceiling evaluates permissions through PermissionAuthorizationHandler.Holds(:433), and the role action reads ErrorType.NotFoundoff 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 onIUserAdministrationService<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 (IsCallerat:510-512), answered 403 withUserAdministration.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 anIPermissionRegistry, a request is refused 403 withUserAdministration.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 underAuthorization:MultiFactor:RequiredForRolesgoes only to an account with two-factor authentication on, otherwise 409UserAdministration.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 tommca.auth.admin_actiontagged 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 throughAdministration.GetAsync.GetSessionsAsync(userId, sessions, cancellationToken)([HttpGet("{userId}/sessions")]at:101, method at:105-115) returns the account's live sessions, newest first, view only, asIReadOnlyList<RefreshSessionSummaryResponse>; it null-guardssessions(:110) and maps failures throughHandleFailure(:114).GetSignInsAsync(userId, sessions, cancellationToken)([HttpGet("{userId}/sign-ins")]at:125, method at:129-139) returns the sign-in history throughsessions.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 unlessViewAs:EnabledandHostsGrantStoreare both true (:178-181), 401 without a caller id (:183-186), and otherwise callsviewAs.StartAsync(staffUserId, userId, request?.Reason, cancellationToken)(:188-190); a failure goes throughHandleFailure(:191-194), and a success recordsAdminActionMetrics.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 holdsusers:view-as(:142-146).LockAsyncandUnlockAsync([HttpPost("{userId}/lock")]at:224and[HttpPost("{userId}/unlock")]at:257, methods at:231-249and:263-281) run the self refusal (:235,:267), thenCheckTargetCeilingAsync(:240,:272), thenAdministration.SetLockedAsync(userId, locked, cancellationToken)(:246,:278), and finish throughCompletedwith theLockorUnlockmetric 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 onLockAsync(: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 withUserAdministration.LockMarkerNotWritten, because the access tokens already issued keep working until they expire (:215-219);LockAsyncdeclares 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) andCheckSecondFactorEnrollmentAsync(:325), then replaces the account's complete role set throughAdministration.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 aNotFound(an unknown target, which has no role to put a ceiling on), the action skips the enrollment check and callsAdministration.SetRolesAsyncanyway, returning its result throughCompleted(: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 toHandleFailure(:322). Both completion paths pass theRoleChangemetric 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 throughCheckTargetCeilingAsync(:407-423), which returns success with no registry and otherwise loadsAdministration.GetRoleAsync(:414), passing through the service's not-found failure for an unknown account (whichLockAsyncandUnlockAsyncreturn as is, andSetRolesAsynchandles 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 noITwoFactorStoreis registered; otherwise it requiresstate?.IsTwoFactorEnabled == true(:461-463).Completed(result, action, metricAction, userId)(:489-505) maps a failure throughHandleFailure; on success it recordsmetricActionon 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,
ProblemDetailson every failure path) ships once in the framework and an app supplies only itsTUserDtoand itsIUserAdministrationService<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 sameactiontag 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
UsersAdminControlleris the current subclass (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/Controllers/UsersAdminController.cs), backed byUserAdministrationService(MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/Administration/UserAdministrationService.cs) implementingIUserAdministrationService<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 fromViewAsButton(MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Auth/ViewAsButton.razor.cs). The framework's coverage isAdministrationControllerBaseTests,UsersAdminSessionsEndpointTests,UsersAdminSignInsEndpointTestsandViewAsEndpointTests. - 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 insideIViewAsService, outside this file; likewise the 503UserAdministration.LockMarkerNotWrittenfailure is produced by the service, not by this controller. Whether ADC registers anIPermissionRegistryor anITwoFactorStore(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 protectedAdministrationproperty (RolesAdminControllerBase.cs:74), andICurrentUserService, re-exposed asCurrentUserService(: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 toIRoleAdministrationService(DIP) plus the caller-derived inputs that service needs. The routing choice onGetCatalogAsyncis 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 namesManageRolesitself or a permission outside the catalog (:41-57); and no operator grants more than they hold: with anIPermissionRegistryregistered, a set that ADDS a permission the caller does not hold is refused 403 with the users-admin codeUserAdministration.PrivilegeCeiling, while keeping or removing one is allowed because the request replaces the whole stored list (:58-64).SetPermissionsAsyncalso records who made the change throughResolveChangedBy()(:160, method at:171-172), which defaults to the caller's ownCurrentUserService.UserIdand is virtual so an app can substitute a display name instead. - Walkthrough
GetAllAsync(cancellationToken)([HttpGet]at:84, method at:88-94) lists every role viaAdministration.ListRolesAsync(:91), returningIReadOnlyList<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, viaAdministration.GetCatalogAsync(:113).GetAsync(role, cancellationToken)([HttpGet("{role}")]at:124, method at:129-136) reads one role's compiled and stored permissions viaAdministration.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 viaAdministration.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 answersConflictwhen 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) isCurrentUserService.UserId?.ToString(CultureInfo.InvariantCulture), ornullwhen 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 noIPermissionRegistry(:182-185), otherwise a closure over the caller that evaluatesPermissionAuthorizationHandler.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 anullpredicate 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 completeIRoleAdministrationServiceover 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. KeepingResolveChangedByvirtual 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
AdminRolesControlleris the current subclass (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/Controllers/AdminRolesController.cs), consumed from the UI atMMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.UI/Pages/Roles/RoleList.razor.cs. The framework's own coverage is inAdministrationControllerBaseTests. - 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 declaredContent-Lengthis over the cap is answered413 Payload Too Largebefore 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:
RequestDelegateandIConfiguration(primary constructor,JsonRequestBodyLimitMiddleware.cs:28); ASP.NET Core'sIRequestSizeLimitMetadata,IHttpMaxRequestBodySizeFeatureandIProblemDetailsService(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 asIRequestSizeLimitMetadata) is left entirely alone (:14-17), so the explicit statement always wins over the default. - Walkthrough:
MaxJsonBodyBytesConfigKey("Api:MaxJsonBodyBytes",:31) andDefaultMaxJsonBodyBytes(1024 * 1024,:34) areinternal const, and the limit is resolved once into_maxJsonBodyBytesbyResolveLimit(configuration)(:36).ResolveLimit(:93-110) reads the key aslong?, returns the 1 MiB default when it is absent (:97-101), and throwsInvalidOperationExceptionnaming 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 tonext(:47-50). In scope, a declaredContentLengthover the limit short-circuits toWritePayloadTooLargeAsync(:52-55). Otherwise it readsIHttpMaxRequestBodySizeFeatureand, when the feature is still writable and its current cap is unbounded or larger than the limit, lowersMaxRequestBodySizeto the limit (:57-62); it never raises a cap that is already smaller. Thennextruns (:64).IsInScope(:72-74): the content type is JSON (HasJsonContentType(), which matchesapplication/jsonandapplication/*+json, ortext/jsonviaIsTextJson,:83-85, because the MVC JSON input formatter accepts it andHasJsonContentTypedoes not,:76-82) and the selected endpoint carries noIRequestSizeLimitMetadata.WritePayloadTooLargeAsync(:116-138) sets 413 (:118), resolvesIProblemDetailsServicefromRequestServiceswith a null-tolerant read (RequestServicesis 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 aBadHttpRequestExceptioncarrying 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). CheckingIsReadOnlyfirst 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
JsonBodySizeLimitstep of the default pipeline (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/Pipeline/MiddlewarePipelineBuilder.cs:82-86), placed immediately afterRouting(:78-80) and ahead of everything that reads the body, starting withCors(:88-92). The step name isMiddlewarePipelineStepNames.JsonBodySizeLimit(MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/Pipeline/MiddlewarePipelineStepNames.cs:42), whose doc restates the key and default (:37-41). The class isinternal, 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 setApi:MaxJsonBodyBytesis 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.RequestAbortedis cancelled) to HTTP 499 Client Closed Request instead of letting it inflate the 500 rate. "A cancellation" means one of three shapes: anOperationCanceledException, a providerDbException, or an EF CoreDbUpdateExceptionwrapping either (see below). Any other cancellation, and any other exception type, is deliberately left alone. - Depends on:
IProblemDetailsService,ILogger<OperationCanceledExceptionHandler>;System.Data.Common.DbExceptionand EF Core'sDbUpdateExceptionfor 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 downstreamHttpClienttimeout, an internal token) IS a server error and must still count as one. A second paragraph (:17-24) explains why aDbExceptionis claimed too: a data provider may report the cancelled command as its own exception rather than anOperationCanceledException(SqlClient answers "Operation cancelled by user." as aSqlException), 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: duringSaveChangesEF Core wraps the provider's report in aDbUpdateException, 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 returnsfalseunlessIsCancellationShaped(exception)holds andhttpContext.RequestAborted.IsCancellationRequestedis true.IsCancellationShaped(:74-76) is a single pattern:exception is OperationCanceledException or DbException or DbUpdateException { InnerException: DbException or OperationCanceledException }, so aDbUpdateExceptionqualifies only when its inner exception is itself a cancellation shape. Past the guard it logs the exception itself (not a narrowed cancellation variable) atLogWarningwith a client-disconnected message (:52), setsStatusCodes.Status499ClientClosedRequest(:54), and still builds a problem document titled"Operation Canceled Exception"(:55-65) which it writes throughTryWriteAsync(:67). Note thatStatus499ClientClosedRequestis a real constant on ASP.NET Core'sStatusCodes, 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 aCancellationTokenwould 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. TheRequestAbortedcheck is the reverse protection: anOperationCanceledExceptionthrown 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 everycatchin the cache-touching middleware and limiters filtersOperationCanceledExceptionout explicitly rather than swallowing it (for exampleSoftDeletedUserMiddleware.cs:98andRedisFixedWindowRateLimiter.cs:223). - Where it's used:
AddCommonExceptionHandlers()(DependencyInjection.cs:162); it fires for request-abort propagation from any handler that honors itsCancellationToken, and only whileRequestAbortedis 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
ValidationExceptioninto a 400 whose problem document carries anerrorsextension 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 atLogWarning(:31, notLogError: an invalid payload is a client mistake, not a system fault), sets 400 (:33), builds the problem document titled"Validation Exception"(:34-44), then groupsvalidationException.ErrorsbyPropertyNameinto aDictionary<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
ModelStateDictionaryserialization front ends already understand. Note the key is the rawPropertyNamefrom FluentValidation, not a camelCased alias, and thatExtensions.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.Attributeonly. 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'sIsEndViewAsEndpoint(:109-111) treats a request as the end-view-as call only when the method is POST andcontext.GetEndpoint()?.Metadata.GetMetadata<ViewAsEndEndpointAttribute>()is not null. - Why it's built this way: it is
internalon 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/endaction 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.resxfamily. 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.resxfamily). - 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
ErrorResourceSourceinstances 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 severalIStringLocalizers as a distinguishableIEnumerable<ErrorResourceSource>(a bareIEnumerable<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 markerinternal bool IsFramework { get; init; }(ErrorResourceSource.cs:22), true only for the framework's ownErrorResourcessource and set only byAddErrorLocalization(DependencyInjection.cs:132). The enumeration and first-match logic live in ErrorLocalizer. - Why it's built this way: the
IsFrameworkflag, 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, andinitplusinternalkeep 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 asksIStringLocalizerFactory.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 insideAddErrorLocalization()(DependencyInjection.cs:129-133), which DependencyInjection'sAddAPIcalls automatically (DependencyInjection.cs:113); modules add theirs by callingAddErrorResources<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
Codesuch as"Email.Empty"plus an English message (IErrorLocalizer.cs:15-16). Translating on theCoderather 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'sfallbackMessageis 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: resolvecodeagainst the current UI culture, otherwise returnfallbackMessage(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
GetServicerather thanGetRequiredService: 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 DetailsDetail(MultiFactorRefusalResultHandler.cs:73). All five hand it to ErrorHttpMapping.BuildErrorsExtension(MMCA.Common/Source/Presentation/MMCA.Common.API/Middleware/ErrorHttpMapping.cs:65), which accepts anulllocalizer and leaves messages in English (ErrorHttpMapping.cs:69) while leaving the machineCodeverbatim 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
IExceptionHandlerthat turns an EF CoreDbUpdateExceptioninto 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;atDbUpdateExceptionHandler.cs:7), and an optional IUniqueConstraintViolationDetector resolved from the request's services (usingat:8, read at:86). Siblings in the same chain: OperationCanceledExceptionHandler, ValidationExceptionHandler, and the catch-all GlobalExceptionHandler. - Concept introduced: the
IExceptionHandlerchain. ASP.NET Core resolves registeredIExceptionHandlerimplementations in registration order and callsTryHandleAsyncon each: returningtrueclaims the exception and stops the chain, returningfalsepasses it on. The framework registers the chain inAddCommonExceptionHandlers()(MMCA.Common/Source/Presentation/MMCA.Common.API/DependencyInjection.cs:157-168) asOperationCanceled(:162), thenDbUpdate(:163), thenValidation(:164), thenGlobal(:165), and that same method callsAddProblemDetailswith a customization that stamps arequestIdextension fromHttpContext.TraceIdentifieronto 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 9457application/problem+jsonthrough the sameIProblemDetailsService, so controllers never need atry/catch.[Rubric §11, Security]applies to this handler specifically, see below. - Walkthrough:
TryHandleAsync(DbUpdateExceptionHandler.cs:34):- Type-tests with
is not DbUpdateException dbUpdateExceptionand returnsfalse(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): aDbUpdateConcurrencyException, or a failure the host's IUniqueConstraintViolationDetector classifies as a unique-key violation, is logged atLogWarningas a 409-answered conflict (:44); anything else is logged atLogError(:48). The detector is read withRequestServices?.GetService<...>(), so with none registered only the concurrency kind counts as expected (:79-83). - When the exception is the
DbUpdateConcurrencyExceptionsubtype, callsConcurrencyConflictMetrics.RecordConflict(concurrencyException)(:53-56), which adds one to thepersistence.concurrency.conflictcounter tagged by entity type (MMCA.Common/Source/Presentation/MMCA.Common.API/Concurrency/ConcurrencyConflictMetrics.cs:37-47). The comment atDbUpdateExceptionHandler.cs:51-52states 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 everyDbUpdateException, 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
ProblemDetailsContexttitled"Database Update Exception"(:64-74) and returnsawait problemDetailsService.TryWriteAsync(context)(:76), so the response body is whatever the configuredProblemDetailsServicewrites.
- Type-tests with
- 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 aDbUpdateConcurrencyExceptionon an action carrying SupportsIfMatchAttribute never reaches this handler: that filter converts it to 412, records the same conflict metric itself, and setsExceptionHandled = 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 duringSaveChangesthat EF Core wraps in aDbUpdateExceptionnever reaches this handler whileRequestAbortedis 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 returnsnull: on a miss it hands back aLocalizedStringwhoseValueis the key itself and whoseResourceNotFoundflag istrue. 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_sourceswith a collection expression that concatenates the non-framework sources (registration order) followed by theIsFrameworkones (ErrorLocalizer.cs:15-16).Localize(ErrorLocalizer.cs:19): returnsfallbackMessageimmediately whencodeis null or empty (ErrorLocalizer.cs:21-24); otherwise walks_sourcesin that order, readingsource.Localizer[code]and returninglocalized.Valueon the first entry where!localized.ResourceNotFound(ErrorLocalizer.cs:26-33); if no source matches it returnsfallbackMessage(ErrorLocalizer.cs:35). The current UI culture is never read explicitly:IStringLocalizerresolves it per call, which is why one singleton can serve requests in different cultures concurrently. - Why it's built this way:
internal sealedkeeps 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 withTryAddSingleton(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 callsservices.AddLocalization()at:127), and that method is called byAddAPI(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-IDresponse 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 publicconst, so clients, tests and downstream code all name the header from one place.MaxLength = 64(:26) is aninternal 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 inboundX-Correlation-IDheader wins when it is not null, empty or whitespace (string.IsNullOrWhiteSpace) and survivesSanitize(:41); otherwiseActivity.Current?.TraceId(the W3C trace ID that OpenTelemetry propagates,:42), else ASP.NET'sHttpContext.TraceIdentifier(:43). The chain is null-coalescing, so a header thatSanitizerejects 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 thanMaxLengthto its first 64 characters with a range slice (:63), then keeps it only when every character is printable ASCII,>= ' 'and<= '~'(:64); any other character yieldsnull.correlationContext.SetCorrelationId(correlationId)(:45) publishes it, thencontext.Response.OnStarting(...)(:46-50) registers a callback that writes the response header. Writing it inOnStartingrather than afternext(...)completes is the only safe way: once the response has begun, header writes throw.return next(context)(:52) continues the pipeline.InvokeAsyncis a plainTask-returning method, notasync(: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.Currentmeans 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, followingExceptionHandlerat:34-36), so everything downstream (including the exception handlers above) logs under a known ID. The step is namedMiddlewarePipelineStepNames.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
errorsextension array that problem documents carry. - Depends on: Error, ErrorType, ErrorTypeSeverity, IErrorLocalizer;
System.Collections.Frozenand ASP.NETStatusCodes(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 inMMCA.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 seeMMCA.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'sTarget(seeLocalizeMessagebelow).ErrorTypeToStatusCode(ErrorHttpMapping.cs:23-35): aFrozenDictionary<ErrorType, int>withValidationto 400,Invariantto 400,NotFoundto 404,Conflictto 409,Unauthorizedto 401,Forbiddento 403,UnprocessableEntityto 422,Unexpectedto 500,TooManyRequeststo 429 (:33), andUnavailableto 503 (:34), the one type that tells the caller a retry later can succeed. There is noFailurerow: that member is gone from the enum and its value 7 is retired (MMCA.Common/Source/Core/MMCA.Common.Shared/Abstractions/ErrorType.cs:17, withUnavailable = 10at:67).FrozenDictionaryis 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) usesGetValueOrDefault(..., 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 toErrorTypeSeverity.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 theerrorsarray either way (:44-53).BuildErrorsExtension(IReadOnlyList<Error>, IErrorLocalizer?)(:65-74) projects each error into an anonymous object withCode,Message,Type(stringified),SourceandTarget. OnlyMessageis localized, and only when a localizer was supplied (:69, throughLocalizeMessage); a null localizer leaves the original English text.Code,Type,SourceandTargetstay verbatim so clients can branch on them regardless of culture (:57-64).LocalizeMessage(IErrorLocalizer, Error)(:82-94) asks the localizer for the text keyed byCode(: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'sTarget, so runtime detail survives translation (the CSV reader puts the malformed line there forCsv.Malformed,:76-81); a translation with a placeholder but noTargetto fill it falls back to the English message, which names the detail itself (:91-93).
- Why it's built this way:
internalvisibility (: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 stableCode. - Where it's used: ApiControllerBase
.HandleFailurewhen converting a failedResultinto anObjectResult(MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/ApiControllerBase.cs:63and:58), and UnhandledResultFailureFilter as the backstop (MMCA.Common/Source/Presentation/MMCA.Common.API/Middleware/UnhandledResultFailureFilter.cs:36and: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>), andIProblemDetailsService(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 withTenancy:RequireTenant(the default) an unresolved tenant is answered400 Bad Requestrather 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, sinceIOptions<TenancySettings>resolves to defaults withEnabledfalse and the middleware passes every request straight through (:15-20). - Walkthrough
UnresolvedTenantTitle(TenantResolutionMiddleware.cs:40): theinternal constproblem 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.EnabledorIsExcluded(...), callnextand return.IsExcluded(:90-95) matchessettings.EffectiveExcludedPathPrefixeswithStartsWithSegmentsunderOrdinalIgnoreCase, 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 withtenantContext.SetTenant(tenantId)(:71) before the pipeline continues. Resolve(:105-122) walkssettings.EffectiveResolutionOrderand switches on the strategy:Claimreadscontext.User?.FindFirst(settings.ClaimType)?.Value(:111), andHeaderreadssettings.HeaderNameonlywhen settings.TrustTenantHeaderis set (:112-113). Every other case, including a listed header the host has not trusted, yieldsnull(: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-21and:100-107). Candidates are trimmed (:118).- Opt-out (
:76-82): withRequireTenantfalse 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, andTenancySettings.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 ofEffectiveResolutionOrder, so the detail can name a source thatResolvedid 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 readsHttpContext.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 withRequireImmediatelyBefore(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
TenantResolutionstep 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
IExceptionHandlerchain. 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, aBadHttpRequestExceptionis 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:
IProblemDetailsServiceandILogger<GlobalExceptionHandler>(primary-constructor injected,GlobalExceptionHandler.cs:42-45), plus CrossTenantWriteException fromMMCA.Common.Infrastructure.Persistence.Interceptors(imported at:8), TransactionCommitAmbiguousException fromMMCA.Common.Infrastructure.Persistence.DbContexts.Factory(:7), CommitOutcomeUnknown fromMMCA.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 returnsfalseon 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) andCrossTenantWriteDetail(:56-58) areinternal conststrings, so the tests assert against the same literals the handler writes.- The tenant-boundary path (
:66-84): aCrossTenantWriteExceptionis logged atLogWarning(: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 setsStatus400BadRequest(:72) and returnsTryWriteAsyncwith the two constants (:73-83). - The bad-request path (
:86-110): aBadHttpRequestException(Kestrel or model binding rejected a malformed or oversize request) is a caller fault, so it is logged atLogWarningwith 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 isStatus413PayloadTooLargeand"Bad Request"otherwise (:102-104), and the detail follows the same split (:105-107). - The commit-unknown path (
:112-115): aTransactionCommitAmbiguousExceptionis handed toWriteCommitOutcomeUnknownAsync(:139-162), which logs atLogError(:141), sets 500 (:143), stamps theCommitOutcomeUnknown.HeaderNameheader withCommitOutcomeUnknown.HeaderValue(:144), builds a problem document titled"Commit outcome unknown"whose detail isCommitOutcomeUnknown.Message(:146-151), and attaches anerrorsextension built by ErrorHttpMapping.BuildErrorsExtensionfrom oneError.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 atLogError(:117), setsStatusCodes.Status500InternalServerError(:119), and returns the result ofproblemDetailsService.TryWriteAsync(...)(:120-130) with the generic title"Internal Server Error"and a "please try again" detail (:127-128). The exception object is attached to theProblemDetailsContext(: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):CrossTenantWriteExceptionderives fromInvalidOperationException, so nothing ahead of this handler claims it, while every other save-time invariant failure of that family still ends at the 500. TheBadHttpRequestExceptionmapping 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. ReturningTryWriteAsync's own boolean rather than a hard-codedtruekeeps 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
IAlwaysRunResultFilterthat catches an action which returned a failed Result inside anOk(...)(or anyObjectResult) 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;
IAlwaysRunResultFilterruns for every result MVC is about to execute.[Rubric §9, API & Contract Design]assesses whether a domain failure can leak as200 OKwith 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 anObjectResultcarrying a failedResult. Note the pattern matches the baseResult, soResult<T>values are caught too. - Logs at
Warningwith 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, matchingApiControllerBase.HandleFailureexactly (: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
ProblemDetailstitled"Unhandled result failure"whose detail names the defect in plain words (:39-44). - Resolves IErrorLocalizer from
HttpContext.RequestServiceswithGetService(:46, so a host without localization simply passes null) and attaches the localizederrorsextension (:47). - Replaces
context.Resultwith anObjectResult(problemDetails) { StatusCode = statusCode }(:49). OnResultExecuted(:53-55) is intentionally empty: there is nothing to do after the response ran.
- The guard
- 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-constructorloggeris used without an allocation per call. The class ispartialfor 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>andTimeProvider, 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 theexpclaim as invariant-culture Unix seconds and accepts it only within0..DateTimeOffset.MaxValueseconds, 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 writestrueunderKeyFor(grantId)(:95). A failed write (other than cancellation) is logged through the[LoggerMessage]errorLogMarkerWriteFailed(: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) isexpiresAt - now, floored at zero, orViewAsGrant.MaxLifetimewhen the token carries no expiry (:110).ClockSkew(IServiceProvider)(:117-122) readsTokenValidationParameters.ClockSkewfrom theJwtBearerDefaults.AuthenticationSchemeoptions and falls back toTokenValidationParameters.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 isinternalbecause 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/endaction of AuthControllerBase (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/AuthControllerBase.cs:439); read by ViewAsGuardMiddleware throughKeyForandTryGetTokenExpiry(ViewAsGuardMiddleware.cs:186,:213);ClockSkewis 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): callnextand return. - View-as switched off or never configured (
:66-72): whenViewAsSettingsis unresolvable orEnabledis 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), viaIsGrantLiveOnThisHostAsync(:94-104), which branches onViewAs:HostsGrantStore. On the store host it resolvesIViewAsService(no service means refuse), parses the grant, actor and subject claims (:127-133) and callsIsGrantActiveAsync(grantId, staffUserId, targetUserId, ...)(:137). On a service without the store,IsGrantLiveWithoutTheStoreAsync(:161-201) requires the same three claims plus a usableexp(TryReadTokenWithoutTheStore,:207-214), refuses an expired token (:169-174), refuses when noICacheServiceis registered (:176-181), and reads the ended marker withGetFromSharedStoreAsync<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
nextruns (: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.
- Not a view-as principal (
- Why it's built this way:
IViewAsServiceis 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
ViewAsGuardstep of the default pipeline (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/Pipeline/MiddlewarePipelineBuilder.cs:118-125), afterSoftDeletedUserFilter(:122-124) and beforeAuthorization(:135-137): after authentication soact_subis on the principal, and after routing so the end action's metadata is readable (:128-132). The step name isMiddlewarePipelineStepNames.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): noUserId, callnextand 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 fromSoftDeletedUserCache.KeyFor(userId.Value)(:85). The read isGetFromSharedStoreAsync<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 anOperationCanceledExceptionis logged and treated as a miss (:98-106), andcacheReachablegoes 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 thantrue(no entry, an unreachable cache, or a strayfalseentry) falls through to the database, so a cached "not deleted" answer is never treated as authoritative. It queriesIsUserSoftDeletedAsync(: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 withSetAsync(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
nextruns (:169). MarkerDurationFor(IServiceProvider?)(:177-180): when an ITokenService is registered, the lifetime isSoftDeletedUserCache.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, soSoftDeletedUserCache.MarkerDurationis 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.
- Anonymous fast path (
- Why it's built this way: every
catchfilters outOperationCanceledException(: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
SoftDeletedUserFilterstep of the default pipeline (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/Pipeline/MiddlewarePipelineBuilder.cs:114-116), placed afterRateLimiting(:106-112) and beforeViewAsGuard(:118-125) andAuthorization(:127-129), so it runs only once a principal exists and before any policy grants access. The step name isMiddlewarePipelineStepNames.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.resxandErrorResources.es.resx, which sit beside it inResources/. It has no members:public sealed class ErrorResources;atMMCA.Common/Source/Presentation/MMCA.Common.API/Resources/ErrorResources.cs:9is the entire declaration, written in the body-less semicolon form. - Depends on: nothing, first-party or otherwise. It has no
usingdirectives and no base type. Dependencies point the other way: ErrorResourceSource wraps theIStringLocalizerbuilt 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.resxneeds 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 errorCode("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 theCodea 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 assemblyMMCA.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.
- Registration.
AddErrorLocalization()callsservices.AddLocalization(), registersErrorLocalizerbehindIErrorLocalizerwithTryAddSingleton, and then contributes the framework's own set as a singletonErrorResourceSourcebuilt fromCreate(typeof(ErrorResources))withIsFramework = true(MMCA.Common/Source/Presentation/MMCA.Common.API/DependencyInjection.cs:125-135, the source at:129-133).AddErrorLocalization()is called automatically fromAddAPI(DependencyInjection.cs:113), so no host has to opt in. - Source construction. The generic
AddErrorResources<TResource>()registers a singleton factory that resolvesIStringLocalizerFactory, callsCreate(typeof(TResource)), and wraps the result in an ErrorResourceSource (DependencyInjection.cs:144-148).ErrorResourcesdoes not go through that method:AddErrorLocalization()builds the framework's source directly and marks itIsFramework = true(DependencyInjection.cs:129-133), while each module passes its own anchor toAddErrorResources<TResource>(), which is why translations are additive rather than an edit to a framework file. - Lookup. ErrorLocalizer snapshots the registered sources with every module source first, in registration order, and the
IsFrameworksource 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 whoseResourceNotFoundis 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.
- Registration.
- Why it's built this way: see ADR-027 (multi-locale i18n). Localizing at the HTTP edge rather than inside the domain keeps
Error.Codeand 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 oneAddErrorResources<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 resolveIErrorLocalizerfrom 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 frameworkError.Codehas 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
IActionModelConventionfound 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, throwingArgumentNullExceptionfornull.Apply(ActionModel)(:24-33) null-guards the action (:26), returns early when the action has no controller or when any ofcontroller.Attributesis an instance ofOptInAttributeType(:28-30), and otherwise callscontroller.Actions.Remove(action)(:32).IsInstanceOfTypemeans a marker inherited from an abstract base controller counts, sincecontroller.Attributescarries inherited attributes (doc:5-8).
- Why it's built this way: one generic convention parameterized by a
Typekeeps each feature's switch a body-less public marker class while the mechanism staysinternal(: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:
GetCursorPageAsyncwith[OptInAction(typeof(SupportsCursorPagingAttribute))](MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/EntityControllerBase.cs:416-417) andGetChangesAsyncwith[OptInAction(typeof(SupportsChangeFeedAttribute))](EntityControllerBase.cs:469-470). Exercised byMMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/Controllers/EntityControllerBaseCursorTests.csandEntityControllerBaseChangeFeedTests.csin 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
AddCommonRateLimitingregisters. - Depends on: nothing. Read by RateLimitingSettings
.Algorithmand 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 intoSegmentsPerWindowsegments 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 separateDistributedflag 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
.Algorithmdefaults it toFixedWindow(MMCA.Common/Source/Presentation/MMCA.Common.API/RateLimiting/RateLimitingSettings.cs:49), andCreateLimitedPartitionbranches on it (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/WebApplicationBuilderExtensions.RateLimiting.cs:287) to build either aSlidingWindowRateLimiterOptionspartition (:239-246) or aFixedWindowRateLimiterOptionsone (: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,
AcquiredandUndecided, plus aRejected(TimeSpan?)factory that allocates a refusal carrying a retry-after hint. - Depends on:
System.Threading.RateLimiting.RateLimitLease(BCL abstract base) and itsMetadataName.RetryAfterkey. 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
RateLimitLeaseon 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):AcquiredandUndecidedare stateless and shared by every request, while a rejection is allocated per call because it carriesMetadataName.RetryAfter, the time until the partition's window resets, which the rate-limiterOnRejectedcallback turns into the 429'sRetry-Afterheader.[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 holdingMetadataName.RetryAfter.Name.Acquired = new(isAcquired: true, retryAfter: null)(:219) andUndecided = new(isAcquired: false, retryAfter: null)(:226) are the two shared instances.Undecidedis 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 setsIsAcquiredand the_retryAfterfield (:228,:230-234).IsAcquiredis an override with a get-only auto property (:237).MetadataNamesreturns an empty collection when_retryAfteris null andRetryAfterMetadataNamesotherwise (:240).Rejected(TimeSpan? retryAfter)(:250) is theinternal staticfactory for an exhausted window; its doc says anullhint means no later window can satisfy the request (:242-249).TryGetMetadata(:253) returns theTimeSpanandtrueonly when a hint is present and the requested name ordinally equalsMetadataName.RetryAfter.Name(:255-260); otherwise it nulls the out parameter and returnsfalse(:262-263). - Why it's built this way:
internal sealed(:214) keeps it an implementation detail of the limiter. Every instance is immutable, so sharingAcquiredandUndecidedacross concurrent requests is safe by construction and there is no dispose-time state to reset. Reporting the hint through the BCL's standardMetadataName.RetryAfterrather than a custom key is what lets the framework's genericOnRejectedwrapper read it without knowing which limiter refused the request. - Where it's used: returned by RedisFixedWindowRateLimiter from
AttemptAcquireCore(:145, alwaysUndecided) and fromAcquireAsyncCoreon all three of its outcomes: the oversized request (:159,Rejected(retryAfter: null)), the counted decision (:175-177,AcquiredorRejected(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), whichAddCommonRateLimitinginstalls as theOnRejectedcallback (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/WebApplicationBuilderExtensions.RateLimiting.cs:451) and which formats it through its ownFormat(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 byEntityControllerBase.GetChangesAsync: the rows changed at or aftersince, 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
changedOnit 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 = trueis what makes the remark at:10work: 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'sGetChangesSinceAsyncserves 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))]onGetChangesAsync(EntityControllerBase.cs:469-470) and referenced in that action's doc (:451). No controller inMMCA.Common/SourceorMMCA.ADC/Sourcecarries it today; it is exercised byMMCA.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 byEntityControllerBase.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
Idas 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'sGetPageByCursorAsyncserves the page, and a service that predates it answers 500. - Where it's used: named by
[OptInAction(typeof(SupportsCursorPagingAttribute))]onGetCursorPageAsync(EntityControllerBase.cs:416-417) and referenced in that action's doc (:403). No controller inMMCA.Common/SourceorMMCA.ADC/Sourcecarries it today; it is exercised byMMCA.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
IApiDescriptionProviderthat walks every API description MVC produced and fills in a placeholderParameterDescriptorwherever 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.ParameterDescriptorandMicrosoft.AspNetCore.Mvc.ApiExplorer.IApiDescriptionProvider(ASP.NET Core), nothing first-party. Registered byAddCommonApiVersioning()andAddCommonOpenApi()on WebApplicationBuilderExtensions. - Concept introduced: the API-explorer provider chain as a repair point. MVC builds its OpenAPI input (the
ApiDescriptionlist) by running a chain ofIApiDescriptionProviderinstances;OnProvidersExecutingruns in ascendingOrder,OnProvidersExecutedin 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 thatGET /openapi/{documentName}.jsonmust 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 parametersVersionedApiDescriptionProvidercontributed 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), flattenscontext.Results.SelectMany(description => description.ParameterDescriptions)(:60) and appliesparameter.ParameterDescriptor ??= new ParameterDescriptor { ... }(:65-71). The??=is the load-bearing operator: an existing descriptor (aControllerParameterDescriptor, which carries theParameterInfothat XML-comment lookups prefer) is never replaced, and the comment states that rule explicitly (:62-64). The synthesized replacement takesparameter.Name ?? string.Empty(:67), and the type falls back throughparameter.Type, thenModelMetadata?.ModelType, thentypeof(string)(:68-70).
- Why it's built this way: the class remarks (
ApiParameterDescriptorBackfillProvider.cs:12-42) document the exact failure it guards. MVC leavesParameterDescriptornull for a route-template token with no matching action parameter (normal for[Route("api/v{version:apiVersion}/orders")]or[Route("api/{tenant}/orders")]), whileAsp.Versioning.OpenApi10.2.1 readsarg.ParameterDescriptor.Namewithout 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 usesTryAddEnumerableso calling bothAddCommonApiVersioning()(WebApplicationBuilderExtensions.cs:39, which calls the helper at:261) andAddCommonOpenApi()(: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
mcprate-limit policy and the per-tool limit inMMCA.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 atMMCA.Common/Source/Presentation/MMCA.Common.API/MMCA.Common.API.csproj:41) for the address fallback; BCLClaimsPrincipalandIPAddress(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 inMMCA.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 theauth-ipandwellknownpolicies, 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 theinternal constpartition 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), elseuser?.Identity?.Name, elseClientAddressKey.For(remoteIpAddress)(IPv6 masked to /64, IPv4-mapped addresses unmapped, doc:16-17), elseUnattributable. The result is nevernull(: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 staysinternal(McpCallerKey.cs:21):MMCA.Common.API.csprojgrantsInternalsVisibleToto the test project and toMMCA.Common.Mcpfor 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:
McpRateLimitPartitionkeys themcppolicy withMcpCallerKey.For(httpContext.User, httpContext.Connection.RemoteIpAddress)(WebApplicationBuilderExtensions.RateLimiting.cs:203-211, the call at:206, doc:193-202), registered inAddCommonRateLimiting(RateLimitingSettings)at:458. InMMCA.Common.Mcp,McpToolGovernance.CallerKeycalls it with the request's remote address fromIHttpContextAccessor(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 byMMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/RateLimiting/McpCallerKeyTests.csandMMCA.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
RateLimitingconfiguration section. It carries five permit counts (global,auth-ip,mcp, anonymous hub andwellknown), 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
Algorithmproperty;System.ComponentModel.DataAnnotationsfor the[Range]attributes (RateLimitingSettings.cs:1). Consumed by WebApplicationBuilderExtensions.AddCommonRateLimitingand, 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 parameterizedAddCommonRateLimitingoverload has always used, so the section is optional inappsettings.jsonand a host that omits it keeps the previous behavior exactly. The doc's own example (:11-20) sets onlyGlobalPermitLimit,Algorithm,SegmentsPerWindowandDistributed. 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 withValidateDataAnnotations().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 apublic 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)]:GlobalPermitLimit300 per authenticated user for the always-on global limiter (:27-28),AuthIpPermitLimit30 per client IP for theauth-ippolicy that throttles anonymous authentication attempts (:34-35), andMcpPermitLimit60 for themcppolicy 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 withqueueLimit: 0. Algorithm(:49) defaults toRateLimitAlgorithm.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 isSlidingWindow, and is ignored otherwise (:51-56).Distributed(:68, defaultfalse) is the interesting one. Its doc (:60-67) states the whole contract: it makes the global limiter, the anonymous hub partition, themcppolicy and theauth-ippolicy 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 anIConnectionMultiplexerin 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, whileauth-ipkeeps counting per instance until Redis recovers (:65-66). The doc names four, but thewellknownpartition is built by the sameCreateLimitedPartitionfactory, 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"]) andAnonymousHubPermitLimit(: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/hubsat the edge (ADR-024 requires it, since the hub authenticates from a query-string token the edge cannot read) left anonymous/hubs/*/negotiatetraffic metered nowhere.HubPathPrefixesnames which paths get that anonymous-IP metering, andAnonymousHubPermitLimitis 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 thewellknownpolicy 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
AddCommonRateLimitinggrow 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 onDistributedis 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). TheAuthIpPermitLimitdefault 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 withsection.Get<RateLimitingSettings>() ?? new RateLimitingSettings()(:427), then hands it toAddCommonRateLimiting(RateLimitingSettings)(:441-478). That overload threads it through every partition selector: the global limiter (GlobalRateLimitPartition,:166-191, registered at:453-454), themcppolicy (McpRateLimitPartition,:203-211, registered at:458, readsMcpPermitLimitat:208), theauth-ippolicy (AuthIpRateLimitPartition,:333-348, registered at:468-470, the only caller passingcountLocallyOnRedisFault: trueat:347) and thewellknownpolicy (WellKnownRateLimitPartition,:356-370, registered at:474-476, readsWellKnownPermitLimitat:366). Each ends inCreateLimitedPartition(:246), which readsDistributed(:255),Algorithm(:287) andSegmentsPerWindow(:292).HubPathPrefixesandAnonymousHubPermitLimitare read byAnonymousPartition(WebApplicationBuilderExtensions.RateLimiting.cs:86-96) andIsAnonymousHubRequest(:106-116, internal soInternalsVisibleTolets it be unit-tested directly): an unauthenticated request that matches a hub prefix is metered per client IP throughCreateLimitedPartitionwithredisScope: "hub"andcountLocallyOnRedisFault: false(:88-95); every other anonymous request keeps takingRateLimitPartition.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
RateLimiterthat 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, andILoggerwith 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 sharedAcquiredandUndecidedinstances, and a per-callRejected(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.
- Layering (
RedisFixedWindowRateLimiter.cs:18-23): the limiter lives inMMCA.Common.APIrather 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 inMMCA.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. - 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 sameApplication:Namespacedo 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]. - 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]. - Count locally instead (
:45-50, theauth-ippolicy 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.
- Layering (
- 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, thenEXPIREonly 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
_countLocallyOnFaultflag and the_circuit(:68-74), plus_lastUsedTimestampseeded fromStopwatch.GetTimestamp()(:79). Three more fields back the local fallback: aLock _localGate(:77),_localWindowinitialized to-1(:82) and_localCount(:85). - Two constructors. The public one (
:101) keeps the original five-parameter shape and chains to the internal one withcountLocallyOnFault: false(:107), so a caller outside the framework always gets fail-open behavior; itstimeProviderdoc names it the substitution point tests use to pin a window (:97-100). The internal one (:124, doc:111-123) addscountLocallyOnFault, guards all four required inputs (:132-135, includingThrowIfLessThan(permitLimit, 1)), defaultstimeProvidertoTimeProvider.System(:141), stores the flag (:142) and fetches the connection's circuit withRedisOutageCircuit.For(connection)(:143). That lookup goes through aConditionalWeakTablekeyed 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) reportsStopwatch.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 owningPartitionedRateLimitertable with one entry per user seen since start-up.GetStatistics()(:160) returnsnullon 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 returnsRedisRateLimitLease.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 synchronousAttemptAcquirefirst on every request and callsAcquireAsynconly 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 withRedisRateLimitLease.Rejected(retryAfter: null)whenpermitCount > _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 intonow(:198), computes the window asnow.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 (AcquireLocallywith_countLocallyOnFault, otherwiseAcquired) and logs nothing, since the fault that opened the circuit already logged. Otherwise it runsScriptEvaluateAsync(RedisCounterScript.Increment, [key], [permitCount, KeyTtlSeconds])(:212-215), casts the result tolong(: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):Acquiredwithin the limit, otherwiseRejected(TimeUntilNextWindow(now, window)). The catch (:223-244) excludesOperationCanceledException, opens the circuit with_circuit.RecordFault(_timeProvider)(:225) and computesfirstInWindowonce viaInterlocked.Exchangeon the static field (:226). With_countLocallyOnFaultset it logs the counting-locally warning on the first fault of the window and returnsAcquireLocally(permitCount, now, window)(:228-236); otherwise it logs the fail-open warning on the first fault of the window (:238-241) and returnsAcquired(: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 withRejected(TimeUntilNextWindow(now, window))when the tally plus the request would pass the limit (:266-269), and otherwise adds the permits and returnsAcquired(: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 thenowthat chose the window keeps the hint consistent with the counter it was refused by.
- One internal constant leads the type:
- Why it's built this way:
partialplus 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 inCreateLimitedPartitionas$"{RateLimitKeyNamespace(requestServices!)}:{redisScope}:{key}"(MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/WebApplicationBuilderExtensions.RateLimiting.cs:275), whose leading namespace (the configuredCache:KeyPrefixwithout 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 areglobal,hub,mcp,auth-ipandwellknown(: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 whensettings.Distributedis true (:255) and anIConnectionMultiplexerresolves (:261-263); the logger falls back toNullLoggerwhen none is registered (:265-266), andRequestServicesis 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 itscountLocallyOnRedisFaultargument (documented at:240-245): the global, hub,mcpandwellknownpartitions passfalse(:190,:95,:211,:369), and theauth-ippolicy passestrue(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
PaginationMetadataonto the HTTP response. A static class with the header-name constant and a singleextension(HttpResponse)member. - Depends on:
PaginationMetadata(the payload),HttpResponse(the extended type), andSystem.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 anextension(HttpResponse response)block (:19), null-guards both arguments (:29-30) and appendsHeaderNamewith the metadata serialized usingJsonSerializerOptions.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
AddCommonRateLimitinguses, 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 sourceMMCA.Common/Source/Build/RateLimiting/RemainingWindowFixedWindowRateLimiter.cs:31(namespaceMMCA.Common.RateLimiting,RateLimitPartitions.cs:2). - Concept introduced (an honest
Retry-Afterfor host policies). The BCL'sRateLimitPartition.GetFixedWindowLimiterstamps every rejection with the whole window length as itsMetadataName.RetryAfterhint, 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 withAddPolicytells the client how long it actually has to wait (docRateLimitPartitions.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 withtimeProvider: null.- The
internaloverload (:39-57) adds aTimeProvider?so tests can drive the hint (doc:29-32). It rejects a non-positivepermitLimit(ThrowIfNegativeOrZero,:45) and a non-positivewindow(:46), then returnsRateLimitPartition.Get(partitionKey, _ => new RemainingWindowFixedWindowRateLimiter(...))(:48-56) withWindow,PermitLimit,QueueLimit = 0andQueueProcessingOrder.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 aPartitionedRateLimiter.CreateorAddPolicyselector (:25). - Where it's used: no caller in
MMCA.Common/SourceorMMCA.ADC/Source; the framework's own partitions build the same limiter directly insideCreateLimitedPartition(WebApplicationBuilderExtensions.RateLimiting.cs:301). It is exercised byMMCA.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
IOpenApiSchemaTransformerthat 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.OpenApiSchemaandJsonSchemaType; the sharedStronglyTypedId.TryDescribehelper 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.
AddStronglyTypedIdsteachesSystem.Text.Jsonto serialize a wrapper as its bare value, but ASP.NET Core's OpenAPI generator still reflects the wrapper's own properties unless something intervenes;IOpenApiSchemaTransformeris 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 modelOrderIdas{ "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
schemaandcontext(: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.Propertiesandschema.Required(:39-40), which erases the object shape the reflection-based generator would otherwise have built, then setsschema.Type = MapType(valueType)andschema.Format = MapFormat(valueType)(:41-42). MapType(:47-50,internal static) returnsJsonSchemaType.Integerforint/long, elseJsonSchemaType.String.MapFormat(:52-61) returns"int32","int64","uuid"(forGuid), ornull, matching the OpenAPI format vocabulary a client generator already understands.
- Null-guards
- Why it's built this way: both mapping methods are
internal staticrather 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()viaoptions.AddSchemaTransformer(new StronglyTypedIdSchemaTransformer())on everyOpenApiOptionsinstance (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/WebApplicationBuilderExtensions.cs:118, inside theConfigureAll<OpenApiOptions>block at:502-506, whose comment states it is inert in a host that declares no wrappers,:498-501).ConfigureAllrather than a single named document is deliberate:AddOpenApi()creates oneOpenApiOptionsper 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
IOpenApiOperationTransformerthat 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/.MapFormatfor the type/format decision, andStronglyTypedId.TryDescribeto 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
operationandcontext(:82-83), then exits early whenoperation.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 asdescribed.ModelMetadata?.ModelType ?? described.Type(:90) and skips it when that type is null or is not a strongly typed identifier perStronglyTypedId.TryDescribe(:91-92). - Matches the description back to the operation's
OpenApiParameterby 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.Schemaoutright with a newOpenApiSchema { 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.
- Null-guards
- Why it's built this way: reusing the sibling transformer's
MapType/MapFormatinstead 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()viaoptions.AddOperationTransformer(new StronglyTypedIdParameterTransformer())(MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/WebApplicationBuilderExtensions.cs:119), inside the sameConfigureAll<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
ForwardedHeadersOptionswith that mask and a cleared proxy/network allowlist. It is the shared posture behind ASP.NET Core's ownUseForwardedHeadersmiddleware. - Depends on:
Microsoft.AspNetCore.HttpOverrides.ForwardedHeadersandForwardedHeadersOptionsonly. CommonForwardedHeadersExtensions and MiddlewarePipelineBuilder both callCreate. - 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. ClearingKnownProxiesandKnownIPNetworksrather 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-flagForwardedHeadersmask.Create(ForwardedHeaders? headers = null)(:40) builds aForwardedHeadersOptionswithForwardedHeaders = 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 throughAddForwardedJwtBearerreads the audience the same way. - Depends on: nothing first-party; BCL
InvalidOperationExceptionandstringonly. The file has nousingdirectives. Its sibling in the same folder is JwtAuthorityExtensions, and both feedAddForwardedJwtBeareron 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 inMMCA.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) asJwt__Audiencewhen supplied as an environment variable.RequireConfigured(string? configuredValue)(:28-32) is an expression-bodied guard: whenstring.IsNullOrWhiteSpaceis true it throwsInvalidOperationExceptionwith 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 fromConfigKey); otherwise it returns the value unchanged. Blank and whitespace-only values are rejected exactly likenull. - 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'sappsettings.jsonand, 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, andForwardedJwtAudienceTestsBaseinMMCA.Common.Testing.Architecturepins 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 ofAddForwardedJwtBearer(...)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 theirbuilder.AddMmcaServiceHost(...)call:MMCA.ADC/Source/Services/MMCA.ADC.Conference.Service/Program.cs:88,MMCA.ADC/Source/Services/MMCA.ADC.Engagement.Service/Program.cs:59andMMCA.ADC/Source/Services/MMCA.ADC.Notification.Service/Program.cs:58. Unit-tested byMMCA.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 inMMCA.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.IConfigurationonly. Its consumer isAddForwardedJwtBeareron 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 hostProgram.csfiles 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'sWithJwksDiscovery(identityService, gateway)sets, and that the Azure deployment template sets in production (:17-20).GetRequiredJwtAuthority()(:36), anextension(IConfiguration configuration)member. It null-guards the configuration itself (:38), then reads the key and throws anInvalidOperationExceptionnaming 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 byAddForwardedJwtBearer's ownArgumentException.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:WithJwksDiscoverysetsAuthentication__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
AddForwardedJwtBearercall site (MMCA.Common/Source/Hosting/MMCA.Common.ServiceHost/ServiceHostBuilderExtensions.cs:139), so every non-issuer service host reaches it throughbuilder.AddMmcaServiceHost(...). ADC: Conference (MMCA.ADC/Source/Services/MMCA.ADC.Conference.Service/Program.cs:88), Engagement (:58of its ownProgram.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 setAuthentication = 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 throughAddCommonAuthenticationinstead (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
.Createand ASP.NET Core'sUseForwardedHeadersextension. - 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-lineextensionmember that callsapp.UseForwardedHeaders(CommonForwardedHeaders.Create(headers)). - Why it's built this way: a named extension on
IApplicationBuilderrather than a bare call toCommonForwardedHeaders.Create()plusUseForwardedHeadersgives 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, insideUseMmcaBlazorWebPipelineat:181), so the ADC Blazor UI host gets it through itsapp.UseMmcaBlazorWebPipeline(...)call (MMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI.Web/Program.cs:120,:130on thenet10.0line). - 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
.UseMiniProfileris 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 testsapplicationSettings.UseMiniProfiler(:28) and only then callsAddMiniProfiler(...)with a/profilerroute base,PopupShowTimeWithChildrenand the dark color scheme (:30-34), sets bothResultsAuthorizeandResultsListAuthorizeto the privateIsDevelopmentpredicate (:35-36), and chains.AddEntityFramework()(:37) so EF and SQL timings appear inline. It returnsserviceseither way (:40) so the call chains.IsDevelopment(HttpRequest)(:45-46) resolvesIHostEnvironmentfrom the request's services withGetService, 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 DEBUGlets 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(...)inMMCA.Common/Source/Presentation/MMCA.Common.API/DependencyInjection.csdoes not invoke it, and no ADC or Store source calls it directly; a host reaches it throughAddMmcaServiceHostor 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 onAddMmcaServiceHostturns profiling on withApplicationSettings:UseMiniProfileralone; a host composing its own pipeline callsUseMiniProfiler()itself. The/profilerresult routes answer only in Development (401 elsewhere) unless the host overridesMiniProfilerOptions.ResultsAuthorizeandResultsListAuthorizewithservices.Configure<MiniProfilerOptions>(...)after this call (doc commentMiniProfilerExtensions.cs:17-24). Which deployments setApplicationSettings:UseMiniProfileris 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 leastJwt:MinimumRsaKeySizeBitsbits, 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, default3072with 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 intoIValidateOptions<T>means a 2048-bit RSA key or a P-256 EC key failsValidateOnStartlike 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 statichelpers 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 measuresJwt:EcPrivateKeyPemandJwt:EcPublicKeyPem(:41-45); for RS256 and PS256 it measuresJwt:RsaPrivateKeyPemandJwt:RsaPublicKeyPem(:46-50), then hands the collected shortfalls toOutcome(:52).AddShortfall(...)(:64) skips a key that is not configured (:71-74), asksJwtKeyMaterial.StrengthShortfallfor 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).StrengthShortfallreturnsnullfor 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), otherwiseValidateOptionsResult.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.
- The primary constructor takes the logger and an optional
- Why it's built this way: an options validator runs where configuration errors already surface, so no separate startup hook is needed, and
TryAddEnumerableregistration (WebApplicationBuilderExtensions.Authentication.cs:148-149) keeps a host that callsAddCommonAuthenticationtwice from validating twice. The environment parameter is nullable and the check isenvironment?.IsDevelopment() == true(:102), so an unknown environment is treated as production: the relaxation is the exception that has to be proven, not the default.AddShortfallandOutcomeareinternal staticrather 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
AddCommonAuthenticationon 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 inMMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/Startup/Auth/JwtKeyStrengthStartupTests.cs. - Caveats / not-in-source: a key that cannot be parsed passes this validator (
StrengthShortfallreturnsnull) 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,IServiceCollectionandSystem.Reflection.Assemblyfrom 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
AddModuleHostbind 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, betweenAddApplication()andAddApplicationDecorators(), 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 avoid-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 writespipeline.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.
_configurationand_moduleAssemblies(ModuleHostContext.cs:23-24) are the discovery arguments captured atAddModuleHosttime that are not also exposed as properties, so the deferred call needs no state from the caller. No environment name is captured:ModuleLoader.DiscoverAndRegisterno longer takes one (doccrefat:54).- The
internalconstructor (:26-38) means only ModuleHostExtensions in the same assembly can build one; a host receives an instance, it never constructs one. ApplicationSettings(:41) andModulesSettings(:44) expose the bound sections, so the host can pass them onward without re-reading configuration (ADC passesmoduleHost.ModulesSettingsstraight intoAddAPI,MMCA.ADC/Source/Services/MMCA.ADC.Conference.Service/Program.cs:386).ModuleLoader(:51) exposes the loader thatAddModuleHostregistered as a singleton. Its doc comment names the two later calls that need it:AddModuleHealthChecksafter the pipeline has run discovery, andInitializeDatabaseAsync(:46-50).RegisterModules(IServiceCollection services)(:69) null-guards the collection (:71), callsModuleLoader.DiscoverAndRegisterwith the captured configuration, both settings objects and the assemblies (:73-78), then runsThrowWhenNoModuleIsEnabled(ModuleLoader)(:80). The signature match withDiscoverAndRegisteris the whole point of the captured fields. The XML doc declares the second failure mode besideArgumentNullException: anInvalidOperationExceptionwhen 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 anInvalidOperationExceptionthat 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. ExposingRegisterModulesas 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 explicitModules:{Name}:Enabled=true: the doc comment (:63-68) records that a host whoseModulessection 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
moduleHostand touches it three times:moduleHost.ModulesSettingsintoAddAPI,pipeline.Register(moduleHost.RegisterModules)insideAddMmcaApplicationPipeline, andmoduleHost.ModuleLoaderintoAddModuleHealthChecks(MMCA.ADC/Source/Services/MMCA.ADC.Conference.Service/Program.cs:386,:348,:364; the Identity, Engagement and Notification services andMMCA.Store/Source/Services/MMCA.Store.Sales.Service/Program.cs:131follow 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
RegisterModulesis ever called, or called in the right place. A host that builds aModuleHostContextand 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 insideRegisterModules. The test file records that there is deliberately no test drivingRegisterModulesthrough 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 sameProgram.csline is safe in every host. - Walkthrough:
MapNotificationHub()(SignalRExtensions.cs:22) resolvesIOptions<PushNotificationSettings>throughGetService<T>(), which returns null when nothing registered it, and takes?.Value(:24). Only whensettings is { Enabled: true }(:25) does it callMapHub<NotificationHub>(settings.HubPath, ...)(:31-33), setting the hub'sCloseOnAuthenticationExpirationfromsettings.CloseConnectionsOnTokenExpiry(PushNotificationSettings,MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Notifications/Push/PushNotificationSettings.cs:100). It returnsappeither way (:36). The doc comment (:16-21) notes it must run afterUseCommonMiddlewarePipeline()so authentication and routing are already in place. - Why it's built this way:
GetServicerather thanGetRequiredService, 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 anaccess_tokenquery-string fallback for/hubson both authentication paths (HubAccessTokenEvents,WebApplicationBuilderExtensions.Authentication.cs:192-207, assigned at:114and:157): a WebSocket cannot send anAuthorizationheader. - 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:
CloseConnectionsOnTokenExpiryis a plainboolwith 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 itsProgram.cs. It returns a ModuleHostContext. - Depends on: ModuleHostContext (which it constructs), ModuleLoader, ApplicationSettings, ModulesSettings and IModule (the interface discovery looks for);
Microsoft.Extensions.Optionsvalidation,IConfiguration,ILogger<T>andSystem.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
ApplicationSettingson 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 eachProgram.csis that line drawn on purpose.[Rubric §15, Best Practices & Code Quality]also applies:ValidateDataAnnotations().ValidateOnStart()on theApplicationSettingssection turns a misconfigured section into a startup failure rather than anullthat 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 forbuilder.Servicesandbuilder.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 throwsInvalidOperationExceptionwhen it is absent (:66-67). The two are not redundant:ValidateOnStartfires when the host starts, while the eagerGet<T>()is what lets the returned context hand the bound settings back to the caller immediately, beforebuilder.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 noApplicationSettingsis not. It is deliberately not registered asIOptions<ModulesSettings>; the comment (:69-70) gives the reason: the bound value is handed to the loader and toAddAPIdirectly, 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
NullLoggerdefault 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).
- Null-guards the builder and the assembly list (
- Why it's built this way: the
moduleAssembliesparameter is required rather than defaulted to anAppDomainscan, 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:209and Notification:187in their own files) and the Store Sales and Catalog hosts (MMCA.Store/Source/Services/MMCA.Store.Sales.Service/Program.cs:131-133), each passingSerilogHostExtensions.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 emptyModulesSettingsfallback (: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
ModuleLoaderinline and callsDiscoverAndRegisterdirectly (MMCA.Helpdesk/Source/Hosts/MMCA.Helpdesk.Web/Program.cs:97and: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 everyJwks:AdditionalKeysentry to the same strength floor (RSA at leastJwt:MinimumRsaKeySizeBitsbits, 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.AddShortfalland.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.jsonis 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 theAdditionalKeyslist. See ADR-149. - Walkthrough: one public member and two private helpers.
- The primary constructor takes
IOptions<JwtSettings>, the logger and an optionalIHostEnvironment(JwksKeyStrengthValidator.cs:20-23). Validate(string?, JwksSettings)(:26) null-guards the options (:28) and reads the floor fromJwtSettings.MinimumRsaKeySizeBits(:30-31). Whenoptions.Enabledit measures the current published key under the configured signing algorithm, or under RS256 when the configured algorithm is HS256 (:34-42). It then walksAdditionalKeysby index, skipping any whose algorithm is not asymmetric (:44-50) and measuring the rest under aJwks:AdditionalKeys:{i}:prefix built with the invariant culture (:52-58). Each measurement goes throughJwtKeyStrengthValidator.AddShortfall, and the result throughJwtKeyStrengthValidator.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 returnsnullfor a blank path or on anIOException,UnauthorizedAccessException,ArgumentExceptionorNotSupportedException(: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.
- The primary constructor takes
- Why it's built this way: reusing the two
internal statichelpers 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
AddCommonAuthenticationon WebApplicationBuilderExtensions viaTryAddEnumerable(WebApplicationBuilderExtensions.Authentication.cs:150-151). It runs whenJwksSettingsoptions are validated; Infrastructure registers those withValidateDataAnnotations().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
AddCommonAuthenticationwithout the InfrastructureJwksSettingsregistration has noValidateOnStartfor that options type, and the check would then run only when something first resolvesIOptions<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.csand.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;
AddAuthorizationPoliciesfromMMCA.Common.API.Authorization; ApiParameterDescriptorBackfillProvider; RateLimitingSettings, RateLimitAlgorithm, RedisFixedWindowRateLimiter and RemainingWindowFixedWindowRateLimiter; RetryAfterRejection (the 429'sRetry-Afterheader); 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 andAsp.Versioningprimitives;Microsoft.IdentityModel.TokensandStackExchange.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 spoofableContent-Typeheader, 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 theapi-versionreader withAssumeDefaultVersionWhenUnspecifiedandReportApiVersions(:44-46), the API explorer group format'v'VVVandSubstituteApiVersionInUrl(:48-51), then the backfill guard (:54). The comment (:39-41) records thatDefaultApiVersionis 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 atCompressionLevel.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 throughservices.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 theservices.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 theAddOpenApicall sites of the project being compiled, and a registration made inside this assembly would carry none of them (doc comment:82-87). Pair it withMapCommonOpenApi()on OpenApiEndpointExtensions, which the same doc comment says fails at startup outside Production when nov1document was registered (:87-89).AddApiParameterDescriptorBackfill()(WebApplicationBuilderExtensions.cs:132, private) registers ApiParameterDescriptorBackfillProvider viaTryAddEnumerable(:119-120), which de-duplicates on implementation type, so calling bothAddCommonApiVersioningandAddCommonOpenApiinstalls the guard exactly once (:111-117).AddCommonCors(IConfiguration)(WebApplicationBuilderExtensions.cs:140): the restrictive production policy takes its origins fromCors:AllowedOriginsand allowlists four headers and five methods withAllowCredentials(:130-136); the development any-origin policy sits under a justified#pragma warning disable S5122explaining 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'sOnRejectedcallback so every 429 carries aRetry-Afterheader whenever the rejecting lease reports aMetadataName.RetryAfterhint (:46-49), formatted by itsFormatin whole seconds, rounded up and never negative (:27-31).Formatis a copy of RetryAfterHeader.Formatbecause 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 policyMapCommonMcpinMMCA.Common.Mcpapplies 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, atRateLimitingSettings.McpPermitLimit(:30-36).RateLimitPolicyWellKnown(:51,"wellknown"): one fixed window per client IP for the public discovery documents,RateLimitingSettings.WellKnownPermitLimitrequests per minute (default 60 per the doc comment,:41).MapJwksEndpointandMapOidcDiscoveryEndpointapply it, so a host that maps either behindUseRateLimitermust register it throughAddCommonRateLimiting;MMCA.Common.Gatewaydoes not register it, and a YARP gateway instead declares a policy of the same name underMmcaGateway:RateLimiterPolicies:wellknown(:42-48). The global limiter still exempts these paths; this policy is what bounds them (:48-49).IsRateLimitBypassed(HttpContext)(:70) exempts/health,/aliveand/.well-known/*(:71-73), then a mapped gRPC endpoint throughIsGrpcEndpoint(: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'sContent-Typeheader: a caller-suppliedContent-Type: application/grpcheader 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 ownMapGrpcServiceregistrations and cannot be forged; the predicate runs from the rate-limiting middleware, afterUseRouting, so the endpoint is already resolved. It isinternalrather than private specifically so the exemption logic is unit-testable throughInternalsVisibleToinstead 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), whereIsAnonymousHubRequestroutes it throughCreateLimitedPartitionkeyed on ClientAddressKey.For(...)of the client IP (or"anonymous-hub"when there is none) withredisScope: "hub",settings.AnonymousHubPermitLimit,queueLimit: 0andcountLocallyOnRedisFault: false(:87-95). The remark (SEC-ADC-25,:80-85) is the reason: a gateway that bypasses/hubsat 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 ofsettings.HubPathPrefixes(:113-115);internalfor the sameInternalsVisibleToreason.GrpcServerMetadataNamespace(:123, the literal"Grpc.AspNetCore.Server") andIsGrpcEndpoint(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).GlobalRateLimitPartitionhas two overloads. The permit-count one (:158-159) simply wraps its argument in a RateLimitingSettings and delegates; the settings one (:166) holds the logic: aNoLimiterfor bypassed infrastructure (:168-171) and, for unauthenticated callers, a delegate toAnonymousPartitionrather than an unconditionalNoLimiter(:173-176), otherwise a partition keyed by the user-id (subject) claim, thenIdentity.Name, then theClientAddressKeyof the remote IP, then the literal"authenticated"(:178-181), built throughCreateLimitedPartitionwithredisScope: "global",queueLimit: 0andcountLocallyOnRedisFault: 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, withredisScope: "mcp",settings.McpPermitLimitandqueueLimit: 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 inMMCA.Common.Mcpthen 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.KeyPrefixwithout 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. Whensettings.Distributedis set (:255) it resolvesIConnectionMultiplexerthrough a nullable local, becauseHttpContext.RequestServicesis declared non-nullable but is genuinely null outside a request pipeline such as a bareDefaultHttpContextin 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'scountLocallyOnRedisFault(: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).countLocallyOnRedisFaultdecides what a Redis fault does:falsefails open (capacity protection never rejects a healthy request),truecounts 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 withSegmentsPerWindowsegments (:287-297) or the default fixed window, built as a RemainingWindowFixedWindowRateLimiter rather thanRateLimitPartition.GetFixedWindowLimiterbecause the framework limiter'sRetry-Afteris always the whole window, while the wrapper reports the time actually left (:299-307). Both run overTimeSpan.FromMinutes(1)withQueueProcessingOrder.OldestFirst.AuthIpRateLimitPartition(:321permit-count overload,:333settings overload) partitions the"auth-ip"policy on theClientAddressKeyof 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-processTestServerand the integration tier to a standstill. It passesredisScope: "auth-ip"andcountLocallyOnRedisFault: true(:340-347), so withDistributedand 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, otherwiseredisScope: "wellknown"atsettings.WellKnownPermitLimit, failing open on a Redis fault (:358-369).AddCommonRateLimitinghas three overloads (allWebApplicationBuilderExtensions.RateLimiting.cs). The permit-count one (:403) keeps the defaultsglobalPermitLimit: 300, authIpPermitLimit: 30and simply builds a RateLimitingSettings from them (:403-408). TheIConfigurationone (:418) null-guards the configuration (:420), registersRateLimitingSettingsas options bound to theRateLimitingsection 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),OnRejectedwrapped byRetryAfterRejection.WithRetryAfterHeaderso a refused caller learns when its window resets, while a lease without the hint (a concurrency rejection) sends no header (:449-451), the always-onGlobalLimiter(: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: theauth-ippolicy takes the client IP fromConnection.RemoteIpAddress, which the shared pipeline has already resolved fromX-Forwarded-ForbecauseUseForwardedHeadersruns beforeUseRateLimiter(:460-467); and thewellknownpolicy 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 whyauthIpPermitLimitis 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, thenRequireHttpsMetadataConfigKey, thentrueeverywhere except Development (:64-66). When the resolved value isfalseoutside Development it registers InsecureJwtMetadataWarningStartupFilter so the deviation is logged once at startup (:68-72), and finally delegates to the privateAddForwardedJwtBearerCore, passing the hub path read byResolveHubPath(configuration)along with the resolved posture (:74). Itsauthorityargument 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 fourthhubPathparameter) does the JWT wiring:Authority,AudienceandRequireHttpsMetadata(:86-88), validation parameters that deliberately leaveValidIssuerunset 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'sissclaim, the public gateway URL (:96-102),ValidAlgorithms = JwtAlgorithms.Asymmetric(RS256, PS256 and ES384,MMCA.Common/Source/Build/Auth/JwtAlgorithms.cs:25-30) andClockSkew = JwtAlgorithms.ClockSkew, 30 seconds (JwtAlgorithms.cs:22;:104-111). The comment (:104-109) gives the reason for the list: each published key carries its ownalg, 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 SignalRaccess_tokenquery-string fallback by assigningoptions.Events = HubAccessTokenEvents(hubPath)(:115) and then callsAddAuthorizationPolicies()(:118).AddCommonAuthentication(IConfiguration)(:142) is the in-process mode: it binds JwtSettings with data-annotation validation on start (:144-147), registers JwtKeyStrengthValidator and JwksKeyStrengthValidator throughTryAddEnumerable(:148-151), so outside Development an RSA key belowJwt: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 throughResolveHubPath(configuration)(:153), reads the optionalJwkssection 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 throughBuildValidationParameters(jwtSettings, jwksSettings)(:165), wires the same access-token fallback throughHubAccessTokenEvents(hubPath)(:169), and adds the authorization policies (:172).ResolveHubPath(IConfiguration)(:182,private static, outside the extension block) reads thePushNotificationssection (PushNotificationSettings.SectionName,MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Notifications/Push/PushNotificationSettings.cs:11) and returns itsHubPath, 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 oneJwtBearerEventsboth modes share.OnMessageReceivedtakes the token from theaccess_tokenquery parameter only when it is non-empty and the request path is under the configuredhubPathor under the literal/hubsfloor (:194-206), so a host that moves its notification hub still authenticates, and a host mapping further hubs under/hubskeeps working. A WebSocket upgrade cannot carry anAuthorizationheader, 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.IsAsymmetricof the configured JwtSigningAlgorithm (:226-227). The asymmetric branch picksEcPublicKeyPemfor ES384 andRsaPublicKeyPemfor RS256 and PS256, and throws a message naming the missing setting and the algorithm that points atAddForwardedJwtBearerwhen 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), setsIssuerSigningKeystojwksSettings?.CreateAdditionalValidationKeys() ?? [](:246;CreateAdditionalValidationKeysatMMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/JwksSettings.cs:183, one RSA or ECDSA key per additional key by its algorithm) beside it, and pinsValidAlgorithms = JwtAlgorithms.Asymmetricwith the 30-secondClockSkew(: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.jsonpublishes, so a signing-key rotation, including one that changes the algorithm, does not reject tokens the previous key signed. The HS256 path builds aSymmetricSecurityKeyfromJwtSettings.DecodeHmacSigningKey(jwtSettings.SecretForKey)and pinsJwtAlgorithms.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) throwsInvalidOperationExceptionwhen 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
ValidAlgorithmspin on both paths is deliberate defense in depth rather than trust in the token header. TakingIConfigurationandIHostEnvironmentas required arguments onAddForwardedJwtBeareris 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 throughCreateLimitedPartitionis 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 callsAddCommonCors,AddCommonApiVersioning,AddCommonRateLimitingandAddCommonResponseCompression(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 andbuilder.Environmentso the framework resolves the metadata posture (ServiceHostBuilderExtensions.cs:132-143). Each ADC service host keeps its ownbuilder.Services.AddOpenApi()line (MMCA.ADC/Source/Services/MMCA.ADC.Conference.Service/Program.cs:86) and the composed host addsAddCommonOpenApi()(ServiceHostBuilderExtensions.cs:130). The"auth-ip"policy is applied by attribute on the login and register actions of AuthControllerBase (AuthControllerBase.cs:78and:96), so every consumer inheriting that base gets it without opting in. The internal partition helpers are exercised directly byWebApplicationBuilderExtensionsTests,RateLimitPartitionTestsandRateLimitAlgorithmSelectionTests; the metadata resolution byForwardedJwtBearerSecurityTests. - 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. LikewiseDistributedonly takes effect when the host also registers anIConnectionMultiplexer; 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
IStartupFilterthat writes a single warning at host startup whenAddForwardedJwtBearerresolvedRequireHttpsMetadatatofalseoutside 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.RequireHttpsMetadataConfigKeyfor the key name it echoes. - Concept introduced (
IStartupFilteras a "log after the logging providers exist" hook). Registration-time code runs while theIServiceCollectionis still being built, so the logging providers are not configured yet and anything written there is dropped.IStartupFilter.Configureruns 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 returnsnextunchanged (: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 atLogLevel.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 callsAddForwardedJwtBearermore than once still gets exactly one warning. Registration is itself conditional (:67): the filter is only added when the resolved value isfalseand 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 byForwardedJwtBearerSecurityTests(MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/Startup/ForwardedJwtBearerSecurityTests.cs). In the deployed apps the ADC service hosts document the override explicitly: Azure setsAuthentication:JwtBearer:RequireHttpsMetadatatofalsebecause 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 twoUseCommonMiddlewarePipelineoverloads, 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 theMiddlewarePipelineOrderTestsBasefitness 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,ArgumentNullExceptionand theInvalidOperationExceptionan 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 theRequestLocalizationstep of the default pipeline, and Blazor UI hosts call it explicitly beforeMapRazorComponentsso SSR prerender runs under the right culture (:46-52).MapCultureEndpoint()(:83) is a one-line default that calls theMapCultureEndpoint(bool httpOnly)overload withhttpOnly: false.MapCultureEndpoint(bool httpOnly)(:96) does the real work: it maps the anonymousGET /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-chosenHttpOnly(:110-121, withSecure = !app.Environment.IsDevelopment() || context.Request.IsHttpsand a one-year expiry), then local-redirects (:128-129) to force a full reload. Both Sonar deviations are justified inline at:109:S3330because the cookie is non-HttpOnly by default for the WASM client, andS2092becauseSecurefollows theSessionCookieJar.BuildOptionsrule (always set outside Development, and in Development whenever the request is HTTPS), so only a plain-HTTP Development host writes the cookie withoutSecure. The redirect target passes throughIsLocalRedirectTargetfirst and falls back to/when the requested target is missing or not local (:125-128):Results.LocalRedirectthrows at execution for a non-local URL, which on this anonymous endpoint would surface as a 500 rather than a redirect. ThehttpOnlyparameter (:89-94) exists so a Server-only host that never runs WASM can passtrueand keep the cookie out of script reach; a host that serves a WebAssembly client must keep the parameterless overload'sfalse, because the WASM runtime reads the cookie directly on startup (MmcaCultureBootstrap.SetBrowserCultureAsync).IsLocalRedirectTarget(string?)(:144, private) applies the ruleLocalRedirectitself 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 whatLocalRedirectrejects 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 theSec-Fetch-Siteheader equalscross-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), thenforeachoverbuilder.Build()invoking each step'sConfigurein 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
ApplyPipelinehere is what lets the order be inspected and asserted while the entry point stays a single line in a host'sProgram.cs. Theconfigure-then-Buildsequence 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 reachUseCommonMiddlewarePipelinethroughawait app.UseMmcaServiceHostAsync(host)(MMCA.Common/Source/Hosting/MMCA.Common.ServiceHost/ServiceHostApplicationExtensions.cs:59and:63), for exampleMMCA.ADC/Source/Services/MMCA.ADC.Conference.Service/Program.cs:379,MMCA.ADC/Source/Services/MMCA.ADC.Notification.Service/Program.cs:152andMMCA.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:201and:211), which the ADC UI host invokes withapp.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 onlyWebApplicationExtensionsin MMCA.Common (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/WebApplicationExtensions.cs:15): the server-rendered UI pipeline isUseMmcaBlazorWebPipeline(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 aWebApplicationwrapper 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
WebApplicationwrapper. Externally it uses onlyIServiceProviderscoping,IOptions<T>, the host's environment and configuration, and EF Core'sDatabaseFacade(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 singleDatabaseInitStrategystring 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 onIServiceProvider(DatabaseInitializationExtensions.cs:39) and one onWebApplication(:151), declared with C#extension(T)syntax like the rest of the framework's DI and startup helpers. The class carries a justifiedCA1708suppression 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 throwsUnknownStrategy(: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: resolvingIEntityDataSourceRegistryand callingGetPhysicalSourcesInUse()(: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 wherePhysicalDataSource.UsesMigrationsis true is also skipped (:99-102); everything left is created outright withEnsureCreatedAsync(: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 theUsesMigrationsexclusion: runningEnsureCreatedagainst a PostgreSQL or SQLite source that does have a migrations assembly writes the tables with no__EFMigrationsHistoryrow, after which every migration is both pending and un-appliable because itsCREATE TABLEhits an existing table. The third (:88-89) is why no engine filter is needed: a SQL Server source always answersUsesMigrationsand is skipped, so only a migration-less source reachesEnsureCreated.UsesMigrationsitself is the per-engine rule on the source record, read from the engine'sMigrationPolicycapability (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 atry(:113), and afinallyrestores 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 toIDbContextFactory.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"callsThrowIfPendingMigrationsAsync(:126). Thedefaultarm rethrowsUnknownStrategy(:129), unreachable in practice because of the guard at:63but 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 theWebApplicationwrapper 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 theMmcaOpenApiDesignTimeconfiguration switch (OpenApiDesignTimeKey,:31) is true (:176-179), and otherwise forwards toInitializeDatabaseAsyncwithmoduleHost.ApplicationSettingsandmoduleHost.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) resolvesIOptions<TenancySettings>withGetServicerather thanGetRequiredService(:205) and returns immediately when tenancy was never registered or no tenants are configured (:206-209). Otherwise it expands the sources into targets viaTenantDataSourceTargets.Expandand keeps only the ones with a tenant id (:211-212), becauseExpandalso emits the shared, tenant-less target for each source, which the pass above already handled. For each target it opens a fresh scope throughIServiceScopeFactory.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, callsITenantContext.SetTenanton 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
UsesMigrationsoff 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 getsMigrateAsyncand anything else getsEnsureCreatedAsync(:233-243), under"None"it defers toApplyNoneStrategyToTenantAsync(: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 withEnsureCreatedAsync(:318-322), mirroring the shared migrationless pass, because nothing else ever creates it (:307-311); every other copy goes toThrowIfTenantPendingMigrationsAsync(:324).- The two out-of-band rails.
ThrowIfTenantPendingMigrationsAsync(:332) no-ops for a non-migrated source (:338-341), otherwise queriesGetPendingMigrationsAsync(:343) and, when anything is pending, throws naming the tenant target, the migrations, and thedotnet ef database updateremedy (:349-352).ThrowIfPendingMigrationsAsync(:361) short-circuits onIDbContextFactory.HasPendingMigrationsAsync(:367-370), then builds a per-source breakdown by re-querying each key whose resolved source answersPhysicalDataSource.IsMigrationTarget(:372-381) before throwing (:383-385).IsMigrationTargetnow lives on the source record (PhysicalDataSource.cs:57-60): a source thatUsesMigrationsand 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.csfiles. PostgreSQL joining the migrationless pass alongside Cosmos and SQLite (ADR-113) is exactly that: a host that names noPostgreSQLMigrationsAssemblygets the sameEnsureCreatedAsynctreatment 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, ...), throughawait app.UseMmcaServiceHostAsync(host)(MMCA.Common/Source/Hosting/MMCA.Common.ServiceHost/ServiceHostApplicationExtensions.cs:54; call sitesMMCA.ADC/Source/Services/MMCA.ADC.Conference.Service/Program.cs:379,MMCA.Store/Source/Services/MMCA.Store.Sales.Service/Program.cs:154), which readsApplicationSettingsandModuleLoaderoff ModuleHostContext (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/ModuleHostContext.cs:41,:51); Helpdesk callsInitializeDatabaseAsyncdirectly 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 byDatabaseInitializationExtensionsTests(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 asTenancySettings:Expandemits 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 anAppAssociationconfiguration 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 inassetlinks.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): theTeamID.BundleIDvalue used by both thewebcredentialsand theapplinkssections.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 initgives 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
AppAssociationconfiguration 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 overridesApplicationIdtoivanball.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
JsonWebKeySetinstance it last served beside that set's serialized JSON, as the positional pair(KeySet, Json)(JwksEndpointExtensions.cs:84). - Depends on:
Microsoft.IdentityModel.Tokens.JsonWebKeySetand BCLstring. 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.
KeySetis the cache key, and the cache compares it by object identity withReferenceEquals, never by value (JwksEndpointExtensions.cs:72).Jsonis 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 singleVolatile.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_entryfield (:67). - Caveats / not-in-source: the simple name is shared with other nested records that have nothing to do with this one:
SerializedDocumentCache.Entryon 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 inInboxConsumeScope(G04), and the health-report cache slot inCachedHealthReportProvider(G16). TheEntryanchor 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 ofapp.UseX()calls. - Depends on: ASP.NET Core's
WebApplication(through theAction<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 (StepNameson 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 untilUseCommonMiddlewarePipelineruns 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 untilConfigureis 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 withValidated(Name), which callsArgumentException.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 secondValidatedoverload, which null-guards the delegate (:38-42).- The
initaccessors 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:
Configureis invoked exactly once, in pipeline order, at the pointUseCommonMiddlewarePipelineis 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 toInsertBefore/InsertAfter/Replace. - Caveats / not-in-source: name uniqueness is not enforced here; it is enforced by the builder's
RequireUniqueNameat 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 stringfields 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 aconstis 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 afterRouting: it reads the selected endpoint's metadata.Cors(:45),Authentication(:48).TenantResolution(:54), whose comment (:50-53) records that it must run immediately afterAuthenticationbecause the claim strategy readsHttpContext.User.RateLimiting(:57), documented as needing to run afterAuthenticationper 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: withViewAs:Enabledfalse it refuses every view-as token.Authorization(:69),OutputCache(:72).JwksEndpoint(:75),OidcDiscoveryEndpoint(:78), andControllers(: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:
constrather thanstatic readonlyso the values are usable in attribute arguments andswitchpatterns, 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; andMiddlewarePipelineOrderTestsBase.ExpectedStepNames(MMCA.Common/Source/Hosting/MMCA.Common.Testing/Conformance/MiddlewarePipelineOrderTestsBase.cs:40-61) lists all nineteen as the frozen expected order, which each app'sMiddlewarePipelineOrderTestssubclasses.
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 theOpenApi:ExposeOutsideDevelopmentswitch istrue(defaultfalse). - Depends on:
Microsoft.AspNetCore.OpenApiforMapOpenApi()and the keyedIOpenApiDocumentProviderit probes;IConfigurationfor the exposure switch. It pairs with the host's ownservices.AddOpenApi(), which registers thev1document, plusAddCommonOpenApi()on WebApplicationBuilderExtensions, which only configures the registered documents and registers none of its own (doc commentOpenApiEndpointExtensions.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 generatedProblemDetailserror schema) is diffed against a committed baseline in-repo byOpenApiBaselineTests(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 plainAddOpenApi()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 orGetValue<bool>reads the switch astrue(:71-72); everywhere else it does nothing and returnsappfor chaining (:87). Where it maps, it first resolvesIServiceProviderIsKeyedServiceand checks that a keyedIOpenApiDocumentProviderexists for"v1"(:74-75); if not, it throwsInvalidOperationExceptiontelling the host to callservices.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 withapp.MapOpenApi().AllowAnonymous()(:84). The anonymous declaration is load-bearing: the framework's fallback authorization policy gates every endpoint that states nothing and/openapiis 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 becauseAddCommonApiVersioning'sAddApiExplorercall lives in this assembly, but no versioned OpenAPI registration exists (Asp.Versioning.OpenApiis not referenced, soWithDocumentPerVersion()is not available). The host serves the single plainv1document. - 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 explicitAllowAnonymous()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 afterUseCommonMiddlewarePipeline(ServiceHostApplicationExtensions,MMCA.Common/Source/Hosting/MMCA.Common.ServiceHost/ServiceHostApplicationExtensions.cs:66). The ADC integration tiers subclassOpenApiContractTestsBase(MMCA.Common/Source/Hosting/MMCA.Common.Testing/Conformance/OpenApiContractTestsBase.cs:32), for exampleMMCA.ADC/Tests/Integration/MMCA.ADC.Conference.IntegrationTests/Contract/OpenApiContractTests.cs:15; the sharedServiceHostTestFactoryturns 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-45registers,:65maps) is whatOpenApiBaselineTestsboots;MapCommonOpenApiAuthorizationTests(MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/OpenApi/MapCommonOpenApiAuthorizationTests.cs) pins the anonymous declaration; andMapCommonOpenApiExposureTestspins the environment gate: 404 outside Development without the switch or with itfalse, 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
IAsyncResourceFilterthat 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 commentOversizeFormResourceFilter.cs:8-14). - Depends on: ASP.NET Core MVC filter and model-binding abstractions (
IAsyncResourceFilter,ActionDescriptor,BindingSource) andBadHttpRequestException. 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 aBadHttpRequestExceptioncarrying 413 (:8-14). - Walkthrough
FilterOrder(OversizeFormResourceFilter.cs:29) is1000: 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) callsReadFormAsyncwith the request-aborted token (:42). ABadHttpRequestExceptionwhose status is not 413 is swallowed (:44), as isInvalidDataException(:48), so a malformed form or one over a form limit is still reported by model binding as before. A 413 propagates. It always callsnext()(:54).BindsForm(:57-60) is true when any action parameter's binding source isFormorFormFile.
- 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
AddAPIon DependencyInjection asoptions.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 commentFormFileUploadExtensions.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) andContentType(: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
ReadBoundedAsyncand 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 byFormFileUploadExtensionsTests(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.jsonand the Apple App Site Association at/.well-known/apple-app-site-association. - Depends on: AppAssociationOptions (Level 0) for every value; ASP.NET
IEndpointRouteBuilderandResults.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) andAppleAppSiteAssociationPath(: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 twoGETs that each returnResults.Json(...), are.AllowAnonymous()and are.ExcludeFromDescription()so they never leak into the OpenAPI document (:42-48).BuildAssetLinks(:54) emits thedelegate_permission/common.handle_all_urlsrelation with the Android package name and the fingerprint list (:56-65).BuildAppleAppSiteAssociation(:68) emits theapplinksdetails block, projecting each configured URL pattern into a{ "/": pattern }component (:78-80), plus thewebcredentialsapps list naming the same app id (:84-87).
- Two path constants:
- 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 byAppAssociationEndpointTests(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
JsonWebKeySetonce 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 commentJwksEndpointExtensions.cs:61-64). - Depends on: Entry (its one cached slot),
Microsoft.IdentityModel.Tokens.JsonWebKeySet,System.Text.Json.JsonSerializerandSystem.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),nulluntil the first request. Serialize(JsonWebKeySet)(:69) reads the field withVolatile.Read(:71); when an entry exists and itsKeySetisReferenceEqualsto 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 withVolatile.Write(:80), and returns its JSON (:81).
- One field,
- 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 callscache.Serialize(provider.GetJsonWebKeySet())per request (:49). The swap case is pinned byWellKnownEndpointHardeningTests.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 oneJsonWebKeySetin 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 commentFormFileUploadExtensions.cs:18-23). - Depends on: UploadedFileContent (Level 0) for
File, and CsvTable forTable. - Concept: the CSV flavor of the bounded upload read taught on FormFileUploadExtensions.
- Walkthrough: two positional components (
:24).Fileis the raw upload, bytes unchanged (:22);Tableis 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
ReadCsvCoreAsyncon 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 byFormFileCsvUploadTests(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 aMemoryStreamcopy per action (doc commentFormFileUploadExtensions.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 atFormFileUploadExtensions.cs:45-48).[Rubric §9, API & Contract Design]: every refused file returns the caller's ownErrorunchanged, 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) throwsArgumentOutOfRangeExceptionformaxBytesbelow 1 or aboveArray.MaxLengthandArgumentNullExceptionfor a null error (:51-53), then delegates toReadBoundedCoreAsync.ReadCsvAsync(maxBytes, invalidUpload)(:72) applies the same argument guards (:74-76) and delegates toReadCsvCoreAsync.ReadBoundedCoreAsync(:82) refuses a null, empty or oversize file withinvalidUpload(:88-89), checks cancellation, allocates onebyte[]of the declared length (:93) and fills it withReadExactlyAsync(:99). A stream shorter than its declared length raisesEndOfStreamException, which is answered with the sameinvalidUpload(: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-onlyMemoryStreamwithCsvReader.ReadTableAsync(:121-125). A parse failure returns the reader's own errors unchanged (MalformedCodewith the line inTarget, orEmptyCode, per the doc comment:65-69); success returns a CsvUpload (:127-129).
- One
- 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
awaitusesConfigureAwait(false)(:99,:116,:124), as packaged non-UI code requires. - Where it's used: ADC actions call it directly:
ReadBoundedAsyncfor 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) andReadCsvAsyncfor the ticket roster import (MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.API/Controllers/TicketRosterImportController.cs:77). Covered byFormFileUploadExtensionsTestsandFormFileCsvUploadTests(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 activeJsonWebKeySetof 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 theCache-Controlvalue both discovery documents are served with. - Depends on: IJwksProvider, resolved from DI per request, whose implementation is RsaJwksProvider; the nested SerializedKeySetCache; WebApplicationBuilderExtensions for the
wellknownrate-limit policy name; plusMicrosoft.IdentityModel.Tokens.JsonWebKeySetandSystem.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 singleGETwhose handler takesHttpContextandIJwksProvideras parameters (:47). Per request it serializes through the cache (:49), setsapplication/json; charset=utf-8explicitly (:50) and theCache-Controlheader (: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
JwksEndpointstep 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 thewellknownpolicy itself: one fixed window per client IP,WellKnownPermitLimitrequests per minute (default 60), registered byAddCommonRateLimiting(WebApplicationBuilderExtensions.RateLimiting.cs:39-51,:472-476). The doc comment draws the consequence: a host that runsUseRateLimitermust callAddCommonRateLimiting(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
JwksEndpointstep 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 thejwks_urivalue that OidcDiscoveryEndpointExtensions advertises, which is in turn whatAddForwardedJwtBearer(on WebApplicationBuilderExtensions) reaches through OIDC discovery. Its behavior is covered byJwksEndpointTestsandJwksMixedKeyTypeTests, and the hardening byWellKnownEndpointHardeningTests, 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 underMMCA.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
Entryrecord, the pair(Issuer, Json)(:153); IJwksProvider (optional) for the algorithm list; JwksEndpointExtensions.DefaultJwksPathforjwks_uri(:124); the outer class's three supported-value arrays andOidcJsonOptions(:31-33,:42-45);System.Text.JsonandSystem.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 withVolatile.Read(:95) and returns the cached JSON when the stored issuer equals the argument underStringComparison.Ordinal(:96-98). Otherwise it buildsnew Entry(issuer, BuildDocument(issuer, SigningAlgorithms(jwksProvider)))(:103), publishes it withVolatile.Write(:104), and returns its JSON (:105). BuildDocument(:114) derivesjwks_urias the issuer with any trailing/trimmed plusDefaultJwksPath(:124), then serializes an anonymous object carryingissuer,jwks_uri,response_types_supported,subject_types_supportedandid_token_signing_alg_values_supportedunderOidcJsonOptions(:126-133).SigningAlgorithms(:142) takes thealgof 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 toDefaultSigningAlgsSupported,["RS256"](:33), when there is no provider or no key carries analg(:150).
- One field,
- 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 inBuildDocument(:116-123) records whyjwks_uricomes from the configured issuer and not the inbound request: Aspire/DCP fronts the Identity service on per-launchSettings ports and rewritesHostviaX-Forwarded-Hostto canonical ports that internal callers cannot always reach, so reusing the issuer keeps issuer andjwks_uriorigin-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 callscache.Serialize(issuer, context.RequestServices.GetService<IJwksProvider>())per request (:75). Covered throughOidcDiscoveryEndpointTests(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 beforeSigningAlgorithmsruns (: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; andBuild()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 isCreateDefault().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()clearingKnownProxies/KnownIPNetworksfor cloud reverse proxies (:49-54; UI hosts take the same options throughUseCommonUiForwardedHeaders), an HTTPS redirect wrapped inUseWhenthat skips negotiated-h2c requests viaIsCleartextHttp2(: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 soact_subis 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 finallyMapControllers()(:148-150). EachConfiguredelegate isstatic, 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.IsHttpsandHttpProtocol.IsHttp2(Request.Protocol)(:368-369), i.e. the connection negotiated HTTP/2 without TLS. It replaced aContent-Type: application/grpcstring 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 ispublicspecifically so a host that rebuilds theHttpsRedirectionstep reuses the same predicate instead of reintroducing the forgeable check.- Four mutators, all returning
thisfor chaining and all validating first:InsertBefore(:161),InsertAfter(:178),Replace(:198) andRemove(:219).Replacekeeps 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:Authenticationimmediately beforeTenantResolution(:258-261). Five precedence checks:AuthenticationbeforeRateLimiting(:263-266, ADR-019),ForwardedHeadersbeforeHttpsRedirection(:268-271),AuthenticationbeforeSoftDeletedUserFilter(:273-276, the check reads the authenticated subject, so ahead of authentication a deleted user's live token passes),AuthenticationbeforeViewAsGuard(:278-281, the guard reads theact_subclaim of ADR-137), andRoutingbeforeViewAsGuard(: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) andRequirePrecedes(: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.
- One field,
- 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 noWebApplicationbuilt at all, which is what puts the fitness function in the fast unit tier. TheIsCleartextHttp2extraction 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 forgedContent-Typecould have served plaintext gRPC traffic that should have been redirected. - Where it's used: only through WebApplicationExtensions
.ApplyPipeline(WebApplicationExtensions.cs:164-175), which bothUseCommonMiddlewarePipelineoverloads 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);MiddlewarePipelineBuilderTestscovers the mutators and the invariants directly, andJsonBodySizeLimitStepTestscovers the body-size step. - Caveats / not-in-source: the builder validates order, not semantics. A
Replacethat keeps a step's name but swaps in an unrelated middleware passes every check, because nothing inspects theConfiguredelegate.
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 (theissuerandjwks_urifields, 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 returns404. - Depends on: the nested SerializedDocumentCache, which composes and caches the document; JwksEndpointExtensions for
DefaultJwksPath(OidcDiscoveryEndpointExtensions.cs:124) andDiscoveryCacheControl(:73); IJwksProvider, resolved optionally from the request services (:75); WebApplicationBuilderExtensions for thewellknownrate-limit policy name (:79);IConfigurationforJwt:Issuer;System.Text.Json. - Concept (OIDC discovery as the bootstrap for JWKS-based validation).
[Rubric §7, Microservices Readiness]and[Rubric §11, Security]:AddForwardedJwtBearersets anAuthority, and the JWT bearer middleware fetches{authority}/.well-known/openid-configurationto learn the issuer and the JWKS URL. This endpoint answers that fetch, which is the other half of ADR-004 alongside JwksEndpointExtensions. - Walkthrough
DefaultOidcDiscoveryPathconstant (OidcDiscoveryEndpointExtensions.cs:29).- Three static arrays:
ResponseTypesSupported(["token"]),SubjectTypesSupported(["public"]) andDefaultSigningAlgsSupported(["RS256"], the fallback when no key advertises an algorithm) (:31-33).OidcJsonOptionssetsPropertyNamingPolicy = null(:42-45). Disabling the naming policy is load-bearing: the field names are already OIDC snake_case per RFC 8414, and camelCasingjwks_uritojwksUriwould leaveOpenIdConnectConfigurationRetrieverunable to recognise the document (:35-41; the comment namesResults.Json, while the document is now serialized byJsonSerializer.Serializeunder the same options,:126-133). MapOidcDiscoveryEndpoint()(:61) creates one SerializedDocumentCache (:63) and maps aGETthat readsJwt:Issuer(:67); a blank issuer returnsResults.NotFound()(:68-71), safe because no downstream points its authority at a non-Identity host. Otherwise it sets the shared five-minuteCache-Controlheader (:73) and returns the cached document asResults.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_uriis built from the configured issuer and not from the request lives in the comment insideSerializedDocumentCache.BuildDocument(:116-123): reusing the issuer keeps issuer andjwks_uriorigin-aligned and routes both through the same gateway that fronts/Auth, so one forwarder rule for/.well-known/*covers everything. Returning a prebuilt string throughResults.Textmeans 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 thewellknownpolicy as onMapJwksEndpoint. - Where it's used: applied unconditionally as the
OidcDiscoveryEndpointstep of the default pipeline (MiddlewarePipelineBuilder.cs:144-146); consumed by the bearer middleware thatAddForwardedJwtBearerconfigures on WebApplicationBuilderExtensions, which deliberately leavesValidIssuerunset so the issuer comes from this document (WebApplicationBuilderExtensions.Authentication.cs:90-103). Covered byOidcDiscoveryEndpointTestsand, for the header and rate limit,WellKnownEndpointHardeningTests(both underMMCA.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 noauthorization_endpointortoken_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 rawIPAddress.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 constant64, the prefix one client is assumed to hold.For(IPAddress?)(:42) returnsnullfor 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 freshIPAddressplus"/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:
AddCommonRateLimitingin 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 byClientAddressKeyTests(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
*Featuresclasses declare flags this host may override" (doc comment,FeatureFlagCatalog.cs:7-8). - Depends on:
System.Reflection.Assemblyonly. - Concept introduced: none of its own; it is the multi-registration input of FeatureFlagCatalog, which teaches the declared-flag catalog. Wrapping a bare
Assemblyin a named record is what lets several modules each contribute one withAddSingletonand the catalog take them all asIEnumerable<FeatureFlagAssembly>, without colliding with any otherAssemblyregistration in the container. - Walkthrough: a positional record,
FeatureFlagAssembly(Assembly Assembly)(FeatureFlagCatalog.cs:9). No members beyond the generated ones. - Where it's used:
AddReloadableFeatureFlagsregisters 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
FeatureFlagsconfiguration section byAddReloadableFeatureFlags(doc commentFeatureFlagOverrideSettings.cs:5-8). - Depends on: nothing first-party.
System.ComponentModel.DataAnnotationsfor[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 onOverrideCacheSeconds(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, default30) 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.AddReloadableFeatureFlagsbinds it with.ValidateDataAnnotations().ValidateOnStart()(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.FeatureFlags.cs:67-70). - Where it's used: the shipped
FeatureFlagOverrideSnapshotturnsOverrideCacheSecondsinto its cache lifetime and foldsDataSourceNameinto its cache-key prefix (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/FeatureFlags/FeatureFlagOverrideSnapshot.cs:55,:62); the internalFeatureFlagOverrideModelContributorreadsDataSourceNameinAppliesToto 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 throughAddReloadableFeatureFlags(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.OverrideCacheSecondsstates. - 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'sICacheServiceunder 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 byStoredOverrideFallbackTests(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
AddReloadableFeatureFlagsand served by FeatureFlagsControllerBase (doc commentIFeatureFlagAdministrationService.cs:6-10). - Depends on: Result; FeatureFlagStatusResponse and SetFeatureFlagOverrideRequest.
- Concept (only a declared flag can be overridden). The declared set is what FeatureFlagRegistry
.Describereports over the assemblies the host passed toAddReloadableFeatureFlags, so an override cannot be written for a name no code reads: a typo is refused withFeatureFlag.Undeclaredrather than stored and left silently inert (IFeatureFlagAdministrationService.cs:11-16).[Rubric §9, API & Contract Design]: failures come back asResultvalues 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
FeatureFlagAdministrationServicealso 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 EngagementAdminFeatureFlagsControllersubclasses 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 byFeatureFlagsControllerBaseTests(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
AddReloadableFeatureFlagsregisters over the owning service's own database (doc commentIFeatureFlagOverrideStore.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
EFFeatureFlagOverrideStorebyAddReloadableFeatureFlags(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.FeatureFlags.cs:76; implementation atMMCA.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
stringonly. 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 forHttpContext, 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 theX-Correlation-IDheader 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 ofInvokeAsync(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
Activitytrace 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:IsPublicAddressandIsAcceptableTargetUri. - 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 address168.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 Teredo2001::/32, 6to42002::/16and the documentation prefixes2001:db8::/32and3fff::/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 "inside2000::/3and in none of the denied ranges" (:87-89).IsAcceptableTargetUri(target, allowInsecure)(:100) always requires the callable shape: absolute,httpsorhttp, no user info, a non-empty host (HasCallableShape,:114-118). UnlessallowInsecure(Development only, per the parameter doc), it also requireshttps, a host that is notlocalhostor*.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 withSequenceEqual, 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
IsAcceptableTargetUriand then requires every resolved address to passIsPublicAddress(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-Afterhint (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-Afterconcept. - Walkthrough: a primary constructor takes the
TimeSpan retryAfter(:137).IsAcquiredis constantfalse(:142).MetadataNamesreturns a static one-element array holdingMetadataName.RetryAfter.Name(:139,:145).TryGetMetadataanswers that name, compared ordinally, with the capturedretryAfter(:148-154) and every other name withnull/false(:156-157). - Where it's used: created only by the parent's
WithRemainingRetryAfter(:129). The rate-limiterOnRejectedcallback turns its hint into the 429'sRetry-Afterheader (: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
OnRejectedwrapper every MMCA rate limiter installs, so each 429 carries aRetry-Afterheader whenever the rejecting lease has aMetadataName.RetryAfterhint (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 aRetry-Afterlets 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 withMath.Ceilingand clamped at zero withMath.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 writesResponse.Headers.RetryAfterwhen the lease answersTryGetMetadata(MetadataName.RetryAfter, ...)(:46-49), then invokespreviouswhen there is one, or completes (:51). A fixed-window rejection carries the hint; a concurrency rejection does not, and sends no header (:36-37). Becausepreviousruns 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).Formatis a copy of RetryAfterHeader.FormatfromMMCA.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 ownOnRejectedlogic 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):AddCommonRateLimitingin 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).GatewayRetryAfterTestspinsFormatto 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-Afterhint. The framework'sFixedWindowRateLimiterstamps every rejection with the whole window length, so a 429 always saidRetry-After: 60however 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(ReplenishingRateLimiterbase, an innerFixedWindowRateLimiter),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: aRetry-Afterthat overstates the wait makes well-behaved clients back off longer than necessary.[Rubric §2, Design Patterns]: a decorator overFixedWindowRateLimiterthat forwards every permit decision unchanged and rewrites only the rejection metadata. - Walkthrough
- The constructor (
:45) copies the options into a new innerFixedWindowRateLimiterwithAutoReplenishment = falseforced (:49-56), because the owning partitioned limiter drives replenishment. It setsReplenishmentPeriodto the window (:57), takesTimeProvider.Systemwhen none is injected (:58), and stamps the window start (:59). IsAutoReplenishingisfalse(:63);IdleDurationandGetStatisticsforward 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.AttemptAcquireCoreandAcquireAsyncCore(:94,:98) both pass the inner lease throughWithRemainingRetryAfter(:121): an acquired lease, or a rejection with noRetryAfterhint (a request larger than the whole allowance,:119-120), is returned untouched (:123-126); any other rejection is disposed and replaced by a RejectedLease carryingTimeUntilNextWindow()(:128-129).Dispose(bool)andDisposeAsyncCoredispose the inner limiter before the base (:102-117).
- The constructor (
- 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.SharedbecauseSystem.Threading.RateLimitingships 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),AddCommonRateLimitingin 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.FeatureManagementFeatureDefinitionthe 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.Configurationin-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 sameFeatureDefinitionconfiguration 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), privateWholeGroup = "100"(:28). ToDefinition(:33) switches on the mode:Onbecomes oneAlwaysOnfilter with empty parameters (:35-39);Percentagea targeting filter with no users or groups and the stored percentage (:40);Targetinga targeting filter with the stored users, groups and percentage (:41);Offa definition with no filters (:42); an unknown mode also evaluates to off (:44-45). A null percentage becomes0.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 groupAudience:Groups:{i}:Namewith aRolloutPercentageofWholeGroup(: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) returnsOfffor a null orDisableddefinition (:53-56) or one with no named filters (:58-65);Onwhen every filter is always-on, or any is and the requirement type isAny(:68-71); otherwiseConditionalwith the filter names (:74).IsAlwaysOnacceptsAlwaysOnorOn, case-insensitively (:77-79).
- Constants:
- Where it's used: StoredOverrideFeatureDefinitionProvider calls
ToDefinitionfor 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*Featuresclasses, 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:
_flagsis aLazy(:19-22) overFeatureFlagRegistry.Describeon the distinct assemblies (:20), de-duplicated by flag name case-insensitively (:21).Flagsexposes 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
TryAddSingletonbyAddReloadableFeatureFlags(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
IFeatureDefinitionProviderthatAddReloadableFeatureFlagslayers 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 callingIFeatureManager, 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 orFeatureFlagDefinitions.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>inAddReloadableFeatureFlags, 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 throughConfigured.
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'sConfiguredwhen 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 ErrorFeatureFlag.Undeclaredfor 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 fromConfiguredProvider(: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>, optionalIHostEnvironment, 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 throughICacheService.RemoveByPrefixAsync, which on a Redis-backed host replaces one generation token so every replica stops addressing the old snapshot; on a memory-only hostFeatureFlags:OverrideCacheSecondsis the staleness bound for other replicas (FeatureFlagOverrideSnapshot.cs:20-24). - Walkthrough
KeyRoot = "featureflags:overrides:"(:53);_lifetimeisOverrideCacheSeconds(:55).Prefix(:62) isKeyRoot+ 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) usesIHostEnvironment.ApplicationName, else the entry assembly name, else"host"(:93).GetAsync(:65) isGetOrCreateAsynconPrefix + "all"(:66) withLoadAsyncas the factory, so the key and the invalidated prefix cannot disagree.InvalidateAsync(:70-71) removes byPrefix.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.IBaseDTOlets generic machinery treat any DTO uniformly through itsId, 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
TIdentifierTypewith awhere TIdentifierType : notnullconstraint (IBaseDTO.cs:10); the singleIdisget; init;(IBaseDTO.cs:13), settable at construction and immutable after. Theinit-not-setchoice 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 aGuid-keyed aggregate and anint-keyed one share the same generic pipeline; thenotnullconstraint forbidsIdbeing 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> atMMCA.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 exampleMMCA.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 responseETag, and the client echoes it back in theIf-Matchheader 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-generatedrowversion, and on PostgreSQL and SQLite it is stamped on every save instead (IConcurrencyAware.cs:17). A read DTO carries the currentRowVersionso 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 toETagtoIf-MatchtoSetOriginalRowVersion.[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 theIf-Matchheader's whole content, so it is never optional. A DTO read from a persisted aggregate always has one (AuditableBaseEntity.RowVersionis non-null), and a write that states no precondition is refused with428 Precondition Requiredrather 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")]onIConcurrencyAware.cs:18: exposing abyte[]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
Sharedmeans 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) andLivePollDTO(MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.Shared/LivePolls/LivePollDTO.cs:8), Store'sOrderDTO(MMCA.Store/Source/Modules/Sales/MMCA.Store.Sales.Shared/Orders/OrderDTO.cs:9) andInventoryItemDTO(MMCA.Store/Source/Modules/Sales/MMCA.Store.Sales.Shared/Inventory/InventoryItemDTO.cs:9), and Helpdesk'sTicketDTO(MMCA.Helpdesk/Source/Modules/Tickets/MMCA.Helpdesk.Tickets.Shared/Tickets/TicketDTO.cs:10). On the server, ApiControllerBase.SetConcurrencyETagwrites theETagresponse 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 publicbyte[] RowVersionproperty off the row's runtime shape (or therowVersionentry 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>.ConcurrencyTagOfpattern-matches the same interface to build the outgoingIf-Matchvalue, 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, andTokenIssuer = 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 againstAuthentication:JwtBearer:Authority,ServiceHostAuthentication.cs:8-11), while the issuer validates in process with its ownJwtsettings 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.Authenticationdefaults to it explicitly (MmcaServiceHostOptions.cs:52).AddMmcaServiceHostbranches on it:TokenIssuercallsAddCommonAuthentication, anything else callsAddForwardedJwtBearerwith the authority fromGetRequiredJwtAuthority()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.ForwardedJwtBearerAudienceIsFailClosedexempts a host file only when it namesServiceHostAuthentication.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
IOpenApiDocumentProviderandIServiceProviderIsKeyedService(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 whetherIOpenApiDocumentProvideris registered as a keyed service under"v1"(the registrationAddOpenApimakes) and returns if so (:26-30); otherwise it throwsInvalidOperationExceptiontelling the developer to callbuilder.Services.AddOpenApi()in the host's ownProgram.cs(:32). - Why it's built this way: the message states the reason. The OpenAPI XML-comment generator attaches controller summaries only at an
AddOpenApicall 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:
DocumentNamekeys the OpenAPI 3.1 pin inAddMmcaServiceHost(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 theIncrementconstant (: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: runningINCRBYandEXPIREas 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 runsINCRBY(: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 runsEXPIRE(: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:
RedisFixedWindowRateLimiterpasses it toScriptEvaluateAsyncwith the window key, the permit count and its key TTL (MMCA.Common/Source/Presentation/MMCA.Common.API/RateLimiting/RedisFixedWindowRateLimiter.cs:212-215);RedisCounterStoredoes the same with an amount of1(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Caching/RedisCounterStore.cs:91).RedisFixedWindowRateLimiterTestsasserts 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, forOpenDuration(10 seconds,:30). - Depends on: nothing first-party; StackExchange.Redis's
IConnectionMultiplexer, the BCLConditionalWeakTable,TimeProvider,VolatileandInterlocked(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 onelongread without a lock on the hot path. - Walkthrough:
OpenDurationisTimeSpan.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 staticConditionalWeakTable, creating it closed on first use (:32), so the table never keeps a disposed connection alive.ShouldAttempt(TimeProvider)(:50) returnstruewhile closed (:52-56); otherwise it returnstrueonly oncenow >= openUntiland the caller wins anInterlocked.CompareExchangethat pushes the window forward by anotherOpenDuration(: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 plusOpenDuration. - 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 ... LinkinMMCA.Common/Source/Core/MMCA.Common.Infrastructure/MMCA.Common.Infrastructure.csproj:18andMMCA.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). InjectingTimeProviderinto 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).RedisCounterStorechecksShouldAttemptbefore 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 inLogFault(:171).RedisFixedWindowRateLimiteranswers an open circuit as a fault would, counting locally for theauth-ippolicy 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/Testsnames 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
IdandName. - 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 returnsBaseLookup<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. BothId(BaseLookup.cs:12) andName(BaseLookup.cs:15) arerequired, 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), bindingIdand the named property into aBaseLookup<TIdentifierType>viaExpression.MemberInit(:262-268). Note the consequence forrequired: an expression-treeMemberInitconstructs the record without the compiler's required-member check, which is legal becauserequiredis 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
AddMmcaServiceHostreturns andUseMmcaServiceHostAsynctakes 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 theConfigurePipelinecallback 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 onApplicationStopped. - 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 toapp.UseMmcaServiceHostAsync(host)(for exampleMMCA.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 eachActionproperty 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
requiredmembers.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), typicallypipeline.Register(moduleHost.RegisterModules)plus gRPC clients andAddBrokerMessaging. Defaulted values:ProtocolsisHttpProtocols.Http2(:42;Http1AndHttp2for the ADR-012 mixed profile),RedeclareCleartextEndpointistrue(:49;falsefor a host that declares endpoints underKestrel:Endpoints),AuthenticationisForwardedJwtBearer(:52),UseRedisOutputCachingisfalse(:55). The optional callbacks, by the point they run:ConfigureConfigurationSourcesfirst of all, before any configuration is read (:66);AfterServiceDefaultsright afterAddServiceDefaults(), the place for vendor exporters and the shared DataProtection key ring (:72);ConfigureOutputCacheafter the always-present no-cache base policy (:60);ConfigureServicesafterAddAPI(:78);RegisterBrokerTransportsimmediately before the pipeline, becauseAddBrokerMessagingpicks 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
sealedwithinit-only members, so a host cannot change it after the call. - Where it's used: passed as
new() { ... }toAddMmcaServiceHostby 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. TheCA1708suppression (:26-29) is justified inline as anextension(T)false positive[Rubric §15, Best Practices]. - Walkthrough: guards first: null builder or options, and an empty
ModuleAssembliesthrowsArgumentException(: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);AddCommonSerilogthenAddServiceDefaults()thenAfterServiceDefaults(:84-86);AddRedisCaching, the Redis output cache when asked for, and the hybrid cache when Redis is configured (:91-97); a bootstrap logger factory andAddModuleHost(:101-104); infrastructure health checks withrequireDatabase: 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, thenAddCommonOpenApi()(:127-130), so a bareAddOpenApi()made before or after still emits 3.1 on both framework lines (ADR-141); token validation byAuthentication(:132-143); exception handlers,AddInfrastructure,AddAPI(:145-147);AddMiniProfilerIfEnabled(:151);ConfigureServices(:153);RegisterBrokerTransports(:156);AddMmcaApplicationPipelinewith the host'sConfigurePipelineas its body (:158);AddApplicationProfilingonly whenApplicationSettings:UseMiniProfileris true, after the pipeline becauseTryDecoratewraps 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 ownbuilder.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 atProgram.cs:55); its layer placement is pinned by Common'sLayerDependencyTestsandCloudVendorIsolationTests.
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) callspipeline.InsertAfter(MiddlewarePipelineStepNames.TenantResolution, ...)with a step that runsapp.UseMiniProfiler()(:25-27). Placing it right after tenant resolution meansHttpContext.Useris 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, whichAddMiniProfilerIfEnabledlimits to Development (:20-21)[Rubric §13, Observability & Operability]. - Where it's used: only by ServiceHostApplicationExtensions when
ApplicationSettings:UseMiniProfileris 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 whenUseMiniProfileris true (:57-64);MapCommonOpenApi(:66); in Development only, the gRPC reflection service markedAllowAnonymousfor the fallback authorization policy (:68-73, ADR-122); and finally registering disposal of the bootstrap logger factory onApplicationStopped(: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,
PermanentorTemporary(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.Permanentis "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) andTemporary(: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
Lifetimeargument every[FeatureFlag]attribute application supplies, acrossMMCA.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, andMMCA.Common/Source/Core/MMCA.Common.Shared/Privacy/PrivacyFeatures.cs; read back by FeatureFlagRegistry.Describeinto each FeatureFlagDescriptor.Lifetime, surfaced to operators as FeatureFlagStatusResponse.Lifetime, and checked by the governance architecture rule that fails aTemporaryflag past itsRemoveBydate (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, orTargeting(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 (= 0to= 3) pin the stored column against a reorder. - Walkthrough:
Off = 0is the kill switch (:13);On = 1is on for everyone (:16);Percentage = 2is 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 = 3is 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):Onbecomes an always-on filter,PercentageandTargetingbecome a targeting filter,Offbecomes 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 pageMMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Administration/FeatureFlagAdmin.razor.csoffers 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, orConditional(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 = 0covers "everyone, including a flag the configuration never mentions" (:12-13);On = 1is on for everyone (:15-16);Conditional = 2is "decided per evaluation by one or more feature filters" (:18-19). - Why it's built this way: FeatureFlagDefinitions
.Describeis 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 isOff(:53-56), a definition with no named filter isOff(:63-66), a definition whose filters are all always-on (or any always-on underRequirementType.Any) isOn(:68-72), and anything else isConditionalwith its filter names (:74). - Where it's used: the
ConfiguredandEffectivefields of FeatureFlagStatusResponse, filled by FeatureFlagAdministrationService (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/FeatureFlags/FeatureFlagAdministrationService.cs:125-130), and rendered byFeatureFlagAdmin.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>.resxsibling 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, orAccept-Languagepreference 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 ofAllso the translation-completeness fitness gate does not demand a.qps-Ploc.resxsibling (: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 againstAll;IsPseudoLocale(string?)(SupportedCultures.cs:76-77) tests case-insensitively againstPseudoLocale. 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 returnsDefault(:53-56), an exact case-insensitiveAllmatch wins (:58-62), otherwise the language subtag is matched, so"es-MX"resolves to"es"(:64-66), and anything left over falls toDefault(:68). The subtag split is done by the privateLanguageOf(:83-87), which returns the input unchanged when there is no-, avoiding an allocation for an already-neutral culture. BecausePseudoLocaleis not inAll, this method can never return it (stated at:42).
- Why it's built this way: a single
constplusIReadOnlyListallowlist keeps the localization middleware, the switcher UI, the fitness gate, and the domain guard from drifting apart; separatingPseudoLocalefromAlllets a diagnostic locale ship in Development without polluting the production culture set or the resx-completeness gate.ResolveClosestexists because web heads get language-level fallback for free from request localization'sAccept-Languagematching, 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
.UseCommonRequestLocalizationbuilds the supported list fromAll(MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/WebApplicationExtensions.cs:55), appendsPseudoLocaleonly in Development (:80), and setsDefaultas the default culture (:85); the culture-switch endpoint validates the incoming value withIsSupportedor, when pseudo is allowed,IsPseudoLocale(:107). MmcaCultureBootstrap falls back toDefaultwhen the stored culture is not supported (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Culture/MmcaCultureBootstrap.cs:46), and PseudoStringLocalizer activates only underIsPseudoLocale(MMCA.Common/Source/Presentation/MMCA.Common.UI/Globalization/PseudoStringLocalizer.cs:17). The MAUI head is theResolveClosestcaller: 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 allowsnullor anIsSupportedculture (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
*Featuresconstant class applies to each flag field, carrying a FeatureFlagLifetime, an optionalRemoveBydate, and an optionalOwner(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.RemoveByis astring?rather than aDateOnly?because "an attribute argument must be a compile-time constant" (FeatureFlagAttribute.cs:44), soTryParseRemoveBy(:60-66) is what turns the constant string back into a real date for the check, parsed strictly againstRemoveByFormat = "yyyy-MM-dd"(:35,63).Ownerexists 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 asLifetime(:38).RemoveByandOwnerareinit-only properties (:46,52), settable only as named attribute arguments.TryParseRemoveByis the one static method: a thin wrapper overDateOnly.TryParseExactwithDateTimeStyles.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
*Featuresconstant classes; read by FeatureFlagRegistry.DescribeviaGetCustomAttribute<FeatureFlagAttribute>(MMCA.Common/Source/Core/MMCA.Common.Shared/FeatureFlags/FeatureFlagRegistry.cs:102). The governance architecture rulesFeatureFlagsDeclareLifetimeandTemporaryFeatureFlagsAreNotPastRemoveBy(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 ofRemoveByFormat(: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,RemoveByandOwnerits[FeatureFlag]attribute carries, if any (MMCA.Common/Source/Core/MMCA.Common.Shared/FeatureFlags/FeatureFlagRegistry.cs:17-22). - Depends on: FeatureFlagLifetime.
- Concept:
Lifetime,RemoveBy, andOwnerare 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 byFlagName(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/FeatureFlags/FeatureFlagCatalog.cs:19-25) and looked up byTryFind(: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
UserIdentifierTypealias forChangedBy(: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
.ToDefinitiontakes 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),UsersandGroups(empty unless the mode is targeting,:9-10),Reason, then the audit pairChangedOn(UTC instant of the last write,:12) andChangedBy(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
Reasonis 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.Temporaryflag gets a build-enforced expiry, a runtime override gets a mandatory explanation instead. - Walkthrough:
ModeandReasonare required positional parameters (:19-20);Percentage(:21),Users(:22) andGroups(:23) default tonull.Percentageis 0 to 100, required forPercentagemode, the share of everyone outside the named audience forTargeting, and ignored otherwise (:11-15). The record itself validates nothing: the rules are enforced by FeatureFlagOverride.Createand.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 intoFeatureFlagOverride.Createorexisting.Change(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/FeatureFlags/EFFeatureFlagOverrideStore.cs:77-78,89); the Blazor admin page sends it throughFeatureFlagAdminService.
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
*Featuresconstant 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*Featuresclass is recognized purely by shape:IsFeatureClassrequires astatic, abstract, sealedtype (the C# pattern for a static class) whose name ends inFeatureClassSuffix = "Features"(:38,77,81-82);FlagFieldsthen takes only itspublic const stringfields (:91,95-97). No registration call, no central list to keep in sync: adding a flag is adding aconst stringfield to the module's*Featuresclass. - 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 byFlagNamewithStringComparer.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) guardsAssembly.GetTypes()againstReflectionTypeLoadException, falling back to the subset of types that did load viaex.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 withinherit: false(:102) and the field's raw constant value viaGetRawConstantValue(), 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
*Featuresclass a plain constant holder with no base type or registration boilerplate. - Where it's used: FeatureFlagCatalog calls
Describelazily over every assembly the host passed toAddReloadableFeatureFlags(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.csexercisesDescribe,IsFeatureClass, andFlagFieldsdirectly. - 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
Sharedlayer of the architecture map (MMCA.Common/Source/Hosting/MMCA.Common.Testing.Architecture/Rules/Governance/ArchitectureRules.FeatureFlags.cs:87-93) with its ownFeatureClassSuffixconstant (:11), because that package takes no framework reference (:7-9); the two copies must be kept in step by hand.FeatureClassSuffixis 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. ReportingConfiguredandEffectiveside by side, with theOverridebetween 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,OwnerandRemoveBy(:16-19) are the declared metadata,nullwhen undeclared (:8-10);ConfiguredandConfiguredFilters(:20-21) are configuration's state and, when conditional, its filter names;Override(:22) isnullwhen 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
.DescribeAsyncbuilds it from a FeatureFlagDescriptor plus the stored override:Configuredcomes from the configuration provider's definition, andEffectivereuses the same FeatureFlagDefinitions.Describeover 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
.GetAllAsyncand.SetOverrideAsync(MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Administration/FeatureFlagsControllerBase.cs:53,74), declared on IFeatureFlagAdministrationService, and consumed by the BlazorFeatureFlagAdminServiceandFeatureFlagAdmin.razor.cspage inMMCA.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), whoseCurrent?.CorrelationIdseeds the default (CorrelationContext.cs:13). Uses BCLGuid. - 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 toAmbientOrigin.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 withArgumentException.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 isTryAddScoped(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:389): scoped, so one instance lives per request, andTryAdd, 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
SetCorrelationIdwith the inboundX-Correlation-IDheader, falling back to the currentActivitytrace ID and then toHttpContext.TraceIdentifier(MMCA.Common/Source/Presentation/MMCA.Common.API/Middleware/CorrelationIdMiddleware.cs:34-38), then echoes the value back on the response throughOnStarting(: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 throughAmbientOrigin(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, soName => 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 requiredReason"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), andTargetSeparator = ','(:42), which is also refused inside a name. - State:
Mode,Percentage,TargetUsers,TargetGroupsandReasonhave private setters (:52-64); the target lists are stored as one joined string, andUsers/Groupssplit them back on read (:67,70,Splitat:136-137). Create(:82) refuses a blank or over-long trimmed name (:90-96), constructs the entity with the trimmed name asId(:98), and runsApply(:99), returning its failure or the entity.Change(:116) runs the sameApply, then revives a cleared override withUndelete()(:124-129).Clear(:134) isDelete().Refusal(:152) checks the scalar half in order: an undefined mode (:154), a blank or over-long reason (:162), thenPercentageFits(:146-149), which requires 0 to 100 forPercentage, allows a null or 0 to 100 forTargeting, and ignores it otherwise.Audience(:179) applies only toTargetingand 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).
- Limits:
- 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
AddFeatureFlagOverridesmigration in both its Conference and Engagement migration projects, for exampleMMCA.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 isMMCA.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 defaultMapToDTOs(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-32is 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 sharedTIdentifierTypeis 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.
- Three generic parameters with matched constraints (
- 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 themScanRegistration.SelfWithInterfaceswith 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
DTOMapperproperty (MMCA.Common/Source/Core/MMCA.Common.Application/Services/Query/EntityQueryService.cs:39,:94, declared on the interface atInterfaces/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 exampleMMCA.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 notnewan entity, it callsEntity.Create(...)and hands the resultingResult<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 isTask<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), withTCreateRequest : ICreateRequestas the type-system guard that stops an update request being passed to the create path. The single member isTask<Result<TEntity>> CreateEntityAsync(TCreateRequest request, CancellationToken cancellationToken = default)(:54). A representative implementation is one method: guard the request, thenTask.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 awaitsrequestMapper.CreateEntityAsync(request, cancellationToken), short-circuiting on failure (:89-90), while the module supplies only the per-entity mapping. Registration is the sameAddAssignableTypesassembly scan as the DTO mappers,ScanRegistration.SelfWithInterfacesand 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 bareResultbecause 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
FeatureFlagOverridestable, as aModelBuilderextension 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) andNameColumn = "Name"(:21); privateModeMaxLength = 16(:24). ApplyFeatureFlagOverrideConfiguration(schema = "dbo")(:34) maps to the table (:40) keyed onId(:41), which is stored in theNamecolumn, non-unicode, atFeatureFlagOverride.NameMaxLength, never generated (:43-48).Modeis stored as its string name so a reordered enum cannot silently change what a row means (:50-54).TargetUsers,TargetGroupsand the requiredReasontake the entity's max lengths (:56-58); the computedName,UsersandGroupsare ignored (:60-62).
- Public constants
- 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 inOnModelCreating(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/ApplicationDbContext.cs:750-756). - Where it's used:
ApplicationDbContext.OnModelCreatingwhen 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.ManageClientson the class (:41), IPermissionRegistry and PermissionAuthorizationHandler.Holdsfor 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:CreateAsyncandRotateAsyncreturn 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, whilePromoteAsyncandRevokeAsync, 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), alongsideMachineClients.RoleNotAllowed(400),MachineClients.NotFound(404),MachineClients.RevokedandMachineClients.NoSecondarySecret(409) (:33-38).[Rubric §9, API & Contract Design]: the controller takes no constructor dependency; the privateEnabledMachineClientsproperty (:45-46) resolves the service withGetServiceand keeps it only whenIsEnabledis 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, viaListAsync.CreateAsync(request, cancellationToken)([HttpPost]at:71, method at:78-96) null-guards the body (:82) and callsCreateAsync(request, CallerHoldsPermission(), cancellationToken)(:88), creating the client and its service account; on success it recordsAdminActionMetrics.MachineClientCreate(:94) and theMachineClientSecretResponsecarries 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 recordsAdminActionMetrics.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) returnsnull, meaning no ceiling, only when the host registers noIPermissionRegistry(:180-183); otherwise it capturesUserand returnspermission => PermissionAuthorizationHandler.Holds(caller, registry, permission)(:185-186).- Every action opens with the same
EnabledMachineClients is not { } machineClientsguard returningNotFound(). List, promote and revoke close withresult.IsFailure ? HandleFailure(result.Errors) : Ok(result.Value); create and rotate branch onIsFailurefirst 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
nullcase 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 isIMachineClientAdminUIService(MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Administration/IMachineClientAdminUIService.cs). The framework tests mount it throughMachineClientTestHost.
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 theRateLimitPolicyAuthIppolicy 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) throughMachineTokenErrorResponse(:120-121), 401 with aWWW-Authenticate: Basic realm="token"header (:129), andCache-Control: no-storeplusPragma: no-cacheon 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 usesFormCollection.Empty(:66-68), extracts the credentials, and callsIssueTokenAsync(form["grant_type"], clientId, clientSecret, ...)(:71-73). Success isOk(result.Value); a failure goes toTokenError(:75).ReadClientCredentials(form)(:85-108) prefers HTTP Basic (RFC 6749 section 2.3.1): it base64-decodes the parameter, returns(null, null)on aFormatException(:96-99) or when there is no:separator, and otherwise form-decodes each half throughFormDecode(:110,+to space, thenUri.UnescapeDataString). Without a Basic header it reads theclient_idandclient_secretform fields (:107).TokenError(errors)(:115-124) switches on the first error's code:MachineClientErrors.UnsupportedGrantTypeCodebecomes 400unsupported_grant_type,InvalidRequestCodebecomes 400invalid_request, and anything else (including an empty list, which defaults toInvalidClientCode) becomesInvalidClient()(:126-131), a 401invalid_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, andMachineClientTestHostexercises 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 asSendHandler(:42) andRedeemHandler(: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) readsConnection.RemoteIpAddress, which behind a proxy is the forwarded value only when the host configuredUseForwardedHeaders(:48-50);ClientUserAgent(:54) reads the User-Agent header. Both are recorded on the session the redeem opens.CreateSendCommand(request)(:61) andCreateRedeemCommand(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 answersAccepted()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 theAuthenticationResponse. 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);AnonymousEndpointTestslists 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>
.ExportAsyncdelegates to: it validates afields=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), andSystem.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 ofEntityControllerBase<TEntity, TEntityDTO, TIdentifierType>letsExportAsyncshrink to validate, delegate, and translate the result (class doc,EntityCsvExporter.cs:11-16).[Rubric §15, Best Practices & Code Quality]:WriteAsynctakes the fetch as a delegate (Func<int, CancellationToken, Task<Result<PagedCollectionResult<object>>>>) rather than the query service itself, so the exporter carries no dependency onIEntityQueryService<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), andUnexportableFields(:51-52), arestatic readonlyfields computed once per closedEntityCsvExporter<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 exceptstring,IsExportableTypeat:239), their camelCase column-name form, and a case-insensitive lookup set forfields=matching. Value objects and other class-typed properties are deliberately not dropped:CsvWriterrendersMoneyas amount plus code,Currencyas its code, and any other record as compact JSON (remarks,:26-29). ValidateFields(fields)(:62) rejects afields=request naming one of those properties as anError.InvalidEntityFieldfailure (:71), before a single byte of the body is written; an empty exclusion set short-circuits tonull.WriteAsync(body, fetchPageAsync, pageSize, maxExportRows, fields, beginResponse, onFailureAfterStart, cancellationToken)(:117) is the page loop. The CSV writer is synchronous, so it never writes tobodydirectly: it renders into an in-memoryMemoryStream(:133) through aStreamWriter(:136), andDrainAsync(:210) copies each page to the body with awaitedWriteAsync/FlushAsyncand empties the buffer. The type doc gives the reason: aStreamWriterover 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 withresult.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 returnsResult.Failurewith nothing written (:145-146) for the caller to turn into Problem Details. On the first successful page it resolves columns, callsbeginResponse()(:161), and writes the BOM and header (:162-163); each page is written byWritePage(:167) and drained (:170). Three termination conditions follow: a page that stopped mid-page marks the export truncated (:173-177),IsLastPageends it on the last page (:179-180), and a cap landing exactly on a page boundary consultsPaginationMetadata.TotalItemCountrather than issuing a wasted page (:184-188). A mid-stream failure after the header started callsonFailureAfterStartand 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 whenrowsWrittenhas reachedTotalItemCount. 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 asKeysetPageRequest.MaxPageSize, which is 1000 atMMCA.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 byfields, for an empty result, so an export of nothing still owes a header row.ShapeRow(:324) andBuildCells(: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) andIncompleteMarker(:363) format the two trailing marker lines withCultureInfo.InvariantCulture.ParseFields(:349) splits afields=value into a case-insensitive set.
- The three exclusion sets,
- Why it's built this way: generic over
TEntityDTOalone, 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 statickeeps it a framework implementation detail behindExportAsync, 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 callsValidateFields(EntityControllerBase.cs:279) andWriteAsync(EntityControllerBase.cs:293). Unit coverage isEntityCsvExporterTestsandEntityCsvExporterValueObjectTests(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
IModelBinderthat parses the structured filter query string (?filters[Name].operator=contains&filters[Name].value=shirt) into aDictionary<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:MaxFiltersis defined asQueryFilterService.MaxFilters(QueryFilterModelBinder.cs:34,usingat:2). Its output is consumed byQueryFilterServicevia 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 throughMaxFilters: 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 byQueryFilterService.ValidateFilterswith a 400 validation errorFilter.TooManybefore 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 withStringComparer.OrdinalIgnoreCase(:42) so client capitalization does not matter.- It iterates
Request.Query.Keys(:46), skipping anything that failsIsFilterKey(:112-115, prefixfilters[plus suffix].operatoror].value), extracts the bracketed property name withGetFilterPropertyName(:122-130, which finds the closing]withkey.AsSpan(startIndex).IndexOf(']')and sliceskey[startIndex..(startIndex + length)],:125-129, returningnullwhen there is no]) and the suffix withGetFilterSuffix(: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
IsIncompleteflags (: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 matchesIS EMPTYorIS NOT EMPTYcase-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) andTask.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:165for the paged read and:263for 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 BCLTimeProvider(falling back toTimeProvider.System,:56-57). - Concept (two-step ceremonies over single-use challenges). A WebAuthn registration or sign-in is two requests: an
optionscall 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 throughPasskeyStepUp.IsSatisfiedBy(User, UtcNow)(:81,:132), refused withPasskeyErrors.StepUpRequired; and the anonymous sign-in pair is bounded by[EnableRateLimiting(RateLimitPolicyAuthIp)](:232,:257). The controller has no constructor dependency:EnabledPasskeyskeeps the service only whenIsEnabledis 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 throughDescribeCaller(:86) and returns the creation options.DescribeCaller(userId)(:97-104) takes the account name fromClaimTypes.Emailor the rawemailclaim, falling back to the user id, and the display name fromClaimTypes.Nameorname, 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) andDeleteAsync(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 409Passkeys.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) passesClientIpAddress(:47) andClientUserAgent(:50) to the service (:273) and returns a token pair whose access token carriesmfa=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) withPasskeysControllerTests; registration support inPasskeysServiceCollectionExtensions(MMCA.Common/Source/Core/MMCA.Common.Passkeys/PasskeysServiceCollectionExtensions.cs); framework coverage inPasskeysControllerBaseTestsandPasskeyTestHost;AnonymousEndpointTestslists 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 asBeginHandler,ConfirmHandler,DisableHandler,RegenerateHandlerandStore(: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),EndSessionsAsyncrevokes 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 exceptOperationCanceledException,: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 throughPasskeyStepUp.IsSatisfiedBy(User, UtcNow)(:134,:168), refused withTwoFactorErrors.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 dispatchesCreateBeginEnrollmentCommand(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,CreateDisableCommandandCreateRegenerateRecoveryCodesCommand(: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'sIAuthenticationService(:288), otherwise callsRevokeAllSessionsAsync(: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,
TwoFactorControllerBaseTestsandTwoFactorControllerTestHost(MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/Controllers/TwoFactor/). UsersAdminControllerBase<TUserDto> reads the sameITwoFactorStoreto 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
FeatureFlagOverridestable mapping to exactly one database's EF model: the source named byFeatureFlags: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, whoseApplyFeatureFlagOverrideConfigurationit 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 callsAddReloadableFeatureFlagskeeps 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) isModelContributorPhase.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 ofsource.Key.Nameagainstsettings.Value.DataSourceName, so every other physical source is left untouched.Configure(modelBuilder, engine)(:96-97) callsmodelBuilder.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
IModelContributorbyAddReloadableFeatureFlags(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.FeatureFlags.cs:73), after the settings are bound withValidateDataAnnotationsandValidateOnStart(: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 whenEnableFeatureFlagOverridesis 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,ReloadableFlagsHostandModelCacheKeyGateTestsunderMMCA.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 protectedCurrentUserService,LegalAcceptanceControllerBase.cs:51), andIOptions<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) isLegalAcceptancePolicy.ResolveCurrentVersion(options.Value),nullwhen no version is configured.GetLegalAcceptanceAsync(cancellationToken)([HttpGet(LegalAcceptanceRoutes.Action)]at:59, method at:63) returnsOk(LegalAcceptanceDTO.Evaluate(null, null, null))when no version is configured (:66-69), a 401 Problem Details failure (Legal.Unauthorized) whenUserIdis null, (:71-75), and otherwise asksGetForCurrentUserAsync(:77), unwraps the result withresult.TryGetValue(out var acceptance)(:81), and returns the standing normalized against the current version throughLegalAcceptancePolicy.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, thenAcceptForCurrentUserAsyncwith the configured version (:119-121), and returns the normalized standing through the sameTryGetValueunwrap (:123-125). A version mismatch comes back as a failure throughHandleFailure, surfaced as a 400 per the declaredProducesResponseType.
- Why it's built this way: the HTTP shape ships once in the framework and an app contributes its
ILegalAcceptanceServiceimplementation, 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 arevirtual, so an app can override one without re-declaring routing. - Where it's used: ADC's
LegalAcceptanceControlleris 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 isLegalAcceptanceControllerBaseTests. 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
HandleFailureatMMCA.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 onTQuery(DataExportControllerBase.cs:61-64). Externals: ASP.NET Core MVC (including itsIOptions<JsonOptions>),System.Text.Json,Microsoft.Extensions.DependencyInjectionandMicrosoft.Extensions.Options(:6-7), andMicrosoft.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"atMMCA.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 protectedCurrentUserServiceproperty (: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 atUsersserves/Users/{userId}/export(:41-43). The declared responses are 200 with aUserDataExportDTO, plus 401/403/404 asProblemDetails(:80-83).- It reads
CurrentUserService.UserIdfirst and, when there is none, short-circuits throughHandleFailurewithError.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 withresult.TryGetValue(out var export), mapping a failure throughHandleFailure(result.Errors)(:98-101), which is what turns the handler's own ownership refusal into a 403. - The role passed to
CreateQueryis the caller's FIRST role claim (ICurrentUserService.Role), which the parameter doc notes is the only one on the single-role tokensTokenServicemints; a host issuing multi-role tokens overridesCreateQueryto pass its privileged role whenCurrentUserService.IsInRoleholds, asOwnershipHelper.IsAdmindoes (:119-124). - On success it serializes the package itself with
JsonSerializer.SerializeToUtf8Bytes(export, json)(:109) and returnsFile(payload, ExportContentType, BuildFileName(...))(:111). The options are the host's MVC JSON options, resolved per request asHttpContext.RequestServices?.GetService<IOptions<JsonOptions>>()?.Value.JsonSerializerOptions, withJsonSerializerOptions.Webonly 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) composesuser-data-{userId}-{yyyyMMdd}.jsonwithCultureInfo.InvariantCulture, taking the date from the package's ownUserDataExportDTO.GeneratedOnso the file name and the document always agree, and so a saved file sorts and parses the same in every locale (:131-136).
- The primary constructor takes the app's query handler and ICurrentUserService (
- 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
CreateQueryfactory rather than as a concrete controller added through an application part because the query type is app-owned (each app'sExportUserDataQuerylives 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 literalUsersrather than[controller], and both say why:[Route("[controller]")]would resolve toUsersDataExportand move the published path (ADC:19-22, Store:9-13). The framework's own coverage isDataExportControllerBaseTests, whoseTestDataExportControlleris 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'sCreate,ChangeandClear, which returnResult.[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 forResolveDataSourceKey()on each access;Overridesis itsSet<FeatureFlagOverride>()(:41).ResolveDataSourceKey(:140-141) delegates toFrameworkTableTargets.ResolveHome<FeatureFlagOverride>with the configuredDataSourceName, 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!IsDeletedpredicate, ordered byId(: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 withIgnoreQueryFilters([ApplicationDbContext.SoftDeleteFilterName])(:69-72), so a soft-cleared row is revived rather than duplicated while theTenantfilter still applies; the comment notes that EF's parameterlessIgnoreQueryFilters()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 throughFeatureFlagOverride.CreateandAddAsync(:77-85); an existing row throughChange(:89). Domain failures return asResult.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); otherwiseClear()and save (:118-125).ToResponse(:128) reportsLastModifiedOn ?? CreatedOnandLastModifiedBy ?? 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:
GetAllAsyncandClearAsynckeep every model filter, andSetAsynckeeps theTenantone; whether theTenantfilter is actually configured forFeatureFlagOverrideon a given host is decided by the modelApplicationDbContextbuilds, not determinable from this file alone.
⬅ Navigation Metadata & Populators (EF-decoupled eager loading) • Index • gRPC & Inter-Service Contracts ➡