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

Onboarding guide

8. Authentication & Authorization

What this group covers. This is the security spine of the framework: how a caller proves who they are (authentication), how the system decides what they may do (authorization), and how both survive the jump from a single-process monolith to a fleet of extracted services. Almost every type here serves one of the clusters below: minting and validating JWTs (TokenService / ITokenService, RsaJwksProvider / IJwksProvider, and the settings that select the algorithm and the key material: JwtSettings, JwtSigningAlgorithm, JwksSettings); the shared login / register / refresh workflow (AuthenticationServiceBase<TUser>, IAuthenticationService, AuthenticationValidators); multi-device refresh sessions (RefreshSession, IRefreshSessionStore, RefreshSessionSettings, RefreshSessionSummaryResponse, and the issuer that owns every session decision, AuthSessionIssuer / IAuthSessionIssuer, with its two private helpers IssuedSession and SessionStampingTokenService); the contracts an app's User aggregate exposes to those shared workflows (IAuthUser, IPasswordChangeableUser, IUserPreferences, IErasableUser, and the opt-in IPasswordRehashableUser); password material (PasswordHasher / IPasswordHasher, and the one complexity rule both server and client read, PasswordComplexity); brute-force and rate-limit protection (LoginProtectionService / ILoginProtectionService, LoginProtectionSettings); the forgot-password token lifecycle (PasswordResetTokenService / IPasswordResetTokenService, PasswordResetEntry, PasswordResetSettings); reading the current caller's identity from claims (CurrentUserService / ICurrentUserService, ClaimsPrincipalExtensions, ClaimBasedUserIdProvider, AuthClaimTypes); the authorization model (permissions and resource ownership under AuthorizationExtensions, PermissionAuthorizationHandler, and OwnerOrAdminFilter); and the HttpOnly session-cookie machinery (SessionCookieEndpoints, SessionCookieAuthenticationHandler, CookieSessionRefresher) that keeps server-side-rendered Blazor pages authenticated across a cold navigation. Five further clusters are opt-in identity completions: a second factor (ITwoFactorService / TotpTwoFactorService, ITwoFactorAuthenticator, ITwoFactorStore, ITwoFactorUserState); email confirmation (IEmailConfirmationTokenService / EmailConfirmationTokenService, IEmailConfirmableUser); operator-editable permission grants (PermissionGrant, IPermissionGrantStore, LayeredPermissionRegistry); a user and role administration API (IUserAdministrationService<TUserDto>, IRoleAdministrationService, StoredPermissionRoleAdministrationService); and Terms of Service acceptance (LegalAcceptancePolicy, ILegalAcceptanceService, ILegalAcceptingUser). Each of those five is a set of contracts plus an abstract or concrete base behind its own Add* call, never a framework feature with a framework table, so a host that does not opt in pays nothing.

Four newer opt-in capabilities extend the same spine: sign-in links and invitations (ISignInLinkTokenService / SignInLinkTokenService), cache-backed like email confirmation; passkeys (IPasskeyService / PasskeyService, with the WebAuthn cryptography behind IPasskeyCeremony in the separate MMCA.Common.Passkeys package); read-only support access (IViewAsService / ViewAsService, ViewAsGrant); and machine clients on the OAuth client credentials grant (IMachineClientService / MachineClientService, MachineClient). The last three do own a table each, but it is mapped only where a host sets the feature's Enabled flag, in the Identity database alone, and every endpoint of the feature answers 404 while it is off (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Passkeys/PasskeySettings.cs:19, MMCA.Common/Source/Core/MMCA.Common.Application/Auth/ViewAs/ViewAsSettings.cs:34, MMCA.Common/Source/Core/MMCA.Common.Application/Auth/MachineClients/MachineClientSettings.cs:19). One authorization rule rounds the set out: MultiFactorAuthorizationSettings withholds a listed role from a bearer session that signed in without a second factor. On the token side, JwksAdditionalKey (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/JwksSettings.cs:204) is what makes a signing-key rotation free of a 401 wave: the next key is staged in the JWKS document before the switch and the previous one stays there until every token it signed has expired, with JwksKeyMaterial (JwksSettings.cs:249) holding the PEM rules both kinds of key share (an inline PEM wins over a path, and the file is read on first use, not at startup).

The governing decisions are ADR-004 (dual-fetch login and cross-service token validation via JWKS, with RS256 as the default because it survives extraction), ADR-097 (hashed, rotating, per-device refresh sessions, which supersedes the storage model of ADR-050 while keeping its rotation and reuse-detection policy), ADR-029 (brute-force protection), ADR-102 (PBKDF2-only password hashing, superseding ADR-032), ADR-091 (the cache-backed forgot-password token), ADR-020 (permission-based authorization), ADR-033 (resource-ownership authorization), ADR-022 (the browser session-cookie scheme), ADR-051 (how each render head holds and reacquires a token), and ADR-047 (runtime revocation for a soft-deleted account), ADR-116 (the second factor, email confirmation, sign-in links, operator-editable permission grants, and the administration API, all shipped as contracts and bases behind their own Add* calls rather than as framework features), ADR-137 (read-only view-as support access), ADR-139 (passkeys), and ADR-140 (machine clients). One neighbouring record also reaches into this chapter by dependency grouping: ADR-115 owns the MMCA.Common.Shared.Identifiers wrapper-struct capability. The rubric lenses are dominated by [Rubric §11, Security], with supporting [Rubric §7, Microservices Readiness] and [Rubric §12, Performance & Scalability]. Auth surfaces all of its expected failures (bad password, lockout, expired session, rejected reset token) as Result failures, never exceptions, so reading the Result pattern first pays off here.

Tokens: one signing switch, two validation worlds

The framework mints two credentials on every successful sign-in: a short-lived access token (a JWT, 15 minutes by default, MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/JwtSettings.cs:97) and an opaque, random refresh token (64 bytes of RandomNumberGenerator output, Base64-encoded, valid 7 days by default, TokenService.cs:190-193, JwtSettings.cs:104), both produced by TokenService (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/TokenService.cs:29). The access token carries a fixed claim spine: sub, jti, iat, plus name, email, and role (TokenService.cs:148-157), and the app adds its own claims (for example speaker_id or customer_id) through the additionalClaims parameter (TokenService.cs:159-162). sub is the single carrier of the user identifier: the duplicate custom claim that used to ride alongside it is gone, because two values that can disagree is two claim names every reader has to know (TokenService.cs:145-147). The port ITokenService (MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Auth/ITokenService.cs:8) publishes both lifetimes as abstract properties (ITokenService.cs:58, ITokenService.cs:64), so every implementation, a hand-written test double included, states the expiry it reports, and the concrete service derives them from the same bound settings it mints with, so the expiry reported to clients matches the token's actual exp (TokenService.cs:197, TokenService.cs:200).

The load-bearing design choice is a single configuration switch, JwtSettings.SigningAlgorithm (TokenService.cs:95). It defaults to JwtSigningAlgorithm.RS256 (JwtSettings.cs:37): the Identity service signs with an RSA private key and every other service validates against the matching public key, which it fetches over JWKS. The enum offers two further asymmetric values, PS256 (RSA-PSS over the same RSA key) and ES384 (an ECDSA key on P-384) (JwtSigningAlgorithm.cs:32, JwtSigningAlgorithm.cs:35). A single-host monolith opts into HS256 explicitly, where one symmetric Base64 secret both signs and validates because issuer and validator are the same process (TokenService.cs:95-109, TokenService.cs:265-272). Asymmetric is the default precisely because it is the shape that survives extraction: a compromised non-Identity service can verify tokens but cannot forge them. Every site that issues or validates a token reads the same algorithm list from JwtAlgorithms (MMCA.Common/Source/Build/Auth/JwtAlgorithms.cs:16), an internal source linked into each project rather than copied: an asymmetric validator accepts exactly RS256, PS256 and ES384, an HMAC validator exactly HS256, and no validator accepts both, so a token HMAC-signed with a public key as the secret never meets a validator that would try it (JwtAlgorithms.cs:25-33, JwtAlgorithms.cs:61-62). The same file pins the 30-second clock skew every framework bearer validator allows (JwtAlgorithms.cs:22). Its sibling JwtKeyMaterial (MMCA.Common/Source/Build/Auth/JwtKeyMaterial.cs:13) loads a PEM by algorithm (an RSA key for RS256 and PS256, a key that must be on P-384 for ES384) and measures it against the strength floor (JwtKeyMaterial.cs:23, JwtKeyMaterial.cs:45-64, JwtKeyMaterial.cs:109-132). An issuer with no explicit public key configured derives one from its own private-key parameters so it can still self-validate during refresh (TokenService.cs:299-304), and the key id from JwksSettings travels into every asymmetric token's kid header so a validator reading the published document selects the right key by name rather than trying each in turn (TokenService.cs:292-296). Key material is materialized once in the constructor and the owned RSA or ECDsa handles are disposed with the service (TokenService.cs:42-43, TokenService.cs:259-263), so token operations never re-parse a PEM. The settings class enforces the pairing rather than trusting the host: it implements IValidatableObject and rejects an HS256 secret that does not decode from Base64 to at least 32 bytes, or an asymmetric algorithm with no private key of the kind it reads (JwtSettings.cs:112-134). Outside Development, host startup also refuses an RSA key below MinimumRsaKeySizeBits, 3072 by default (JwtSettings.cs:15, JwtSettings.cs:81).

The public half is served by RsaJwksProvider (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/RsaJwksProvider.cs:24), which lazily builds a JsonWebKeySet from a PEM key configured through JwksSettings (an RSA PEM inline or read from a path, or an inline P-384 PEM when the issuer signs ES384), resolved by the internal JwksKeyMaterial helper (RsaJwksProvider.cs:42-69, JwksSettings.cs:249, JwksSettings.cs:255-283), behind the IJwksProvider port (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/IJwksProvider.cs:11). Publishing is off by default, and when disabled or unconfigured the provider returns an empty key set (RsaJwksProvider.cs:44-47, RsaJwksProvider.cs:53-56) so the endpoint stays queryable but a non-issuer host advertises nothing. The current key is published first, followed by every JwksAdditionalKey entry in JwksSettings.AdditionalKeys, the previous or staged next key of a rotation, none of which is ever used to sign (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/JwksSettings.cs:81, JwksSettings.cs:204, RsaJwksProvider.cs:58-66); the issuer's refresh flow accepts the same set, so a token the pre-rotation key signed still refreshes (TokenService.cs:100-104, JwksSettings.cs:183-184). The cache is a Lazy<JsonWebKeySet> in PublicationOnly mode rather than the default ExecutionAndPublication (RsaJwksProvider.cs:26-32): the default caches a factory exception forever, so a single transient IO failure reading the PEM would brick the endpoint (and with it cross-service auth) until the process restarted. The endpoint itself, /.well-known/jwks.json, is mapped in the API layer by JwksEndpointExtensions (path constant at MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/Endpoints/JwksEndpointExtensions.cs:20, mapped anonymously behind the wellknown rate-limit policy with a five-minute public Cache-Control at JwksEndpointExtensions.cs:28, JwksEndpointExtensions.cs:43-57), paired with the OIDC discovery document from OidcDiscoveryEndpointExtensions (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/Endpoints/OidcDiscoveryEndpointExtensions.cs:29); OpenIdConnectMetadataWarmupTask pre-fetches that document as a startup warm-up task (MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Warmup/OpenIdConnectMetadataWarmupTask.cs:25) so the first authenticated request on a cold replica does not pay the discovery round trip. Validation pins the accepted algorithm family so an attacker cannot force a swap: GetPrincipalFromExpiredToken sets ValidAlgorithms to the list JwtAlgorithms.AcceptedFor returns for the configured algorithm (every asymmetric algorithm for an asymmetric issuer, because a rotation may change the algorithm; HS256 alone for an HMAC issuer) (TokenService.cs:90-93, TokenService.cs:224) and then re-checks the token header against that list after ValidateToken returns (TokenService.cs:233-237). Only the lifetime check is skipped there (TokenService.cs:218), because the method exists to read claims out of an already-expired token during refresh.

The shared authentication workflow

Login, registration, refresh, revocation, and device listing are not re-implemented per app. They live once in AuthenticationServiceBase<TUser> (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/AuthenticationServiceBase.cs:78), an abstract base each app's Identity module seals over its concrete User aggregate. The base owns the sequence; the sealed subclass supplies the genuinely app-specific pieces through abstract and virtual hooks: EmailExistsAsync (the app decides whether soft-deleted accounts count, AuthenticationServiceBase.cs:757-761; the sign-in lookup itself is the shared untracked UserEmailLookup.FindUntrackedByEmailAsync over IEmailIdentifiedUser.Email, MMCA.Common/Source/Core/MMCA.Common.Application/Users/UserEmailLookup.cs:38-43, AuthenticationServiceBase.cs:187-190), CreateUser (AuthenticationServiceBase.cs:764), CreateAccessToken (AuthenticationServiceBase.cs:803), the two optional candidate gates (AuthenticationServiceBase.cs:911-916), the post-commit OnUserRegisteredAsync (AuthenticationServiceBase.cs:922), and the overridable "refresh user vanished" error (AuthenticationServiceBase.cs:930, 401 by default because a token for a deleted user is indistinguishable from an invalid one). What the base does not own is the session: it decides who is signed in and hands everything about what they are given to IAuthSessionIssuer, a constructor dependency (AuthenticationServiceBase.cs:51-54, AuthenticationServiceBase.cs:83), so the workflow never touches a session row. Even the token service a subclass mints through is the issuer's (AuthenticationServiceBase.cs:124), which is how the sid and mfa claims reach an app's token without the app's claim code knowing they exist (see the refresh-session section below).

LoginAsync (AuthenticationServiceBase.cs:156) shows the shape. It validates the request first, then runs the ADR-029 lockout check (AuthenticationServiceBase.cs:171-179), then does the dual-fetch: an untracked, no-change-tracking query to verify the password cheaply (AuthenticationServiceBase.cs:185-190, AuthenticationServiceBase.cs:207), and only on success a second tracked re-fetch of the instance the app's CreateAccessToken hook mints from, which is also what turns a race that deleted the account between the two steps into a clean 404 (AuthenticationServiceBase.cs:253-266). The email is normalized through the Email value object before the query so the EF predicate compares same-typed converted values (AuthenticationServiceBase.cs:181-183). Soft-deleted accounts fall out through EF global query filters and return the same generic 401 as a wrong password (AuthenticationServiceBase.cs:185-215), and so does an account with no stored credential at all (the external-OAuth shape), which also pays one throwaway key derivation so its 401 does not come back measurably faster than a real check (AuthenticationServiceBase.cs:192-205, AuthenticationServiceBase.cs:960-968): the API never reveals whether an email exists. The app's candidate gate, the email-confirmation gate and the second-factor challenge all run after the password check (AuthenticationServiceBase.cs:217-251), and a successful login clears the attempt counters (AuthenticationServiceBase.cs:269) before handing off to the shared token-issue path (AuthenticationServiceBase.cs:271-281).

The last step of a sign-in is a best-effort password rehash (AuthenticationServiceBase.cs:290): when the tokens were issued, the app's User implements IPasswordRehashableUser, and the hasher reports NeedsRehash, the base re-derives the hash from the plaintext it still holds and saves it on its own through the unit of work (AuthenticationServiceBase.cs:1006-1037). It runs after issue so the session save never carries the user row, and on CancellationToken.None with every failure contained, so a refused invariant, a concurrency conflict or a dropped connection cannot fail a sign-in that has already succeeded: the record is simply upgraded on a later sign-in (AuthenticationServiceBase.cs:994-1002). A refusal by the aggregate is logged through AuthenticationServiceLog (AuthenticationServiceBase.cs:1053), an internal source-generated companion with two warnings: PasswordRehashRejected carries the user id and the error codes, never password material (AuthenticationServiceBase.cs:1058-1061), and SignInFailed is the one line every failed password sign-in writes, carrying the outcome and a 12-hex-character hash of the normalized address, never the address (AuthenticationServiceBase.cs:1056, AuthenticationServiceBase.cs:1063-1065), alongside the failure count on the MMCA.Common.Auth meter (AuthenticationServiceBase.cs:978-986); it is a separate non-generic class so the public base does not have to be partial (AuthenticationServiceBase.cs:1049-1052). Any other failure is logged and counted on the MMCA.Common.BestEffort meter under the password-rehash operation name (AuthenticationServiceBase.cs:89, AuthenticationServiceBase.cs:1013-1015). The logger is AuthenticationValidators.Logger, created from the injected ILoggerFactory under the fixed MMCA.Common.Application.Auth.AuthenticationService category and carried on that dependency bundle rather than as another constructor parameter (AuthenticationValidators.cs:22, AuthenticationValidators.cs:41). The throwaway derivation above is the hasher's own BurnVerificationCost, which costs what verifying the most expensive record the hasher can have stored costs (for the shipped hasher, the larger of its current and legacy work factors), so an unknown address costs the same as an account still on an older record (AuthenticationServiceBase.cs:951-959, AuthenticationServiceBase.cs:967).

RegisterAsync (AuthenticationServiceBase.cs:296) first refuses a request that did not accept the Terms of Service when the host configures a current terms version (AuthenticationServiceBase.cs:311-314, covered in the Terms of Service section below), then rate-limits by source IP, rejects a duplicate email as a conflict, hashes the password, saves, and only then runs the app's post-commit hook, counts the registration, and opens the session (AuthenticationServiceBase.cs:316-392), unless the email-confirmation gate would refuse the new account's sign-in, in which case it returns RegistrationOutcome.ConfirmationPending with no session (AuthenticationServiceBase.cs:382-388). The up-front email check is a check-then-act, so two concurrent registrations for the same address both pass it and the loser only fails on the insert. The save is therefore wrapped in a deliberately broad catch that re-checks the address and, if it now exists, returns the same conflict the serialized path would have produced, rethrowing anything else (AuthenticationServiceBase.cs:345-373); the shared failure factory keeps the two paths indistinguishable to the caller (AuthenticationServiceBase.cs:1044). The catch is broad because the Application layer has no EF Core dependency by layer rule and cannot name DbUpdateException; the re-check is what narrows it, and it deliberately runs on CancellationToken.None so a cancelled save can still be classified (AuthenticationServiceBase.cs:365-367). The password rule a registration is validated against is defined exactly once, in PasswordComplexity (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/PasswordComplexity.cs:18): 8 to 128 UTF-16 code units (PasswordComplexity.cs:21, PasswordComplexity.cs:24) with an uppercase letter, a lowercase letter, a digit and a special character, each a Unicode-aware generated regex with a one-second match timeout, so an accented or CJK letter counts as a letter and never as the special character (PasswordComplexity.cs:12-16, PasswordComplexity.cs:27-43), combined in Evaluate (PasswordComplexity.cs:52-57). It lives in Shared because both sides read it: the server's StrongPasswordRules matches the same four patterns and the same ceiling (MMCA.Common/Source/Core/MMCA.Common.Application/Validation/CommonValidationRules.cs:256-260), and the client form attribute calls Evaluate (MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/PasswordComplexityAttribute.cs:25), so the two cannot give different verdicts for one input, which is the validation-parity point of rubric §24 the type's own remarks cite (PasswordComplexity.cs:5-10).

RefreshTokenAsync (AuthenticationServiceBase.cs:396) extracts claims from the expired access token (signature still verified, only lifetime skipped, AuthenticationServiceBase.cs:408-410), reads the identifier off sub through ClaimsPrincipalExtensions (AuthenticationServiceBase.cs:417-420), carries the mfa claim the user already earned across the rotation so a signed-in session is not quietly demoted every fifteen minutes (AuthenticationServiceBase.cs:440-445), and then hands the presented refresh token to the issuer's RotateAsync (AuthenticationServiceBase.cs:455-461). Every failure path returns a Result rather than throwing, matching the framework-wide Result pattern (see primer §2).

The request and response DTOs for these flows (LoginRequest, RegisterRequest, RefreshTokenRequest, AuthenticationResponse, ChangePasswordRequest, OAuthCodeExchangeRequest) are compact readonly record structs in MMCA.Common.Shared. A native client can describe its device with the optional DeviceMetadata record (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/DeviceMetadata.cs:24), whose DeviceId is a per-install GUID the client keeps rather than a hardware serial; the server truncates each value to its column width, and browser clients report nothing and are described from the user-agent instead. When a host requires a confirmed address before sign-in, registration succeeds without a session: RegistrationOutcome (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Responses/AuthenticationResponse.cs:28) is the token-less success value that lets RegisterAsync keep its return type, and the register endpoint then answers 202 Accepted with a RegistrationPendingResponse (AuthenticationResponse.cs:21) instead of 201. Password sign-in outcomes are counted on an OpenTelemetry meter, AuthSignInMetrics (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/AuthenticationServiceBase.cs:1101), whose tags carry only the low-cardinality outcome, never an address, a user id or a client IP. The same meter carries the untagged mmca.auth.refresh_reuse counter in AuthSecurityMetrics (AuthenticationServiceBase.cs:1161, AuthenticationServiceBase.cs:1164-1167), one increment per presented refresh token that had already been rotated and so revoked its whole family. Several of them mark boundaries worth noting: password change is dispatched straight through its command handler at the controller layer rather than brokered by IAuthenticationService (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/IAuthenticationService.cs:12), the same is true of the forgot/reset pair below (ForgotPasswordRequest, ResetPasswordRequest), and ExternalLoginAsync is an abstract member with no default body, so every implementation supplies it (IAuthenticationService.cs:163-170), because OAuth account linking stays coupled to the app's own User factory. OAuthCodeExchangeRequest carries only an opaque single-use code (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Requests/OAuthCodeExchangeRequest.cs:11) precisely so the token pair never appears in the address bar, browser history, a Referer header, or an access log. The FluentValidation rules that guard the requests are bundled into one parameter object, AuthenticationValidators (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/AuthenticationValidators.cs:33), which keeps the app's AuthenticationService constructor below the arity ceiling. The framework ships all three validators the bundle takes (AuthenticationValidators.cs:34-36): LoginRequestValidator and RefreshTokenRequestValidator, both deliberately minimal presence-and-shape checks so a rejection never reveals which field was wrong (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Validation/LoginRequestValidator.cs:21, MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Validation/RefreshTokenRequestValidator.cs:10), and RegisterRequestValidator (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Validation/RegisterRequestValidator.cs:20), which composes the shared email, strong-password and required-name rule sets (100-character caps for the email and each name, RegisterRequestValidator.cs:23, RegisterRequestValidator.cs:26, RegisterRequestValidator.cs:31-34), validates the address only when one is supplied (RegisterRequestValidator.cs:36-38), and answers every rule under its own Register.{Field}.{Rule} code so a host localizes each message by code. It leaves AcceptedTerms alone, because whether terms are required depends on the configured version the authentication service checks (RegisterRequestValidator.cs:16-19). Change-password gets the same treatment from ChangePasswordRequestValidator (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Validation/ChangePasswordRequestValidator.cs:15): the current password is required and the new one passes the same strong-password rules under ChangePassword.NewPassword codes (ChangePasswordRequestValidator.cs:20-23), so a change is not a way around the complexity policy. Both are registered by AddApplication() with the other framework request validators (RegisterRequestValidator.cs:16-17, ChangePasswordRequestValidator.cs:14).

Refresh sessions: one row per device

A refresh token is no longer a column on the user row. Every issue opens its own RefreshSession (MMCA.Common/Source/Core/MMCA.Common.Domain/Auth/RefreshSession.cs:46), so signing in on a phone leaves a laptop signed in, and the store holds only the token's digest: Create hashes on the way in so the plaintext never reaches a property (RefreshSession.cs:184-286), and HashToken is an unsalted, deterministic SHA-256 rendered as 64 upper-case hex characters precisely because lookups are by hash (RefreshSession.cs:301-305, width constant at RefreshSession.cs:49). The encoding is part of the contract, not an implementation detail: the type's own remarks give the byte-for-byte SQL Server equivalent a consumer's data migration has to reproduce (RefreshSession.cs:292-298). The row is deliberately not an aggregate: no audit stamps, no soft-delete flag, no concurrency token, like OutboxMessage and AuditTrailEntry, because a row is edited only to be revoked or anonymized, is deleted only by the retention sweep, and no global query filter may hide a revoked row from the reuse check while it is kept (RefreshSession.cs:27-37). Revoke is idempotent by refusal, so the first reason and instant recorded are the ones kept (RefreshSession.cs:315-330), and the five reason constants (Rotated, SignedOut, ReuseDetected, SessionCapExceeded, AccountDeleted, RefreshSession.cs:67-79) are what an operator reads afterwards. The row is also an IAnonymizable (RefreshSession.cs:46): the captured IpAddress and UserAgent are personal data (RefreshSession.cs:39-44, RefreshSession.cs:123, RefreshSession.cs:130), so Anonymize clears both for an erasure while the hashes and the revocation chain stay, which keeps reuse detection working on an anonymized row (RefreshSession.cs:339-351).

Rotation leaves a chain, and the chain is the security mechanism. Using a session revokes it and records the successor in ReplacedByTokenHash (RefreshSession.cs:103), so presenting an already-rotated token lands on a revoked row rather than on nothing: that is the ADR-050 reuse signal, and AuthSessionIssuer answers it by revoking every live session the user holds (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Sessions/AuthSessionIssuer.cs:364-368, AuthSessionIssuer.cs:702-721). The three rejections behind the single generic error are deliberately different in what they do (AuthSessionIssuer.cs:407-487): an unknown hash, or one belonging to another account, is failed alone, since revoking the family on it would let anyone holding one of this user's expired access tokens sign them out everywhere by posting a random string (AuthSessionIssuer.cs:438-441); a revoked row splits by why it was revoked, so one rotated away (or already flagged as reuse) is the reuse signal and revokes the family, while one signed out or evicted by the session cap only lost its session and fails alone (AuthSessionIssuer.cs:443-452, classified by IsReuseSignal at AuthSessionIssuer.cs:604-614, which treats a missing or unrecognized reason as reuse); an expired row is an ordinary end of life, so that device re-authenticates while the others keep working (AuthSessionIssuer.cs:484-486). One window softens the reuse answer: a row revoked as Rotated less than RefreshSessionSettings.ReuseGraceSeconds ago (AuthSessionIssuer.cs:624-632) is a sibling race (a second tab, or one browser served by two replicas), answered 409 Conflict with the code Auth.RefreshSuperseded and nothing revoked (AuthSessionIssuer.cs:454-459, AuthSessionIssuer.cs:401-403). Two requests presenting the same still-live token go through the same classification: rotation is claimed atomically through IRefreshSessionStore.TryRotateAsync (AuthSessionIssuer.cs:558-560), the request that loses the claim re-reads the row as the database holds it now (AuthSessionIssuer.cs:568-570), and then a sign-out or cap eviction fails it alone, a rotation inside the grace is a 409, and anything else is answered exactly like a replay (AuthSessionIssuer.cs:571-589).

IRefreshSessionStore (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/IRefreshSessionStore.cs:21) is the narrow persistence port: add, find by hash (revoked and expired rows included, which is load-bearing for reuse detection, IRefreshSessionStore.cs:28-37), list a user's un-revoked sessions (IRefreshSessionStore.cs:45), list every row a user holds, revoked and expired included, because account erasure has to anonymize them all (IRefreshSessionStore.cs:49-61), return the distinct users holding a live session and count each requested user's live sessions in one grouped query, both evaluated in the store against a caller-supplied now (IRefreshSessionStore.cs:85-99, IRefreshSessionStore.cs:116-128), find one of a user's sessions by id with the owner inside the query so another account's id is indistinguishable from a nonexistent one (IRefreshSessionStore.cs:130-143), re-read one session by id untracked for the rotation loser above (IRefreshSessionStore.cs:145-159, an abstract member; a null answer reads as "cannot tell" and is met with the conservative family revocation), save, and TryRotateAsync (IRefreshSessionStore.cs:195). Implementations must return tracked instances from every lookup except that read-only re-read, because revocation is a mutation on an instance the store handed out and a no-tracking read would drop it at save time (IRefreshSessionStore.cs:15-20). The default TryRotateAsync body (revoke in memory, add, save) is atomic only per instance, which is all an in-memory or test store can offer; the shipped EF implementation EFRefreshSessionStore overrides it with a conditional ExecuteUpdateAsync the database arbitrates (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Auth/EFRefreshSessionStore.cs:332-357). That is the [Rubric §8, Data Architecture] half of the story, and the store is registered scoped alongside the unit of work it shares a DbContext with, so a login and its session insert commit together (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:185-191).

The workflow around the port lives in AuthSessionIssuer (AuthSessionIssuer.cs:42), not in the authentication base, and is small and worth reading end to end. IssueTokensAsync (AuthenticationServiceBase.cs:703), through its private core IssueTokensCoreAsync (AuthenticationServiceBase.cs:737-755), hands the user's id and a minting callback to the issuer's IssueAsync (AuthSessionIssuer.cs:86), which opens the session before it mints the access token, because the token carries the session's id and a session only has an id once it has been created (AuthSessionIssuer.cs:76-89). OpenSessionAsync (AuthSessionIssuer.cs:494) mints the refresh token, builds the row, and, before staging the insert, enforces the per-user cap by revoking the oldest live sessions (AuthSessionIssuer.cs:515, AuthSessionIssuer.cs:723-745), so one account cannot grow the table without bound while a legitimate sign-in never fails. OpenSessionAsync and its rotation twin RotateSessionAsync (AuthSessionIssuer.cs:535) both return IssuedSession (AuthSessionIssuer.cs:752), the private pair of "the plaintext token, which exists nowhere else" and "the row id". The id reaches the client as the standard sid claim, stamped by SessionStampingTokenService (AuthSessionIssuer.cs:766), a private pass-through ITokenService that the issuer exposes as its TokenService (AuthSessionIssuer.cs:67-77) and arms through MintForSession for the duration of the app's CreateAccessToken call (AuthSessionIssuer.cs:133-148, reached from AuthenticationServiceBase.cs:823-824). Doing it with a wrapper rather than by changing the hook's signature is what makes the claim additive: every existing subclass keeps compiling and starts emitting sid with no edit. GetSessionsAsync (AuthenticationServiceBase.cs:505) delegates to the issuer's ListActiveAsync (AuthSessionIssuer.cs:261), which projects the user's live sessions into RefreshSessionSummaryResponse (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Responses/RefreshSessionSummaryResponse.cs:28), newest first, flagging the caller's own device by comparing against the session id the caller passes from the token's sid (AuthSessionIssuer.cs:269-283); the response deliberately omits the token hash and the rotation link, since nothing a client does with a session needs anything but its id (RefreshSessionSummaryResponse.cs:6-11). RevokeSessionByIdAsync (AuthenticationServiceBase.cs:533, delegating to AuthSessionIssuer.cs:318) signs one device out and treats an already-revoked row as a success that writes nothing, because a device list clicked twice is the most ordinary duplicate in the feature (AuthSessionIssuer.cs:333-340), while RevokeTokenAsync (AuthenticationServiceBase.cs:471, delegating to AuthSessionIssuer.cs:193) degrades to signing every device out when the presented token does not identify a live session of this user's (AuthSessionIssuer.cs:203-217). Those methods surface on IAuthenticationService (IAuthenticationService.cs:69, IAuthenticationService.cs:98, IAuthenticationService.cs:134) and are exposed by AuthControllerBase as revoke, my-sessions, and a per-session route (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/AuthControllerBase.cs:223, AuthControllerBase.cs:284, AuthControllerBase.cs:472).

RefreshSessionSettings (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/RefreshSessionSettings.cs:9) is where a host tunes the model: MaxActiveSessionsPerUser (default 10, range 1 to 1000, RefreshSessionSettings.cs:34-35), RetentionDays (default 30, RefreshSessionSettings.cs:71-72), CleanupIntervalHours (default 6, RefreshSessionSettings.cs:79-80), the DataSourceName that says which database carries the table (RefreshSessionSettings.cs:51-52), and Enabled (RefreshSessionSettings.cs:25), which gates the model, not the workflow: the service that owns identity sets it, every other service in a modular host leaves it alone, and that is what keeps the table, its migrations, and its sweep in exactly one database. Retention is not decoration: the settings' own remarks state that the sweep bounds reuse detection, because once a revoked row is swept, a replay of its token reads as an unknown token and fails alone (RefreshSessionSettings.cs:59-66). ReuseGraceSeconds (default 10, range 0 to 300, RefreshSessionSettings.cs:98-99) is the rotation-race window described above, matched to the cookie refresher's rotation grace, and its remarks state the trade-off plainly: a stolen-token replay arriving inside the window of a legitimate rotation is answered 409 instead of revoking the family, and 0 treats every returning rotated token as reuse (RefreshSessionSettings.cs:82-96). The hosted sweep RefreshSessionCleanupService (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Auth/RefreshSessionCleanupService.cs:53) is registered only when the flag is set, so a service with no RefreshSessions table never starts a sweep over a table it does not have (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:237-245), and the mapping itself is opt-in through RefreshSessionModelBuilderExtensions.ApplyRefreshSessionConfiguration (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Auth/RefreshSessionModelBuilderExtensions.cs:50). This whole cluster is [Rubric §7, Microservices Readiness] as much as [Rubric §11, Security]: the credential store is one service's table, not a column every service's user model has to carry.

Sign-in history and devices

The refresh-session rows double as the account's sign-in record. A sign-in is one rotation chain: RefreshSessionSignIn (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/RefreshSessionSignIn.cs:19) carries the chain's identifier, the issue instant of its earliest retained row, and its newest row (the head), which holds the last activity, the device, and how the sign-in ended; a store may return the head untracked, so it is read-only. SignInHistory (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Sessions/SignInHistory.cs:20) shapes the store's capped aggregate (IRefreshSessionStore.GetRecentSignInsAsync, bounded by MaxEntries) into SignInSummaryResponse rows (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Responses/SignInSummaryResponse.cs:40) for both the self-service list (AuthSessionIssuer.ListSignInsAsync) and the administrator's (UserSessionsAdministrationService.GetSignInsAsync), so the two read a history the same way, and nothing reads more than that capped aggregate however many times a sign-in rotated. The newest row decides the ending: live, revoked (its instant and reason), or expired. SignInEndReasons (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Responses/SignInEndReasons.cs:9) lists the values, each revocation reason matching the session's own constant, plus Expired and ViewAsEnded, the two no session revocation writes. SignInHistoryEntryKind (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Responses/SignInHistoryEntryKind.cs:10) says what a row records and serializes by name, so a client built against an older list reads a newer kind as an unknown string rather than a bare number; a view-as grant is what the viewed account's history shows as "Viewed by support" (MMCA.Common/Source/Core/MMCA.Common.Domain/Auth/ViewAsGrant.cs:18). RefreshSessionDevice (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Sessions/RefreshSessionDevice.cs:11) is the one place a session's device columns are shaped into DeviceMetadata, shared by the device list, the sign-in history and the administrator's view so the three cannot drift.

What the app's User aggregate must expose

The shared workflows never see an app's User class. They see four small Domain-layer contracts, each sized to one workflow, which is the [Rubric §1, SOLID] interface-segregation story in miniature. IAuthUser (MMCA.Common/Source/Core/MMCA.Common.Domain/Auth/IAuthUser.cs:15) is now the password surface and nothing else: the hash and the salt whose length once selected an algorithm (IAuthUser.cs:19-23). Refresh tokens are deliberately absent, and the interface says why: they used to live here as a single plaintext column, which capped every account at one signed-in device and put a usable credential in the users table (IAuthUser.cs:9-13). Profile fields, roles, and linked aggregates stay app-specific and are reached only through the per-app hooks. IPasswordChangeableUser (MMCA.Common/Source/Core/MMCA.Common.Domain/Auth/IPasswordChangeableUser.cs:11) extends it with ChangePassword (IPasswordChangeableUser.cs:19), because both the rotation workflow and the reset workflow have to write a new credential through the aggregate rather than around it. Beside the four sits an opt-in sibling, IPasswordRehashableUser (MMCA.Common/Source/Core/MMCA.Common.Domain/Auth/IPasswordRehashableUser.cs:16), which extends IAuthUser with RehashPassword (IPasswordRehashableUser.cs:25) for the sign-in's hash upgrade and is kept apart from ChangePassword because a rehash is not a password change (see the passwords section below). IUserPreferences (MMCA.Common/Source/Core/MMCA.Common.Domain/Auth/IUserPreferences.cs:10) carries the stored culture and theme plus a single UpdatePreferences mutator that always replaces both fields (IUserPreferences.cs:13-25); the shared workflow is what preserves the other preference, passing the stored value for any field the request left null (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/ChangePreferences/ChangePreferencesHandlerBase.cs:53-55), which is the null-means-unchanged contract stated on ChangePreferencesRequest and mirrored by UserPreferencesResponse (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Requests/ChangePreferencesRequest.cs:10, MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Responses/UserPreferencesResponse.cs:9).

IErasableUser (MMCA.Common/Source/Core/MMCA.Common.Domain/Auth/IErasableUser.cs:22) is the subtlest of the four. It extends IAnonymizable and redeclares Delete() (IErasableUser.cs:30) rather than inheriting it from AuditableBaseEntity<TId>, because an app User commonly hides the base method (public new Result Delete()) to add account-specific behavior. A hidden method is not an override, so a shared workflow calling through the class constraint would silently run the base implementation and skip that behavior; routing the call through this interface makes the interface map resolve to the most derived Delete() (IErasableUser.cs:11-16). The base entity deliberately does not implement the interface, so a consumer that forgets to add it fails the generic constraint at compile time instead of losing behavior at run time (IErasableUser.cs:17-20). These four contracts are consumed by the shared handler bases in group 14: ChangePasswordHandlerBase<TUser, TCommand> (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/ChangePassword/ChangePasswordHandlerBase.cs:47), ChangePreferencesHandlerBase<TUser, TCommand> (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/ChangePreferences/ChangePreferencesHandlerBase.cs:23), GetUserPreferencesHandlerBase<TUser> (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/GetPreferences/GetUserPreferencesHandlerBase.cs:19), ResetPasswordHandlerBase<TUser, TCommand> (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/ResetPassword/ResetPasswordHandlerBase.cs:42), and DeleteUserHandlerBase<TUser, TCommand> (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/DeleteUser/DeleteUserHandlerBase.cs:62), each of which constrains TUser to the matching contract.

Passwords and brute-force protection

Password material is handled by PasswordHasher (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/PasswordHasher.cs:22), which hashes with PBKDF2-HMAC-SHA512 at 210,000 iterations, the OWASP Password Storage Cheat Sheet figure for that hash (PasswordHasher.cs:8-12, PasswordHasher.cs:34), over a 32-byte random salt (PasswordHasher.cs:25, PasswordHasher.cs:74) into a 64-byte output (PasswordHasher.cs:28), and verifies in constant time via CryptographicOperations.FixedTimeEquals (PasswordHasher.cs:109) to close the timing side channel. PBKDF2 is the only path (ADR-102), so one algorithm derives and verifies every stored credential (PasswordHasher.cs:8-12). What can move is the work factor, so every hash the type writes carries its own: a 69-byte record of a 0x01 version byte, a 4-byte big-endian iteration count and the 64-byte PBKDF2 output (PasswordHasher.cs:14-15, PasswordHasher.cs:70-83). A bare 64-byte hash is the earlier header-less format, always derived at 600,000 iterations, and it still verifies (PasswordHasher.cs:15-17, PasswordHasher.cs:36-37). Verification accepts exactly those two shapes and nothing else: a salt of the wrong size, a hash of any other length, or a versioned hash whose stored count falls outside 100,000 to 2,000,000 verifies nothing (PasswordHasher.cs:99-102, PasswordHasher.cs:143-159). That closes two holes at once: an empty hash and salt (the external-OAuth account shape) can no longer compare two empty spans as equal (PasswordHasher.cs:92-98), and a tampered row can neither lower the cost of guessing its password nor turn a sign-in into a CPU denial of service (PasswordHasher.cs:48-58). That is a compact [Rubric §11, Security] story: a modern KDF, a self-describing work factor and a constant-time compare in one small type, all behind the IPasswordHasher port (MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Auth/IPasswordHasher.cs:6) so the algorithm can be strengthened without touching an Application handler.

Strengthening it does not strand existing records, because the port also answers whether a hash that has just verified should be re-derived. NeedsRehash (IPasswordHasher.cs:20-28) is a default interface member that answers false, so a custom hasher keeps compiling and never triggers a rehash; the shipped hasher answers true for a legacy 64-byte hash and for a versioned hash whose stored count differs from the current one, and false for material it does not recognize, since that never verifies (PasswordHasher.cs:124-136). The upgrade itself is the last step of the sign-in described above, and it runs only for an app User that opts in through IPasswordRehashableUser (MMCA.Common/Source/Core/MMCA.Common.Domain/Auth/IPasswordRehashableUser.cs:16). Its single RehashPassword (IPasswordRehashableUser.cs:25) is deliberately separate from ChangePassword: a rehash keeps the same password, so it must not raise the password-changed domain event or anything else a real password change triggers, such as revoking sessions or notifying the owner (IPasswordRehashableUser.cs:10-14). A User that does not implement it keeps its stored hash exactly as it is (IPasswordRehashableUser.cs:8-9).

LoginProtectionService (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/LoginProtectionService.cs:42) adds the ADR-029 gates on top, backed by ICacheService rather than a database so the counters are cheap and self-expiring. Counter keys are built from an Email-normalized identity (LoginProtectionService.cs:82, LoginProtectionService.cs:84), so User@x.com, user@x.com, and a padded variant collapse onto one lockout instead of handing an attacker three independent budgets. The normalization itself lives once, in the internal EmailIdentity helper (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/EmailIdentity.cs:14), which every cache-keyed auth service calls: a valid address becomes the Email value object's normalized value, and a malformed one (which never matches a user but can still mint a key) falls back to the same trim-and-lowercase shape so its attempts land on one key too (EmailIdentity.cs:28-45). The key never carries the address itself: KeySegment is a 64-character hex SHA-256 of the normalized address, because a key travels further than the entry it names (Redis key names, the two-level cache's read-fault warnings, Redis client exception messages) and none of those places may carry an email address (EmailIdentity.cs:16-26); the registration counter hashes the client IP, normalized by ClientAddressKey.For, for the same reason (LoginProtectionService.cs:284-287). After LoginProtectionSettings.MaxFailedAttempts consecutive failures (default 5, MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/LoginProtectionSettings.cs:18) it applies an exponential-backoff lockout capped at MaxLockoutSeconds (default 300, LoginProtectionSettings.cs:24), with a deliberately clamped shift exponent so a persistent attacker cannot wrap the TTL back to something small (LoginProtectionService.cs:174), and it rate-limits registrations per source IP (default 10 per 60-minute window, LoginProtectionSettings.cs:37-43, LoginProtectionService.cs:214-269). Every setting carries a [Range] attribute, which is what makes the clamp argument airtight: MaxLockoutSeconds cannot exceed 3600 (LoginProtectionSettings.cs:23), and 1 << 30 already dwarfs that. The ILoginProtectionService port (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/ILoginProtectionService.cs:10) is what the workflow depends on, and it calls the gates at exactly the right points (increment on failed login, reset on success), so the protection is centralized rather than sprinkled through each app's controller. One documented trade-off is stated in source: the attempt increment is a read-modify-write rather than an atomic counter, because the native Redis INCR path wrote a key shape IDistributedCache could not read back (LoginProtectionService.cs:102-110). Sequential guessing, which is what a credential-stuffing run looks like, still trips the lockout.

The second factor: one optional step in the same sign-in

Two-factor authentication ships as contracts plus a stateless implementation, never as a feature that turns itself on: the account row belongs to the app, and making a second factor mandatory would be a behavior change in a deployed system (ADR-116). The cryptography lives in ITwoFactorService (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/TwoFactor/ITwoFactorService.cs:16) and its implementation TotpTwoFactorService (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/TwoFactor/TotpTwoFactorService.cs:34): mint a shared secret encoded by the internal Base32 helper (TotpTwoFactorService.cs:39-40, MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/TwoFactor/Base32.cs:13, lenient on decode in the ways authenticator secrets are typed: optional padding, either letter case), render the otpauth://totp/... provisioning URI an authenticator app is keyed from (TotpTwoFactorService.cs:43, TotpTwoFactorService.cs:53), verify a code inside the configured skew window (TotpTwoFactorService.cs:57, with the RFC 6238 step arithmetic in Totp, MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/TwoFactor/Totp.cs:24, called at TotpTwoFactorService.cs:88, which computes and compares every candidate step without stopping at a match so the reply time does not say which step matched, Totp.cs:18-21), and generate and match single-use recovery codes (TotpTwoFactorService.cs:99, TotpTwoFactorService.cs:126). It is deliberately stateless and persistence-free, so a data migration enrolling existing accounts can call it directly and every method is testable against a fixed clock (ITwoFactorService.cs:10-15). Recovery codes travel as a RecoveryCodeSet (ITwoFactorService.cs:97), plaintext and hashes paired positionally so a caller cannot store one set and display another, and the plaintext exists only in the returned value. Matching compares in fixed time through CryptographicOperations.FixedTimeEquals with no early exit (TotpTwoFactorService.cs:148), and the codes are Base32 rather than Base64 because that alphabet has no case ambiguity for a user reading one off paper (TotpTwoFactorService.cs:106-108).

TwoFactorSettings (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/TwoFactor/TwoFactorSettings.cs:15) binds from Authentication:TwoFactor (TwoFactorSettings.cs:18) and defaults to the RFC 6238 values every authenticator app assumes: six digits (TwoFactorSettings.cs:30), a thirty-second step (TwoFactorSettings.cs:34), one step of tolerated skew on each side, which widens the accepted window to roughly ninety seconds (TwoFactorSettings.cs:46), a twenty-byte secret (TwoFactorSettings.cs:61), and ten recovery codes of ten random bytes each (TwoFactorSettings.cs:50, TwoFactorSettings.cs:57). They are configurable so a host can match an existing enrollment base, not because moving them is a good idea: an app keyed against one period cannot read codes minted with another (TwoFactorSettings.cs:9-14).

State is the app's, so it is reached through two contracts rather than a framework table. ITwoFactorUserState (MMCA.Common/Source/Core/MMCA.Common.Domain/Auth/ITwoFactorUserState.cs:27) is what the app's User exposes: the enabled flag, the shared secret in the protected form the framework writes, and the unspent recovery-code hashes (ITwoFactorUserState.cs:30, ITwoFactorUserState.cs:37, ITwoFactorUserState.cs:43). The protection is its own port, ITwoFactorSecretProtector (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/TwoFactor/ITwoFactorSecretProtector.cs:13): enrollment protects the freshly minted secret before it reaches the store and the shipped authenticator unprotects it to verify a code, so the app's store only ever holds the protected form. The default, DataProtectionTwoFactorSecretProtector (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/TwoFactor/DataProtectionTwoFactorSecretProtector.cs:15), uses the host's data-protection key ring under the purpose MMCA.Common.Auth.TwoFactor.Secret.v1, so a multi-replica host needs the shared key ring (ADR-069), and a replica that cannot read a secret another wrote sees a failed unprotect, never an exception. The TwoFactorStatusResponse (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Responses/TwoFactorResponses.cs:51) reports an account's enrollment state to the client. The load-bearing invariant is stated on the interface itself: a stored secret is not an enabled second factor, because starting an enrollment writes the secret while the flag stays false, so an enrollment the user abandons half way can never gate a later sign-in (ITwoFactorUserState.cs:22-25). ITwoFactorStore (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/TwoFactor/ITwoFactorStore.cs:24) is the matching persistence port, split along that invariant: StartEnrollmentAsync stores the secret without activating anything (ITwoFactorStore.cs:47), CompleteEnrollmentAsync activates it and stores the first recovery hashes only after a code minted from that secret has verified (ITwoFactorStore.cs:57), DisableAsync clears both so a later enrollment starts from a fresh secret rather than reviving an old one (ITwoFactorStore.cs:69), and the recovery set is replaced wholesale or spent one code at a time (ITwoFactorStore.cs:79, ITwoFactorStore.cs:96). Every mutating member returns a Result so an aggregate that refuses can say so without an exception crossing the layer, and implementations save their own work, because a workflow treats one call's result as final (ITwoFactorStore.cs:13-22). The framework ships no EF implementation here the way it does for refresh sessions, because the secret and the hashes belong to the app's user row (ITwoFactorStore.cs:6-10).

The sign-in hook is a third contract, ITwoFactorAuthenticator (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/TwoFactor/ITwoFactorAuthenticator.cs:24), and it is a separate collaborator on purpose: AuthenticationServiceBase<TUser> takes it as an optional constructor dependency, so an app that has not adopted the second factor passes nothing and its sign-in does not even pay a query (ITwoFactorAuthenticator.cs:13-16). The challenge runs after the password check, for the same reason the account-state gate does: reaching it proves the caller owns the credential, so answering "this account needs a second factor" tells the owner something rather than telling an address sweeper which accounts are protected (ITwoFactorAuthenticator.cs:19-21). The shipped TwoFactorAuthenticator (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/TwoFactor/TwoFactorAuthenticator.cs:43) reads the state and returns TwoFactorOutcome.NotEnrolled when there is no active factor, so an unenrolled account's sign-in is unchanged (TwoFactorAuthenticator.cs:66-69, ITwoFactorAuthenticator.cs:73); otherwise it verifies a TOTP code (TwoFactorAuthenticator.cs:73-77, each time step accepted once, TwoFactorAuthenticator.cs:196-206), falls back to matching and spending a recovery code (TwoFactorAuthenticator.cs:79, TwoFactorAuthenticator.cs:149), and fails with one of the two TwoFactorErrors codes: Authentication.TwoFactorRequired when a code was needed and none arrived, Authentication.TwoFactorInvalid when one arrived and did not verify (TwoFactorAuthenticator.cs:74, TwoFactorAuthenticator.cs:83, MMCA.Common/Source/Core/MMCA.Common.Application/Auth/TwoFactor/TwoFactorErrors.cs:18, TwoFactorErrors.cs:21). Which method satisfied the challenge is what the issued token records: AuthClaimTypes names the mfa claim and its two values, otp and recovery (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/AuthClaimTypes.cs:63, AuthClaimTypes.cs:66, AuthClaimTypes.cs:69), read back through ClaimsPrincipalExtensions.HasMultiFactor and FindMultiFactorMethod (ClaimsPrincipalExtensions.cs:161, ClaimsPrincipalExtensions.cs:180), which is how a presence check stays out of ICurrentUserService. The wire shapes are TwoFactorCodeRequest with its TwoFactorCodeRequestValidator, TwoFactorSetupResponse and TwoFactorRecoveryCodesResponse.

Forgot password: a cache-backed single-use token

A user who has lost the password cannot present one, so this flow is anonymous by necessity, which makes every one of its responses a potential account-enumeration oracle. It is also built without a schema change: the token lives in the cache, hashed, and expires by TTL rather than being reaped by a sweeper (ADR-091). The port is IPasswordResetTokenService (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/IPasswordResetTokenService.cs:10), two methods wide: IssueAsync mints a token for an address (IPasswordResetTokenService.cs:23) and ValidateAndConsumeAsync redeems it exactly once (IPasswordResetTokenService.cs:36). The implementation, PasswordResetTokenService (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/PasswordResetTokenService.cs:34), rides on ICacheService and buys four properties in a few lines each:

  • One active token per email. Issuing writes the same per-address key (PasswordResetTokenService.cs:55, PasswordResetTokenService.cs:95), so requesting a new link retires the previous one.
  • Hashed at rest. Only the Base64 of the token's SHA-256 is stored (PasswordResetTokenService.cs:59-60, PasswordResetTokenService.cs:89-95), so a cache dump hands out no working reset links, and the comparison on redemption is constant time through CryptographicOperations.FixedTimeEquals (PasswordResetTokenService.cs:151).
  • An attempt cap. A wrong token increments a counter on the record, and the record is discarded at MaxValidationAttempts (PasswordResetTokenService.cs:165-186, default 5, MMCA.Common/Source/Core/MMCA.Common.Application/Auth/PasswordResetSettings.cs:36). The rewrite after a wrong guess uses the record's remaining lifetime rather than a fresh one (PasswordResetTokenService.cs:179-185), so guessing cannot extend the redeemable window.
  • A per-email request throttle. A counter carrying the window's TTL caps how often one address can trigger an email (PasswordResetTokenService.cs:68-84, default 3 per 60 minutes, PasswordResetSettings.cs:40, PasswordResetSettings.cs:44), and a successful redemption deletes the token and that counter (PasswordResetTokenService.cs:159-160) so a legitimate reset does not leave the user throttled out of a later one.

Keys are built from an Email-normalized identity, through the same EmailIdentity helper and for the same reason LoginProtectionService does it (PasswordResetTokenService.cs:49-57). The cached record, PasswordResetEntry (PasswordResetTokenService.cs:204), is deliberately all JSON primitives: cache values round-trip through System.Text.Json, so a value object or a byte[] member would not survive a distributed backing store (PasswordResetTokenService.cs:195-199). Token material is 32 random bytes, Base64Url encoded (PasswordResetTokenService.cs:41, PasswordResetTokenService.cs:86), redeemable for TokenLifetimeMinutes (default 30, PasswordResetSettings.cs:29), and every rejection (unknown, expired, mismatched, attempt-capped) collapses into one generic failure (PasswordResetTokenService.cs:188-192). The settings bind from the PasswordReset configuration section and the service is registered scoped in Infrastructure DI (PasswordResetSettings.cs:13, MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:179-183).

The workflow around the port lives in the group-14 handler bases, and it is where the anti-enumeration rule is enforced. ForgotPasswordHandlerBase<TUser, TCommand> (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/ForgotPassword/ForgotPasswordHandlerBase.cs:63) answers the inline dispatch by scheduling itself as an internal command and returning success (ForgotPasswordHandlerBase.cs:86-88, ForgotPasswordHandlerBase.cs:92-102); the scheduled run resolves the account by email through the read repository, issues a token, and mails it through IEmailSender (ForgotPasswordHandlerBase.cs:114-117, ForgotPasswordHandlerBase.cs:124, ForgotPasswordHandlerBase.cs:136). A malformed address, an address with no account and a throttled request all log and return success alike (ForgotPasswordHandlerBase.cs:107-111, ForgotPasswordHandlerBase.cs:118-121, ForgotPasswordHandlerBase.cs:125-128), while a failed send propagates out of the scheduled run, where the processor logs it and retries the row (ForgotPasswordHandlerBase.cs:131-136). The only 400 comes from ForgotPasswordRequestValidator (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Validation/ForgotPasswordRequestValidator.cs:11), which inspects the shape of the address and nothing else. The email carries both a prefilled link (composed from PasswordResetSettings.ResetUrl, deliberately not required so a host that has not configured a UI base still boots, PasswordResetSettings.cs:25, ForgotPasswordHandlerBase.cs:186-189) and the raw token, because a client without deep linking (the MAUI head) needs it typed into the reset page by hand (ForgotPasswordHandlerBase.cs:151-153). ResetPasswordHandlerBase<TUser, TCommand> (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/ResetPassword/ResetPasswordHandlerBase.cs:42) consumes the token before the save on a stated trade-off (leaving it live until the write succeeds opens a replay window; a token burned by a later invariant failure costs the user one more reset request, ResetPasswordHandlerBase.cs:74-84), hashes through IPasswordHasher and writes the credential through the aggregate's ChangePassword (ResetPasswordHandlerBase.cs:110-111), then clears the login-protection counters so a user who reset because of a lockout is not left locked out (ResetPasswordHandlerBase.cs:120). ResetPasswordRequestValidator (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Validation/ResetPasswordRequestValidator.cs:12) includes the same StrongPasswordRules<T> that registration and change-password use (ResetPasswordRequestValidator.cs:23), so a reset is not a way around the complexity policy. The endpoints are PasswordResetAuthControllerBase<TForgotPasswordCommand, TResetPasswordCommand> (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/PasswordResetAuthControllerBase.cs:43): both actions are [AllowAnonymous] and rate-limited per IP exactly as login and register are (PasswordResetAuthControllerBase.cs:77-78, PasswordResetAuthControllerBase.cs:101-102), forgot-password answers 202 for any well-formed request (PasswordResetAuthControllerBase.cs:79, PasswordResetAuthControllerBase.cs:92), and reset-password collapses every rejection into a single 401 (PasswordResetAuthControllerBase.cs:105).

Email confirmation: the same token shape, a different prefix

Confirming an address is the forgot-password flow's twin, and it is built that way on purpose: member for member, IEmailConfirmationTokenService (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/EmailConfirmation/IEmailConfirmationTokenService.cs:15) mirrors the reset port, with IssueAsync minting a token for an address and account (IEmailConfirmationTokenService.cs:28) and ValidateAndConsumeAsync redeeming it exactly once and returning the confirmed account's identifier (IEmailConfirmationTokenService.cs:59). The implementation EmailConfirmationTokenService (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/EmailConfirmationTokenService.cs:42) rides on ICacheService under its own key prefix and buys the same four properties: 32 random bytes Base64Url encoded (EmailConfirmationTokenService.cs:48, EmailConfirmationTokenService.cs:76), only the token's SHA-256 stored (EmailConfirmationTokenService.cs:173), a constant-time comparison on redemption (EmailConfirmationTokenService.cs:141), and every rejection collapsed into one generic failure (EmailConfirmationTokenService.cs:198-200). Its token and request-counter keys go through the same EmailIdentity normalization as the reset keys (EmailConfirmationTokenService.cs:168, EmailConfirmationTokenService.cs:170). The cached record is EmailConfirmationEntry (EmailConfirmationTokenService.cs:212), JSON primitives only for the same round-trip reason PasswordResetEntry is.

EmailConfirmationSettings (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/EmailConfirmation/EmailConfirmationSettings.cs:10) binds from Authentication:EmailConfirmation (EmailConfirmationSettings.cs:13) and differs from the reset settings where the use case does: the token is redeemable for a day rather than half an hour (TokenLifetimeMinutes default 1440, EmailConfirmationSettings.cs:29), because a confirmation mail is commonly opened much later, while the attempt cap (5, EmailConfirmationSettings.cs:36) and the per-address request throttle (3 per 60 minutes, EmailConfirmationSettings.cs:40, EmailConfirmationSettings.cs:44) match. The gate is RequireConfirmedEmail (EmailConfirmationSettings.cs:55), off unless a host sets it and the app's user implements IEmailConfirmableUser (MMCA.Common/Source/Core/MMCA.Common.Domain/Auth/IEmailConfirmableUser.cs:22), a two-member contract: the IsEmailConfirmed flag and a Result-returning ConfirmEmail() that writes it through the aggregate (IEmailConfirmableUser.cs:25, IEmailConfirmableUser.cs:33). A user type that does not implement the interface is never asked about confirmation (IEmailConfirmableUser.cs:12), which is what keeps the feature inert for the apps that have not adopted it. The two failures are named in EmailConfirmationErrors (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/EmailConfirmation/EmailConfirmationErrors.cs:10): Authentication.EmailNotConfirmed for a sign-in blocked by the gate and Authentication.InvalidConfirmationToken for every rejected redemption (EmailConfirmationErrors.cs:13, EmailConfirmationErrors.cs:16, EmailConfirmationErrors.cs:33, EmailConfirmationErrors.cs:56). The requests are SendEmailConfirmationRequest and ConfirmEmailRequest, guarded by SendEmailConfirmationRequestValidator and ConfirmEmailRequestValidator. Confirming an address that already has a password is an account claim, handled by IAccountClaimService (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/EmailConfirmation/IAccountClaimService.cs:17) and its default AccountClaimService (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/EmailConfirmation/AccountClaimService.cs:20), which AddEmailConfirmation registers: either verify the current password under the same lockout accounting a password sign-in uses, or let the mailbox owner claim the account with a new password, which revokes every refresh session and removes any second factor (IAccountClaimService.cs:30, IAccountClaimService.cs:46). It changes the account aggregate but never saves it, so the caller owns the unit of work (IAccountClaimService.cs:11-16). A sibling constant class, AuthErrorCodes (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/AuthErrorCodes.cs:12), names the authentication outcomes a client has to branch on rather than merely display: Auth.EmailAlreadyExists (AuthErrorCodes.cs:19), returned identically by the registration pre-check and by the unique-index race recovery so the two paths stay indistinguishable, and Auth.TermsNotAccepted (AuthErrorCodes.cs:25), returned only when a current terms version is configured (next section).

Terms of Service acceptance: one version string, one rule set

Recording consent to a host's Terms of Service is opt-in the same way, and unset is the off switch. LegalAcceptanceOptions (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Legal/LegalAcceptanceOptions.cs:12) binds from the Legal section (LegalAcceptanceOptions.cs:15) through AddLegalAcceptance(configuration) (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Auth.cs:148-154) and carries a single value, CurrentTermsVersion (LegalAcceptanceOptions.cs:21). With no version configured, registration does not ask, the read endpoint reports every user as current, and the accept endpoint has nothing to accept (LegalAcceptanceOptions.cs:7-11); changing the version asks every signed-in user to accept again (LegalAcceptanceOptions.cs:17-20).

The rules live once, in LegalAcceptancePolicy (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Legal/LegalAcceptancePolicy.cs:10), so the registration flow and the API controller base cannot apply them differently. ResolveCurrentVersion trims the configured value and treats null or whitespace as "none" (LegalAcceptancePolicy.cs:18-22). EnsureAcceptsCurrentVersion accepts only an ordinal match against a configured version (LegalAcceptancePolicy.cs:33-36), so a dialog left open across a version bump cannot record consent to text the user never saw (the client echoes the version it showed in AcceptLegalTermsRequest, MMCA.Common/Source/Core/MMCA.Common.Shared/Legal/AcceptLegalTermsRequest.cs:6-12). Normalize re-derives the standing from the accepted version and instant alone, so the answer never depends on a consumer filling the computed fields correctly (LegalAcceptancePolicy.cs:47-52). The standing is LegalAcceptanceDTO (MMCA.Common/Source/Core/MMCA.Common.Shared/Legal/LegalAcceptanceDTO.cs:18): current version, accepted version, accepted instant and IsCurrent (LegalAcceptanceDTO.cs:21, LegalAcceptanceDTO.cs:24, LegalAcceptanceDTO.cs:27, LegalAcceptanceDTO.cs:33), built through Evaluate, where an unconfigured version always yields IsCurrent = true so a client never blocks a user on a host that has not opted in (LegalAcceptanceDTO.cs:42-53, LegalAcceptanceDTO.cs:9-11).

Registration reads the version without a new constructor dependency: AuthenticationValidators takes the options as an optional parameter and exposes CurrentTermsVersion (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/AuthenticationValidators.cs:38, AuthenticationValidators.cs:84), which AuthenticationServiceBase<TUser> surfaces to its subclasses (AuthenticationServiceBase.cs:145). When a version is configured and the plain AcceptedTerms flag on RegisterRequest (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Requests/RegisterRequest.cs:26) is false, RegisterAsync fails before the rate limit with LegalAcceptanceErrors.TermsNotAccepted (AuthenticationServiceBase.cs:311-314, MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Legal/LegalAcceptanceErrors.cs:22-25); it is a flag rather than a version because the anonymous register page cannot read the version (AuthenticationServiceBase.cs:308-310). The app's CreateUser override then stamps the configured version on a user that implements ILegalAcceptingUser (AuthenticationServiceBase.cs:137-140), a Domain contract of two read-only properties and a Result-returning AcceptTerms that should treat the version already on record as an ordinary repeat (MMCA.Common/Source/Core/MMCA.Common.Domain/Auth/ILegalAcceptingUser.cs:21, ILegalAcceptingUser.cs:24, ILegalAcceptingUser.cs:27, ILegalAcceptingUser.cs:29-37). A user created outside RegisterAsync (the external-login path) is left unstamped and asked by the UI's acceptance gate on first sign-in (AuthenticationServiceBase.cs:141-142).

After registration the standing is read and recorded through ILegalAcceptanceService (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Legal/ILegalAcceptanceService.cs:21), which each app implements over its own User (GetForCurrentUserAsync and AcceptForCurrentUserAsync, ILegalAcceptanceService.cs:28, ILegalAcceptanceService.cs:41). The version rules are explicitly not the implementation's job (ILegalAcceptanceService.cs:11-20): LegalAcceptanceControllerBase resolves the version, refuses an acceptance of any other version before the service is called, and normalizes every answer on the way out (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Legal/LegalAcceptanceControllerBase.cs:54, LegalAcceptanceControllerBase.cs:110, LegalAcceptanceControllerBase.cs:83, LegalAcceptanceControllerBase.cs:125). LegalAcceptanceRoutes (MMCA.Common/Source/Core/MMCA.Common.Shared/Legal/LegalAcceptanceRoutes.cs:7) declares the action template me/legal-acceptance and the full Users/me/legal-acceptance path the UI client calls, so the controller base and the client cannot drift (LegalAcceptanceRoutes.cs:13, LegalAcceptanceRoutes.cs:16). The two failure codes live where their callers can reach them: Auth.TermsNotAccepted on AuthErrorCodes because it is a registration outcome, and Legal.VersionNotCurrent on LegalAcceptanceErrorCodes (MMCA.Common/Source/Core/MMCA.Common.Shared/Legal/LegalAcceptanceErrorCodes.cs:7, LegalAcceptanceErrorCodes.cs:13), with LegalAcceptanceErrors aliasing both and building each as a validation error (LegalAcceptanceErrors.cs:14, LegalAcceptanceErrors.cs:17, LegalAcceptanceErrors.cs:33-36). Versioned, dated consent that a host can re-ask on a terms change is the [Rubric §30, Compliance/Privacy/Data Governance] reading of this cluster.

Reading identity from claims

Once a request is authenticated, downstream code needs the caller's identity without re-parsing the JWT, and it needs one answer no matter which pipeline produced the principal. That is the job of ClaimsPrincipalExtensions (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/ClaimsPrincipalExtensions.cs:18): FindUserIdValue reads the raw sub claim and falls back to the ClaimTypes.NameIdentifier form the JWT bearer handler maps it onto (ClaimsPrincipalExtensions.cs:26-28), GetUserId parses that value through IParsable<T> in the invariant culture so the solution-wide identifier alias can change shape without editing any reader (ClaimsPrincipalExtensions.cs:40-44), and FindSessionId reads the sid claim, treating absence as an ordinary "the caller's own device is unknown" rather than an error (ClaimsPrincipalExtensions.cs:143-147). AuthClaimTypes (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/AuthClaimTypes.cs:9) names the three claim types this group cares about: the framework-custom "permission" (AuthClaimTypes.cs:24) used by the authorization model below, plus the standard sub (AuthClaimTypes.cs:34) and sid (AuthClaimTypes.cs:47), each documented with the pipeline caveat that motivates reading it through the extensions.

CurrentUserService (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Context/CurrentUserService.cs:17) is the scoped adapter over IHttpContextAccessor: it exposes the ClaimsPrincipal, the parsed user id, and the first role claim, caching the parsed values behind a per-request Lazy<T> (CurrentUserService.cs:19-23) and reading the identifier through the shared extensions (CurrentUserService.cs:20). Its generic GetClaimValue<T> (CurrentUserService.cs:35) is what the ownership filter uses to read app-specific owner claims, and it parses in the invariant culture because claims are machine-written and the ambient request culture must not decide how a separator reads (CurrentUserService.cs:39-41). The interface itself, ICurrentUserService (MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Auth/ICurrentUserService.cs:10), carries the multi-role logic as default interface members: Roles reads every role claim across the three claim-type spellings the JWT middleware may produce and falls back to the single Role property when a hand-written double populates only that (ICurrentUserService.cs:46-61), and IsInRole does a case-insensitive membership check over that set (ICurrentUserService.cs:83-84). A sibling adapter, ClaimBasedUserIdProvider (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Context/ClaimBasedUserIdProvider.cs:11), plugs the same identifier into SignalR's IUserIdProvider so Clients.User(userId) routes hub messages to the right connections (ClaimBasedUserIdProvider.cs:14-15).

Authorization: permissions and ownership

There is one authorization model here, and it is capabilities, not role names. The single AddAuthorizationPolicies() extension in AuthorizationExtensions (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/AuthorizationExtensions.cs:19, AuthorizationExtensions.cs:67) wires the whole mechanism: the permission handler and the on-demand policy provider (AuthorizationExtensions.cs:76-78), the shared registry, built once and exposed under both IPermissionRegistry and IPermissionCatalog (AuthorizationExtensions.cs:203-204, AuthorizationExtensions.cs:210-211), and the fallback policy described at the end of this section. Role names still exist as data, but the framework ships no constant class naming them: roles get a value-object base, RoleValue (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/RoleValue.cs:26), so each app can fix its own role set with case-insensitive, type-guarded equality (RoleValue.cs:91-97), a frozen interned lookup (RoleValue.cs:76-85), and Result-returning validation (RoleValue.cs:43) while staying dependency-free enough to use from Blazor WASM. What no longer exists is a shipped policy per role: an endpoint states the capability it needs and the registry maps roles to capabilities (ADR-020).

HasPermissionAttribute (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/HasPermissionAttribute.cs:13) marks a controller or action with a permission such as "sessions:manage"; under the hood it is an AuthorizeAttribute whose policy name is perm:sessions:manage (PermissionPolicy.NameFor, MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/PermissionPolicy.cs:12, PermissionPolicy.cs:17, applied at HasPermissionAttribute.cs:17-18). Rather than pre-registering a named policy per permission, PermissionPolicyProvider (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/PermissionPolicyProvider.cs:13) materializes those policies on demand for any perm: name and falls through to the default provider for everything else (PermissionPolicyProvider.cs:31-47). The requirement it attaches, PermissionRequirement (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/PermissionRequirement.cs:10), is evaluated by PermissionAuthorizationHandler (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/PermissionAuthorizationHandler.cs:14), which grants access when the principal holds the permission directly (a permission claim) or derives it from one of its roles via IPermissionRegistry (PermissionAuthorizationHandler.cs:30-32, MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Permissions/IPermissionRegistry.cs:14), reading the caller's roles through ClaimsPrincipalExtensions.GetRoleValues (PermissionAuthorizationHandler.cs:30, MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/ClaimsPrincipalExtensions.cs:60), which is the one place the three claim-type spellings the JWT middleware may produce are reconciled. The registry itself (PermissionRegistry, MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Permissions/PermissionRegistry.cs:16) is an immutable, frozen role-to-permission map with case-insensitive role keys and ordinal permission values (PermissionRegistry.cs:33-36) built by PermissionRegistryBuilder (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Permissions/PermissionRegistryBuilder.cs:8); each module contributes only its own grants through AddPermissions(...) (AuthorizationExtensions.cs:115), duplicate grants union rather than collide (PermissionRegistryBuilder.cs:47), and the shared registry is built lazily on first resolve, after every module has registered (AuthorizationExtensions.cs:204, PermissionRegistryBuilder.cs:62). The same instance answers as IPermissionCatalog (PermissionRegistry.cs:16, PermissionRegistry.cs:55, PermissionRegistry.cs:58), explicitly implemented because a catalog's flat list of permission names and the registry's per-role lookup are different questions that would otherwise share a member name. That module-local contribution is the [Rubric §7, Microservices Readiness] touch: an extracted service carries only its own permission grants.

The same capabilities reach inside the CQRS pipeline, not just the HTTP boundary: a command or query that implements IRequiresPermission is checked by AuthorizationCommandDecorator<TCommand, TResult> and AuthorizationQueryDecorator<TQuery, TResult> against the same registry. Because those decorators are registered unconditionally, a host with no Identity module and no grants would fail to activate every handler in the pipeline, which is what UnconfiguredPermissionRegistry (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/UnconfiguredPermissionRegistry.cs:20) exists to prevent: it is registered with TryAdd, so a host that called AddAuthorizationPolicies() keeps its own registry and never constructs this one (MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.cs:154). It grants nothing, so a permission-gated request is denied rather than allowed (UnconfiguredPermissionRegistry.cs:37, UnconfiguredPermissionRegistry.cs:44), and it says so exactly once, through an interlocked one-shot flag, in a log message naming the call that would fix it (UnconfiguredPermissionRegistry.cs:25, UnconfiguredPermissionRegistry.cs:60, UnconfiguredPermissionRegistry.cs:68). The warning is deferred to the first real check rather than raised at startup, because a host with no permission-gated request is correctly configured: it simply never needs a registry (UnconfiguredPermissionRegistry.cs:13-19). Fail-closed plus a diagnosable message is the [Rubric §11, Security] and [Rubric §13, Observability & Operability] reading of that type.

The second style is resource ownership. OwnerOrAdminFilter (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/OwnerOrAdminFilter.cs:31) is an action filter for endpoints that mix admin and owner access (carts, orders, bookmarks). It lets a bypass role through (OwnerOrAdminFilter.cs:43), then compares the caller's owner claim against the resource id taken from either the route or a bound argument (OwnerOrAdminFilter.cs:49, OwnerOrAdminFilter.cs:93-111), returning 403 otherwise. The important property is that it denies by default: when the owner claim is missing (OwnerOrAdminFilter.cs:51-55) or the owner parameter cannot be resolved at all, the request is rejected rather than waved through (OwnerOrAdminFilter.cs:57-71), because "nothing to compare" must not read as "nothing to enforce". An action that legitimately has no owner parameter opts out explicitly with AllowMissingOwnerAttribute (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/AllowMissingOwnerAttribute.cs:21), honored from either the action or its declaring controller via endpoint metadata (OwnerOrAdminFilter.cs:82-85, AllowMissingOwnerAttribute.cs:20), and the attribute's own remarks require the application site to name the guard that replaces the check (AllowMissingOwnerAttribute.cs:15-19). The filter's vocabulary (claim type, bypass role, route parameter) is configurable through OwnerOrAdminFilterOptions (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/OwnerOrAdminFilterOptions.cs:13) whose defaults preserve the original customer_id / Admin / id behavior (OwnerOrAdminFilterOptions.cs:16-31, ADR-033), with OwnershipHelper (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/OwnershipHelper.cs:11) supplying both the bypass-role check (OwnershipHelper.cs:24) and the query-scoping specification factory that controllers use to narrow collection endpoints to the caller's own rows (OwnershipHelper.cs:41-74).

Compiled grants are the baseline, not the ceiling. A host that needs an operator to move a capability between roles without a redeploy calls AddStoredPermissionGrants(configuration) (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Auth.cs:183), which binds PermissionGrantSettings (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Permissions/PermissionGrantSettings.cs:12, bound at DependencyInjection.Auth.cs:185-188), registers the EF-backed IPermissionGrantStore (DependencyInjection.Auth.cs:194), and decorates the compiled registry with LayeredPermissionRegistry (DependencyInjection.Auth.cs:216-227). The layering rule is a union with no deny row: a role holds a permission when either the compiled registry or the stored grants say so (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Permissions/LayeredPermissionRegistry.cs:30, LayeredPermissionRegistry.cs:55-65), so a bad edit can add a capability but can never take away one an endpoint's own module declared. Because HasPermission is synchronous, the stored half cannot be read from the database on the hot path: IPermissionGrantCache (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Permissions/IPermissionGrantCache.cs:21) is the boundary over an in-memory snapshot, refreshed on demand (IPermissionGrantCache.cs:37, IPermissionGrantCache.cs:11-19), and IPermissionGrantCacheInvalidator (IPermissionGrantCache.cs:53, IPermissionGrantCache.cs:61) is what an edit calls. The consequence a host accepts is that a grant edit reaches other replicas within CacheSeconds (default 300, PermissionGrantSettings.cs:25), with DataSourceName naming the one database that carries the rows (PermissionGrantSettings.cs:42), exactly as RefreshSessionSettings does. The row itself, PermissionGrant (MMCA.Common/Source/Core/MMCA.Common.Domain/Auth/PermissionGrant.cs:24), is a two-column identity (PermissionGrant.cs:39, PermissionGrant.cs:45) trimmed and length-validated in a Result-returning factory (PermissionGrant.cs:64, widths at PermissionGrant.cs:27 and PermissionGrant.cs:30), and its table is mapped only for the host that opted in, through a model gate whose mere registration is the opt-in the context reads (DependencyInjection.Auth.cs:190-192).

The administration API sits on top of the same grants. IRoleAdministrationService (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Administration/IRoleAdministrationService.cs:35) lists roles, reads one role, returns the catalog of role and permission names, and replaces a role's stored grants (IRoleAdministrationService.cs:43, IRoleAdministrationService.cs:51, IRoleAdministrationService.cs:64, IRoleAdministrationService.cs:84); it ships filled in as StoredPermissionRoleAdministrationService (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/Administration/StoredPermissionRoleAdministrationService.cs:62, its four methods at :72, :98, :111, :133) because both halves of that surface are framework-owned. A set of a role's stored grants is a diff against the rows already there, so it runs through the internal PermissionRoleEditUnit (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/Administration/PermissionRoleEditUnit.cs:22): a per-role distributed lock (exclusive across replicas when the host has Redis) around one transactional unit, so two administrators editing the same role cannot each diff against the rows before the other's writes, a refusal part-way through leaves no row written, and an edit that cannot take the lock answers PermissionGrant.RoleBusy (PermissionRoleEditUnit.cs:25, PermissionRoleEditUnit.cs:43-65). The edit's inputs travel as the private SetRequest record (the role as named and its canonical spelling, the desired permissions, the caller's privilege ceiling and the audit label) (StoredPermissionRoleAdministrationService.cs:162, StoredPermissionRoleAdministrationService.cs:379). The user half cannot be: IUserAdministrationService<TUserDto> (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Administration/IUserAdministrationService.cs:25) is generic in the app's own DTO, and each app implements reading, locking and role assignment over its own User (IUserAdministrationService.cs:33, IUserAdministrationService.cs:62, IUserAdministrationService.cs:71). Listing is not on it: the roster comes from the app's generic paged entity endpoint (IUserAdministrationService.cs:6-8), and the DTO that endpoint serves implements IUserAdminDTO (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Administration/IUserAdminDTO.cs:25), an IBaseDTO<UserIdentifierType> adding only the Email, Role and IsLocked values the shared list component renders itself (IUserAdminDTO.cs:28, IUserAdminDTO.cs:31, IUserAdminDTO.cs:37), so an app can map its own lock spelling through an explicit implementation instead of renaming its wire contract (IUserAdminDTO.cs:19-23). A lock should also revoke the account's live sessions through RefreshSessionRevocation, or it waits for the access token to expire (IUserAdministrationService.cs:48-57). The device view of another account is framework-owned again: IUserSessionsAdministrationService (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Administration/IUserSessionsAdministrationService.cs:13) is read-only (it never revokes) and offers a user's live sessions newest first, a user's recent sign-ins, a roster's "signed in" filter (a predicate over the user entity that runs as one database subquery when users and sessions share a data source, and otherwise carries a bounded id list that fails rather than answer from a cut list), and a per-user live-session count for one roster page (IUserSessionsAdministrationService.cs:23, IUserSessionsAdministrationService.cs:36, IUserSessionsAdministrationService.cs:40-59, IUserSessionsAdministrationService.cs:72). Its default UserSessionsAdministrationService (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Administration/UserSessionsAdministrationService.cs:19) sits directly on IRefreshSessionStore and a TimeProvider: it drops expired rows in memory, marks every row IsCurrent: false because an administrator is never on the viewed user's device, makes no user lookup so an unknown id is an empty list rather than a 404, and answers an empty count request without touching the store (UserSessionsAdministrationService.cs:41-65, UserSessionsAdministrationService.cs:35-40, UserSessionsAdministrationService.cs:128-132). The two capabilities that gate the whole surface are named once in AdministrationPermissions (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Permissions/AdministrationPermissions.cs:15): users:manage and roles:manage (AdministrationPermissions.cs:18, AdministrationPermissions.cs:21). The wire shapes are SetUserRolesRequest, SetRolePermissionsRequest, RolePermissionsResponse and PermissionCatalogResponse, each guarded by its own FluentValidation rule (SetUserRolesRequestValidator, SetRolePermissionsRequestValidator).

The last piece of the authorization wiring is defensive rather than declarative. AddAuthorizationPolicies() installs a fallback policy, so an endpoint carrying no authorization metadata at all is denied rather than served. The requirement is its own type, FallbackAuthorizationRequirement (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/Fallback/FallbackAuthorizationRequirement.cs:16), and FallbackAuthorizationHandler (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/Fallback/FallbackAuthorizationHandler.cs:35) grants it to an authenticated caller, to a request whose path matches one of the exempt prefixes, to a request that matched no endpoint and names no web-root file (so the host's not-found page renders a 404 instead of a sign-in redirect), and to a request routed to an API-versioning rejection endpoint (so the caller gets the 400 version error rather than a 401 challenge) (FallbackAuthorizationHandler.cs:49-54, rationale at FallbackAuthorizationHandler.cs:19-31). A bare RequireAuthenticatedUser() would not do, because a Blazor host maps endpoint-routed static and framework surfaces that carry no metadata of their own and would be gated along with everything else (FallbackAuthorizationRequirement.cs:11-15), which is why the requirement is path-aware. FallbackAuthorizationOptions (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/Fallback/FallbackAuthorizationOptions.cs:14) carries the Enabled switch (on by default, FallbackAuthorizationOptions.cs:52) and the editable exempt-prefix list seeded from the framework defaults (FallbackAuthorizationOptions.cs:64); the handler is registered with TryAddEnumerable and the policy attached only while the switch is set (AuthorizationExtensions.cs:92-93, AuthorizationExtensions.cs:98-101).

A sign-in link reuses the email-confirmation token design for a third purpose (ADR-116). ISignInLinkTokenService (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/SignInLinks/ISignInLinkTokenService.cs:18) issues and redeems single-use tokens whose material lives outside the database, hashed at rest, with a per-address request throttle and a per-token validation-attempt cap; its implementation SignInLinkTokenService (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/SignInLinks/SignInLinkTokenService.cs:45) keeps each record as a SignInLinkEntry (SignInLinkTokenService.cs:212) in ICacheService. A token is keyed by address and SignInLinkPurpose (ISignInLinkTokenService.cs:63), not by account: SignIn is the short-lived link the owner asks for, Invite the long-lived one an organizer sends to an address that may have no account yet, and redeeming an invitation is what creates the account, named from the optional SignInLinkProfile (ISignInLinkTokenService.cs:75) the redeemed SignInLinkGrant carries (ISignInLinkTokenService.cs:80). One active token per address and purpose means asking for a sign-in link never invalidates an outstanding invitation. The cache keys carry their own signinlink: prefix so this workflow cannot silently invalidate another's link, and redemption deliberately takes no distributed lock: two concurrent redemptions of one token would both open a session for the account the link already proved, which is what a double tap asks for. SignInLinkSettings (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/SignInLinks/SignInLinkSettings.cs:10) binds Authentication:SignInLinks; SendSignInLinkRequest and RedeemSignInLinkRequest (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Requests/SignInLinkRequests.cs:11, SignInLinkRequests.cs:23) are guarded by SendSignInLinkRequestValidator and RedeemSignInLinkRequestValidator (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Validation/SignInLinkRequestValidators.cs:11, SignInLinkRequestValidators.cs:24), and failures use SignInLinkErrors (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/SignInLinks/SignInLinkErrors.cs:9). PasswordCredential (MMCA.Common/Source/Core/MMCA.Common.Domain/Auth/Credentials/PasswordCredential.cs:8) is the one definition of "this account holds a password credential" shared by password sign-in and this workflow (an empty hash and an empty salt is the passwordless shape an external-login account already carries, ADR-036), and IPasswordClearableUser (MMCA.Common/Source/Core/MMCA.Common.Domain/Auth/Credentials/IPasswordClearableUser.cs:24) moves an account to that shape through ClearPassword. An account type that holds password material without implementing it has its sign-in-link redemption refused while it is unconfirmed, because the workflow never confirms an address whose existing password it cannot remove.

Passkeys: WebAuthn in its own package

Passkey sign-in (ADR-139) splits the workflow from the cryptography, so a host that never opts in carries no WebAuthn library at all. IPasskeyService (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Passkeys/IPasskeyService.cs:12) is the ceremonies plus the management of an account's passkeys, implemented by PasskeyService (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Passkeys/PasskeyService.cs:33), while IPasskeyCeremony (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Passkeys/IPasskeyCeremony.cs:19) builds the options a browser signs and verifies what comes back, exchanging WebAuthn JSON so nothing outside the implementation names a library type. That implementation, Fido2PasskeyCeremony (MMCA.Common/Source/Core/MMCA.Common.Passkeys/Fido2PasskeyCeremony.cs:20), sits over Fido2NetLib in the opt-in MMCA.Common.Passkeys package (discoverable credentials, user verification preferred, attestation none), and PasskeysServiceCollectionExtensions (MMCA.Common/Source/Core/MMCA.Common.Passkeys/PasskeysServiceCollectionExtensions.cs:10) registers the pieces through AddPasskeys. PasskeySettings (PasskeySettings.cs:19) binds the Passkeys section and is validated at startup by PasskeySettingsValidator (MMCA.Common/Source/Core/MMCA.Common.Passkeys/PasskeySettingsValidator.cs:12); a credential is bound to the relying-party id, so changing the domain orphans every passkey. PasskeyCredential (MMCA.Common/Source/Core/MMCA.Common.Domain/Auth/PasskeyCredential.cs:20) is one registered credential, framework bookkeeping like RefreshSession rather than an aggregate, persisted through IPasskeyCredentialStore (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Passkeys/IPasskeyCredentialStore.cs:10). Nothing in it is secret: the id and the public key only verify signatures, and the sign count is what detects a cloned authenticator.

Two guards carry the security argument. PasskeyChallenges (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Passkeys/PasskeyChallenges.cs:21) stores each issued challenge under a random flow id in the shared cache and burns it on redeem inside a distributed lock (the OAuth exchange-code pattern), so a completion replayed on any replica finds nothing; the same class serializes an account's passkey deletes. PasskeyStepUp (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Passkeys/PasskeyStepUp.cs:17) admits a new registration only from a session whose auth_time claim shows a recent interactive sign-in, and deliberately not the token's age or the mfa claim: both ride every refresh, so either would let a stolen refresh token plant its own passkey, whereas auth_time is carried over unchanged and only a new sign-in renews it. Failures are vague to the caller and specific in the log: an unknown credential, a bad signature and a counter that did not advance all answer the one PasskeyErrors code AssertionFailed (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Passkeys/PasskeyErrors.cs:10), and because a discoverable sign-in has no email for LoginProtectionService to key on, failures are metered by the auth-ip rate-limit policy instead. The wire shapes are PasskeyOptionsResponse, PasskeyRegisterRequest, PasskeySignInRequest, PasskeyRenameRequest and PasskeyResponse, and the records that cross the ceremony port are PasskeyChallenge, PasskeyAttestation and PasskeyStoredKey.

Step-up for listed roles: withholding, not re-issuing

MultiFactorAuthorizationSettings (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/MultiFactor/MultiFactorAuthorizationSettings.cs:28) binds Authorization:MultiFactor:RequiredForRoles per service. With a role listed, that role confers nothing on a bearer session that signed in without a second factor (no mfa claim), and the token itself is never changed; the request's principal is. MultiFactorBearerWithholding (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/MultiFactor/MultiFactorBearerWithholding.cs:19), registered once by AddAuthorizationPolicies, is a post-configure step that chains MultiFactorRoleWithholding (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/MultiFactor/MultiFactorRoleWithholding.cs:30) onto the OnTokenValidated event of every JWT bearer scheme, after whatever handler is already there. The validated identity loses the listed role and the permission claims that came with it and gains AuthClaimTypes markers recording what was withheld, so every reader of the principal (role and permission checks, ICurrentUserService) sees an account without the role, while plain [Authorize] endpoints such as sign-out, profile and the two-factor endpoints stay reachable so the account can enroll. Unauthenticated principals, machine clients, sessions carrying mfa and cookie schemes are left alone, and an empty list returns before reading anything. MultiFactorRoleAuthorizationHandler (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/MultiFactor/MultiFactorRoleAuthorizationHandler.cs:33) never succeeds a requirement; it only turns the refusal into a coded one when the permission would have come through a withheld role, and MultiFactorRefusalResultHandler (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/MultiFactor/MultiFactorRefusalResultHandler.cs:25) wraps the host's IAuthorizationMiddlewareResultHandler so that refusal answers a 403 Problem Details carrying Authorization.MultiFactorRequired instead of a body-less forbid (a gRPC request keeps the default). AuthorizationExtensions installs that wrapper through its private ResultHandlerWrapper (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/AuthorizationExtensions.cs:222), which rebuilds the originally registered handler from its descriptor and doubles as the marker that a descriptor is already wrapped. A caller whose withheld role would not have granted the permission keeps the plain 403 and never learns a step-up exists.

Read-only support access: view-as

ADR-137 lets a staff user see the app as another account, for a bounded time and a stated reason, without changing anything. IViewAsService (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/ViewAs/IViewAsService.cs:10) and ViewAsService (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/ViewAs/ViewAsService.cs:42) mint the view-as token through the raw ITokenService rather than the SessionStampingTokenService wrapper, so it carries no sid and no mfa, opens no refresh session and is never renewed; it carries the viewed account's standard claims plus act_sub (the staff user) and vag (the grant), and lives the lesser of 15 minutes and the configured access-token lifetime. There is no lateral access: an account whose role holds users:view-as is never viewed, nor is a machine client's service account or a locked account, as read through the consumer's IViewAsSubjectResolver (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/ViewAs/IViewAsSubjectResolver.cs:8) into a ViewAsSubject (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/ViewAs/ViewAsSubject.cs:15), soft-deleted rows included so a deleted account is refused rather than reported missing. Each grant is a ViewAsGrant row (ViewAsGrant.cs:18), framework bookkeeping like RefreshSession and itself the audit record of the access, persisted through IViewAsGrantStore (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/ViewAs/IViewAsGrantStore.cs:11) and filtered for the support access log by ViewAsGrantLogQuery (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/ViewAs/ViewAsGrantLogQuery.cs:12), one translatable predicate chain so the EF store and the in-memory test store cannot disagree on a filter.

ViewAsSettings (ViewAsSettings.cs:34) is off by default, and even then the guard middleware stays in the pipeline and refuses any view-as token with 401. In a multi-service host only the Identity service keeps HostsGrantStore; the others enforce the read-only rule and learn that a grant ended from a marker the Identity service writes to the shared cache, failing closed when they cannot read it. The command decorator refuses every command; ViewAsReadOnlyEndpointAttribute (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/ViewAsReadOnlyEndpointAttribute.cs:18) is the host's explicit, unverifiable assertion that a POST endpoint (a read that fans out over gRPC, say) performs no write, and it relaxes the method rule only. On a web host with the same-origin proxy, ViewAsOverlayCookie (MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/ViewAsOverlayCookie.cs:35) holds the view-as token in a separate short-lived HttpOnly cookie (mmca_view_as, its value protected with DataProtection under its own purpose, ViewAsOverlayCookie.cs:38, ViewAsOverlayCookie.cs:46) that, while unexpired, wins over the session access token everywhere the browser's identity is read (including CookieTokenReader) and leaves the staff user's own session cookies untouched. The wire shapes are StartViewAsRequest and ViewAsGrantListRequest (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Requests/AdministrationRequests.cs:34, AdministrationRequests.cs:40), ViewAsGrantResponse, ViewAsGrantSummaryResponse and ViewAsGrantStatus.

Machine clients: the client credentials grant

ADR-140 gives a program its own access tokens. A MachineClient (MMCA.Common/Source/Core/MMCA.Common.Domain/Auth/MachineClients/MachineClient.cs:21, an AuditableBaseEntity<Guid>) is backed one to one by a service-account user whose role decides what its tokens may do; it is revoked, never deleted. Secrets follow MachineClientSecret (MMCA.Common/Source/Core/MMCA.Common.Domain/Auth/MachineClients/MachineClientSecret.cs:15): 32 random bytes handed out once base64url-encoded, stored only as a SHA-256 hash and compared in constant time. A plain hash rather than a password hash is deliberate, because 256 random bits leave a slow hash nothing to protect and the token endpoint stays cheap under a burst; a primary and a secondary hash are both accepted during a rotation, so a program switches without downtime. IMachineClientService (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/MachineClients/IMachineClientService.cs:11) / MachineClientService (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/MachineClients/MachineClientService.cs:41) run the grant and the administration. Like view-as, a machine token is minted by the raw ITokenService, so it carries no sid, mfa or auth_time and opens no refresh session, but it does carry the service account's standard claims and role permissions plus client_id and token_use=machine. A role granting users:view-as, users:manage, roles:manage or clients:manage never backs a client, checked at create and again at every mint because a role can gain a permission later. The consumer supplies IServiceAccountProvisioner (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/MachineClients/IServiceAccountProvisioner.cs:15) over its own User aggregate, returning a ServiceAccount (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/MachineClients/ServiceAccount.cs:13); a service account has no password and no external login and is refused on every interactive sign-in path and as a view-as target. MachineClientSettings (MachineClientSettings.cs:19) is off by default, and MachineClientSettingsValidator (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/MachineClients/MachineClientSettingsValidator.cs:15) fails startup when the feature is enabled without a provisioner registration, naming it. Because a machine client holds whatever its role holds, an endpoint that only asks for a signed-in caller is open to every client; RefuseMachineClientsAttribute (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/RefuseMachineClientsAttribute.cs:34) states on the endpoint that the caller must be a person and answers 403 to a token_use=machine token. Rows go through IMachineClientStore (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/MachineClients/IMachineClientStore.cs:10), failures use MachineClientErrors (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/MachineClients/MachineClientErrors.cs:6), and the wire shapes are CreateMachineClientRequest, MachineClientResponse, MachineClientSecretResponse, MachineTokenResponse and MachineTokenErrorResponse.

User administration and adjacent contracts

UserAdministrationServiceBase<TUser, TUserDto> (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Administration/UserAdministrationServiceBase.cs:62) is the shipped workflow behind IUserAdministrationService<TUserDto> for an aggregate that stores exactly one role: a request with zero or two roles is a validation failure, re-assigning the held role is a no-op success that saves and revokes nothing, and a real change revokes the live refresh sessions because the role travels in the access token. Locking an account also writes the deleted-or-locked marker that blocks its already-issued access tokens, through ISoftDeletedUserMarkerWriter and SoftDeletedUserMarkerWriter (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/SoftDeletedUsers/ISoftDeletedUserMarkerWriter.cs:9, MMCA.Common/Source/Core/MMCA.Common.Application/Auth/SoftDeletedUsers/SoftDeletedUserMarkerWriter.cs:13), which sizes the marker from the host's access-token lifetime through SoftDeletedUserCache.MarkerDurationFor and removes it on unlock. The write and the clear are best effort: the account change is already saved, so a cache fault is logged as a warning and the call still succeeds.

A few Shared wire contracts sit beside this surface. AuditHistoryEntryDTO (MMCA.Common/Source/Core/MMCA.Common.Shared/Auditing/AuditHistoryEntryDTO.cs:12) is one recorded change as the audit-history endpoint serves it, deliberately minimal, with values in their invariant string forms and personal-data values read as the redaction placeholder. ImportConventions (MMCA.Common/Source/Core/MMCA.Common.Shared/Imports/ImportConventions.cs:25) fixes the import endpoints' conventions (a synchronous commit answers 200 with a report, a queued one 202 with the app's own run DTO, and an unreadable file a 400 Problem Details rather than a report, because a report describes rows); ImportReportDTO (MMCA.Common/Source/Core/MMCA.Common.Shared/Imports/ImportReportDTO.cs:12) carries the outcome with a RowErrors list of ImportRowErrorDTO entries (MMCA.Common/Source/Core/MMCA.Common.Shared/Imports/ImportRowErrorDTO.cs:9) that is always an array, never null. OidcDiscoveryResponse (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/ExternalProviders/OidcDiscoveryResponse.cs:10) is the home-realm discovery answer of GET auth/oauth/discover?email=: the configured OIDC provider whose domain list holds the address's domain, so the sign-in page can start that provider's challenge. OidcReservedProviderNames (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/ExternalProviders/OidcReservedProviderNames.cs:12) lists, case-insensitively, the names a generic OAuth:Oidc:<Name> section may not take: the three built-in providers and the controller's own literal route segments under auth/oauth/, which would shadow the provider's challenge route; the API refuses such a section at startup and the UI never lists one (OidcReservedProviderNames.cs:14-17, OidcReservedProviderNames.cs:22).

Session cookies: keeping SSR authenticated

The final cluster solves a Blazor-specific problem: an interactive Blazor app keeps its access token in browser memory, but a cold server-side render (a new tab, an F5, an external deep link) has no memory to read, so an [Authorize] page would bounce to /login before the interactive phase starts. The fix is a pair of HttpOnly cookies (mmca_auth_access, mmca_auth_refresh, MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/SessionCookieEndpoints.cs:23-24). The server is their only writer: no endpoint takes a token from the browser (SessionCookieEndpoints.cs:16-18). Server components that obtain tokens themselves (the same-origin API proxy) store them through the ISessionCookieStore port (MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/ISessionCookieStore.cs:17, Write and Clear at ISessionCookieStore.cs:23 and ISessionCookieStore.cs:27), implemented by the internal SessionCookieStore (ISessionCookieStore.cs:31-43), and the server-side refresher below writes the rotated pair itself. SessionCookieEndpoints (SessionCookieEndpoints.cs:21, mapped at SessionCookieEndpoints.cs:36-114) exposes only a DELETE /auth/session-cookie that clears the jar at logout, anonymous by declaration so it runs whether or not the session is still valid and refused when Sec-Fetch-Site says cross-site so another site cannot sign the user out (SessionCookieEndpoints.cs:40-71), plus the token endpoint described below. Before clearing, that delete ends the server-side session too when an ICookieSessionEnder is registered (SessionCookieEndpoints.cs:49, SessionCookieEndpoints.cs:56-58): the web head holds the HttpOnly refresh cookie but not the session store, so CookieSessionEnder (MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/CookieSessionEnder.cs:28) posts the token server-to-server to the identity endpoint's anonymous auth/session/end as an EndSessionRequest (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Requests/RefreshTokenRequest.cs:19), through the refresher's named client within a 5-second timeout. It is best effort: a transport failure, timeout or non-success answer is logged and the sign-out goes ahead (CookieSessionEnder.cs:14, CookieSessionEnder.cs:17-20, CookieSessionEnder.cs:33, CookieSessionEnder.cs:39). Every write goes through one shared set of attributes in SessionCookieJar (MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/SessionCookieJar.cs:24: HttpOnly, Secure outside Development and on any HTTPS request, Path=/, SameSite from SessionCookieSettings, Lax by default and Strict on the same-origin API proxy, MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/SessionCookieSettings.cs:19, and a max age resolved from SessionCookieSettings.Lifetime, else the configured refresh-token lifetime, else 7 days, because a cookie must not outlive the credential it carries, SessionCookieJar.cs:76-93, SessionCookieJar.cs:105-118, SessionCookieSettings.cs:28). The access cookie value is protected with ASP.NET Core DataProtection under a fixed purpose and unprotected on every read, so a value that does not unprotect reads as no cookie; the refresh cookie is stored as issued (SessionCookieEndpoints.cs:32, SessionCookieJar.cs:33-36, SessionCookieJar.cs:45, SessionCookieJar.cs:57-67). During prerender the cookies are read by CookieTokenReader (MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/CookieTokenReader.cs:17), which returns a live view-as overlay's token first (ViewAsOverlayCookie, see the view-as section above), then a token the refresher just minted, then the unprotected access cookie (CookieTokenReader.cs:46-57). SessionCookieAuthenticationHandler (MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/SessionCookieAuthenticationHandler.cs:25) is a custom authentication scheme that reads the cookie JWT, checks only its expiry against the handler's injectable TimeProvider (SessionCookieAuthenticationHandler.cs:56) because the API still performs full validation on every API call (SessionCookieAuthenticationHandler.cs:18-24), and populates HttpContext.User so SSR authorization passes (SessionCookieAuthenticationHandler.cs:61-64); a challenge redirects to /login with a returnUrl (SessionCookieAuthenticationHandler.cs:73-78). It is registered through SessionCookieAuthenticationExtensions (SessionCookieAuthenticationHandler.cs:91).

When the access cookie has expired but the refresh cookie is still valid, CookieSessionRefreshMiddleware (MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/CookieSessionRefreshMiddleware.cs:13, registered by CookieSessionRefreshMiddlewareExtensions at CookieSessionRefreshMiddleware.cs:35) runs before UseAuthentication on qualifying navigations (GET plus an Accept header containing text/html, CookieSessionRefreshMiddleware.cs:28-31) and delegates to CookieSessionRefresher (MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/CookieSessionRefresher.cs:80) through the ICookieSessionRefresher port (CookieSessionRefresher.cs:34). The refresher first tries to read a still-valid expiry out of the access cookie with a 30-second skew allowance (CookieSessionRefresher.cs:91, CookieSessionRefresher.cs:270-299); failing that it exchanges the refresh cookie at the API's auth/refresh endpoint server-to-server (CookieSessionRefresher.cs:212-218), so the refresh token never reaches browser JS. That call carries the browser's user-agent and IP, captured from the triggering request by the private BrowserOrigin before the lock is taken, so the rotated session records the real device instead of this host's empty user-agent and loopback address (CookieSessionRefresher.cs:143, CookieSessionRefresher.cs:216, CookieSessionRefresher.cs:321-344). It then writes the rotated pair back as cookies and stashes the fresh access token on HttpContext.Items (CookieSessionRefresher.cs:150-154) so the current request's authentication reads the new token: CookieTokenReader checks that item before falling back to the request cookie (CookieTokenReader.cs:26, CookieTokenReader.cs:51-57). Concurrent refreshes are collapsed into a single flight by a KeyedSemaphoreStripe keyed on the refresh token plus a 10-second rotation-grace IMemoryCache entry keyed by the old refresh token (CookieSessionRefresher.cs:92, CookieSessionRefresher.cs:94, CookieSessionRefresher.cs:158-176, CookieSessionRefresher.cs:235), so a queued herd of requests cannot double-rotate. Both keys are a lowercase hex SHA-256 of the refresh token, so no credential sits in a cache key (CookieSessionRefresher.cs:301-303). The entry is a private RotationGraceEntry record pairing the rotated response with the BrowserOrigin that triggered it (CookieSessionRefresher.cs:319), and a lookup is a hit only when the origin matches: the same refresh token from another IP or user-agent misses and goes to the identity endpoint, which refuses the already-rotated token, rather than this cache handing a stranger the successor pair (CookieSessionRefresher.cs:178-191). Striping rather than one process-wide lock is deliberate and stated in source: the lock is held across an outbound HTTP call, so a single semaphore serialized every unrelated user's cold navigation behind whichever refresh was in flight (CookieSessionRefresher.cs:73-78); two unrelated tokens sharing a stripe is harmless because the grace cache is re-checked per token after acquiring (CookieSessionRefresher.cs:169-173). Failures are kept apart as a SessionRefreshOutcome carrying a SessionRefreshStatus: only a 400, 401 or 403 from the identity endpoint is Rejected (the session is over), while anything else, including the 409 Auth.RefreshSuperseded answer to a rotation race, is Unavailable, so a caller that clears cookies on failure does so only for a session that is really dead (CookieSessionRefresher.cs:121-133, CookieSessionRefresher.cs:43-51). A transport failure, including the resilience pipeline's own refusals, is not cached and renders the request anonymously rather than throwing a 500 out of SSR (CookieSessionRefresher.cs:198-204, CookieSessionRefresher.cs:238-246). The same refresher backs the same-origin POST /auth/session/token endpoint the browser polls to hydrate its in-memory claims (SessionCookieEndpoints.cs:78-111), guarded by the cookies' configured SameSite plus a Sec-Fetch-Site cross-site rejection (SessionCookieEndpoints.cs:85-88, SessionCookieEndpoints.cs:120-122). A live view-as overlay is answered first, without touching the staff user's own session (SessionCookieEndpoints.cs:90-96); otherwise the endpoint refreshes as needed and answers a JSON 401 no_session when there is no valid session (SessionCookieEndpoints.cs:98-102). Either way the browser gets an unsigned copy of the claims built by SessionClaimsToken, never the credential (SessionCookieEndpoints.cs:104-107), carried in SessionTokenResponse (CookieSessionRefresher.cs:25), the browser-safe counterpart of the internal SessionTokenResult (CookieSessionRefresher.cs:19), which holds the access token but deliberately omits the refresh token. This whole cluster is ADR-022's server half; the client half across Blazor Server, WASM, and MAUI is ADR-051.

Privacy: the data-subject export package

Three members of this group belong to the privacy surface that sits beside erasure. UserDataExportDTO (MMCA.Common/Source/Core/MMCA.Common.Shared/Privacy/UserDataExportDTO.cs:15) is the portable GDPR/CCPA export envelope: a document FormatVersion consumers read before parsing (UserDataExportDTO.cs:22), the generation instant, the subject id, an app-owned Subject snapshot typed as object so each app decides which of its own fields are portable (UserDataExportDTO.cs:40), and an ordered list of UserDataExportSectionDTO envelopes (UserDataExportDTO.cs:48, UserDataExportDTO.cs:61). Each section reports Available explicitly (UserDataExportDTO.cs:72) so a reader can tell "this subject has no data here" apart from "this contributor could not be reached", and an unavailable section carries only a caller-safe reason string, never an exception message or a connection string (UserDataExportDTO.cs:88). One failing contributor therefore degrades one section instead of denying the subject their whole export, which is the [Rubric §30, Compliance/Privacy/Data Governance] point of the shape. PrivacyFeatures (MMCA.Common/Source/Core/MMCA.Common.Shared/Privacy/PrivacyFeatures.cs:8) holds the single flag name Privacy.DataExport (PrivacyFeatures.cs:12) that keeps the whole surface off until a host turns it on, applied as a [FeatureGate] on DataExportControllerBase<TQuery>. The composing workflow (ExportUserDataHandlerBase<TUser, TQuery> and the IUserDataExportSection contributors) lives in group 14 (ADR-076).

Shared primitives and adjacent members

Several group members are general-purpose primitives that landed in this chapter because of how the dependency grouping fell, though one of them is now load-bearing for auth. KeyedSemaphoreStripe (MMCA.Common/Source/Core/MMCA.Common.Shared/Concurrency/KeyedSemaphoreStripe.cs:22) and its Releaser handle (KeyedSemaphoreStripe.cs:78) serialize work per logical key across a fixed set of semaphores (256 by default, KeyedSemaphoreStripe.cs:25, with an explicit-width constructor at KeyedSemaphoreStripe.cs:37; acquisition maps the key onto one stripe at KeyedSemaphoreStripe.cs:60-75). That is the bounded alternative to a semaphore-per-key dictionary, which forces a choice between two defects: removing the entry on release opens a window where one caller waits on a semaphore no longer in the table while another creates a fresh one, and never removing it lets caller-supplied keys grow the table without bound (KeyedSemaphoreStripe.cs:7-16). Its consumers today are CookieSessionRefresher (above, CookieSessionRefresher.cs:94), the IdempotencyFilter (MMCA.Common/Source/Presentation/MMCA.Common.API/Idempotency/IdempotencyFilter.cs:93), CachingQueryDecorator<TQuery, TResult> (MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Decorators/CachingQueryDecorator.cs:266), and the GetOrCreateAsync lock table on MemoryCacheService (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Caching/MemoryCacheService.cs:58). InProcessDistributedLock is the deliberate exception: it keys on the exact key in a ConcurrentDictionary instead, because its contract has a bounded wait, and stripe false-sharing would turn that into a spurious "held elsewhere" answer for a key nobody holds (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Concurrency/InProcessDistributedLock.cs:19-24).

The HTTP and convention helpers sit in MMCA.Common.Shared for the same structural reason: both ends of an exchange need them and the two packages do not reference each other. IdempotencyHeaders (MMCA.Common/Source/Core/MMCA.Common.Shared/Http/IdempotencyHeaders.cs:13) is a two-constant class holding Idempotency-Key and X-Idempotent-Replay, read by the API filter and written by the UI service bases (IdempotencyHeaders.cs:19, IdempotencyHeaders.cs:25). CommitOutcomeUnknown (MMCA.Common/Source/Core/MMCA.Common.Shared/Http/CommitOutcomeUnknown.cs:28) names the answer to a write whose commit may or may not have landed: the Transaction.CommitOutcomeUnknown error code in the Problem Details body and an X-Commit-Outcome: unknown header a synchronous retry predicate can read without consuming the body, with Is overloads for an Error, a Result and a raw response (CommitOutcomeUnknown.cs:31-37, CommitOutcomeUnknown.cs:47-59). Its one rule is never to resend such a write automatically, because the idempotency filter stores only a 2xx and a resend under the same key would re-execute the handler; Common's UI retry policy and offline write queue honor it (CommitOutcomeUnknown.cs:13-19). QueryFilterKeys (MMCA.Common/Source/Core/MMCA.Common.Shared/Http/QueryFilterKeys.cs:20) owns the key convention of the filters[Key] query string: an aliased key such as Name~search carries a second filter on the same property, so a list page's search box and the grid's own column filter on that property are ANDed rather than one overwriting the other (QueryFilterKeys.cs:7-11). Alias builds the key and PropertyOf strips the tag back off (QueryFilterKeys.cs:34, QueryFilterKeys.cs:48) around the ~ separator and the search tag (QueryFilterKeys.cs:23, QueryFilterKeys.cs:26); the UI list page base writes it and the Application filter resolution reads it (QueryFilterKeys.cs:15-18). ConcurrencyETag (MMCA.Common/Source/Core/MMCA.Common.Shared/Http/ConcurrencyETag.cs:24) translates between the EF Core rowversion token and the HTTP entity tag that represents it: Format renders the base64 of the raw token as a weak tag (ConcurrencyETag.cs:40-45), weak on purpose because the same row version renders differently under a fields= projection and a strong tag would be promising byte-for-byte equality it cannot deliver (ConcurrencyETag.cs:12-18), and the parse side tolerates the weak prefix and the quotes while treating a blank value, the * wildcard, and a non-base64 payload alike as "no concrete token" for the caller to classify (ConcurrencyETag.cs:27-33, ConcurrencyETag.cs:52-60). ProblemDetailsResultReader (MMCA.Common/Source/Core/MMCA.Common.Shared/Http/ProblemDetailsResultReader.cs:59) is the client-side inverse of the API's error contract: it turns a response body back into Error values, synthesizing a status-derived code (Http.404 and friends, ProblemDetailsResultReader.cs:66) when the payload carries no machine-readable code, and it is explicit that the reverse mapping is lossy for 400, where Validation and Invariant both collapse onto one status and the reader picks Validation (ProblemDetailsResultReader.cs:50-57). ModuleNameConventions (MMCA.Common/Source/Core/MMCA.Common.Shared/Conventions/ModuleNameConventions.cs:10) derives a type's owning module from its namespace under the MMCA.{App}.{Module}.{Layer} convention (ModuleNameConventions.cs:38-45); it lives in Shared because both persistence (schema and data-source names) and the Application-layer CQRS logging decorators need it, and Application may not reference Infrastructure (ModuleNameConventions.cs:6-8). Its layer list deliberately omits Shared (ModuleNameConventions.cs:17) so a framework namespace never resolves to a phantom module. IcsEvent and IcsCalendarBuilder (MMCA.Common/Source/Core/MMCA.Common.Shared/Calendars/IcsEvent.cs:15, MMCA.Common/Source/Core/MMCA.Common.Shared/Calendars/IcsCalendarBuilder.cs:12) build RFC 5545 calendar (.ics) exports from UTC-normalized event times, with 75-octet line folding and CRLF endings (IcsCalendarBuilder.cs:14 for the MaxLineOctets budget; the folding and the \r\n writes both live in AppendLine, IcsCalendarBuilder.cs:83-104).

Two further Shared clusters land here the same way. The feature-flag lifecycle metadata closes the flag-debt trade-off of ADR-031: FeatureFlagAttribute (MMCA.Common/Source/Core/MMCA.Common.Shared/FeatureFlags/FeatureFlagAttribute.cs:32) is applied to the public const string fields of a *Features class (FeatureFlagAttribute.cs:9, FeatureFlagAttribute.cs:31) and carries a FeatureFlagLifetime (MMCA.Common/Source/Core/MMCA.Common.Shared/FeatureFlags/FeatureFlagLifetime.cs:9), an optional RemoveBy date in a fixed yyyy-MM-dd format, and an owner (FeatureFlagAttribute.cs:35, FeatureFlagAttribute.cs:38, FeatureFlagAttribute.cs:46, FeatureFlagAttribute.cs:52). The distinction is the whole point: a Permanent flag is a capability a host chooses to run with or without and must not carry a removal date, while a Temporary one exists only until a migration or experiment finishes, must carry one, and fails the build once that date has passed (FeatureFlagLifetime.cs:11-20). FeatureFlagRegistry (MMCA.Common/Source/Core/MMCA.Common.Shared/FeatureFlags/FeatureFlagRegistry.cs:35) is the runtime half, reflecting over assemblies to project every declared flag into a FeatureFlagDescriptor (FeatureFlagRegistry.cs:17, FeatureFlagRegistry.cs:46, FeatureFlagRegistry.cs:64) with the two recognizers the fitness rules also use (FeatureFlagRegistry.cs:77, FeatureFlagRegistry.cs:91). PrivacyFeatures above is one of the framework's own annotated flags.

The strongly typed identifier capability is the opt-in wrapper struct of ADR-115, shipped complete and adopted by nothing, with the ADR-048 primitive aliases left as the default. IStronglyTypedId<TSelf, TValue> (MMCA.Common/Source/Core/MMCA.Common.Shared/Identifiers/IStronglyTypedId.cs:60) is two members, a Value getter and a static abstract From (IStronglyTypedId.cs:65, IStronglyTypedId.cs:72), so a wrapper is a positional readonly record struct plus one factory line; IParsable<TSelf> arrives as explicit default implementations, which is the only form an inherited static abstract member allows, so OrderId.Parse(...) does not compile and every framework boundary parses through the interface (IStronglyTypedId.cs:25-36). The static helper StronglyTypedId (MMCA.Common/Source/Core/MMCA.Common.Shared/Identifiers/StronglyTypedId.cs:19) is what those boundaries call: Parse/TryParse (StronglyTypedId.cs:40, StronglyTypedId.cs:63), the CanParseValues and GetValueType/IsStronglyTypedId reflection probes (StronglyTypedId.cs:85, StronglyTypedId.cs:97, StronglyTypedId.cs:108), and TryDescribe (StronglyTypedId.cs:118), with the per-primitive delegate cache StronglyTypedIdValueParser<TValue> and its StronglyTypedIdValueParserDelegate<TValue> (StronglyTypedId.cs:173, StronglyTypedId.cs:161) keeping the reflection off the hot path. Each boundary then gets one adapter: JSON through StronglyTypedIdJsonConverterFactory and its private StronglyTypedIdConverter<TSelf, TValue> (MMCA.Common/Source/Core/MMCA.Common.Shared/Identifiers/StronglyTypedIdJsonConverterFactory.cs:22, StronglyTypedIdJsonConverterFactory.cs:25, StronglyTypedIdJsonConverterFactory.cs:38), MVC route and query binding through StronglyTypedIdTypeConverter<TSelf, TValue> and the StronglyTypedIdTypeConverters registrar (MMCA.Common/Source/Core/MMCA.Common.Shared/Identifiers/StronglyTypedIdTypeConverter.cs:21, StronglyTypedIdTypeConverter.cs:82, StronglyTypedIdTypeConverter.cs:89, StronglyTypedIdTypeConverter.cs:119), object mapping through StronglyTypedIdMappings<TSelf, TValue>, whose two static methods (ToValue and ToIdentifier) are the contract because Mapperly discovers them by signature on a closed generic type (MMCA.Common/Source/Core/MMCA.Common.Shared/Identifiers/StronglyTypedIdMappings.cs:36, StronglyTypedIdMappings.cs:43, StronglyTypedIdMappings.cs:48), and discovery through StronglyTypedIdRegistry (MMCA.Common/Source/Core/MMCA.Common.Shared/Identifiers/StronglyTypedIdRegistry.cs:22), which scans assemblies up front and hands out the type list (StronglyTypedIdRegistry.cs:28, StronglyTypedIdRegistry.cs:66, StronglyTypedIdRegistry.cs:73) because EF needs it before any entity exists. One more Shared constant class rounds the group out: MessageHeaders (MMCA.Common/Source/Core/MMCA.Common.Shared/Messaging/MessageHeaders.cs:22) names the five MMCA--prefixed transport headers a message carries across a boundary (tenant, user, roles, permissions, and correlation id, MessageHeaders.cs:25, MessageHeaders.cs:28, MessageHeaders.cs:31, MessageHeaders.cs:38, MessageHeaders.cs:41), so a publisher and a consumer in different services spell them identically.

Two genuine auth members sit at the edge of the group. ISoftDeletedUserValidator (MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Auth/ISoftDeletedUserValidator.cs:7) is the small contract the API's SoftDeletedUserMiddleware uses to reject an otherwise-valid token whose backing account has since been soft-deleted (BR-133, ADR-047), implemented by each Identity module so Common never takes a cross-module domain reference. Its fast path is SoftDeletedUserCache (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/SoftDeletedUserCache.cs:19), which owns both the key shape and the 20-minute marker lifetime (SoftDeletedUserCache.cs:44, SoftDeletedUserCache.cs:76-77) so the module that deletes an account writes exactly the key the middleware reads. The marker has to outlive every access token issued before the delete, because a host that does not run Identity registers no validator query and the marker is the only thing that rejects a deleted user's still-valid token there; a token is accepted until its expiry plus the bearer clock skew, so the marker covers the default 15-minute access-token lifetime plus the JWT library's 5-minute default skew (a host may configure its own validator, so the framework's 30-second skew is not assumed), and a host that raises either writes a longer marker through MarkerDurationFor, which never returns less than the 20-minute floor (SoftDeletedUserCache.cs:25, SoftDeletedUserCache.cs:28-44, SoftDeletedUserCache.cs:54-58). The key is formatted invariantly on purpose, because a culture-sensitive identifier would be written under one request's culture and missed under another (SoftDeletedUserCache.cs:76-77). The controller surface that drives everything above (AuthControllerBase, OAuthControllerBase, UserAccountAuthControllerBase<TChangePasswordCommand, TChangePreferencesCommand>, PasswordResetAuthControllerBase<TForgotPasswordCommand, TResetPasswordCommand>, ExternalAuthExtensions) and the gRPC token forwarding (JwtForwardingClientInterceptor) live in later groups; this chapter is the engine those endpoints call into.

AllowMissingOwnerAttribute

MMCA.Common.API · MMCA.Common.API.Authorization · MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/AllowMissingOwnerAttribute.cs:21 · Level 0 · class (sealed attribute, marker)

  • What it is: a marker attribute placed on an action or a whole controller to declare that the action legitimately has no owner parameter, exempting it from OwnerOrAdminFilter's requirement that the request carry a resolvable owner identifier.
  • Depends on: nothing first-party; System.Attribute and AttributeUsageAttribute (BCL). It is read (never constructed) by OwnerOrAdminFilter.
  • Concept introduced, the explicit opt-out that makes deny-by-default safe. [Rubric §11, Security] (assesses whether a guard fails closed rather than open) and [Rubric §34, Architecture Governance & Documentation] (assesses whether a deliberate exemption is written down where it applies, so it can be audited later). The filter this attribute exempts from denies the request when it cannot resolve an owner parameter, because "no owner to compare" must not read as "no restriction" (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/AllowMissingOwnerAttribute.cs:6-13). Deny-by-default only works if the genuinely parameter-less actions have a way to say so, and that is the entire job of this type. The doc comment names the two shapes that qualify: a collection endpoint whose rows are already narrowed to the caller by an ownership specification, and an action restricted to administrators by its own authorization policy (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/AllowMissingOwnerAttribute.cs:9-12).
  • Walkthrough: the whole type is its [AttributeUsage] declaration plus an empty body (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/AllowMissingOwnerAttribute.cs:20-23). AttributeTargets.Class | AttributeTargets.Method allows both controller-wide and per-action application; AllowMultiple = false because a second copy would mean nothing; Inherited = true so a controller base class can carry it. It holds no data: presence in the endpoint metadata is the entire signal, which is exactly what OwnerOrAdminFilter.HasAllowMissingOwner looks for (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/OwnerOrAdminFilter.cs:84-85).
  • Why it's built this way: an empty marker keeps the opt-out cheap to apply and impossible to mis-configure, but the <remarks> block (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/AllowMissingOwnerAttribute.cs:15-19) is the load-bearing half of the design: applying it is an assertion that the action is guarded elsewhere, so every application site is expected to name the replacement guard in a comment. That turns a silent hole into a reviewable claim (ADR-033 records the audit that produced the current application sites).
  • Where it's used: honored by OwnerOrAdminFilter through endpoint metadata. In MMCA.Store it marks four actions on MMCA.Store/Source/Modules/Sales/MMCA.Store.Sales.API/Controllers/ShoppingCartsController.cs:92,107,136,172 and six on MMCA.Store/Source/Modules/Identity/MMCA.Store.Identity.API/Controllers/CustomersController.cs:53,65,82,114,135,150, both controllers naming the replacing guard in an inline comment next to the attribute (ShoppingCartsController.cs:87-92, CustomersController.cs:51-53).
  • Caveats / not-in-source: nothing enforces the assertion. No analyzer or compile-time rule checks that an action carrying this attribute really is guarded another way; the guarantee is a review convention. Store closes the specific gap it opens with a hand-written RequireResolvableOwner() gate on the collection reads (ShoppingCartsController.cs:79-84), but that gate is per-controller code, not something the attribute demands.

FallbackAuthorizationOptions

MMCA.Common.API · MMCA.Common.API.Authorization.Fallback · MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/Fallback/FallbackAuthorizationOptions.cs:14 · Level 0 · class (options)

  • What it is: a host-configurable options object controlling the framework's fallback authorization policy, whether it runs at all and which request path prefixes it never gates.
  • Depends on: nothing first-party.
  • Concept introduced, deny-by-default as the ASP.NET Core FallbackPolicy. [Rubric §11, Security] (assesses whether an endpoint with no authorization metadata fails closed rather than publishing itself anonymously) and [Rubric §17, DevOps & Deployment] (assesses whether the rule ships with a documented, code-level opt-out rather than forcing every host to fork it). An endpoint that declares neither [Authorize] nor [AllowAnonymous] used to be anonymous by omission; this options type is what a host tunes before flipping that default.
  • Walkthrough: DefaultExemptPathPrefixes (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/Fallback/FallbackAuthorizationOptions.cs:21-44) is a static, read-only seed list of framework and static surfaces that are endpoint-routed but carry no authorization metadata of their own: Blazor's framework files and circuit (/_framework, /_blazor, /_content, /_vs), health probes (/health, /alive), well-known documents (/.well-known, /robots.txt, /sitemap.xml, /manifest.json, /site.webmanifest, /service-worker.js, /apple-app-site-association), and static asset roots (/css, /js, /lib, /images, /img, /fonts, /media, /favicon.ico). Enabled (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/Fallback/FallbackAuthorizationOptions.cs:52) defaults to true; the doc comment states the opt-out is deliberate (AddAuthorizationPolicies(options => options.Enabled = false)) rather than by omission (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/Fallback/FallbackAuthorizationOptions.cs:47-49). ExemptPathPrefixes (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/Fallback/FallbackAuthorizationOptions.cs:64) is a mutable IList<string> seeded with [.. DefaultExemptPathPrefixes], so a host appends its own static roots without losing the framework defaults; the doc comment is explicit that application endpoints belong on [AllowAnonymous], not in this list, because that is what the anonymous-endpoint fitness gate reads (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/Fallback/FallbackAuthorizationOptions.cs:58-59).
  • Why it's built this way: matching is segment-based and case-insensitive against these prefixes (per the ExemptPathPrefixes doc comment), so a coarse prefix like /_framework covers everything beneath it without enumerating individual asset paths.
  • Caveats / not-in-source: the exemption is purely path-based. An undecorated controller routed under one of these prefixes would pass ungated, and the doc comment names AnonymousEndpointTestsBase.Endpoints_DeclareAnAuthorizationDecision as the gate that keeps such a controller from landing (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/Fallback/FallbackAuthorizationOptions.cs:59-62). That test is off by default, so a repo only gets this protection once it opts into the stricter gate (MMCA.Common/Source/Hosting/MMCA.Common.Testing.Architecture/Bases/Api/AnonymousEndpointTestsBase.cs:59-60,122).
  • Where it's used: bound via services.AddOptions<FallbackAuthorizationOptions>() and read by FallbackAuthorizationHandler inside AuthorizationExtensions.AddAuthorizationPolicies.

FallbackAuthorizationRequirement

MMCA.Common.API · MMCA.Common.API.Authorization.Fallback · MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/Fallback/FallbackAuthorizationRequirement.cs:16 · Level 0 · class (sealed)

  • What it is: the marker IAuthorizationRequirement attached to the framework's fallback authorization policy.
  • Depends on: Microsoft.AspNetCore.Authorization.IAuthorizationRequirement (framework).
  • Concept introduced, the requirement half of the fallback requirement/handler pair. [Rubric §11, Security] and [Rubric §2, Design Patterns] (assesses whether the ASP.NET Core requirement/handler split is used as designed even for a policy with no data of its own). Unlike PermissionRequirement, this requirement carries no permission string: the whole type is a one-line marker, public sealed class FallbackAuthorizationRequirement : IAuthorizationRequirement; (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/Fallback/FallbackAuthorizationRequirement.cs:16).
  • Walkthrough: no members; presence in a policy's requirement list is the entire signal FallbackAuthorizationHandler reacts to.
  • Why it's built this way: a data-free requirement is enough here because the decision (is the caller authenticated, or is the path exempt) needs no configuration carried on the requirement itself; the configuration instead lives on FallbackAuthorizationOptions, injected into the handler.
  • Where it's used: attached to the built-in AuthorizationPolicy set as ASP.NET Core's AuthorizationOptions.FallbackPolicy by AuthorizationExtensions.AddAuthorizationPolicies when FallbackAuthorizationOptions.Enabled is true, and evaluated by FallbackAuthorizationHandler.

OwnerOrAdminFilterOptions

MMCA.Common.API · MMCA.Common.API.Authorization · MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/OwnerOrAdminFilterOptions.cs:13 · Level 0 · class (options)

  • What it is: a host-configurable options object that supplies the three vocabulary values OwnerOrAdminFilter needs: which claim carries the caller's owner id, which role bypasses the ownership check, and which route or argument parameter names the resource owner.
  • Depends on: nothing first-party; System.ComponentModel.DataAnnotations for [Required].
  • Concept introduced, externalizing a filter's vocabulary through the options pattern. [Rubric §11, Security] (assesses whether the ownership rule is enforced consistently; here the rule is fixed in code while its identifiers are configuration, and the bypass role is required rather than defaulted) and [Rubric §15, Best Practices & Code Quality] (assesses whether a second host can reuse a component without forking it). The class doc comment (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/OwnerOrAdminFilterOptions.cs:5-12) states the current shape: the claim and route parameter keep the framework's conventional names (customer_id and id), but the bypass role has no default because the framework knows no role names, so a host that applies the filter configures its own role through services.Configure<OwnerOrAdminFilterOptions>(o => o.BypassRole = MyRoleNames.Admin), and a host that never applies the filter configures nothing.
  • Walkthrough: three mutable auto-properties. OwnerClaimType still defaults to "customer_id" (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/OwnerOrAdminFilterOptions.cs:16). BypassRole now carries [Required] and defaults to string.Empty, not "Admin" (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/OwnerOrAdminFilterOptions.cs:23-24); its doc comment states the options are validated against their data annotations on first resolve, so a host that applies the filter without naming a role fails loudly instead of silently bypassing for nobody (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/OwnerOrAdminFilterOptions.cs:19-22). OwnerParameterName still defaults to "id" (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/OwnerOrAdminFilterOptions.cs:31); its doc comment (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/OwnerOrAdminFilterOptions.cs:26-30) spells out that the parameter is looked up as a route value first and a model-bound query or body argument second, which is exactly the two-step lookup the filter performs.
  • Why it's built this way: get; set; (not init) is the shape the ASP.NET Core options binder expects, so the values can arrive from appsettings or a Configure callback; requiring BypassRole rather than defaulting it to "Admin" means a host cannot silently ship a filter that bypasses for a role it never granted to anyone.
  • Where it's used: injected as IOptions<OwnerOrAdminFilterOptions> into OwnerOrAdminFilter (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/OwnerOrAdminFilter.cs:33). MMCA.ADC's Engagement module is the host that configures it rather than taking the defaults, pointing the shared filter at ClaimTypes.NameIdentifier, the Organizer bypass role, and a userId parameter (MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.API/DependencyInjection.cs:44,52-54); the comment above those assignments explains why NameIdentifier and not the raw sub claim is the type the principal actually carries by the time the filter runs (MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.API/DependencyInjection.cs:46-51).

PermissionPolicy

MMCA.Common.API · MMCA.Common.API.Authorization · MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/PermissionPolicy.cs:9 · Level 0 · class (static)

  • What it is: the naming convention that turns a permission string such as "sessions:manage" into the ASP.NET Core policy name "perm:sessions:manage", and back.
  • Depends on: nothing first-party.
  • Concept introduced, permission policies as prefixed policy names. [Rubric §11, Security] (assesses whether authorization is expressed as capabilities rather than hard-coded role checks) and [Rubric §2, Design Patterns] (assesses deliberate use of a known pattern; here a reserved-prefix naming convention is what lets an on-demand provider recognize its own policies). Rather than pre-register one named policy per permission, the codebase encodes the permission inside the policy name behind a reserved prefix; PermissionPolicyProvider then materializes any policy whose name starts with that prefix on demand (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/PermissionPolicy.cs:3-8). This class owns both ends of that encoding.
  • Walkthrough: Prefix = "perm:" (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/PermissionPolicy.cs:12), the reserved marker; and NameFor(string permission) (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/PermissionPolicy.cs:17), an expression-bodied Prefix + permission that builds the policy name. HasPermissionAttribute calls NameFor to build the [Authorize] policy string, and PermissionPolicyProvider strips Prefix back off to recover the permission.
  • Why it's built this way: a single shared prefix constant means the attribute that writes the policy name and the provider that reads it cannot disagree; both reference PermissionPolicy.Prefix.
  • Where it's used: by HasPermissionAttribute (encode) and PermissionPolicyProvider (decode).

PermissionRequirement

MMCA.Common.API · MMCA.Common.API.Authorization · MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/PermissionRequirement.cs:10 · Level 0 · class (sealed)

  • What it is: an ASP.NET Core IAuthorizationRequirement carrying the single permission a principal must hold for a given policy to succeed.
  • Depends on: Microsoft.AspNetCore.Authorization.IAuthorizationRequirement (framework).
  • Concept introduced, the requirement/handler pair. [Rubric §11, Security] and [Rubric §2, Design Patterns] (assesses whether the ASP.NET Core authorization model is used as designed: it splits what is required from how it is checked). A requirement is a passive data object; a matching AuthorizationHandler<T> decides whether it is satisfied. This type is the passive half; PermissionAuthorizationHandler is the active half, as the doc comment states (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/PermissionRequirement.cs:5-9).
  • Walkthrough: a sealed class implementing IAuthorizationRequirement (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/PermissionRequirement.cs:10). Its constructor (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/PermissionRequirement.cs:14-18) guards with ArgumentException.ThrowIfNullOrWhiteSpace(permission) (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/PermissionRequirement.cs:16) and stores the value into the get-only Permission property (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/PermissionRequirement.cs:21), so a requirement can never carry an empty permission.
  • Why it's built this way: keeping Permission immutable and non-empty means the handler can trust it without re-validating; the requirement is a value carrier with no behavior of its own.
  • Where it's used: attached to a policy by PermissionPolicyProvider (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/PermissionPolicyProvider.cs:43) and evaluated by PermissionAuthorizationHandler.

FallbackAuthorizationHandler

MMCA.Common.API · MMCA.Common.API.Authorization.Fallback · MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/Fallback/FallbackAuthorizationHandler.cs:35 · Level 1 · class (sealed)

  • What it is: the AuthorizationHandler<FallbackAuthorizationRequirement> that decides whether an endpoint carrying no authorization metadata of its own should be allowed through: it succeeds for an authenticated caller, an exempt path, a request that matched no endpoint and names no web-root file, or an API-versioning rejection endpoint, and otherwise leaves the requirement unsatisfied.
  • Depends on: FallbackAuthorizationRequirement, FallbackAuthorizationOptions (the exempt path prefixes, taken as IOptions<FallbackAuthorizationOptions> on the primary constructor, MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/Fallback/FallbackAuthorizationHandler.cs:35); Microsoft.AspNetCore.Http, Microsoft.AspNetCore.Authorization.
  • Concept introduced, path-based exemption over endpoint routing's ambient resource. [Rubric §11, Security] (assesses whether the fail-closed default still lets framework and static surfaces through without requiring [AllowAnonymous] on infrastructure that was never meant to declare authorization metadata) and [Rubric §7, Microservices Readiness] (assesses whether the handler works without extra DI plumbing; it needs no IHttpContextAccessor).
  • Walkthrough: HandleRequirementAsync (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/Fallback/FallbackAuthorizationHandler.cs:42-58) null-guards both arguments and succeeds the requirement when any of context.User.Identity?.IsAuthenticated == true, IsExemptPath(context.Resource), IsUnmatchedRequest(context.Resource) or IsApiVersioningRejection(context.Resource) holds (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/Fallback/FallbackAuthorizationHandler.cs:49-52); otherwise it returns without calling context.Succeed, leaving the requirement unmet. IsUnmatchedRequest (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/Fallback/FallbackAuthorizationHandler.cs:79-96) returns false for a non-HTTP resource or any request that matched an endpoint (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/Fallback/FallbackAuthorizationHandler.cs:81-84); for an unmatched request it consults the IWebHostEnvironment.WebRootFileProvider and passes only when neither a file nor a directory exists at the path (or no web root is available) (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/Fallback/FallbackAuthorizationHandler.cs:88-95). Nothing sits behind such a request, and challenging it would turn an unknown URL into a sign-in redirect instead of letting the host's not-found re-execute render the 404; a request for an existing web-root file keeps the gate because UseStaticFiles would still serve it. IsApiVersioningRejection (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/Fallback/FallbackAuthorizationHandler.cs:67-74) recognizes Asp.Versioning's client-error endpoints (no metadata, request delegate declared in the Asp.Versioning.Routing namespace, constant at MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/Fallback/FallbackAuthorizationHandler.cs:39), so an anonymous caller with a bad api-version gets the 400 version error rather than a 401 (rationale comment at MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/Fallback/FallbackAuthorizationHandler.cs:60-66). IsExemptPath has one body per framework line, chosen by #if NET11_0_OR_GREATER (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/Fallback/FallbackAuthorizationHandler.cs:98-127). On .NET 11 it switches on the resource: an HttpContext is used as is, a SignalR HubInvocationContext yields the connection's own HttpContext through invocation.Context.GetHttpContext(), and anything else is not exempt (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/Fallback/FallbackAuthorizationHandler.cs:106-116). The comment above it (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/Fallback/FallbackAuthorizationHandler.cs:99-105) gives the reason: .NET 11 SignalR authorizes a hub method whenever the method carries any attribute (a compiler NullableContextAttribute is enough), so the fallback policy also runs per invocation; Blazor's circuit hub hits this on ConnectCircuit, and without the branch a signed-out visitor's reconnect after a dropped connection was refused. An invocation is therefore decided by the path the connection itself was admitted on. On .NET 10, which never ran the fallback for a hub invocation, the #else body keeps the plain HttpContext pattern match and returns false for anything else (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/Fallback/FallbackAuthorizationHandler.cs:118-126). Both bodies end in IsExemptRequestPath (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/Fallback/FallbackAuthorizationHandler.cs:129-132), which checks the path against the non-empty entries of options.Value.ExemptPathPrefixes with StartsWithSegments(prefix, StringComparison.OrdinalIgnoreCase). The comment above IsUnmatchedRequest (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/Fallback/FallbackAuthorizationHandler.cs:76-78) explains why no IHttpContextAccessor is needed: under endpoint routing the authorization resource IS the HttpContext, and a non-HTTP resource (a SignalR hub invocation) is never an unmatched request, so it falls through to the exempt-path and authenticated-user rules.
  • Why it's built this way: reading the resource directly off AuthorizationHandlerContext instead of injecting IHttpContextAccessor keeps the handler stateless and singleton-safe; never calling context.Fail() follows the same ASP.NET Core convention as PermissionAuthorizationHandler, abstaining rather than vetoing. The hub-invocation branch is version-specific code written the dual-framework way (ADR-141): only under #if NET11_0_OR_GREATER, with the unchanged .NET 10 body as the #else.
  • Where it's used: registered as an IAuthorizationHandler singleton and wired as ASP.NET Core's AuthorizationOptions.FallbackPolicy handler by AuthorizationExtensions.AddAuthorizationPolicies whenever FallbackAuthorizationOptions.Enabled is true.

HasPermissionAttribute

MMCA.Common.API · MMCA.Common.API.Authorization · MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/HasPermissionAttribute.cs:13 · Level 1 · class (sealed attribute)

  • What it is: an [Authorize]-derived attribute that requires the authenticated principal to hold a named permission, applied to a controller or an action.
  • Depends on: PermissionPolicy (to build the policy name); Microsoft.AspNetCore.Authorization.AuthorizeAttribute (framework base).
  • Concept introduced, capability-based endpoint authorization. [Rubric §11, Security] (assesses whether endpoints depend on capabilities rather than hard-coded role names) and [Rubric §7, Microservices Readiness] (assesses whether a module can be lifted out on its own; permissions travel as claims or through a per-module registry, so an extracted service authorizes without embedding the issuer's role taxonomy). The doc comment (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/HasPermissionAttribute.cs:5-11) states the intent directly: prefer [HasPermission("sessions:manage")] over role-based [Authorize(Policy = ...)] so an endpoint declares the capability it needs, with the mapping from roles to that capability living in one registry (IPermissionRegistry).
  • Walkthrough: sealed class HasPermissionAttribute : AuthorizeAttribute (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/HasPermissionAttribute.cs:13) with [AttributeUsage(... AllowMultiple = true, Inherited = true)] (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/HasPermissionAttribute.cs:12) so several permission requirements can stack on one target and subclasses inherit them. The constructor (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/HasPermissionAttribute.cs:17-18) chains to the base with PermissionPolicy.NameFor(permission): setting the inherited Policy to "perm:<permission>" is what routes the check through PermissionPolicyProvider. It also stores the bare permission on the get-only Permission property (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/HasPermissionAttribute.cs:21).
  • Why it's built this way: deriving from AuthorizeAttribute (rather than inventing a filter) means the standard MVC authorization pipeline picks it up for free, and encoding the permission into the inherited Policy string is what removes the per-permission registration step.
  • Where it's used: on controllers and actions across both apps; its policy name is resolved by PermissionPolicyProvider and satisfied by PermissionAuthorizationHandler against the grants each module declares through AuthorizationExtensions.AddPermissions.

PermissionAuthorizationHandler

MMCA.Common.API · MMCA.Common.API.Authorization · MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/PermissionAuthorizationHandler.cs:14 · Level 1 · class (sealed)

  • What it is: the AuthorizationHandler<PermissionRequirement> that decides whether the current principal satisfies a PermissionRequirement, either because it carries the permission as an explicit claim or because one of its roles grants it.
  • Depends on: PermissionRequirement, IPermissionRegistry (the role-to-permission map, taken as a primary constructor parameter at MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/PermissionAuthorizationHandler.cs:14), and the shared ClaimsPrincipal extension methods HasPermissionClaim / GetRoleValues (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/PermissionAuthorizationHandler.cs:31-32).
  • Concept introduced, resolving a permission through claim-or-role. [Rubric §11, Security] (assesses correctness of the grant decision; there are two independent grant paths, a direct permission claim and a role-derived one) and [Rubric §7, Microservices Readiness] (assesses whether a service stands alone; the role lookup used by GetRoleValues() reads out of the token regardless of how the JWT middleware mapped the role claim type, so it survives inbound-claim mapping being on or off).
  • Walkthrough: the decision lives in the internal static method Holds(ClaimsPrincipal user, IPermissionRegistry? permissionRegistry, string permission) (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/PermissionAuthorizationHandler.cs:29-32), which its doc comment (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/PermissionAuthorizationHandler.cs:17-28) calls the one evaluation of "this principal holds this permission" every API-side check shares. It is true only for an authenticated principal (so an anonymous caller never holds anything) that either carries the permission as a claim (user.HasPermissionClaim(permission), a direct grant) or holds a role the registry grants it to (permissionRegistry?.HasPermission(user.GetRoleValues(), permission) == true, a role-derived grant). The registry parameter is nullable: when the host registered none, the permission claim alone decides. HandleRequirementAsync (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/PermissionAuthorizationHandler.cs:35) null-guards both arguments (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/PermissionAuthorizationHandler.cs:39-40) and succeeds the requirement when Holds(context.User, permissionRegistry, requirement.Permission) is true (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/PermissionAuthorizationHandler.cs:42-45). The handler carries no role-gathering helper of its own: the three-claim-type role lookup (the standard ClaimTypes.Role URI plus the raw "role"/"roles" claims) lives once, on the shared ClaimsPrincipalExtensions.GetRoleValues() used by both this handler and ICurrentUserService.Roles, so the two call sites cannot restate the predicate and drift.
  • Why it's built this way: never calling context.Fail() (only context.Succeed) is the ASP.NET Core convention that lets multiple handlers vote independently: this handler abstains rather than vetoes when it cannot grant. Lifting the grant test into the static Holds lets every other API-side permission check reuse the exact predicate the authorization middleware applies instead of restating it.
  • Where it's used: registered as an IAuthorizationHandler singleton by AuthorizationExtensions.AddAuthorizationPolicies (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/AuthorizationExtensions.cs:75-76); invoked by the authorization middleware for every policy that carries a PermissionRequirement. Holds is called directly by MultiFactorRoleAuthorizationHandler (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/MultiFactor/MultiFactorRoleAuthorizationHandler.cs:56), by PublicEndpointOutputCachePolicy for its bypass permissions (MMCA.Common/Source/Presentation/MMCA.Common.API/Caching/PublicEndpointOutputCachePolicy.cs:257), and by UsersAdminControllerBase when checking that the caller holds every permission of a role (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Administration/UsersAdminControllerBase.cs:433).

PermissionPolicyProvider

MMCA.Common.API · MMCA.Common.API.Authorization · MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/PermissionPolicyProvider.cs:13 · Level 1 · class (sealed)

  • What it is: an IAuthorizationPolicyProvider that lazily builds an AuthorizationPolicy for any policy name starting with the PermissionPolicy prefix, attaching a PermissionRequirement for the encoded permission, and delegates every other policy name to the default provider.
  • Depends on: PermissionPolicy (the prefix), PermissionRequirement; Microsoft.AspNetCore.Authorization, Microsoft.Extensions.Options.
  • Concept introduced, on-demand policy materialization. [Rubric §11, Security] and [Rubric §15, Best Practices & Code Quality] (assesses whether the design scales without repetitive registration; a system with an open-ended set of permissions cannot pre-register a named policy for each, so the policy is built from its own name at resolution time). The doc comment (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/PermissionPolicyProvider.cs:6-12) explains the design: "perm:*" names are materialized here, and every other name falls through to the default provider, so a policy the application registers itself is still resolved the usual way.
  • Walkthrough: the constructor (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/PermissionPolicyProvider.cs:19-20) wraps a DefaultAuthorizationPolicyProvider built from the ambient AuthorizationOptions and keeps it in _fallbackPolicyProvider (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/PermissionPolicyProvider.cs:15). GetDefaultPolicyAsync and GetFallbackPolicyAsync (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/PermissionPolicyProvider.cs:23-28) delegate straight to that fallback. GetPolicyAsync (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/PermissionPolicyProvider.cs:31) is the interesting one: it rejects a null or blank name outright (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/PermissionPolicyProvider.cs:33), and if the name does not start with PermissionPolicy.Prefix it defers to the fallback (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/PermissionPolicyProvider.cs:35-38); otherwise it slices the prefix off with the range expression policyName[PermissionPolicy.Prefix.Length..] (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/PermissionPolicyProvider.cs:40) and builds a policy that requires an authenticated user plus a fresh PermissionRequirement(permission) (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/PermissionPolicyProvider.cs:41-44). Note the RequireAuthenticatedUser() at MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/PermissionPolicyProvider.cs:42: it makes anonymous requests fail with a challenge before the handler ever runs, which is why the handler can treat "not authenticated" as a plain abstain.
  • Why it's built this way: composing over DefaultAuthorizationPolicyProvider rather than reimplementing it means all pre-registered policies survive; only the perm: namespace is intercepted. That is what lets HasPermissionAttribute work for any permission string without a registration step.
  • Where it's used: installed (via Replace) as the single IAuthorizationPolicyProvider by AuthorizationExtensions.AddAuthorizationPolicies (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/AuthorizationExtensions.cs:77-78).
  • Caveats / not-in-source: a policy object is built on every GetPolicyAsync call for a perm: name; no cache is present in this type, and whether ASP.NET Core caches the result upstream is not determinable from this source file.

RefuseMachineClientsAttribute

MMCA.Common.API · MMCA.Common.API.Authorization · MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/RefuseMachineClientsAttribute.cs:34 · Level 4 · class (sealed attribute, IAuthorizationFilter)

  • What it is: an MVC authorization filter, declared as an attribute on a controller or action, that answers 403 to a machine client (ADR-140) on an endpoint where a person takes part, and leaves every other caller alone.
  • Depends on: AuthClaimTypes (the TokenUse claim type and the TokenUseMachine value), Error (Error.Forbidden), ErrorHttpMapping (the standard errors extension) and, when registered, IErrorLocalizer; Microsoft.AspNetCore.Mvc.Filters.IAuthorizationFilter and Microsoft.AspNetCore.Mvc.Infrastructure.ProblemDetailsFactory.
  • Concept introduced, refusing a caller kind rather than a missing grant. [Rubric §11, Security] (assesses whether endpoints meant for people cannot be driven by a service credential). The remarks (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/RefuseMachineClientsAttribute.cs:20-32) state the gap it closes: a machine client holds what its backing role holds, so an endpoint that asks only for a signed-in caller (casting a vote, saving a bookmark, checking in) is open to every machine client whatever its role. The attribute states on the endpoint that the caller must be a person; whether the caller is signed in, and what it may do, stays with [Authorize] and the permission attributes such as HasPermissionAttribute (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/RefuseMachineClientsAttribute.cs:13-19).
  • Walkthrough: [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)] (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/RefuseMachineClientsAttribute.cs:33). The public constant ErrorCode = "MachineClients.EndpointRefused" (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/RefuseMachineClientsAttribute.cs:37) is the code the 403 carries. OnAuthorization (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/RefuseMachineClientsAttribute.cs:40-50) null-guards the context and returns without effect unless the user carries the claim AuthClaimTypes.TokenUse with the value AuthClaimTypes.TokenUseMachine (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/RefuseMachineClientsAttribute.cs:44-47); for a machine token it sets context.Result, which short-circuits the action (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/RefuseMachineClientsAttribute.cs:49). The private Refusal (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/RefuseMachineClientsAttribute.cs:57-77) builds the problem body the way the rest of the API does: through the registered ProblemDetailsFactory when there is one, otherwise a plain ProblemDetails, both with status 403, title "Not available to machine clients" and a fixed detail (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/RefuseMachineClientsAttribute.cs:59-70). It adds the errors extension from ErrorHttpMapping.BuildErrorsExtension over one Error.Forbidden(ErrorCode, detail, nameof(RefuseMachineClientsAttribute)), localized when an IErrorLocalizer is registered (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/RefuseMachineClientsAttribute.cs:72-74), and returns an ObjectResult with status 403 (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/RefuseMachineClientsAttribute.cs:76).
  • Why it's built this way: an IAuthorizationFilter runs before model binding and the action, so a refused machine token never reaches the handler, and it is independent of the policy pipeline, so it composes with any [Authorize] or permission attribute without changing what they grant. The remarks (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/RefuseMachineClientsAttribute.cs:27-31) fix the scope: on a controller it covers every action, permission-gated ones included, so it goes on single actions when a program must still call the others; it adds nothing to the API description.
  • Where it's used: declared on TwoFactorControllerBase (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/TwoFactor/TwoFactorControllerBase.cs:59). In MMCA.ADC the architecture fitness test MachineClientParticipationTests requires it at class level on every Engagement participation controller, matched by its full type name (MMCA.ADC/Tests/Architecture/MMCA.ADC.Architecture.Tests/Api/MachineClientParticipationTests.cs:29-30).

ResultHandlerWrapper

MMCA.Common.API · MMCA.Common.API.Authorization · MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/AuthorizationExtensions.cs:222 · Level 5 · class (private sealed, nested in AuthorizationExtensions)

  • What it is: the private helper AuthorizationExtensions uses to replace the registered IAuthorizationMiddlewareResultHandler with a MultiFactorRefusalResultHandler wrapped around it.
  • Depends on: MultiFactorRefusalResultHandler and the ServiceDescriptor it replaces (primary constructor parameter original, MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/AuthorizationExtensions.cs:222); ActivatorUtilities, ILogger<T> and NullLogger<T>.
  • Concept introduced, decorating a framework service by descriptor. [Rubric §15, Best Practices & Code Quality] (assesses whether framework extension is done without losing the host's own registration). The doc comment (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/AuthorizationExtensions.cs:216-221) states both jobs: build the originally registered result handler the way its descriptor says, and serve, through its own type, as the marker that a descriptor has already been wrapped.
  • Walkthrough: Create(IServiceProvider provider) (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/AuthorizationExtensions.cs:224-234) builds the inner handler from the original descriptor in order: its ImplementationInstance, else the result of its ImplementationFactory, else ActivatorUtilities.CreateInstance over its ImplementationType (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/AuthorizationExtensions.cs:226-228). It resolves an ILogger<MultiFactorRefusalResultHandler>, falling back to NullLogger<MultiFactorRefusalResultHandler>.Instance (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/AuthorizationExtensions.cs:230-231), and returns new MultiFactorRefusalResultHandler(inner, logger) (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/AuthorizationExtensions.cs:233).
  • Why it's built this way: WrapResultHandler registers the bound method wrapper.Create as the replacement factory, so ImplementationFactory.Target is the wrapper instance; checking Target is ResultHandlerWrapper (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/AuthorizationExtensions.cs:179) is how a second AddAuthorizationPolicies call recognizes an already-wrapped slot and avoids wrapping twice. Honoring all three descriptor shapes keeps whatever result handler the host (or the framework default) registered as the inner handler.
  • Where it's used: only inside AuthorizationExtensions.WrapResultHandler (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/AuthorizationExtensions.cs:184-188); no usage outside the defining file.

AuthorizationExtensions

MMCA.Common.API · MMCA.Common.API.Authorization · MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/AuthorizationExtensions.cs:19 · Level 6 · class (static, extension block)

  • What it is: the DI wiring for the whole authorization model: one overload set that turns on ASP.NET Core authorization, installs the permission mechanism (handler, on-demand provider, registry), the role-level second-factor requirement and the framework's fallback policy, and one method each module uses to declare its role-to-permission grants.
  • Depends on: PermissionAuthorizationHandler, PermissionPolicyProvider, IPermissionRegistry, IPermissionCatalog, PermissionRegistryBuilder, FallbackAuthorizationOptions, FallbackAuthorizationHandler, MultiFactorRoleAuthorizationHandler, MultiFactorAuthorizationSettings, MultiFactorBearerWithholding, MultiFactorRefusalResultHandler and its own nested ResultHandlerWrapper; Microsoft.Extensions.DependencyInjection plus its Extensions namespace for TryAddEnumerable.
  • Concept introduced, extension(T) DI members and lazy registry accumulation. [Rubric §6, CQRS & Event-Driven Design] (assesses whether a concern is configured once for every host rather than re-wired per application) and [Rubric §7, Microservices Readiness] (assesses per-module self-sufficiency: each module contributes only the permissions it owns, so an extracted module carries its own grants). The extension(IServiceCollection services) block (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/AuthorizationExtensions.cs:21) is the C# extension(T) DI idiom taught in the primer: it adds AddAuthorizationPolicies and AddPermissions directly onto IServiceCollection. The doc comment on the no-argument overload (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/AuthorizationExtensions.cs:23-28) states the permission model plainly: an endpoint states the capability it needs and the registry maps roles to capabilities, so no policy name has to be pre-registered per role. The parameterized overload's doc comment (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/AuthorizationExtensions.cs:33-66) states the fallback half: an endpoint declaring NO authorization metadata now requires an authenticated caller instead of publishing anonymously by omission, exempt paths are seeded from FallbackAuthorizationOptions.DefaultExemptPathPrefixes, the opt-out is AddAuthorizationPolicies(options => options.Enabled = false), and two surfaces need a decision before adopting it in an existing host: a YARP gateway's proxied routes need "AuthorizationPolicy": "anonymous" per public route (or the opt-out), and a routable Blazor page is gated by AuthorizeRouteView, which reads attributes and ignores this policy entirely, so a page still declares [Authorize]/[AllowAnonymous] for itself. The same comment also notes that a request matching no endpoint and naming no web-root file is not gated, so it reaches the 404 (and a host's not-found re-execute) instead of a sign-in challenge (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/AuthorizationExtensions.cs:45-46).
  • Walkthrough
    • AddAuthorizationPolicies() (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/AuthorizationExtensions.cs:30-31): a one-line forward to AddAuthorizationPolicies(configureFallback: null), so the fallback policy is enabled with its default exempt list unless a host opts out.
    • AddAuthorizationPolicies(Action<FallbackAuthorizationOptions>? configureFallback) (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/AuthorizationExtensions.cs:67): calls services.AddAuthorization() (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/AuthorizationExtensions.cs:69) to bring in the framework's authorization services, then wires the permission mechanism: TryAddEnumerable adds PermissionAuthorizationHandler as a singleton IAuthorizationHandler (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/AuthorizationExtensions.cs:75-76), Replace installs PermissionPolicyProvider as the transient IAuthorizationPolicyProvider (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/AuthorizationExtensions.cs:77-78), and EnsurePermissionRegistry(services) guarantees a registry exists (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/AuthorizationExtensions.cs:79). Next it calls AddMultiFactorRoleRequirement(services) (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/AuthorizationExtensions.cs:81-84), the role-level second factor driven by Authorization:MultiFactor:RequiredForRoles, which the comment there notes is inert while that list is empty. It then binds FallbackAuthorizationOptions, applies configureFallback when supplied, registers FallbackAuthorizationHandler as a singleton IAuthorizationHandler, and configures AuthorizationOptions.FallbackPolicy through the options pipeline (Configure<IOptions<FallbackAuthorizationOptions>>) rather than inline, so the Enabled flag is read after every AddAuthorizationPolicies/Configure call the host makes (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/AuthorizationExtensions.cs:86-103): a FallbackAuthorizationRequirement-carrying policy when Enabled is true, null (no fallback policy) when it is false.
    • AddPermissions(Action<PermissionRegistryBuilder> configure) (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/AuthorizationExtensions.cs:115): the per-module entry point for declaring grants. It guards the callback (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/AuthorizationExtensions.cs:117), fetches the shared builder via EnsurePermissionRegistry, and invokes configure(builder) so the module's grants accumulate (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/AuthorizationExtensions.cs:119-120). The doc comment (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/AuthorizationExtensions.cs:108-114) notes it is safe to call once per module because grants union into a single registry; the union itself happens in PermissionRegistryBuilder.Grant (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Permissions/PermissionRegistryBuilder.cs:45-52).
    • AddMultiFactorRoleRequirement(IServiceCollection) (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/AuthorizationExtensions.cs:129-155): idempotent, because the comment above it (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/AuthorizationExtensions.cs:126-128) notes AddAuthorizationPolicies runs more than once in a Blazor web host. Only when no non-keyed IAuthorizationHandler descriptor already names MultiFactorRoleAuthorizationHandler (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/AuthorizationExtensions.cs:131-135) does it add that handler as a singleton and bind MultiFactorAuthorizationSettings from MultiFactorAuthorizationSettings.SectionName, reading IConfiguration with GetService so a host without configuration binds nothing and the rule stays off (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/AuthorizationExtensions.cs:137-146); binding once keeps the role list from being appended to twice, and the settings take no validation because every value, the empty default included, is valid. It then TryAddEnumerables MultiFactorBearerWithholding as an IPostConfigureOptions<JwtBearerOptions>, which withholds a listed role from a bearer principal without a second factor on every JWT bearer scheme (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/AuthorizationExtensions.cs:149-152), and finally calls WrapResultHandler (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/AuthorizationExtensions.cs:154).
    • WrapResultHandler(IServiceCollection) (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/AuthorizationExtensions.cs:161-189): walks the collection backwards for the last non-keyed IAuthorizationMiddlewareResultHandler descriptor (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/AuthorizationExtensions.cs:163-171) and returns if none is found; the comment (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/AuthorizationExtensions.cs:157-160) notes services.AddAuthorization() has already TryAdded the framework default, so there is always one. A descriptor whose factory target is already a ResultHandlerWrapper is left alone (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/AuthorizationExtensions.cs:178-182); otherwise the slot is replaced in place by a descriptor whose factory is wrapper.Create, keeping the original lifetime (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/AuthorizationExtensions.cs:184-188), so a 403 from the multi-factor rule is answered through MultiFactorRefusalResultHandler with a coded body.
    • EnsurePermissionRegistry(IServiceCollection) (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/AuthorizationExtensions.cs:194): the idempotent core. If a PermissionRegistryBuilder is already registered as a singleton instance it returns that existing one (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/AuthorizationExtensions.cs:196-200); otherwise it creates one, registers it, and registers the built PermissionRegistry as a singleton factory (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/AuthorizationExtensions.cs:202-204). Both IPermissionRegistry and IPermissionCatalog are then registered as singleton factories that resolve that same concrete PermissionRegistry (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/AuthorizationExtensions.cs:210-211); the inline comment (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/AuthorizationExtensions.cs:206-209) states why: both contracts must forward to the ONE built instance so what an administration screen enumerates and what an authorization check answers from can never disagree, and calling builder.Build() a second time to satisfy the second contract would build two. Because the registry is built on first resolve, every module's AddPermissions call has already contributed by the time any request evaluates a permission, which is the point the comment at MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/AuthorizationExtensions.cs:191-193 makes.
  • Why it's built this way: TryAddEnumerable lets the permission handler (and, separately, the fallback handler) coexist with any other authorization handlers a host registers; Replace guarantees exactly one policy provider (the permission-aware one); and the lazy builder.Build() factory is what makes module registration order irrelevant, since all grants are collected before the first Build(). Resolving IPermissionRegistry and IPermissionCatalog from the same singleton factory output (rather than each calling builder.Build()) is what keeps the read side and the enforcement side of the permission model looking at one object.
  • Where it's used: AddAuthorizationPolicies() is called at the end of both framework authentication-wiring helpers, so a host that wires authentication through either gets the authorization model without an explicit call: AddForwardedJwtBearerCore (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/WebApplicationBuilderExtensions.Authentication.cs:77, the call at WebApplicationBuilderExtensions.Authentication.cs:118) and AddCommonAuthentication (WebApplicationBuilderExtensions.Authentication.cs:142, the call at WebApplicationBuilderExtensions.Authentication.cs:172). The Blazor web host also calls the parameterized overload with its own fallback configuration (MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/Hosting/BlazorWebHostExtensions.cs:130), which is why the multi-factor registration has to be idempotent. AddPermissions(...) is called by each module that owns permissions: in MMCA.ADC by Conference (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.API/DependencyInjection.cs:41), Engagement (MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.API/DependencyInjection.cs:57), Identity (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/DependencyInjection.cs:39) and Notification (MMCA.ADC/Source/Modules/Notification/MMCA.ADC.Notification.API/DependencyInjection.cs:37), and in MMCA.Store by Catalog (MMCA.Store/Source/Modules/Catalog/MMCA.Store.Catalog.API/DependencyInjection.cs:41), Sales (MMCA.Store/Source/Modules/Sales/MMCA.Store.Sales.API/DependencyInjection.cs:40) and Identity (MMCA.Store/Source/Modules/Identity/MMCA.Store.Identity.API/DependencyInjection.cs:42).
  • Caveats / not-in-source: a host that never calls either method has no IPermissionRegistry registered at all. That case is covered elsewhere in this group by UnconfiguredPermissionRegistry, whose diagnostic message names these two methods as the fix (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/UnconfiguredPermissionRegistry.cs:68).

OwnershipHelper

MMCA.Common.API · MMCA.Common.API.Authorization · MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/OwnershipHelper.cs:11 · Level 9 · class (static)

  • What it is: static helpers a controller calls to enforce ownership: to scope a query to the current user's own data (a specification that filters by owner id, or null when the caller holds the privileged bypass role), to refuse a scoped read whose owner claim cannot be resolved, and to check that the caller owns one specific record.
  • Depends on: ICurrentUserService (Application layer, imported at MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/OwnershipHelper.cs:1), plus Result and Error for the two gate methods. The specification it hands back is typically a Specification<TEntity, TIdentifierType>, though the helper itself never says so (see caveats).
  • Concept introduced, ownership scoping at the query level, as distinct from the filter's gate. [Rubric §11, Security] (assesses row-level data isolation: a non-admin caller can only read their own rows) and [Rubric §1, SOLID] (assesses separation of responsibility: the helper produces a specification, the repository applies it). Where OwnerOrAdminFilter blocks a request that names someone else's id, this helper narrows the result set so a list endpoint returns only the caller's rows without them passing any id at all. ADR-033 calls these the two enforcement points of one ownership axis: reject-one for single-resource routes, filter-many for collection routes.
  • Walkthrough
    • IsAdmin(ICurrentUserService, string bypassRole) (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/OwnershipHelper.cs:24): delegates to currentUserService.IsInRole(bypassRole) (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/OwnershipHelper.cs:27), so it checks every role the caller holds, the same check a controller makes inline. Role is only the first role claim, so comparing against it alone would have treated a caller holding the bypass role second as non-privileged (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/OwnershipHelper.cs:18-22). bypassRole has no default argument: every caller supplies its own, normally sourced from OwnerOrAdminFilterOptions.BypassRole, so the framework itself declares no role names (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/OwnershipHelper.cs:14-17). OwnerOrAdminFilter reuses this same method so the gate and the scoping agree on who bypasses.
    • GetOwnershipSpecification<TSpec, TId>(...) (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/OwnershipHelper.cs:41): the general form. It returns null for a bypass-role caller (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/OwnershipHelper.cs:52-55, no scoping needed); otherwise it reads the owner id from the named claim via currentUserService.GetClaimValue<TId>(claimType) and, when present, calls the supplied specFactory(id.Value) to build the scoping specification (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/OwnershipHelper.cs:57-58). Like IsAdmin, bypassRole is a required parameter with no default (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/OwnershipHelper.cs:45). The where TId : struct, IParsable<TId> constraint (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/OwnershipHelper.cs:47) is what lets the claim string be parsed into a strongly-typed id.
    • GetOwnershipSpecification<TSpec>(...) (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/OwnershipHelper.cs:71): the convenience overload that fixes TId to int and the claim to "customer_id", but still takes bypassRole as a required parameter and forwards it (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/OwnershipHelper.cs:74).
    • RequireResolvableOwner<TId>(currentUserService, claimType, bypassRole, source, target) (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/OwnershipHelper.cs:97): the fail-closed gate to call before a read scoped through GetOwnershipSpecification. It returns Result.Success() when the caller passes IsAdmin or carries a parsable owner claim, and otherwise a Forbidden failure (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/OwnershipHelper.cs:107-109). The doc comment frames a missing claim as an authorization answer (403), never an unscoped read and never a 500 (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/OwnershipHelper.cs:79-84).
    • ValidateOwnershipAsync<TId>(..., isOwnedBy, source, target, cancellationToken) (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/OwnershipHelper.cs:139): the single-record gate. A bypass-role caller passes without a lookup (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/OwnershipHelper.cs:152-155); an unresolvable owner claim is refused with the same Forbidden failure and the lookup never runs (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/OwnershipHelper.cs:157-160); otherwise the private CheckOwnershipAsync (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/OwnershipHelper.cs:165) awaits the caller-supplied isOwnedBy(ownerId, cancellationToken) predicate (typically an ExistsAsync query) and answers Error.NotFound with the given source and target when it is false.
    • AccessDenied(source, target) (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/OwnershipHelper.cs:180): the one private factory both gates share, Error.Forbidden("Error.Forbidden", "Access denied.", source, target).
  • Why it's built this way: returning null for bypass-role callers (rather than a "match everything" specification) lets the caller skip filtering entirely on the privileged path; producing a specification rather than running the query keeps the helper in the API layer while the actual filtering runs in the query pipeline. Every method takes bypassRole as a required parameter and checks it through the same IsAdmin, so the scope and both gates agree on who is privileged, and, like OwnerOrAdminFilterOptions.BypassRole, the framework names no default role anywhere in the ownership axis. ValidateOwnershipAsync answers a non-owner with 404 rather than 403 so the existence of another owner's record cannot be probed for (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/OwnershipHelper.cs:119-120).
  • Where it's used: MMCA.Store's ShoppingCartsController wraps GetOwnershipSpecification and RequireResolvableOwner in private helpers (MMCA.Store/Source/Modules/Sales/MMCA.Store.Sales.API/Controllers/ShoppingCartsController.cs:65-67,79-84), and OrdersController does the same (MMCA.Store/Source/Modules/Sales/MMCA.Store.Sales.API/Controllers/OrdersController.cs:66-68,80-85), also routing its mutating endpoints through ValidateOwnershipAsync (MMCA.Store/Source/Modules/Sales/MMCA.Store.Sales.API/Controllers/OrdersController.cs:353-357). In MMCA.ADC, EventQuestionAnswersController and SessionQuestionAnswersController scope by user id with GetOwnershipSpecification and gate with RequireResolvableOwner (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.API/Controllers/Events/EventQuestionAnswersController.cs:112,140, MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.API/Controllers/Sessions/SessionQuestionAnswersController.cs:112,140). IsAdmin also decides the export override AllowUnscopedExport on all four controllers (for example MMCA.Store/Source/Modules/Sales/MMCA.Store.Sales.API/Controllers/OrdersController.cs:249) and is the bypass check inside OwnerOrAdminFilter (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/OwnerOrAdminFilter.cs:43).
  • Caveats / not-in-source: two gaps are worth knowing. TSpec is an open generic with only a class constraint (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/OwnershipHelper.cs:46), so the helper does not itself require the returned type to be a specification: that contract is the caller's. And GetOwnershipSpecification also returns null for a non-admin caller whose claim is missing or unparseable (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/OwnershipHelper.cs:58), which means no scoping. It does not distinguish that case from the bypass role; RequireResolvableOwner does, but only if the caller invokes it before the read, which nothing in the helper enforces.

OwnerOrAdminFilter

MMCA.Common.API · MMCA.Common.API.Authorization · MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/OwnerOrAdminFilter.cs:31 · Level 10 · class (sealed action filter)

  • What it is: an MVC async action filter that lets a request proceed only if the caller holds the bypass role or owns the resource named by the request, returning 403 Forbidden otherwise.

  • Depends on: OwnershipHelper (for the IsAdmin check), OwnerOrAdminFilterOptions (the vocabulary), AllowMissingOwnerAttribute (the opt-out it honors), ICurrentUserService (claims); Microsoft.AspNetCore.Mvc.Filters, Microsoft.Extensions.Options, System.Globalization.

  • Concept introduced, per-request ownership enforcement as a filter, and deny-by-default. [Rubric §11, Security] (assesses whether a resource-level access gate runs before the action body and whether it fails closed) and [Rubric §17, DevOps & Deployment] (assesses whether the rule is expressed once and attached, rather than re-coded in each action). This is the gate counterpart to OwnershipHelper's query scoping: the helper narrows a list, this filter blocks an attempt to read or mutate a specific id the caller does not own (ADR-033, cited at MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/OwnerOrAdminFilter.cs:15). The deny-by-default half is the more important lesson, and the class doc comment spells it out (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/OwnerOrAdminFilter.cs:16-23): a gate that treats "nothing to compare" as "nothing to enforce" silently stops guarding every action whose parameter is optional, non-integer, or carried inside a bound model.

  • Walkthrough: OnActionExecutionAsync (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/OwnerOrAdminFilter.cs:36) null-guards its arguments and reads the current settings = options.Value (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/OwnerOrAdminFilter.cs:38-41), then walks four decisions in order:

    1. Bypass role: if OwnershipHelper.IsAdmin(currentUserService, settings.BypassRole) it calls next() and returns (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/OwnerOrAdminFilter.cs:43-47).
    2. Missing owner claim: it reads the caller's owner id with currentUserService.GetClaimValue<int>(settings.OwnerClaimType) (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/OwnerOrAdminFilter.cs:49) and short-circuits to ForbidResult when the claim is absent (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/OwnerOrAdminFilter.cs:51-55).
    3. Unresolvable owner parameter: if TryGetOwnerParameter cannot produce an int, the request is denied unless the endpoint carries AllowMissingOwnerAttribute, in which case it falls through to next() (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/OwnerOrAdminFilter.cs:57-71). Note the ordering: the opt-out excuses only a missing parameter, and it is checked after the claim check, so an [AllowMissingOwner] action still requires a valid owner claim.
    4. Mismatch: a resolved parameter that does not equal the claim value yields ForbidResult (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/OwnerOrAdminFilter.cs:73-77); only an exact match reaches await next() (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/OwnerOrAdminFilter.cs:79).

    Two private helpers back that flow. HasAllowMissingOwner (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/OwnerOrAdminFilter.cs:84-85) reads context.ActionDescriptor.EndpointMetadata.OfType<AllowMissingOwnerAttribute>(), which is how one lookup covers the attribute whether it sits on the action or on its declaring controller: MVC has already composed both into the metadata (comment at OwnerOrAdminFilter.cs:82-83). TryGetOwnerParameter (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/OwnerOrAdminFilter.cs:93-111) resolves the id from the route values first (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/OwnerOrAdminFilter.cs:95-100) and, failing that, from the model-bound action arguments (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/OwnerOrAdminFilter.cs:102-107), reporting failure by setting value = 0 and returning false (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/OwnerOrAdminFilter.cs:109-110). Both parses pass NumberStyles.Integer and CultureInfo.InvariantCulture explicitly (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/OwnerOrAdminFilter.cs:97,104); the comment above the method states the convention (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/OwnerOrAdminFilter.cs:90-92): an owner id off the wire is not a number the request's ambient culture formatted, so the host's CurrentCulture must not decide which strings are ids.

  • Why it's built this way: denying on an unresolvable parameter, with an explicit attribute as the only escape, converts a silent failure mode into a visible one: the action either compares an owner id or documents the guard that replaces the comparison (ADR-033's deny-by-default decision and the audit table that came with it). Reading the vocabulary from injected options keeps a single filter reusable across hosts, and checking the route before the bound arguments means a conventional /{id} route costs one dictionary lookup.

  • Where it's used: registered scoped by AddAPI (MMCA.Common/Source/Presentation/MMCA.Common.API/DependencyInjection.cs:88, next to IdempotencyFilter at DependencyInjection.cs:87; scoped because this filter takes the scoped ICurrentUserService, per the comment at DependencyInjection.cs:84-86) and applied as [ServiceFilter(typeof(OwnerOrAdminFilter))], per the remarks at MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/OwnerOrAdminFilter.cs:25-30. MMCA.Store applies it at controller level on ShoppingCartsController (MMCA.Store/Source/Modules/Sales/MMCA.Store.Sales.API/Controllers/ShoppingCartsController.cs:49) and CustomersController (MMCA.Store/Source/Modules/Identity/MMCA.Store.Identity.API/Controllers/CustomersController.cs:34), which covers every action on those controllers, so adoption there was an audit of the whole controller and the actions with no owner parameter carry AllowMissingOwnerAttribute. MMCA.ADC instead applies it per action, on two BookmarksController endpoints (MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.API/Controllers/BookmarksController.cs:91,147), against the Engagement vocabulary configured at MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.API/DependencyInjection.cs:44-55.

  • Caveats / not-in-source: the owner id is parsed as int only (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/OwnerOrAdminFilter.cs:97,104), and the claim is read as GetClaimValue<int> (OwnerOrAdminFilter.cs:49), so a host whose owner id is a Guid or a string cannot use this filter as-is. It also assumes the owner parameter is the owning id, which holds for a cart or a customer profile but not for a resource with its own id and a foreign-key owner (ADR-033 lists orders as that case, handled with a specification or an explicit per-id check instead).

MultiFactorAuthorizationSettings

MMCA.Common.API · MMCA.Common.API.Authorization.MultiFactor · MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/MultiFactor/MultiFactorAuthorizationSettings.cs:28 · Level 0 · class

  • What it is: the options class for the role-level second-factor rule: the list of roles that confer nothing on a bearer session that did not sign in with a second factor. Empty by default, which switches the rule off (MultiFactorAuthorizationSettings.cs:3-7).
  • Depends on: nothing first-party; it is a plain bound options type.
  • Concept introduced, role-level step-up by withholding. [Rubric §11, Security] assesses whether authentication strength and authorization are enforced at the boundary rather than trusted to callers. Here a host names the powerful roles (for example Admin), and a session without the mfa claim loses those roles and the permission claims that came with them at token validation, so every later role and permission check sees an account without the role (MultiFactorAuthorizationSettings.cs:10-17). Plain [Authorize] endpoints (sign-out, profile, the two-factor endpoints) stay reachable so the account can enroll (MultiFactorAuthorizationSettings.cs:14-15). The moving parts are this settings class, MultiFactorRoleWithholding (the claim surgery), MultiFactorBearerWithholding (where it runs), MultiFactorRoleAuthorizationHandler (the coded refusal reason) and MultiFactorRefusalResultHandler (the coded 403 body).
  • Walkthrough: SectionName is the constant "Authorization:MultiFactor" (MultiFactorAuthorizationSettings.cs:31); RequiredForRoles is a get-only IList<string> initialized to an empty collection (MultiFactorAuthorizationSettings.cs:34), so binding appends into it. The remarks give the JSON shape and the environment-variable form Authorization__MultiFactor__RequiredForRoles__0=Admin, and state that blank entries are ignored and roles match case-insensitively (MultiFactorAuthorizationSettings.cs:22-25).
  • Why it's built this way: each service binds its own section, so every service that hosts permission endpoints for a listed role must set the list itself (MultiFactorAuthorizationSettings.cs:22-23). It is bound in AuthorizationExtensions through AddOptions<MultiFactorAuthorizationSettings>().Configure<IServiceProvider>(...) with GetService<IConfiguration>(), deliberately with no ValidateDataAnnotations or ValidateOnStart, because every value, the empty default included, is valid (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/AuthorizationExtensions.cs:140-146). That is a conscious exception to the fail-fast contract of ADR-070; the permission model it layers onto is ADR-020.
  • Where it's used: read per request by MultiFactorRoleWithholding (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/MultiFactor/MultiFactorRoleWithholding.cs:42) and injected into MultiFactorRoleAuthorizationHandler (MultiFactorRoleAuthorizationHandler.cs:35). UsersAdminControllerBase<TUserDto> reads the same list to refuse giving a listed role to an account that has not enrolled a second factor when a two-factor store is registered (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Administration/UsersAdminControllerBase.cs:472; documented at MultiFactorAuthorizationSettings.cs:17-19).

MultiFactorRoleWithholding

MMCA.Common.API · MMCA.Common.API.Authorization.MultiFactor · MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/MultiFactor/MultiFactorRoleWithholding.cs:30 · Level 1 · class (static, internal)

  • What it is: the static helper that removes every listed role, and the permission claims that came with it, from a validated principal whose session has no second factor, and records what it removed as marker claims (MultiFactorRoleWithholding.cs:9-14).
  • Depends on: MultiFactorAuthorizationSettings, IPermissionRegistry, AuthClaimTypes, ClaimsPrincipalExtensions (GetRoleValues, HasMultiFactor, IsRoleClaim); externals System.Security.Claims and Microsoft.Extensions.Options.
  • Concept: the withholding half of the rule introduced at MultiFactorAuthorizationSettings. [Rubric §11, Security] (assesses least privilege at the boundary): the request's principal is changed, never the token, so every reader of the principal (role checks, permission checks, the current-user service, the ambient origin of scheduled work) sees the reduced account, while the subject, tenant, session and unlisted roles stay intact (MultiFactorRoleWithholding.cs:17-21).
  • Walkthrough:
    • Apply(ClaimsPrincipal?, IServiceProvider?) (MultiFactorRoleWithholding.cs:38) returns at once when the principal is null or the request services yield no non-empty RequiredForRoles (MultiFactorRoleWithholding.cs:40-44), then delegates with the resolved IPermissionRegistry, which may be null (MultiFactorRoleWithholding.cs:46).
    • Apply(principal, requiredForRoles, permissionRegistry) (MultiFactorRoleWithholding.cs:56) builds a case-insensitive set of non-blank role names (MultiFactorRoleWithholding.cs:61-63) and returns when it is empty or the principal is not subject to the rule (MultiFactorRoleWithholding.cs:64-67).
    • It removes every listed role claim from every identity (MultiFactorRoleWithholding.cs:71-72) and stops if none was present (MultiFactorRoleWithholding.cs:73-76). A claim counts as a role through the shared predicate claim.IsRoleClaim(includeIdentityRoleClaimType: true): the three spellings ClaimTypes.Role, "role", "roles" plus whatever type the claim's own identity names as its RoleClaimType, which is what ClaimsPrincipal.IsInRole reads, so no spelling of a listed role survives (MultiFactorRoleWithholding.cs:69-70, MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/ClaimsPrincipalExtensions.cs:85, ClaimsPrincipalExtensions.cs:92-94).
    • It then removes every permission claim except those the remaining roles still grant through the registry; with no remaining role or no registry, every permission claim goes (MultiFactorRoleWithholding.cs:80-83). The comment explains why: the token carries one permission claim per granted permission, so leaving them would keep the role's power in place (MultiFactorRoleWithholding.cs:78-79).
    • It adds one MultiFactorWithheldRole marker per distinct withheld role and one MultiFactorWithheldPermission marker per distinct withheld permission to the primary ClaimsIdentity (MultiFactorRoleWithholding.cs:85-89).
    • IsSubjectToTheRule requires an authenticated principal that is not a machine client (token_use = machine) and carries no second factor (MultiFactorRoleWithholding.cs:93-96). RemoveClaims copies the matches before removing them, because an identity's claim list cannot change while it is enumerated (MultiFactorRoleWithholding.cs:107-118).
  • Why it's built this way: removing the role and its permission claims, rather than adding a separate check to each endpoint, means every existing role and permission check refuses the caller with no change to that check. The markers let MultiFactorRoleAuthorizationHandler tell "refused because withheld" from "never had it". It is idempotent: a second run finds no listed role left (MultiFactorRoleWithholding.cs:26-27). Permission model: ADR-020.
  • Where it's used: called from MultiFactorBearerWithholding on every JWT bearer OnTokenValidated (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/MultiFactor/MultiFactorBearerWithholding.cs:35), and exercised directly by MultiFactorRoleRequirementTests and MultiFactorTestPrincipals under MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/Authorization/MultiFactor/.
  • Caveats / not-in-source: markers are added only when principal.Identity is a ClaimsIdentity (MultiFactorRoleWithholding.cs:85), while the removals cover every identity of the principal (MultiFactorRoleWithholding.cs:110).

MultiFactorBearerWithholding

MMCA.Common.API · MMCA.Common.API.Authorization.MultiFactor · MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/MultiFactor/MultiFactorBearerWithholding.cs:19 · Level 2 · class (internal, sealed)

  • What it is: an IPostConfigureOptions<JwtBearerOptions> that chains MultiFactorRoleWithholding onto the OnTokenValidated event of every JWT bearer scheme, after whatever handler is already there (MultiFactorBearerWithholding.cs:6-11).
  • Depends on: MultiFactorRoleWithholding; externals Microsoft.AspNetCore.Authentication.JwtBearer and Microsoft.Extensions.Options.
  • Concept: the placement of the withholding introduced at MultiFactorAuthorizationSettings. [Rubric §2, Design Patterns] (assesses whether patterns solve a real problem idiomatically): a post-configure step is the options-pipeline way to decorate a value after every configure delegate has run, so it wraps event handlers the framework or host assigned in AddJwtBearer, such as the hub access-token events (MultiFactorBearerWithholding.cs:13-14).
  • Walkthrough: PostConfigure (MultiFactorBearerWithholding.cs:22) guards the options, creates Events if absent (MultiFactorBearerWithholding.cs:26), captures the existing OnTokenValidated delegate (MultiFactorBearerWithholding.cs:27), and installs a new one that awaits the previous delegate first (MultiFactorBearerWithholding.cs:28-33) and then calls MultiFactorRoleWithholding.Apply(context.Principal, context.HttpContext.RequestServices) (MultiFactorBearerWithholding.cs:35).
  • Why it's built this way: changing the identity inside OnTokenValidated happens before the authentication ticket is built, so every later reader of the request sees the same principal (MultiFactorBearerWithholding.cs:9-10). The role list is read per request, so with an empty list the call returns before any work (MultiFactorBearerWithholding.cs:15-16). It is registered with TryAddEnumerable, which keys on the implementation type, so repeated AddAuthorizationPolicies calls add it once (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/AuthorizationExtensions.cs:149-152).
  • Where it's used: registered by AuthorizationExtensions (AuthorizationExtensions.cs:151-152); referenced from the doc comment of MultiFactorRoleAuthorizationHandler (MultiFactorRoleAuthorizationHandler.cs:16).
  • Caveats / not-in-source: a non-bearer scheme (a cookie session) is not touched (MultiFactorBearerWithholding.cs:16-17); MultiFactorRoleAuthorizationHandler is the backstop for a principal this path did not reach.

MultiFactorRoleAuthorizationHandler

MMCA.Common.API · MMCA.Common.API.Authorization.MultiFactor · MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/MultiFactor/MultiFactorRoleAuthorizationHandler.cs:33 · Level 2 · class (internal, sealed)

  • What it is: an AuthorizationHandler<PermissionRequirement> that fails a permission requirement with the coded reason AuthErrorCodes.MultiFactorRequired when the permission was withheld along with a listed role, or when a listed role is still held without a second factor. It never succeeds a requirement (MultiFactorRoleAuthorizationHandler.cs:9-13).
  • Depends on: PermissionRequirement, PermissionAuthorizationHandler (Holds), IPermissionRegistry, MultiFactorAuthorizationSettings, AuthClaimTypes, AuthErrorCodes, ClaimsPrincipalExtensions; external Microsoft.AspNetCore.Authorization.
  • Concept: the refusal half of the rule introduced at MultiFactorAuthorizationSettings. [Rubric §11, Security] (assesses defense in depth): the withholding already makes the plain permission check refuse; this handler only codes the refusal, and also catches a principal the withholding did not reach, so the rule never depends on one path alone (MultiFactorRoleAuthorizationHandler.cs:71-73).
  • Walkthrough:
    • The primary constructor takes the registry and the bound settings (MultiFactorRoleAuthorizationHandler.cs:33-35).
    • HandleRequirementAsync (MultiFactorRoleAuthorizationHandler.cs:38) returns at once when RequiredForRoles is empty (MultiFactorRoleAuthorizationHandler.cs:45-48) or the user is not authenticated (MultiFactorRoleAuthorizationHandler.cs:50-54).
    • It asks PermissionAuthorizationHandler.Holds whether the user holds the permission (MultiFactorRoleAuthorizationHandler.cs:56). If it does, it fails only when the user still carries a listed role without a second factor; if it does not, it fails only when the permission was withheld (MultiFactorRoleAuthorizationHandler.cs:57-60). The failure carries an AuthorizationFailureReason whose handler is this and whose message is AuthErrorCodes.MultiFactorRequired (MultiFactorRoleAuthorizationHandler.cs:59).
    • WasWithheld requires a withheld-role marker and either a matching withheld-permission marker or a registry grant of the permission to a withheld role (MultiFactorRoleAuthorizationHandler.cs:66-69).
    • HoldsThroughAnUnwithheldListedRole requires no second factor, not a machine client, and any non-blank listed role held (MultiFactorRoleAuthorizationHandler.cs:74-77).
  • Why it's built this way: a caller whose withheld role would not have granted the permission keeps the plain 403 and never learns about the step-up, matching the CQRS authorization gate (MultiFactorRoleAuthorizationHandler.cs:25-26); a principal with no marker gets exactly the answer the permission check gives (MultiFactorRoleAuthorizationHandler.cs:26-28). Never succeeding means it cannot widen access. Permission model: ADR-020.
  • Where it's used: registered as a singleton IAuthorizationHandler by AuthorizationExtensions, with an explicit already-registered check (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/AuthorizationExtensions.cs:131-138). MultiFactorRefusalResultHandler recognizes its failure reasons by handler type (MultiFactorRefusalResultHandler.cs:46). Covered by MultiFactorRoleRequirementTests and MultiFactorPermissionBackstopTests under MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/Authorization/MultiFactor/.

MultiFactorRefusalResultHandler

MMCA.Common.API · MMCA.Common.API.Authorization.MultiFactor · MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/MultiFactor/MultiFactorRefusalResultHandler.cs:25 · Level 4 · class (internal, sealed, partial)

  • What it is: a decorator over the host's IAuthorizationMiddlewareResultHandler that turns a refusal raised by MultiFactorRoleAuthorizationHandler into a coded 403 Problem Details body (Authorization.MultiFactorRequired in the errors extension) instead of the default body-less forbid; every other result goes to the wrapped handler unchanged (MultiFactorRefusalResultHandler.cs:14-19).
  • Depends on: MultiFactorRoleAuthorizationHandler, PermissionRequirement, AuthErrorCodes, Error, IErrorLocalizer, ErrorHttpMapping; externals Microsoft.AspNetCore.Authorization.Policy, ProblemDetails/IProblemDetailsService, Microsoft.Extensions.Logging.
  • Concept: the response half of the rule introduced at MultiFactorAuthorizationSettings. [Rubric §9, API & Contract Design] (assesses consistent, machine-readable error contracts): a client gets a stable error code it can act on (prompt for enrollment or a second sign-in) in the same errors extension shape the rest of the API uses.
  • Walkthrough:
    • Constants: the application/problem+json content type, the title "Second factor required" and the user-facing message (MultiFactorRefusalResultHandler.cs:29-32).
    • HandleAsync (MultiFactorRefusalResultHandler.cs:35) forwards to the inner handler unless the result is Forbidden, at least one failure reason came from MultiFactorRoleAuthorizationHandler, and the request is not gRPC (MultiFactorRefusalResultHandler.cs:45-51). Otherwise it takes the first PermissionRequirement's permission name (MultiFactorRefusalResultHandler.cs:53), logs it (MultiFactorRefusalResultHandler.cs:54) and writes the refusal (MultiFactorRefusalResultHandler.cs:56).
    • IsGrpc checks for an application/grpc content-type prefix (MultiFactorRefusalResultHandler.cs:59-60).
    • WriteRefusalAsync builds Error.Forbidden(AuthErrorCodes.MultiFactorRequired, Message, "HasPermission") (MultiFactorRefusalResultHandler.cs:66), a ProblemDetails with the RFC 9110 section 15.5.4 type, status 403 and a detail localized through IErrorLocalizer when one is registered (MultiFactorRefusalResultHandler.cs:68-74), and the errors extension from ErrorHttpMapping.BuildErrorsExtension (MultiFactorRefusalResultHandler.cs:75). It sets status 403 and Cache-Control: no-store (MultiFactorRefusalResultHandler.cs:78-79), prefers IProblemDetailsService.TryWriteAsync (MultiFactorRefusalResultHandler.cs:81-89) and falls back to WriteAsJsonAsync with the problem content type (MultiFactorRefusalResultHandler.cs:91-92).
    • MultiFactorRefused is a source-generated [LoggerMessage] at Information that logs the permission name only, no user id and no address (MultiFactorRefusalResultHandler.cs:95-97).
  • Why it's built this way: wrapping, rather than replacing, keeps whatever result handler the host registered in charge of every other outcome. A gRPC request keeps the default forbid so a JSON body cannot break its framing (MultiFactorRefusalResultHandler.cs:21). [Rubric §13, Observability & Operability]: the refusal is logged with no personal data.
  • Where it's used: AuthorizationExtensions replaces the last registered non-keyed IAuthorizationMiddlewareResultHandler with a factory that builds the original (instance, factory or type) and wraps it, keeping its lifetime, and skips a descriptor that is already the wrapper (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/AuthorizationExtensions.cs:157-188, AuthorizationExtensions.cs:222-234). Covered end to end by MultiFactorRefusalEndpointTests under MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/Authorization/MultiFactor/.
  • Caveats / not-in-source: when no IAuthorizationMiddlewareResultHandler is registered, the wrap is skipped (AuthorizationExtensions.cs:173-176); the code comment states AddAuthorization() always TryAdds the framework default first (AuthorizationExtensions.cs:158-159).

BrowserOrigin

MMCA.Common.API · MMCA.Common.API.SessionCookies · MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/CookieSessionRefresher.cs:321 · Level 0 · record struct

  • What it is: a private nested value type inside CookieSessionRefresher that captures the browser's user-agent and remote IP from the triggering request, so the refresher's server-to-server auth/refresh call can pass them on.
  • Depends on: HttpContext and HttpRequestMessage (ASP.NET Core / BCL) only. It is private readonly record struct, so nothing outside the refresher can name it.
  • Concept introduced, carry the real device through a server-side hop. [Rubric §11, Security] assesses whether session records describe the true client. The type comment (MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/CookieSessionRefresher.cs:313-318) explains that the origin is captured before the lock is taken, so the rotated session records the real device and IP instead of this host's own (empty user-agent, loopback address), and that the identity endpoint trusts X-Forwarded-For through CommonForwardedHeaders.
  • Walkthrough: From(HttpContext) (:291-297) reads the User-Agent header, storing null when it is blank, and Connection.RemoteIpAddress as a string (possibly null). ApplyTo(HttpRequestMessage) (:299-312) copies each non-null value onto the outgoing request: User-Agent and X-Forwarded-For, both through TryAddWithoutValidation (:305, :310) because a real browser user-agent does not always parse as a strict product token list and the value is informational only (comment :303-304).
  • Why it's built this way: the doc comment says the origin is captured from the triggering request before the lock is taken, and a readonly record struct gives value equality and no per-refresh heap allocation for two strings' worth of state.
  • Where it's used: created by the refresher's GetOrRefreshAsync path (MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/CookieSessionRefresher.cs:143), passed through RefreshAsync (:152) and CallRefreshAsync (:171), and applied to the auth/refresh request at :190. No ADR names it and no usage exists outside the defining file.

ICookieSessionEnder

MMCA.Common.API · MMCA.Common.API.SessionCookies · MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/CookieSessionEnder.cs:14 · Level 0 · interface

  • What it is: the internal contract for ending the refresh session behind a browser's refresh cookie when the browser signs out through DELETE /auth/session-cookie. It has one member, Task EndAsync(HttpContext context) (:24); its only implementation, the internal sealed CookieSessionEnder (:28), sits in the same file.
  • Depends on: ASP.NET Core HttpContext. The implementation takes IHttpClientFactory and ILogger<CookieSessionEnder> (:28-30), reads SessionCookieEndpoints.RefreshTokenCookieName (:45), reuses CookieSessionRefresher.RefreshClientName (:55) and posts an EndSessionRequest (:59).
  • Concept introduced, a server-side revoke at cookie sign-out. [Rubric §11, Security] assesses session lifecycle and credential revocation. The type doc (:7-13) states the gap it closes: the Blazor web head holds the HttpOnly refresh cookie but not the session store, so deleting the cookies alone would leave the refresh session alive at the identity endpoint. The web head therefore posts the token server-to-server to the identity endpoint's anonymous auth/session/end before the cookies go. The comment above the DELETE route (MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/SessionCookieEndpoints.cs:40-48) adds why this is the only place it can happen: a Server circuit signing out during a view-as never holds the staff user's own access token.
  • Walkthrough: the member doc (:16-21) is the contract: best effort, never throwing for a transport failure, a timeout or a non-success answer, each logged. In CookieSessionEnder, EndSessionPath = "auth/session/end" (:33) is relative to the gateway root, and Timeout defaults to 5 seconds (:39, doc :35-38: the browser is waiting on the cookie delete). EndAsync (:41-73) returns at once when the request carries no refresh cookie (:45-49). Otherwise it creates its own CancellationTokenSource(Timeout) (:52) instead of using the request's token, so a browser leaving mid-request does not cancel the revoke (comment :51), creates the refresher's named client (:55), posts the EndSessionRequest as JSON (:57-61) and logs a non-success status through LogEndRefused (:62-65, a Warning at :75-76). Any exception is caught under a scoped CA1031 suppression and logged through LogEndFailed (:67-72, a Warning at :78-79), whose message records that the session then lapses at its expiry.
  • Why it's built this way: the sign-out goes ahead whatever the identity endpoint says, so a failure is a log line, never an error the browser sees (ADR-022). The short bound keeps a slow identity service from holding the cookie delete, and reusing the refresher's client means the identity base address is configured once.
  • Where it's used: registered as a singleton by AddServerAuthSessionCookie (MMCA.Common/Source/Presentation/MMCA.Common.API/DependencyInjection.cs:198, comment :196-197). The DELETE /auth/session-cookie route of SessionCookieEndpoints resolves it optionally (MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/SessionCookieEndpoints.cs:56-59), so a host without AddServerAuthSessionCookie keeps the cookie-only delete. Pinned by MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/SessionCookies/SessionCookieEndOnDeleteTests.cs: a refresh cookie ending its session and deleting the cookies (:26), a refusal (:49) or an unreachable endpoint (:62) still answering 204, no refresh cookie calling nothing (:74), a cross-site delete refused with 403 and ending nothing (:87), and a hanging endpoint abandoned at the timeout (:100).

ISessionCookieStore

MMCA.Common.API · MMCA.Common.API.SessionCookies · MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/ISessionCookieStore.cs:17 · Level 0 · interface

  • What it is: the public port for writing and clearing the two HttpOnly session cookies from server code that obtained the tokens itself, so it can store them without a browser round trip.
  • Depends on: HttpContext (ASP.NET Core) only. Its one implementation is SessionCookieStore, a thin adapter over the internal SessionCookieJar that applies SessionCookieSettings.
  • Concept introduced, a public door onto an internal cookie writer. [Rubric §11, Security] assesses whether cookie hardening has one definition. The jar is internal, so before this interface only MMCA.Common.API itself could set the session cookies. The doc comment (MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/ISessionCookieStore.cs:8-16) names the new caller: the same-origin API proxy in MMCA.Common.UI.Web, which receives tokens from the identity endpoint and must persist them with exactly the options (HttpOnly, Secure outside Development, the configured SameSite, 7-day lifetime) that the session-cookie endpoints and the server-side refresher already use. Exposing two methods instead of making the jar public keeps the option-building in one place.
  • Walkthrough: void Write(HttpContext context, string accessToken, string refreshToken) (:19) appends both cookies; void Clear(HttpContext context) (:23) expires both. Neither returns anything: the cookies are a side effect on context.Response.
  • Why it's built this way: the proxy keeps every credential server-side (ADR-131), so it is the one writer of the cookies on a proxied host and needs a supported way to write them that cannot drift from the endpoints' own writes.
  • Where it's used: registered as a singleton by AddServerAuthSessionCookie (MMCA.Common/Source/Presentation/MMCA.Common.API/DependencyInjection.cs:209); injected into SameOriginApiProxyEndpoint (MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/SameOriginProxy/SameOriginApiProxyEndpoint.cs:34), SameOriginProxyTransformer (MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/SameOriginProxy/SameOriginProxyTransformer.cs:40) and the handoff route of SessionHandoffEndpoints (MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/SameOriginProxy/SessionHandoffEndpoints.cs:59).

SessionClaimsToken

MMCA.Common.API · MMCA.Common.API.SessionCookies · MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/SessionClaimsToken.cs:14 · Level 0 · class

  • What it is: a static helper that turns a signed access token into a claims-only copy: the same payload under an unsecured header with an empty signature, readable by the browser but useless as a credential.
  • Depends on: BCL and NuGet only: Base64Url (System.Buffers.Text), Encoding, and JwtSecurityTokenHandler (System.IdentityModel.Tokens.Jwt). Switched on by SessionCookieSettings.ClaimsOnlyBrowserTokens.
  • Concept introduced, the claims-only browser token. [Rubric §11, Security] and [Rubric §26, Front-End Security] both assess what an XSS payload could steal. The doc comment (MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/SessionClaimsToken.cs:7-13) states the trade: the client can still read the user's claims and the expiry to render its authentication state, but the token authorizes nothing, because every API validates signatures and rejects an unsigned token. Script on the page therefore holds nothing worth exfiltrating, while the UI keeps working off the same claims it always read.
  • Walkthrough: UnsecuredHeader (:17) is computed once as the base64url (no padding) encoding of {"alg":"none","typ":"JWT"}, as the comment at :16 records. Create(string? accessToken) (:25) returns null for a blank value or anything JwtSecurityTokenHandler.CanReadToken refuses (:27-30), then splits on . and, for a three-segment compact JWT, returns {UnsecuredHeader}.{payload}. (:32-33); any other shape is also null. The trailing dot keeps the three-segment compact form with an empty signature.
  • Why it's built this way: copying the payload segment verbatim (rather than re-serializing claims) guarantees the browser sees exactly the claims and exp the API issued (ADR-131).
  • Where it's used: the /auth/session/token route of SessionCookieEndpoints, for both the view-as overlay answer (MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/SessionCookieEndpoints.cs:95) and the session answer (:84-86), the proxy's response rewrite (MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/SameOriginProxy/SameOriginProxyTransformer.cs:259) and its refresh answer (MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/SameOriginProxy/SameOriginApiProxyEndpoint.cs:474). Pinned by MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/SessionCookies/SessionClaimsTokenTests.cs: claims and expiry kept but signature dropped (:20), the result rejected by a signature-validating API (:37), and null for non-JWT input (:56).
  • Caveats / not-in-source: "authorizes nothing" is a property of each API's JWT bearer validation (signature required), not of this type; the test at :37 checks it against one validating handler.

SessionCookieSettings

MMCA.Common.API · MMCA.Common.API.SessionCookies · MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/SessionCookieSettings.cs:11 · Level 0 · class

  • What it is: the options object for both session cookies: which SameSite mode they carry and how long they live, plus how long one server-side refresh call may take. It has exactly three properties.
  • Depends on: SameSiteMode (ASP.NET Core) and TimeSpan (BCL) only. Read through IOptions<SessionCookieSettings> by SessionCookieEndpoints, SessionCookieStore, CookieSessionRefresher and SessionCookieJar.ResolveLifetime.
  • Concept introduced, one options object for every cookie write. [Rubric §11, Security] assesses cookie hardening. A cookie delete only matches when it repeats the write's attributes, so the refresh, store and clear paths all read SameSite from this one object instead of each choosing a value. What the browser is handed is not a setting here: POST /auth/session/token always answers with a claims-only SessionClaimsToken, never the credential.
  • Walkthrough: SameSite (MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/SessionCookieSettings.cs:19) defaults to SameSiteMode.Lax; the doc comment (:13-18) explains the same-origin API proxy raises it to Strict because the cookie then authenticates data calls, not only server-side rendering. Lifetime (:28, a TimeSpan?, doc :21-27) is the Max-Age of both cookies: null (the default) derives it from Jwt:RefreshTokenExpirationDays when that section is bound in the host, otherwise 7 days, so a cookie neither outlives nor undershoots the refresh token it carries. A UI host that does not bind Jwt and runs a non-default refresh lifetime sets it here. The resolution itself lives in SessionCookieJar.ResolveLifetime. RefreshTimeout (:38-46, doc :30-37) bounds one server-side refresh call to the identity endpoint and defaults to 10 seconds (:46); its setter (a C# field-backed accessor) throws ArgumentOutOfRangeException for a zero or negative value (:43). A call that runs past it is abandoned and answered as unavailable, so the cookies are kept and the next navigation retries.
  • Why it's built this way: the defaults are the long-standing cookie behavior (the comment at DependencyInjection.cs:200-201 says so), so a host that never opts in keeps Lax cookies; the proxy tightens SameSite in one place (ADR-131). RefreshTimeout exists because the refresh runs under a lock stripe shared with other users' refreshes: the doc (:30-37) notes that without its own bound a hung identity call would hold that stripe for as long as the HTTP client's resilience pipeline allows, up to 90 seconds under the service defaults.
  • Where it's used: registered with defaults by AddServerAuthSessionCookie (MMCA.Common/Source/Presentation/MMCA.Common.API/DependencyInjection.cs:202, comment at :200-201). CookieSessionRefresher builds its refresh call's CancellationTokenSource from RefreshTimeout and the injected TimeProvider (MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/CookieSessionRefresher.cs:209, comment :205-208), so a timeout lands in its OperationCanceledException path as unavailable. The proxy's registration in SameOriginApiProxyServiceExtensions configures it (MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/SameOriginProxy/SameOriginApiProxyServiceExtensions.cs:69-70), copying SameSite from SameOriginApiProxySettings.SessionCookieSameSite (default Strict, MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/SameOriginProxy/SameOriginApiProxySettings.cs:116). The configured SameSite reaching the logout delete is pinned by MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/SessionCookies/ClaimsOnlySessionCookieEndpointsTests.cs:65. RefreshTimeout is pinned by MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/SessionCookies/CookieSessionRefresherTests.cs: a hanging identity call abandoned at the timeout as unavailable (:537), a non-positive value rejected (:563), and the 10-second default (:571).

SessionRefreshStatus

MMCA.Common.API · MMCA.Common.API.SessionCookies · MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/SessionRefreshOutcome.cs:4 · Level 0 · enum

  • What it is: the three ways a validate-or-refresh attempt can end: Refreshed = 0 (:10), Rejected = 1 (:16) and Unavailable = 2 (:23).
  • Depends on: nothing. Carried by SessionRefreshOutcome.
  • Concept introduced, a dead session is not the same as an unreachable identity endpoint. [Rubric §29, Resilience, Reliability & Business Continuity] assesses whether a transient fault is treated as a permanent one. The doc comments draw the line: Refreshed means a usable access token is available (still-valid cookie, or a rotated pair written back, :6-9); Rejected means no refresh cookie or the identity endpoint refused it with 400, 401 or 403, so clearing the cookies is correct (:12-15); Unavailable covers a 5xx, 429 or other non-refusal status, a timeout, a network failure or an unreadable body, where the cookies may still hold a live session and must be kept for a retry (:18-22). A caller that clears cookies on any failure would sign a user out over a gateway blip.
  • Where it's used: produced by CookieSessionRefresher (its ClassifyFailure, CookieSessionRefresher.cs:130-133) and branched on by the proxy's FailRefreshAsync (MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/SameOriginProxy/SameOriginApiProxyEndpoint.cs:300).

SessionTokenResponse

MMCA.Common.API · MMCA.Common.API.SessionCookies · MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/CookieSessionRefresher.cs:25 · Level 0 · record

  • What it is: the JSON body returned by POST /auth/session/token: the access token and its UTC expiry, and nothing else.
  • Depends on: BCL only. Produced by SessionCookieEndpoints from a SessionTokenResult.
  • Concept introduced, the refresh token never crosses the wire to the browser. [Rubric §9, API & Contract Design] assesses whether a response exposes only what its client needs. This record carries the access token, which the SPA holds in memory for its Bearer calls, and deliberately omits the refresh token, which stays exclusively in the HttpOnly cookie. The doc comment states the rule outright (MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/CookieSessionRefresher.cs:21-24).
  • Walkthrough: public sealed record SessionTokenResponse(string AccessToken, DateTime AccessTokenExpiry) (:20). It is the serialized projection of the internal SessionTokenResult, which is why the two types carry the same two members and different visibility of intent.
  • Where it's used: constructed and returned by the /auth/session/token handler (MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/SessionCookieEndpoints.cs:85).

SessionTokenResult

MMCA.Common.API · MMCA.Common.API.SessionCookies · MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/CookieSessionRefresher.cs:19 · Level 0 · record struct

  • What it is: the internal carrier for a validated access token plus its UTC expiry, returned by the refresher. A readonly record struct, so the validate path allocates nothing to report success.
  • Depends on: BCL only. Returned by ICookieSessionRefresher and projected onto the wire-facing SessionTokenResponse.
  • Concept: the value-type twin of SessionTokenResponse. Same two members, but this one stays server-side and is used as SessionTokenResult? at every call site, so "no valid session" is expressed by the absence of a value rather than by a sentinel string or a thrown exception. [Rubric §12, Performance & Scalability] assesses avoidable allocation; a readonly record struct is the light choice for a result produced on every qualifying navigation.
  • Walkthrough: public readonly record struct SessionTokenResult(string AccessToken, DateTime AccessTokenExpiry) (MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/CookieSessionRefresher.cs:19), with the one-line summary at :13 naming its provenance ("acquired from the session cookies").
  • Where it's used: the return type of ICookieSessionRefresher.GetOrRefreshAsync (:36); constructed by CookieSessionRefresher at :71 (cookie still valid) and :92 (after a rotation); unwrapped by SessionCookieEndpoints at SessionCookieEndpoints.cs:85.

ViewAsOverlayCookie

MMCA.Common.API · MMCA.Common.API.SessionCookies · MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/ViewAsOverlayCookie.cs:35 · Level 0 · class

  • What it is: a static helper for the view-as overlay cookie, mmca_view_as: a separate, short-lived HttpOnly cookie that carries a read-only view-as access token, protected with ASP.NET Core DataProtection, on a web host running the same-origin API proxy, so the staff user's own session cookies stay untouched for the length of the view (doc comment, MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/ViewAsOverlayCookie.cs:12-16).
  • Depends on: ASP.NET Core (HttpRequest, HttpContext, CookieOptions, SameSiteMode, IWebHostEnvironment), IDataProtectionProvider / IDataProtector (Microsoft.AspNetCore.DataProtection) and JwtSecurityTokenHandler (System.IdentityModel.Tokens.Jwt). The SameSite its callers pass is the session cookies' own, from SessionCookieSettings.
  • Concept introduced, an overlay instead of a session swap. [Rubric §11, Security] assesses support access and credential handling. Viewing as another user could have replaced the staff user's session cookies, but then ending the view would need the staff session back from somewhere. The overlay sits beside the session instead: the remarks (:17-34) state that while it holds an unexpired token it wins wherever the browser's identity is read (the proxy's forwarded bearer, CookieTokenReader during server rendering, POST /auth/session/token, and the Blazor Server handoff), and an expired one is ignored, so the browser falls back to the staff user's own session (:23-28). It carries an access token and nothing to renew it with; the refresh path never reads it, so a view-as token is never renewed. Only the proxy writes it, from a successful view-as grant response, and only the proxy's end-view-as and sign-out paths (or an expired or refused token) delete it (:18-22). Because no reader validates the JWT's signature, the value is protected: a value the browser planted, or one protected under another purpose, does not unprotect and is treated exactly as an expired overlay (:29-33).
  • Walkthrough: Name = "mmca_view_as" (:38). ProtectionPurpose = "MMCA.Common.API.SessionCookies.ViewAsOverlayCookie" (:46, doc :40-45) is deliberately different from SessionCookieEndpoints.AccessTokenCookieProtectionPurpose, so a value written into one cookie never unprotects as the other; it is public so a test host that seeds the overlay directly can protect the value with the host's own provider. IsPresent(HttpRequest) (:51-55) reports whether the cookie is there at all, expired or not. TryRead(HttpRequest, IDataProtectionProvider, DateTimeOffset now, out string? token, out DateTime expiresAt) (:69-119) returns false for a blank value (:82-85), for a value that throws CryptographicException or FormatException while being unprotected (:88-95), for anything JwtSecurityTokenHandler.CanReadToken refuses (:98-101), and for a token whose ValidTo is at or before now (:106-109); a malformed token that throws ArgumentException or FormatException while being read is also false (:115-118). Otherwise it returns the token and its UTC expiry. Write(HttpContext, IDataProtectionProvider, string token, DateTime expiresAt, SameSiteMode, DateTimeOffset now) (:131-144) takes the current instant from the caller's clock (param doc :130) and computes the lifetime as expiresAt - now.UtcDateTime (:137), writes nothing when that is not positive (:138-141), and otherwise appends the protected token with that lifetime as MaxAge (:143), so the cookie lives exactly as long as the token it carries. Delete(HttpContext, SameSiteMode) (:149-153) expires it with the same options and a null lifetime. The private CreateProtector (:157-158) binds the purpose inside this type, so no caller can read or write the overlay under another cookie's protector (comment :155-156). The private BuildOptions (:163-177) emits HttpOnly = true, Secure = !development || context.Request.IsHttps, the caller's SameSite and Path = "/" (:171-174); it resolves IWebHostEnvironment through a nullable RequestServices because that property is null on a bare DefaultHttpContext (comment :165).
  • Why it's built this way: the comment at :160-161 names SessionCookieJar as the rule it copies: Secure outside Development whatever the request scheme, and in Development whenever the request itself is HTTPS. The conditional Secure is bracketed by the same scoped #pragma warning disable S2092 with an inline justification (:162, :178). Taking now as a parameter in both TryRead and Write, rather than reading the system clock inside, lets a caller measure liveness and lifetime against an injected TimeProvider. Reading the expiry from the token on every check (rather than trusting the cookie's own Max-Age) is what lets every reader ignore an expired overlay even if the browser still sends it, and treating an unprotect failure the same way means a forged overlay can never become the identity a page renders as (ADR-137, ADR-131).
  • Where it's used: read by CookieTokenReader.ReadAccessToken (MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/CookieTokenReader.cs:46) and by the /auth/session/token route of SessionCookieEndpoints (MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/SessionCookieEndpoints.cs:93), both passing the injected clock's GetUtcNow(); that type's DELETE /auth/session-cookie route also expires a present overlay at sign-out (:62-65). On the proxy side, SameOriginApiProxyEndpoint checks presence and liveness (MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/SameOriginProxy/SameOriginApiProxyEndpoint.cs:412-413, :449), SameOriginProxyTransformer lists its name among the session cookie names (MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/SameOriginProxy/SameOriginProxyTransformer.cs:61), deletes it (:105) and writes it from a grant response, passing TimeProvider.System.GetUtcNow() as now (:212), and SessionHandoffEndpoints prefers it (MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/SameOriginProxy/SessionHandoffEndpoints.cs:40) and deletes a present one (:79-81). The protection is pinned by MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/SessionCookies/ViewAsOverlayCookieTests.cs: distinct purposes (:19), a write that never stores the raw token (:23), the lifetime measured from the given instant (:37), and a raw JWT, a value under the access-cookie purpose, or one from another key ring reading as no overlay (:69, :80, :90). The behavior end to end is pinned by MMCA.Common/Tests/Presentation/MMCA.Common.UI.Web.Tests/SameOriginProxy/SameOriginApiProxyViewAsTests.cs: the grant moving the token into the overlay and leaving the session alone (:26), a live overlay replacing the session bearer (:86), an expired overlay ignored and deleted (:138), the session-token endpoint preferring a live overlay (:171), and a forged raw overlay ignored and deleted (:191).
  • Caveats / not-in-source: the remarks (:19-20) say only the proxy's end-view-as and sign-out paths delete the overlay, but the code also expires it from the API package's DELETE /auth/session-cookie (SessionCookieEndpoints.cs:62-65) and from the handoff endpoints (SessionHandoffEndpoints.cs:79-81); the code is the authority. The proxy-side readers and the grant write pass TimeProvider.System, not an injected clock.

RotationGraceEntry

MMCA.Common.API · MMCA.Common.API.SessionCookies · MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/CookieSessionRefresher.cs:319 · Level 1 · record

  • What it is: the private memory-cache value CookieSessionRefresher stores after a successful rotation: the rotated AuthenticationResponse paired with the BrowserOrigin that triggered it.
  • Depends on: AuthenticationResponse and BrowserOrigin. Nested private sealed record inside CookieSessionRefresher, so nothing outside that class can see it.
  • Concept introduced, a short replay window scoped to one browser. [Rubric §29, Resilience, Reliability & Business Continuity] and [Rubric §11, Security] meet here. Two requests from the same browser often carry the same expired access cookie at once; the first rotates the refresh token, so the second would present an already-rotated token. The grace entry lets that late sibling reuse the rotated pair instead, but only when its origin matches: the comment at MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/CookieSessionRefresher.cs:178-180 states that the same refresh token from another IP or user agent is a miss, so it goes to the identity endpoint, which refuses the already-rotated token instead of this cache handing over the successor pair.
  • Walkthrough: the whole type is one line, private sealed record RotationGraceEntry( AuthenticationResponse Response, BrowserOrigin Origin) (:316). It is written by CallRefreshAsync with cache.Set(cacheKey, new RotationGraceEntry(auth, origin), RotationGrace) (:232), keyed by the OLD refresh token's hash (comment :230-231) and living for RotationGrace = TimeSpan.FromSeconds(10) (:92). TryGetGraceEntry (:181-191) reads it and answers only when entry.Origin == origin (:183), relying on record-struct value equality of BrowserOrigin. RefreshAsync checks it before taking the per-token lock (:162) and again after acquiring it (:170, comment :169), so a request queued behind the rotation picks up its result.
  • Why it's built this way: a record gives the cache a typed, immutable pair with no extra class surface, and storing the origin beside the response is what turns a plain dedup cache into one that cannot hand a rotated session to a different browser (ADR-022).
  • Where it's used: only inside CookieSessionRefresher.cs (:183, :232); the cache itself is the IMemoryCache injected at :82 and registered by AddServerAuthSessionCookie (MMCA.Common/Source/Presentation/MMCA.Common.API/DependencyInjection.cs:187).

SessionRefreshOutcome

MMCA.Common.API · MMCA.Common.API.SessionCookies · MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/SessionRefreshOutcome.cs:32 · Level 9 · class

  • What it is: the result of ICookieSessionRefresher.ValidateOrRefreshAsync and .RefreshAsync: a SessionRefreshStatus, the token when the status is Refreshed, and the upstream's Retry-After hint when it is Unavailable (doc comment, MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/SessionRefreshOutcome.cs:26-31).
  • Depends on: SessionRefreshStatus and SessionTokenResult; TimeSpan from the BCL.
  • Concept: a closed result type built only through named factories, so a caller cannot assemble an inconsistent combination (a Rejected outcome carrying a token, say). It is the richer sibling of the nullable SessionTokenResult? that GetOrRefreshAsync still returns: that shape cannot tell a dead session from a transient failure, this one can. [Rubric §29, Resilience, Reliability & Business Continuity] is the lens, as introduced at SessionRefreshStatus.
  • Walkthrough: the constructor is private (:36-41). Status (:44), Session (:47, set only for Refreshed) and RetryAfter (:53, set only for Unavailable when the identity endpoint sent one) are get-only. The factories are Refreshed(SessionTokenResult session) (:58-59), Rejected() (:63), which returns one cached RejectedOutcome instance (:34) since it carries no data, and Unavailable(TimeSpan? retryAfter = null) (:68-69).
  • Where it's used: built throughout CookieSessionRefresher and consumed by the proxy's FailRefreshAsync (MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/SameOriginProxy/SameOriginApiProxyEndpoint.cs:298-310): Rejected ends the session, while Unavailable keeps the cookies and answers 503 with a Retry-After taken from outcome.RetryAfter or a short default (ADR-131).

ICookieSessionRefresher

MMCA.Common.API · MMCA.Common.API.SessionCookies · MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/CookieSessionRefresher.cs:34 · Level 10 · interface

  • What it is: the "validate-or-refresh over the HttpOnly session cookies" port. It returns a currently-valid access token for the request, rotating from the refresh cookie when the access cookie has expired, in two shapes (a nullable token, or a SessionRefreshOutcome that separates a dead session from a transient failure), plus a forced rotation for when an API rejected a still-valid-looking access token.
  • Depends on: HttpContext (ASP.NET Core), SessionTokenResult, SessionRefreshOutcome and SessionRefreshStatus. Its only implementation is CookieSessionRefresher.
  • Concept introduced, server-side refresh that browser script never sees. [Rubric §11, Security] assesses where the long-lived credential lives. The type comment (MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/CookieSessionRefresher.cs:27-33) is the contract in prose: if the access cookie's JWT is still valid it is returned as-is; otherwise the refresh cookie is exchanged at the API's auth/refresh endpoint server-to-server, so the refresh token never reaches browser JS; the rotated pair is written back as HttpOnly cookies; and the fresh access token is stashed on HttpContext.Items so the current request's SSR authentication can read it before the Set-Cookie takes effect on the next request.
  • Walkthrough: three members. Task<SessionTokenResult?> GetOrRefreshAsync(HttpContext context, CancellationToken cancellationToken = default) (:39) keeps the simple vocabulary: a value means "here is a good access token", null means "no session, treat this caller as anonymous"; its doc comment (:34-38) flags that setting fresh cookies is a side effect. Task<SessionRefreshOutcome> ValidateOrRefreshAsync(...) (:49) is the same operation with the failure kept apart: Rejected when there is no refresh cookie or the identity endpoint refused it, Unavailable for any other outcome (5xx, 429, 408, a misrouted 404, a 409 Auth.RefreshSuperseded, a timeout or a network failure), "so a caller that clears cookies on failure does so only for a session that is really dead" (:41-48). Task<SessionRefreshOutcome> RefreshAsync(...) (:60) exchanges the refresh cookie even when the access cookie still looks valid (the API rejected it: revoked, or signed with a rotated key), and is single-flighted exactly like GetOrRefreshAsync, so concurrent callers holding the same refresh cookie share one rotation (:51-59).
  • Why it's built this way: one interface lets the SSR middleware, the /auth/session/token endpoint and the same-origin proxy share a single refresh path, so exactly one type decides validity and exactly one type rotates (ADR-022, ADR-131). Callers that render anonymously on any failure keep the nullable method; callers that clear cookies use the outcome methods. It is also what makes every caller testable against a mock.
  • Where it's used: GetOrRefreshAsync by CookieSessionRefreshMiddleware (which runs before authentication on navigations), by the /auth/session/token handler (MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/SessionCookieEndpoints.cs:98) and by SessionHandoffEndpoints (MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/SameOriginProxy/SessionHandoffEndpoints.cs:45); ValidateOrRefreshAsync and RefreshAsync by SameOriginApiProxyEndpoint (MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/SameOriginProxy/SameOriginApiProxyEndpoint.cs:105, :321, :358). Registered as a singleton at MMCA.Common/Source/Presentation/MMCA.Common.API/DependencyInjection.cs:194.

CookieSessionRefreshMiddleware

MMCA.Common.API · MMCA.Common.API.SessionCookies · MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/CookieSessionRefreshMiddleware.cs:13 · Level 2 · class

  • What it is: an ASP.NET Core middleware that runs before UseAuthentication on full-page navigations and, when the access cookie's JWT has expired but the refresh cookie is still good, refreshes server-side so SSR [Authorize] survives instead of bouncing to /login.
  • Depends on: RequestDelegate and ICookieSessionRefresher, both primary-constructor parameters (MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/CookieSessionRefreshMiddleware.cs:13). Registered through CookieSessionRefreshMiddlewareExtensions.
  • Concept introduced, refresh before authenticate for prerender. [Rubric §11, Security] and [Rubric §18, UI Architecture] meet here. A Blazor Web App prerenders [Authorize] pages on a cold GET (new tab, F5, external deep link), and authentication reads the cookie before any interactive code runs. If the access cookie has just expired, plain authentication fails and the user is redirected even though a perfectly good refresh token is sitting in the next cookie over. This middleware inserts a refresh attempt first, so the token the refresher stashes on HttpContext.Items is what authentication then reads.
  • Walkthrough: InvokeAsync (:16-26) null-checks the context (:18), asks ShouldAttempt (:20), and on a match awaits refresher.GetOrRefreshAsync(context, context.RequestAborted) (:22) before invoking the rest of the pipeline (:25). The refresh is a side effect only: the return value is discarded and the pipeline always continues, leaving the actual authentication decision to the downstream scheme. ShouldAttempt (:28-31) gates strictly to GET requests whose Accept header contains text/html, so it never fires on static assets, API calls, or XHR.
  • Why it's built this way: the narrow gate keeps a cookie read and a possible outbound HTTP call off every static-asset request, and delegating single-flight to the refresher means the middleware itself cannot double-rotate a token (ADR-022).
  • Where it's used: registered immediately before UseAuthentication() by the shared Blazor web pipeline, MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/Hosting/BlazorWebHostExtensions.cs:203 (with UseAuthentication() on the very next statement at :205), which both Blazor Server hosts call through UseMmcaBlazorWebPipeline (MMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI.Web/Program.cs:120 and MMCA.Store/Source/Hosts/UI/MMCA.Store.UI.Web/Program.cs:92). Its gating rules are pinned one test per branch in MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/SessionCookies/CookieSessionRefreshMiddlewareTests.cs: an HTML navigation refreshes (:19), a browser-style multi-value Accept list still matches (:31), a non-HTML Accept (:45), a missing Accept (:60) and a POST (:74) all skip, and a null refresh result still calls next (:90).
  • Caveats / not-in-source: the ordering rule (before UseAuthentication) is enforced by the host that calls the extension, not by this class. Getting it wrong silently disables the SSR refresh rather than failing loudly.

SessionCookieEndpoints

MMCA.Common.API · MMCA.Common.API.SessionCookies · MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/SessionCookieEndpoints.cs:21 · Level 3 · class

  • What it is: the minimal-API mapper for the two session-cookie routes: DELETE /auth/session-cookie (end the refresh session and clear the HttpOnly cookies, plus any view-as overlay, at logout) and POST /auth/session/token (the same-origin validate-or-refresh the browser calls to hydrate its in-memory claims, answered with a claims-only token, never the credential). No route takes a token from the browser: the server is the only writer of the cookies (doc comment, MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/SessionCookieEndpoints.cs:12-20). It also owns the cookie-name constants, the access-cookie protection purpose and the cross-site guard.
  • Depends on: SessionCookieJar, ICookieSessionRefresher, ICookieSessionEnder (resolved optionally), SessionCookieSettings (via IOptions<T>), SessionClaimsToken, SessionTokenResponse, ViewAsOverlayCookie, IDataProtectionProvider, TimeProvider, and ASP.NET Core routing plus Results. The cookies are written by SessionCookieStore and CookieSessionRefresher and read back by CookieTokenReader.
  • Concept introduced, the cookie names are the shared contract. AccessTokenCookieName = "mmca_auth_access" and RefreshTokenCookieName = "mmca_auth_refresh" (:23-24) are public const, and every other type in this feature (the jar, the reader, the refresher, the ender, the proxy) references them instead of a string literal, so the names have exactly one definition. AccessTokenCookieProtectionPurpose = "MMCA.Common.API.SessionCookies.AccessTokenCookie" (:32, doc :26-31) is the DataProtection purpose the access cookie is protected under: the server writes it protected and unprotects it on every read, and a value that does not unprotect reads as no access cookie. [Rubric §9, API & Contract Design] is the other lens: two tightly-scoped routes, both excluded from OpenAPI (ExcludeFromDescription at :69 and :109) because they are browser plumbing, not public API surface.
  • Walkthrough: the mapping method lives inside an extension(IEndpointRouteBuilder endpoints) block (:34), the C# extension-member syntax this codebase uses for fluent registration (primer §2), so hosts call app.MapSessionCookieEndpoints(). Inside MapSessionCookieEndpoints (:36-114): the async DELETE /auth/session-cookie (:49-71) refuses a cross-site request with 403 (:51-54). It then resolves an ICookieSessionEnder from RequestServices and, when one is registered, awaits its best-effort EndAsync (:56-59), calls SessionCookieJar.Delete with the configured SameSite (:61), expires a present view-as overlay with the same SameSite (:62-65) and returns 204 (:67); it is excluded from description, AllowAnonymous() and DisableAntiforgery() (:69-71). The comment above it (:40-48) explains each choice: it clears the jar whether or not the session is still valid, so it must declare anonymity explicitly because the default fallback authorization policy (SEC-Common-16) requires an authenticated caller on any undeclared endpoint; the cross-site refusal stops another site from signing the user out; the overlay goes too, so the next sign-in never opens on the viewed account; and the refresh session is ended first because a Server circuit signing out during a view never holds the staff user's own access token, while a host without AddServerAuthSessionCookie keeps the cookie-only delete. The /auth/session/token POST (:78-111) takes ICookieSessionRefresher, IDataProtectionProvider and a [FromServices] TimeProvider (:79-83) and first rejects an obvious cross-site request with 403 (:85-88). Next, a live view-as overlay (ViewAsOverlayCookie.TryRead, judged at timeProvider.GetUtcNow(), :93) is answered directly with a claims-only copy of its token and its expiry (:95); the comment at :90-92 explains that this answer never touches the staff user's session and is never refreshed, so an expired overlay, or one that does not unprotect, falls through to the session path. That path awaits refresher.GetOrRefreshAsync (:98); a null result becomes a 401 JSON body { error = "no_session" } (:101). Otherwise the answer is a SessionTokenResponse carrying SessionClaimsToken.Create(...) ?? string.Empty and the access token's expiry (:105-107, comment :104: the browser gets an unsigned copy of the claims, never the credential). That route is AllowAnonymous() (:110) because it authenticates via the cookies themselves. The private IsCrossSite (:120-122) inspects the Sec-Fetch-Site request header and treats a missing header as allowed, which the comment at :117-119 attributes to older browsers.
  • Why it's built this way: CSRF is defended in depth rather than by antiforgery tokens. The comments at :73-77 and :117-119 spell it out: the cookies' configured SameSite (which already blocks cross-site cookie attachment on a POST or DELETE; the comments name Lax as the default and Strict on the same-origin proxy, both set through SessionCookieSettings), and the Sec-Fetch-Site check together stop a cross-site page from driving these endpoints, which is what makes disabling antiforgery safe here (ADR-022). [Rubric §11, Security]. The explicit AllowAnonymous() is the same defense-in-depth posture applied to authentication instead of CSRF: it is a deliberate, commented opt-out of the fallback policy (SEC-Common-16) rather than an oversight. Having no route that accepts a token, and answering only claims, is what keeps a credential out of reach of script on the page (ADR-131). Answering a live overlay ahead of the session is what makes the browser render as the viewed user during read-only support access while the staff session stays intact underneath (ADR-137).
  • Where it's used: mapped by the shared Blazor Web pipeline, UseMmcaBlazorWebPipeline (MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/Hosting/BlazorWebHostExtensions.cs:212), so no host maps it by hand. The routes are exercised end to end by MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/SessionCookies/SessionCookieEndpointsTests.cs, whose CreateHostAsync (:225) builds a real pipeline around the mapper; the cases that matter most are the cross-site 403 on the DELETE that clears nothing (:23) and on the token route (:90), the DELETE expiring a view-as overlay too (:72), the no-session 401 (:121), the claims-only answer that never carries the refresh token (:134), and a forged raw overlay ignored in favor of the session (:170). The sign-out revoke through the ender is pinned by MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/SessionCookies/SessionCookieEndOnDeleteTests.cs (:26, :49, :62, :87). MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/SessionCookies/ClaimsOnlySessionCookieEndpointsTests.cs pins an unsigned claims copy instead of the credential (:26), that POST /auth/session-cookie is not mapped at all, so script cannot seed the cookies (:46), and the delete using the configured SameSite (:65).

SessionCookieJar

MMCA.Common.API · MMCA.Common.API.SessionCookies · MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/SessionCookieJar.cs:24 · Level 3 · class

  • What it is: the one internal static helper that writes, reads and clears the two HttpOnly auth cookies, so the endpoints, the server-side refresher, the reader and the public cookie store all emit identical cookie options and agree on how the access cookie is protected.
  • Depends on: CookieOptions, HttpContext, IWebHostEnvironment and SameSiteMode (ASP.NET Core), IDataProtectionProvider / IDataProtector (ASP.NET Core DataProtection), plus the cookie-name constants and AccessTokenCookieProtectionPurpose on SessionCookieEndpoints. The SameSite value its callers pass comes from SessionCookieSettings.
  • Concept introduced, the server is the only writer, and the access cookie proves it. The remarks (MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/SessionCookieJar.cs:16-23) state that the access-token cookie carries the token protected with DataProtection, so a browser cannot plant a self-made token in it: the claims-reading session-cookie handler never validates the JWT signature, and an unprotect failure reads as no access cookie at all (the refresh cookie then re-issues one). The refresh cookie stays as issued, because it is opaque and the identity endpoint validates it server-side on every exchange.
  • Concept introduced, one place to build cookie options. [Rubric §11, Security] assesses cookie hardening. Centralizing BuildOptions (:111-118) means every write is HttpOnly = true (:113), Secure set by !environment.IsDevelopment() || context.Request.IsHttps (:114), SameSite set to the caller's mode (:115), and Path = "/" (:116). The Secure rule has two halves. Outside Development the flag is always on, whatever the request scheme, because production sits behind a TLS-terminating ingress (Azure Container Apps) where Request.IsHttps is only true once the forwarded-headers step has applied X-Forwarded-Proto, so the flag deliberately does not depend on it. In Development the request decides: the local HTTPS stack gets TLS-only cookies, and only a plain-http Development request (any host name, so http://localhost dev still works) goes without the flag (comment :105-109). Drift between the refresh, store and clear paths is structurally impossible because all of them call this method. The conditional Secure is the one thing an analyzer objects to, and the suppression carries its justification inline (:110 and :119 bracket a scoped #pragma warning disable S2092), which is the house style for an accepted deviation.
  • Walkthrough: DefaultLifetime = TimeSpan.FromDays(7) (:28) is the refresh-token lifetime's default (JwtSettings.RefreshTokenExpirationDays, MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/JwtSettings.cs:104), used when the host configures neither the cookie lifetime nor the Jwt section (comment :26-27). CreateAccessTokenProtector(IDataProtectionProvider) (:33-37) returns the protector under AccessTokenCookieProtectionPurpose; callers create it once and hold it. Append has two overloads: the five-argument form (:39-40) forwards with SameSiteMode.Lax, and the six-argument form (:42-47) builds options once with the given SameSite and the resolved lifetime, writes the access cookie as accessTokenProtector.Protect(accessToken) (:45) and the refresh cookie as issued (:46), both with that lifetime as MaxAge. ReadAccessToken(HttpRequest, IDataProtector) (:57-73, doc :49-56) returns null for a missing or blank cookie (:60-63) and for a value that throws CryptographicException or FormatException on unprotect (:69-72), so a value written by anyone but this server, under a rotated-out key, or tampered with reads as no access cookie, never an exception. ResolveLifetime(HttpContext) (:80-93, doc :75-79) picks the lifetime in order: SessionCookieSettings.Lifetime when the host set it (:85-88), else JwtSettings.RefreshTokenExpirationDays when the Jwt section is bound and positive (:90-92), else DefaultLifetime. It reads both through context.RequestServices with GetService, null-tolerant because the property is null on a bare DefaultHttpContext (comment :82). Delete mirrors Append: the three-argument form (:95-96) forwards with Lax, and the four-argument form (:98-103) rebuilds the options from the same HttpContext with TimeSpan.Zero, which :117 turns into a null MaxAge, and calls Cookies.Delete for both names.
  • Why it's built this way: a delete must send back the same Path, SameSite and Secure attributes as the original write or the browser will not match the cookie and will not clear it. Sharing BuildOptions between Append and Delete (both pass the request, so an HTTPS Development delete carries the same Secure flag as its write), and having every caller pass the same configured SameSite, guarantees that (ADR-022). The Lax-defaulting overloads keep the long-standing call shape for callers with no settings in hand.
  • Where it's used: SessionCookieEndpoints (clear at SessionCookieEndpoints.cs:61), CookieSessionRefresher (protector at CookieSessionRefresher.cs:95, reads at :104 and :117, rewrite after rotation at :150), SessionCookieStore (protector at ISessionCookieStore.cs:36, write at :39, clear at :42), the write and clear paths all passing SessionCookieSettings.SameSite, and CookieTokenReader (protector at CookieTokenReader.cs:30, read at :53). Its BuildOptions is also named in the culture cookie's conditional Secure suppression (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/WebApplicationExtensions.cs:109), as the rule that cookie follows: Secure always outside Development and in Development whenever the request is HTTPS (WebApplicationExtensions.cs:119), so only a plain-HTTP Development host writes it without the flag. The attributes it emits are asserted directly by MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/SessionCookies/SessionCookieJarTests.cs, including the HTTPS Development cases for Append and Delete (:141, :158), the protected access cookie (:30), its round trip (:48) and a value that does not unprotect reading as no cookie (:61).

CookieSessionRefreshMiddlewareExtensions

MMCA.Common.API · MMCA.Common.API.SessionCookies · MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/CookieSessionRefreshMiddleware.cs:35 · Level 3 · class

  • What it is: a one-method registration helper (UseCookieSessionRefresh) that adds CookieSessionRefreshMiddleware to the request pipeline.
  • Depends on: IApplicationBuilder (ASP.NET Core) and CookieSessionRefreshMiddleware.
  • Concept: the standard UseXxx() middleware-registration idiom, written with the codebase's extension(IApplicationBuilder app) member syntax (MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/CookieSessionRefreshMiddleware.cs:37); see primer §2. Nothing new beyond putting a name and a doc comment on UseMiddleware<T>.
  • Walkthrough: UseCookieSessionRefresh() (:43-47) null-guards the builder (:45) and returns app.UseMiddleware<CookieSessionRefreshMiddleware>() (:46). The XML comment (:39-42) states the load-bearing rule in bold: register it immediately before UseAuthentication() on the Blazor Server (UI.Web) host.
  • Where it's used: the shared Blazor web pipeline (MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/Hosting/BlazorWebHostExtensions.cs:203), which the two Blazor Server hosts call (MMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI.Web/Program.cs:120, MMCA.Store/Source/Hosts/UI/MMCA.Store.UI.Web/Program.cs:92). Both the null guard and the pipeline wiring are covered directly at MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/SessionCookies/CookieSessionRefreshMiddlewareTests.cs:115 and :123.

SessionCookieStore

MMCA.Common.API · MMCA.Common.API.SessionCookies · MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/ISessionCookieStore.cs:31 · Level 4 · class

  • What it is: the internal implementation of ISessionCookieStore: a thin adapter that forwards to SessionCookieJar with the configured SameSite and the access-token DataProtection protector.
  • Depends on: IWebHostEnvironment, IOptions<SessionCookieSettings> and IDataProtectionProvider (primary constructor, MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/ISessionCookieStore.cs:31-34), SessionCookieSettings and SessionCookieJar.
  • Concept: the adapter half of the public-port-over-internal-helper split introduced at ISessionCookieStore. It adds no cookie behavior of its own, which is the point: every cookie option still comes from the jar's single BuildOptions, and the protector comes from the jar's CreateAccessTokenProtector (MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/SessionCookieJar.cs:33-37), so the store and the refresher protect under the same purpose string.
  • Walkthrough: the field initializer builds _accessTokenProtector once from the injected provider (:36). Write (:38-39) calls SessionCookieJar.Append(context, _accessTokenProtector, accessToken, refreshToken, environment, settings.Value.SameSite), which protects the access token before it reaches the cookie and writes the refresh token as issued (SessionCookieJar.cs:42-47); Clear (:41-42) calls SessionCookieJar.Delete(context, environment, settings.Value.SameSite). Reading settings.Value on each call means writes and deletes always agree on SameSite.
  • Why it's built this way: internal sealed, so consumers outside MMCA.Common.API depend on the interface and the jar stays hidden; the one-line summary at :30 names it "the ISessionCookieStore over SessionCookieJar". Protecting the access cookie means a browser cannot plant a self-made token in it, since the claims-reading session-cookie handler never validates the JWT signature (SessionCookieJar.cs:16-23). [Rubric §11, Security].
  • Where it's used: registered as the singleton ISessionCookieStore by AddServerAuthSessionCookie (MMCA.Common/Source/Presentation/MMCA.Common.API/DependencyInjection.cs:209), right after services.AddDataProtection() (:203, with the multi-replica key-ring note at :199-202); see ISessionCookieStore for the proxy types that consume it.

CookieTokenReader

MMCA.Common.API · MMCA.Common.API.SessionCookies · MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/CookieTokenReader.cs:17 · Level 4 · class

  • What it is: the read side of the cookie feature. It pulls the access JWT and the refresh token out of the request cookies the server wrote (or out of a live view-as overlay, or the freshly-refreshed token stashed on HttpContext.Items) for server-side token storage during SSR prerender, when JS interop and therefore localStorage are unreachable.
  • Depends on: IHttpContextAccessor, IDataProtectionProvider and TimeProvider (primary constructor, MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/CookieTokenReader.cs:17-20, params documented at :11-16), SessionCookieJar for the protector and the unprotecting read, the cookie-name constants on SessionCookieEndpoints, plus ViewAsOverlayCookie for the overlay check. Consumed by SessionCookieAuthenticationHandler and by ServerTokenStorageService.
  • Concept introduced, the fresh-token handoff. [Rubric §29, Resilience, Reliability & Business Continuity] covers request-scoped state. The internal const string FreshAccessTokenItemKey = "mmca.fresh-access-token" (:27) is the agreed HttpContext.Items key under which CookieSessionRefresher parks a just-rotated access token, as the comment at :22-26 explains. ReadAccessToken checks that key before the cookie, so on the very request that triggered a refresh, SSR authentication uses the new token instead of the still-expired one sitting in the request cookie; the Set-Cookie from the rotation only affects the next request.
  • Walkthrough: two private fields keep the provider (:29) and the access-cookie protector built once by SessionCookieJar.CreateAccessTokenProtector (:30). The doc comment (:32-36) states the precedence: a live view-as overlay's token first, else a token the refresher just minted, else the unprotected session access cookie. ReadAccessToken (:38-58) returns null when there is no HttpContext (:41-44), then returns the overlay token when ViewAsOverlayCookie.TryRead finds one that unprotects and has not expired as of timeProvider.GetUtcNow() (:46-49), then prefers a non-empty string under FreshAccessTokenItemKey (:51-55), and otherwise falls back to SessionCookieJar.ReadAccessToken (:57), which answers null for a cookie that does not unprotect. The fresh is string freshToken pattern plus the whitespace check mean a wrong-typed or blank item silently falls through to the cookie rather than poisoning the request. Judging the overlay's expiry against the injected clock rather than the system clock lets a test move time past the overlay's end instead of waiting for it. [Rubric §14, Testability]. ReadRefreshToken (:62-63, doc :60) reads the refresh cookie directly with a null-conditional accessor, as issued and unprotected, and has neither the overlay nor the fresh-item fallback, because the overlay is never renewed and only the access token is ever swapped mid-request.
  • Why it's built this way: the Items-before-cookie precedence is exactly what makes the middleware's server-side refresh take effect on the request that triggered it instead of only on the next one (ADR-022). Putting the overlay ahead of both is what makes server rendering show the viewed user during read-only support access while the staff session's own cookies stay untouched (ADR-137).
  • Where it's used: injected into SessionCookieAuthenticationHandler (SessionCookieAuthenticationHandler.cs:29) and into the UI host's server-side token store (MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/Services/ServerTokenStorageService.cs:50). Registered scoped by AddServerAuthSessionCookie (MMCA.Common/Source/Presentation/MMCA.Common.API/DependencyInjection.cs:188), which also registers the system TimeProvider with TryAdd (:214) for a host that has no other clock registration. Covered by MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/SessionCookies/CookieTokenReaderTests.cs, including a cookie that is not server-protected reading as null (:46), a live protected overlay winning over the session (:118), a forged raw overlay ignored in favor of the session (:130), and the overlay's expiry judged against the injected clock (:178).

SessionCookieAuthenticationHandler

MMCA.Common.API · MMCA.Common.API.SessionCookies · MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/SessionCookieAuthenticationHandler.cs:25 · Level 4 · class

  • What it is: an ASP.NET Core AuthenticationHandler that reads the JWT out of the session cookie, parses its claims, and populates HttpContext.User during SSR prerender, so both Blazor's internal SSR authorization and endpoint-level [Authorize] pass on a fresh GET before the interactive phase starts.
  • Depends on: AuthenticationHandler<AuthenticationSchemeOptions> and its three framework constructor arguments (IOptionsMonitor, ILoggerFactory, UrlEncoder) plus CookieTokenReader (MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/SessionCookieAuthenticationHandler.cs:25-30), and System.IdentityModel.Tokens.Jwt. Registered by SessionCookieAuthenticationExtensions.
  • Concept introduced, a deliberately non-validating scheme. [Rubric §11, Security] assesses where the trust decision is actually made. The <remarks> block (:18-23) is load-bearing: this handler does not validate the JWT signature. The cookie was minted by the UI host in response to a successful login against the API, and every real API call still performs full JWT validation, so the handler exists only to extract claims for ASP.NET Core's auth system during prerender. That is what lets a deep-linked [Authorize] page render instead of flashing a redirect. Read it next to ADR-004: the API remains the single validation authority via JWKS, and the UI host deliberately does not duplicate it.
  • Walkthrough: SchemeName = "SessionCookie" (:32) is the canonical scheme name, exposed as a public const so registration never repeats a literal. HandleAuthenticateAsync (:35-69) reads the token through CookieTokenReader (:37) and returns AuthenticateResult.NoResult() when there is none (:38-41), which lets other schemes have their turn rather than hard-failing the request. It then rejects anything that is not a readable JWT (:46-49), and fails when jwt.ValidTo is in the past according to the base handler's injectable TimeProvider (:55-58, with the rationale at :53-54). On success it builds a ClaimsIdentity from the JWT claims with ClaimTypes.NameIdentifier and ClaimTypes.Role as the name and role claim types (:60), wraps it in a ClaimsPrincipal and an AuthenticationTicket stamped with the scheme name (:61-63), and returns Success. Malformed-token exceptions are narrowed to ArgumentException and FormatException and returned as Fail (:65-68). HandleChallengeAsync (:72-77) redirects to /login?returnUrl=... with the original path and query URL-escaped (:74-75), and HandleForbiddenAsync (:80-84) sets a bare 403.
  • Why it's built this way: validating the signature here would duplicate the API's JWKS validation and couple the UI host to the signing key. Extracting claims only, while the API stays the single authority, keeps the trust boundary in one place (ADR-004 and ADR-022). Reading the clock through the base handler's TimeProvider rather than DateTime.UtcNow keeps the expiry check on the same injectable clock as the rest of the auth stack and its tests. [Rubric §14, Testability].
  • Where it's used: registered as the SessionCookie scheme on both Blazor Server hosts, MMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI.Web/Program.cs:105-106 and MMCA.Store/Source/Hosts/UI/MMCA.Store.UI.Web/Program.cs:111-112. Covered directly by MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/SessionCookies/SessionCookieAuthenticationHandlerTests.cs, including the fresh-token-from-Items path (:95, which stashes the token under CookieTokenReader.FreshAccessTokenItemKey at :102 and asserts it wins over an expired cookie) and the proof that expiry is judged by the handler's TimeProvider rather than the system clock (:112).

CookieSessionRefresher

MMCA.Common.API · MMCA.Common.API.SessionCookies · MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/CookieSessionRefresher.cs:80 · Level 5 · class

  • What it is: the singleton implementation of ICookieSessionRefresher. It unprotects the access cookie and validates its JWT locally and, when that fails (or when a caller forces it), exchanges the refresh cookie at the API's auth/refresh endpoint server-to-server, writes the rotated pair back as cookies, single-flights concurrent refreshes from the same browser so a burst of requests rotates the token only once, forwards the browser's own user-agent and IP to the identity endpoint, and classifies every failure as a dead session or a transient one.
  • Depends on: IHttpClientFactory, IMemoryCache, IWebHostEnvironment, ILogger<CookieSessionRefresher>, TimeProvider, IOptions<SessionCookieSettings> and IDataProtectionProvider (primary constructor, MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/CookieSessionRefresher.cs:80-87); KeyedSemaphoreStripe (:94); SessionCookieJar, which also supplies the access-token protector (:95); SessionCookieSettings for the cookie SameSite and the RefreshTimeout bound on the outbound call; SessionRefreshOutcome and SessionRefreshStatus; CookieTokenReader for the Items key; SessionCookieEndpoints for the cookie names; and the AuthenticationResponse / RefreshTokenRequest contracts from MMCA.Common.Shared.Auth. It reads token expiry with System.IdentityModel.Tokens.Jwt and names Polly.ExecutionRejectedException in its catch filter.
  • Concept introduced, single-flight refresh under a thundering herd. [Rubric §12, Performance & Scalability] assesses behavior under concurrent load. When an access token expires, many queued navigations can arrive at once; rotating for each would burn the refresh token repeatedly and log the user out. The type comment (:65-79) states the design: the lock is a striped KeyedSemaphoreStripe keyed by refresh token rather than one process-wide semaphore, because the lock is held across an outbound HTTP call and a single semaphore would serialize every unrelated user's cold navigation behind whichever refresh happened to be in flight. Two unrelated tokens can still land on the same one of the stripe's 256 lanes (MMCA.Common/Source/Core/MMCA.Common.Shared/Concurrency/KeyedSemaphoreStripe.cs:25), which the comment calls out as harmless precisely because the rotation-grace cache is re-checked per token after acquiring. Alongside the lock, a 10-second RotationGrace (:92) caches the rotated pair keyed by a SHA-256 hash of the OLD refresh token (:235, key built at :307-308), so a slightly-late sibling carrying the same expired pair gets the same result instead of rotating again. Each entry is a private RotationGraceEntry (:319) that also records the BrowserOrigin that rotated it, and TryGetGraceEntry (:181-191) answers only when the caller's origin matches (:183): the same refresh token arriving from another IP or user agent is a miss and goes to the identity endpoint, which refuses the already-rotated token, so a stolen refresh token replayed inside the grace window does not receive the successor pair (comments :70-72, :178-180). [Rubric §11, Security].
  • Walkthrough: GetOrRefreshAsync (:97-98) is a projection: it awaits ValidateOrRefreshAsync and returns its .Session, so every failure becomes null. ValidateOrRefreshAsync (:100-111) reads the access cookie through SessionCookieJar.ReadAccessToken with the protector (:104), which returns null for a missing cookie or one that does not unprotect (MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/SessionCookieJar.cs:57-73), and, if TryReadValidExpiry passes, returns a Refreshed outcome around it untouched (:105-108, wrapped in Task.FromResult); otherwise it returns the task from RefreshFromCookiesAsync (:110) directly. Both are non-async methods that return a Task without awaiting it, so they add no state machine of their own. The public RefreshAsync (:113-119) reads the cookie the same way (:117), skips the validity check and returns RefreshFromCookiesAsync (:118), which is the forced rotation the interface promises. RefreshFromCookiesAsync (:135-156) returns Rejected when there is no refresh cookie (:137-141), captures the browser's identity with BrowserOrigin.From(context) (:143), calls the private RefreshAsync (:144) and passes its failure through (:145-148), writes the rotated pair with SessionCookieJar.Append, the protector and the configured SameSite (:150), stashes the fresh (unprotected) access token on context.Items[CookieTokenReader.FreshAccessTokenItemKey] (:154, with the reason at :152-153), and returns a Refreshed outcome around the new SessionTokenResult (:155). The private RefreshAsync (:158-176) is textbook double-checked locking: it computes the hashed key once (:161), a same-origin grace hit returns immediately (:162-165), otherwise it acquires the stripe for that key (:167) and re-checks the grace entry before doing any work (:170-173). CallRefreshAsync (:193-247) creates the named client (:196), creates its own CancellationTokenSource from cookieSettings.Value.RefreshTimeout and the injected TimeProvider (:209), builds an HttpRequestMessage POST to the relative auth/refresh URI carrying a RefreshTokenRequest as JSON content (:212-215), lets the captured origin stamp its headers (:216), and sends it with that source's token rather than the request's (:218). The comment at :205-208 gives both halves of the reason: once the lock is held the rotation must complete and write its cookies even if the triggering request was aborted, but it must also be bounded, because the lock stripe it holds is shared with other users' refreshes. A non-success status goes through ClassifyFailure (:220-225): Rejected, or Unavailable carrying the parsed Retry-After. The body is read under the same bounded token (:227), and an empty access token is Unavailable (:228-231). Success caches a RotationGraceEntry pairing the AuthenticationResponse with the origin, under the hashed old refresh token, for RotationGrace (:235). ClassifyFailure (:130-133) is internal static: 400, 401 and 403 are the identity endpoint refusing the token, so Rejected; anything else (5xx, 429, 408, a 404 from a misrouted gateway, and a 409) says nothing about the token, so Unavailable (doc :121-129). The 409 case is Auth.RefreshSuperseded: another request (a second tab, or the same browser served by another replica) rotated this token a moment ago, inside RefreshSessions:ReuseGraceSeconds, and the browser picks up the winner's cookie on its next request, so the session is kept (ADR-097). ReadRetryAfter (:249-268) accepts either form of the header, a delta (:256-259) or a date measured against the injected TimeProvider (:261-265), and clamps a negative result to zero. TryReadValidExpiry (:270-299) rejects a blank token, refuses anything JwtSecurityTokenHandler cannot read (:279-282), treats the token as expired when jwt.ValidTo <= timeProvider.GetUtcNow().UtcDateTime + ClockSkew (:287, with ClockSkew a 30-second margin at :91), and swallows only ArgumentException/FormatException (:295-298); it is an instance method because it reads the injected clock. CacheKey (:307-308) builds mmca:session-refresh: followed by the lowercase hex SHA-256 of the refresh token, the string that is both the cache key and the striping key; the doc at :301-306 explains the hash (no credential sits in a cache key, since diagnostics and cache dumps list keys) and that it is internal rather than private so a concurrency test can pick two refresh tokens that do not collide on a stripe, which is a nice example of a testability affordance that costs nothing at runtime. [Rubric §14, Testability]: the injected TimeProvider is the same kind of affordance, letting tests move the clock instead of minting tokens around the wall clock.
  • Concept, forwarding the browser's identity on a server-to-server hop. [Rubric §11, Security] and [Rubric §13, Observability & Operability] apply to what the identity endpoint records. Because this host, not the browser, calls auth/refresh, a bare call would stamp the rotated session with the host's own empty user-agent and loopback address. The private BrowserOrigin record struct (:321-345) is captured from the triggering request before the lock is taken (:143, doc :313-318, which sits above RotationGraceEntry at :319): From reads the User-Agent header, treating blank as null, and the connection's remote IP (:323-329). ApplyTo (:331-344) adds User-Agent and X-Forwarded-For to the outbound request with TryAddWithoutValidation (:337, :342), because a real browser user-agent does not always parse as a strict product-token list and the value is informational only. The identity endpoint trusts X-Forwarded-For through CommonForwardedHeaders. Capturing it before RefreshAsync matters because the work that follows runs under the lock and cache, where the triggering HttpContext is no longer the thing being read.
  • Concept, an SSR-safe failure mode that does not sign users out. [Rubric §29, Resilience, Reliability & Business Continuity] and [Rubric §13, Observability & Operability] apply to the outbound call. CallRefreshAsync wraps the POST in a try whose filter narrows to HttpRequestException, OperationCanceledException, JsonException, NotSupportedException and Polly.ExecutionRejectedException (:241-242); the comment at :238-240 explains the last one: the resilience pipeline's own refusals (a timed-out attempt, an open circuit, a rate-limited call) throw it, for example TimeoutRejectedException with the gateway down, which is neither transport exception. A call that outlives RefreshTimeout (10 seconds by default, a non-positive value refused by the setter, MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/SessionCookieSettings.cs:38-46) is cancelled and lands in the same catch as an OperationCanceledException; the property doc (SessionCookieSettings.cs:30-36) notes that without it a hung identity call would hold the shared stripe for as long as the client's resilience pipeline allows. The catch logs one warning through the source-generated LogRefreshCallFailed (:244, declared with [LoggerMessage] at :310-311, which is why the class is partial at :80) and returns Unavailable (:245). The comment at :198-204 gives the reasoning: this code runs during SSR, so an escaping exception would turn a signed-in user's navigation into a 500 instead of an anonymous render; it is Unavailable, not Rejected, because nothing said the refresh token is dead, so a caller that clears cookies must keep them. The failure is deliberately not cached (only a successful rotation reaches cache.Set at :235), so the next navigation retries, and a missing BaseAddress raises InvalidOperationException and is left to propagate because that is a host misconfiguration rather than a runtime condition.
  • Why it's built this way: keying the grace cache by the OLD token's hash is what lets a slightly-late sibling find the already-rotated pair without a credential ever sitting in a cache key, matching on the browser origin keeps that shortcut from serving a replayed token, and striping the lock keeps one user's slow refresh from blocking everyone else's cold navigation. The server-to-server call is what keeps the refresh token off browser JS (ADR-022). [Rubric §11, Security]. Separating Rejected from Unavailable is what lets the same-origin proxy clear cookies only for a session that is really over and answer a transient identity-endpoint fault with 503 plus Retry-After (ADR-131).
  • Where it's used: resolved as ICookieSessionRefresher by CookieSessionRefreshMiddleware, by the /auth/session/token endpoint, and by the same-origin proxy (SameOriginApiProxyEndpoint, SessionHandoffEndpoints). Its named HttpClient, RefreshClientName = "SessionCookieRefreshClient" (:89), is configured with the API base address in AddServerAuthSessionCookie (MMCA.Common/Source/Presentation/MMCA.Common.API/DependencyInjection.cs:190-191), which also registers the refresher as a singleton (:194) with an inline note (:193) that a shared instance across requests is what makes single-flight work at all, registers DataProtection for the access-cookie protector (:208, with the multi-replica key-ring note at :204-207), and registers TimeProvider.System with TryAdd (:214) because a Blazor Web host calling only this method has no other clock registration (comment :211-213). The same named client also carries the sign-out revoke of CookieSessionEnder. The validate, rotate, grace-cache and failure paths are covered by MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/SessionCookies/CookieSessionRefresherTests.cs, including refusal as Rejected (:419, :434), undecidable statuses as Unavailable with no cookies written (:446), the rotation-race 409 as Unavailable that keeps the cookies (:476, :490), resilience-pipeline rejections (:522), a hung identity call abandoned at the refresh timeout as Unavailable (:537), the timeout's 10-second default and its non-positive guard (:571, :563), both Retry-After forms (:586, :602), the forwarded user-agent and IP (:79, :96), expiry judged against the injected clock (:60), the grace entry refused to another browser origin and served to the same one (:296, :322), and the cache key being a hash rather than the token (:341).

CookieSessionEnder

MMCA.Common.API · MMCA.Common.API.SessionCookies · MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/CookieSessionEnder.cs:28 · Level 6 · class

  • What it is: the internal sealed implementation of ICookieSessionEnder. When a browser deletes its session cookies at sign-out, it posts the refresh cookie server-to-server to the identity endpoint's anonymous auth/session/end, so the refresh session behind the cookie is revoked rather than left to lapse at its expiry. It is best effort: nothing it meets stops the sign-out.
  • Depends on: IHttpClientFactory and ILogger<CookieSessionEnder> (primary constructor, MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/CookieSessionEnder.cs:28-30); the named client of CookieSessionRefresher (RefreshClientName, :55); SessionCookieEndpoints for the refresh-cookie name (:45); and the EndSessionRequest contract from MMCA.Common.Shared.Auth.Requests (:59).
  • Concept, revoking a session the browser cannot reach. [Rubric §11, Security] assesses whether sign-out actually ends server-side state. The refresh cookie is HttpOnly and the Blazor web head does not own the session store, so deleting the cookies alone would leave a live refresh session at the identity endpoint; the interface doc (:7-13) states the split, and the delete endpoint's comment (SessionCookieEndpoints.cs:40-48) adds that a Server circuit signing out during a view-as never holds the staff user's own access token, so this call is the only place that session can be revoked. [Rubric §29, Resilience, Reliability & Business Continuity] covers the other half: the revoke is a courtesy to the session store, so it is bounded and can never fail the sign-out (interface doc :16-21).
  • Walkthrough: EndSessionPath = "auth/session/end" (:33) is the relative path against the client's gateway base address. Timeout (:39, doc :35-38) is an internal init-only property defaulting to 5 seconds, short because the browser is waiting on the cookie delete. EndAsync (:41-73) guards a null context (:43), reads the refresh cookie (:45) and returns without a call when it is blank (:46-49). Otherwise it builds its own CancellationTokenSource from Timeout (:52) rather than taking the request's token, so the browser leaving mid-request does not cancel the revoke (comment :51). Inside the try it creates the named client (:55), POSTs an EndSessionRequest as JSON (:57-61), and logs a non-success status through LogEndRefused (:62-65). Any exception is caught (:68, with CA1031 suppressed and the reason stated at :67) and logged through LogEndFailed (:71). Both log methods are source-generated [LoggerMessage] warnings (:75-76, :78-79), which is why the class is partial. Unlike the refresher, the timeout source is built without a TimeProvider.
  • Why it's built this way: posting from the server keeps the refresh token off browser JS, the same reason the refresher calls auth/refresh server-to-server (ADR-022). The identity side, EndSessionAsync on AuthControllerBase (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/AuthControllerBase.cs:201-215), is anonymous and always answers 204, revoking a live matching session through IAuthSessionIssuer (:213) and changing nothing for an unknown, expired or already-revoked token, so the answer reveals nothing about the token (remarks :190-196). That makes swallowing every failure on this side safe: the worst case is a session that lapses at its own expiry, which is what a cookie-only delete would have done anyway.
  • Where it's used: registered as the singleton ICookieSessionEnder by AddServerAuthSessionCookie (MMCA.Common/Source/Presentation/MMCA.Common.API/DependencyInjection.cs:198, comment :196-197), and resolved optionally by the DELETE /auth/session-cookie endpoint before it deletes the cookies (SessionCookieEndpoints.cs:56-59), so a host without that registration keeps the cookie-only delete. Covered by MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/SessionCookies/SessionCookieEndOnDeleteTests.cs: the session ended and the cookies deleted (:26), a refusal or an unreachable endpoint still deleting the cookies with 204 (:49, :62), no call without a refresh cookie (:74), a cross-site delete refused with 403 and nothing ended (:87), and a hanging identity endpoint abandoned at the timeout (:100).

SessionCookieAuthenticationExtensions

MMCA.Common.API · MMCA.Common.API.SessionCookies · MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/SessionCookieAuthenticationHandler.cs:91 · Level 5 · class

  • What it is: the registration helper for SessionCookieAuthenticationHandler: a single AddSessionCookieAuthentication() that wires the scheme into an AuthenticationBuilder.
  • Depends on: AuthenticationBuilder (ASP.NET Core) and SessionCookieAuthenticationHandler.
  • Concept: the same extension(T) DI-registration idiom introduced by the other extension helpers in this group. The method is declared inside an extension(AuthenticationBuilder builder) block (MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/SessionCookieAuthenticationHandler.cs:93) and reads at the call site as an instance method on the builder; see primer §2.
  • Walkthrough: AddSessionCookieAuthentication() (:98-100) is a single expression: builder.AddScheme<AuthenticationSchemeOptions, SessionCookieAuthenticationHandler>( SessionCookieAuthenticationHandler.SchemeName, displayName: null, configureOptions: null). The scheme name comes from the handler's own constant rather than a duplicated literal, and the two explicit null arguments are named, so the call site says what it is skipping. The doc comment (:94-97) directs callers to use it after AddAuthentication(SessionCookieAuthenticationHandler.SchemeName).
  • Where it's used: MMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI.Web/Program.cs:106 and MMCA.Store/Source/Hosts/UI/MMCA.Store.UI.Web/Program.cs:112, chained onto the host's AddAuthentication(SessionCookieAuthenticationHandler.SchemeName) call on the preceding line.

PasswordResetSettings

MMCA.Common.Application · MMCA.Common.Application.Auth · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/PasswordResetSettings.cs:10 · Level 0 · class (sealed)

  • What it is: the bound options object for the forgot-password workflow: where the reset page lives, how long a token stays redeemable, how many wrong guesses a token tolerates, and how often one address may ask for a reset (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/PasswordResetSettings.cs:6-9).
  • Depends on: System.ComponentModel.DataAnnotations for the range attributes and System.Diagnostics.CodeAnalysis for one scoped suppression (BCL, :1-2). Nothing first-party. Read by the implementation behind IPasswordResetTokenService and by the shared ForgotPasswordHandlerBase<TUser, TCommand>.
  • Concept: validated options whose defaults keep an unconfigured host bootable. [Rubric §17, DevOps & Deployment] assesses whether policy knobs are configuration rather than constants buried in a handler, and [Rubric §11, Security] assesses whether the security-relevant knobs (token lifetime, attempt cap, request throttle) are bounded rather than free-form. Every numeric member carries a [Range] attribute, and the host binds the section with ValidateDataAnnotations().ValidateOnStart() (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:179-182), so a typo such as TokenLifetimeMinutes: 0 fails the host at startup instead of silently issuing tokens that are already expired.
  • Walkthrough: const string SectionName = "PasswordReset" (:13) names the configuration section the host binds. ResetUrl (:25) defaults to string.Empty and is deliberately not [Required]: the doc comment (:15-20) records that a host which has not configured a UI base must still boot, and an empty value degrades to a token-only email the user pastes into the reset page by hand. That degradation is visible in the caller, which emits the bare token when the URL is blank and otherwise appends the escaped address and token as a URL fragment, #email=...&token=... (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/ForgotPassword/ForgotPasswordHandlerBase.cs:186-189). A fragment is never sent to the server in the HTTP request, which is the reason the doc comment gives (:16-17): the live token never reaches a server or proxy access log the way a query string would. The property carries a scoped CA1056 suppression (:21-24) explaining why it is a string and not a System.Uri: it is bound from PasswordReset__ResetUrl, concatenated with a URL fragment, and the empty default is not a valid Uri. The four numeric knobs follow: TokenLifetimeMinutes (:29, [Range(1, 1440)], default 30), MaxValidationAttempts (:36, [Range(1, 100)], default 5), MaxRequestsPerEmail (:40, [Range(1, 100)], default 3), and RequestWindowMinutes (:44, [Range(1, 1440)], default 60). All five members are init-only, so the bound instance is immutable afterwards.
  • Why it's built this way: the defaults are a working policy on their own, so adopting the feature costs a registration call and no configuration at all, while the [Range] bounds plus ValidateOnStart make the one genuinely dangerous class of misconfiguration (a zero or negative lifetime, an unbounded attempt cap) unreachable. The decision to keep the whole reset credential in configuration and cache rather than in schema is ADR-091.
  • Where it's used: bound in the framework's Infrastructure registration (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:179-182, immediately before the token service that reads it is registered at :171); consumed by PasswordResetTokenService as a snapshot field (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/PasswordResetTokenService.cs:47) for the request window, the throttle ceiling, the token lifetime, and the attempt cap; and exposed to the shared forgot-password handler as a protected Settings property (ForgotPasswordHandlerBase.cs:77) that states the expiry in the email body (:160, :167) and renders the fragment link (:186-189).

RefreshSessionSettings

MMCA.Common.Application · MMCA.Common.Application.Auth · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/RefreshSessionSettings.cs:9 · Level 0 · class (sealed)

  • What it is: the bound options object for multi-device refresh sessions: whether this host owns the RefreshSessions table, which database carries it, how many live sessions one user may hold, how long dead session rows are retained before a sweep deletes them, and the two windows that soften BR-206 reuse detection (a rotation race, and an opt-in lost-response recovery) (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/RefreshSessionSettings.cs:5-8). A host that omits the section gets the defaults.
  • Depends on: System.ComponentModel.DataAnnotations (BCL, :1). Nothing first-party. Read by AuthSessionIssuer, by EFRefreshSessionStore, by ApplicationDbContext, and by RefreshSessionCleanupService.
  • Concept introduced: a flag that places a table rather than switching a feature. [Rubric §8, Data Architecture] assesses whether each table has exactly one owning database, and [Rubric §7, Microservices Readiness] assesses whether that ownership survives splitting a modular host into services. The doc comment on Enabled states the distinction precisely (:20-23): the flag "gates the model, not the workflow". The workflow always issues, rotates and revokes sessions; Enabled decides which host maps the table, runs its migrations, and sweeps it. In a modular host the service that owns identity sets it to true and every other service leaves it false, which is what keeps one table in one database instead of one per service. The Scheduler:Enabled precedent is named in the same comment as the pattern being followed.
  • Walkthrough: eight members, all init-only apart from the constant.
    • const string SectionName = "RefreshSessions" (:12) names the configuration section.
    • Enabled (:25) defaults to false. Two places read it: the model gate in RefreshSessionModelContributor, which enables the table only when the flag is set and the context instance's physical source name equals DataSourceName (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Auth/RefreshSessionModelBuilderExtensions.cs:146-148, a contributor ApplicationDbContext keeps only when its AppliesTo passes, MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/ApplicationDbContext.cs:550-553), and the hosted-service registration, which starts the retention sweep only when the flag is set (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:237-245, whose comment explains that registering it unconditionally would start a sweep in every service of a modular host, all but one of which has no table to sweep).
    • MaxActiveSessionsPerUser (:35, [Range(1, 1000)], default 10) caps live sessions per user. The comment (:28-33) records the deliberate behavior at the ceiling: signing in on device number cap + 1 revokes the oldest live session rather than refusing the login, so the table is bounded without a legitimate sign-in ever failing.
    • DataSourceName (:52, [MinLength(1)], default "Default") names the logical data source whose database holds the table. The comment (:37-49) is worth reading in full: the value answers two questions that must agree, which context maps the table and which context the shipped IRefreshSessionStore reads and writes through, and naming a source that does not exist fails loudly on the first session query rather than reading the wrong database. It is ignored for routing when the consumer ships its own entity configuration for the session entity.
    • RetentionDays (:72, [Range(0, 3650)], default 30) is measured from the instant a session died (its revocation, or its expiry when never revoked), so a live session is never a sweep candidate. The comment (:59-66) states the constraint that makes the number security-relevant: retention bounds reuse detection, because BR-206 catches a replayed refresh token by landing on its revoked row, and a swept row turns that replay into an unknown token that fails alone instead of revoking the family. Thirty days sits well past the seven-day refresh-token lifetime for exactly that reason. 0 keeps every row forever (:67-69).
    • CleanupIntervalHours (:80, [Range(1, 168)], default 6) is how often the sweep runs, ignored when RetentionDays is 0, and matches the outbox sweep cadence because the deadline is measured in days (:74-77).
    • ReuseGraceSeconds (:99, [Range(0, 300)], default 10) is how long after a session was rotated a second presentation of its token counts as a rotation race rather than reuse (:82-97). Two tabs, or one browser served by two replicas, can present the same refresh token a moment apart; the later request is answered 409 Conflict (Auth.RefreshSuperseded) with nothing revoked, and the client retries with the winner's token. The default matches the cookie refresher's rotation grace. The comment is explicit that this is a security trade-off: a stolen-token replay arriving inside the window gets a 409 instead of the BR-206 family revocation. Only a row revoked as Rotated qualifies: a row already flagged as reuse fails that request alone, without revoking the family a second time, however recent (:92-94), and 0 treats every rotated token that comes back as reuse.
    • LostResponseRecoveryMinutes (:123, [Range(0, 1440)], default 0, which is off) is how long after a rotation a client that never received the rotation's response can still recover its session by presenting the old token again (:101-121). The case is a mobile client whose refresh succeeded on the server while the response was lost (the app suspended mid-request, or the network dropped): it presents the old pair minutes later and BR-206 would revoke every session the user holds. With a window set, that presentation is recovered instead when, and only when, the presented row was revoked as Rotated inside the window and its successor is still live, meaning nobody ever presented the successor; the successor is then rotated in its place through the normal rotation claim (:106-112). The comment names this a security trade-off as well (:114-120): a thief replaying inside the window while the legitimate client is idle is handed a session, and the legitimate client's next refresh presents a successor that was rotated away, which is reuse, so the whole family, thief included, is revoked. Detection is delayed by one refresh, never lost, and a successor that was already used is never recovered.
  • Why it's built this way: the same AddOptions(...).Bind(...).ValidateDataAnnotations().ValidateOnStart() treatment as every other settings class in the framework (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:187-190) means an out-of-range cap, a negative retention window or a recovery window past a day fails the host at startup, not at the first login. Defaulting Enabled to false is the safe direction for a multi-service host: a service that never opts in never grows a table it does not own. Defaulting LostResponseRecoveryMinutes to 0 keeps the strict BR-206 answer unless a host with mobile clients chooses the trade-off.
  • Where it's used: bound at MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:187-190; injected as IOptions<RefreshSessionSettings> into AuthSessionIssuer (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Sessions/AuthSessionIssuer.cs:57, read for the reuse grace at :601, the lost-response recovery window at :624 and the cap at :707), into EFRefreshSessionStore (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Auth/EFRefreshSessionStore.cs:38, which routes by DataSourceName at :357), and into RefreshSessionCleanupService (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Auth/RefreshSessionCleanupService.cs:56, snapshotted at :55). The design-time context helper supplies an instance (with Enabled = true and DataSourceName set to the context's physical source) to the refresh-session model contributor when EnableRefreshSessions is set, so dotnet ef can build a model that includes the table (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/Design/DesignTimeDbContextHelper.cs:196-197). The app Identity services do not take it: the issuer owns it, so ADC's AuthenticationService has no reference to it.

SoftDeletedUserCache

MMCA.Common.Application · MMCA.Common.Application.Auth · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/SoftDeletedUserCache.cs:19 · Level 1 · class (static)

  • What it is: the shared cache contract for the soft-deleted user marker (BR-133), which now means "deleted or locked": the key shape, the marker lifetime, and the helpers that write and clear it. The API middleware reads the marker on every authenticated request and answers 401 while it is set; the module that soft-deletes a user, an administrator's lock (UserAdministrationServiceBase) and a machine-client revocation write it, and an unlock clears it (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/SoftDeletedUserCache.cs:6-12).

  • Depends on: ICacheService from MMCA.Common.Application.Interfaces (:2), CrossServiceCacheKeys for the unqualified key prefix, the UserIdentifierType alias, and System.Globalization.CultureInfo (BCL, :1).

  • Concept introduced: revoking a stateless credential without a per-request lookup. [Rubric §11, Security] assesses whether a revoked principal actually loses access, and [Rubric §12, Performance & Scalability] assesses whether such a concern is factored so both ends share one definition. A JWT is a bearer credential: signature validation never asks "is this account still active?", so soft-deleting or locking a user leaves an already-issued access token passing validation until it expires (ADR-047). The textbook fixes (a deny-list, or an account-status query on every request) reintroduce exactly the per-request state that stateless JWT was chosen to avoid. This type is the middle path: a short-lived cache marker written at deletion or lock time and read cheaply on the hot path.

    The remarks (:13-18) explain why the constants live in the Application layer rather than next to the middleware that reads them: a downstream application deleting an account has to write the exact same key the middleware reads, and a private constant in the presentation layer is unreachable from an application-layer command handler. Same reasoning as IdempotencyHeaders, applied one layer up.

  • Walkthrough: six static members, no state.

    • A private DefaultClockSkew of 5 minutes (:25), the JWT bearer library's default, used as the fallback when the host's skew is unknown. The framework's own validators set 30 seconds, so the fallback errs on the long side (:21-24).
    • MarkerDuration => TimeSpan.FromMinutes(20) (:44). The remarks (:30-43) justify the number rather than leaving it magic: the marker must outlive every access token issued before the delete or lock. A host that does not run Identity registers no validator query, and the Identity host's query checks deletion only, so the marker is the only thing that rejects a deleted user's token on the first and a locked user's on any host. A token is accepted until its expiry plus the bearer clock skew. The framework's validators set a 30-second skew, but a host may configure its own bearer validator, so the marker covers the library default: the default 15-minute access-token lifetime (the BR-205 default on ITokenService) plus 5 minutes. It is a constant because the static helper cannot reach the JWT settings; a host with a longer lifetime or skew writes a longer marker through MarkerDurationFor. Only positive markers are written.
    • MarkerDurationFor(TimeSpan accessTokenLifetime, TimeSpan? clockSkew = null) (:54-58) returns the lifetime plus the skew (the 5-minute default when null), never less than MarkerDuration (:56-57).
    • KeyFor(UserIdentifierType userId) (:76-77) builds {CrossServiceCacheKeys.Prefix}user:deleted:{userId} through string.Create(CultureInfo.InvariantCulture, ...). The remarks (:66-69) name the bug the invariant culture prevents: an identifier renders differently under some cultures (digit shapes, group separators), so a culture-sensitive key would be written under one request's culture and missed under another, silently letting a deleted user keep making requests. The second paragraph (:70-74) explains the prefix: the Identity service writes the marker and every other service's middleware reads it, so the key must not be qualified with each host's own namespace, or a service that does not host Identity would never see a lock.
    • MarkDeletedForAsync(ICacheService cache, UserIdentifierType userId, TimeSpan duration, CancellationToken cancellationToken = default) (:100-120) is the one writer, with an explicit lifetime the caller sizes through MarkerDurationFor. It null-guards the cache (:106), then writes true under KeyFor(userId) (:111) and reads it back through ICacheService.GetFromSharedStoreAsync<bool?> (:112), the same read the middleware makes, up to two attempts (:109-116). If the shared store still does not hold the marker it throws InvalidOperationException (:118-119). The remarks (:92-99) give the reason: a two-level cache does not report a failed shared-store write (HybridCache logs the L2 fault and keeps only this process's local copy, which no middleware reads), so without the read-back a lock or erasure during a shared-store fault would look written while every already-issued token kept working. The exception lets the caller surface it.
    • ClearMarkerAsync(cache, userId, ...) (:137-145) removes the marker through ICacheService.RemoveAsync (:144), so a token issued after an unlock is accepted at once. The remarks (:130-136) explain why that is enough on every replica: another replica may still hold a local copy, but the middleware never reads one, it reads the marker through GetFromSharedStoreAsync.
  • Why it's built this way: publishing the key shape and the TTL as framework API is what keeps the writers and the reader honest, and it is a precondition for the module boundary in ADR-047: Identity owns the delete and the lock, every service hosts the middleware, and the only thing they share is a cache entry rather than a database. [Rubric §7, Microservices Readiness] applies directly: an extracted service can enforce the revocation without a reference to the Identity database.

  • Where it's used: read by SoftDeletedUserMiddleware, which builds the key (MMCA.Common/Source/Presentation/MMCA.Common.API/Middleware/SoftDeletedUserMiddleware.cs:85) and, when it caches a deleted answer itself, sizes it with MarkerDurationFor(tokens.AccessTokenLifetime, ...) or falls back to MarkerDuration when no ITokenService is registered (:177-180). Written through SoftDeletedUserMarkerWriter, the default ISoftDeletedUserMarkerWriter, which writes through MarkDeletedForAsync for MarkerDurationFor(tokenService.AccessTokenLifetime) and clears through ClearMarkerAsync (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/SoftDeletedUsers/SoftDeletedUserMarkerWriter.cs:17-25). The shared delete workflow calls that writer (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/DeleteUser/DeleteUserHandlerBase.cs:207) and catches any non-cancellation fault, the unconfirmed-write exception included, logging it (:209-211) so a failed marker cannot turn a committed erasure into an error the caller would retry. MachineClientService writes the marker for a revoked client's service account with a lifetime computed from its own token lifetime (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/MachineClients/MachineClientService.cs:261-263).

  • Caveats / not-in-source: the marker is best effort at the reader by design: the middleware fails open on a cache fault (SoftDeletedUserMiddleware.cs:98). At the writer the read-back turns a silently lost write into an exception, and what happens next is the caller's choice: the delete workflow logs it and continues (DeleteUserHandlerBase.cs:209). The exposure a lost marker leaves is bounded by the access-token lifetime, which is the trade-off ADR-047 accepts explicitly.

UnconfiguredPermissionRegistry

MMCA.Common.Application · MMCA.Common.Application.Auth · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/UnconfiguredPermissionRegistry.cs:20 · Level 1 · class (internal sealed partial)

  • What it is: the fallback IPermissionRegistry (and, since it also implements IPermissionCatalog, the fallback catalog) for a host that wired the CQRS pipeline without declaring any role-to-permission grants. It grants nothing, so a permission-gated command or query is denied rather than allowed, and it logs one warning naming the call that would fix it (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/UnconfiguredPermissionRegistry.cs:6-11).
  • Depends on: IPermissionRegistry and IPermissionCatalog (:20), IRequiresPermission by reference in the doc comment (:9), and Microsoft.Extensions.Logging for the source-generated log message (:1).
  • Concept introduced: failing closed, and only where it costs nothing. [Rubric §11, Security] assesses the direction a misconfiguration fails in: a registry that answered "no permission model, therefore allow" would silently open every gated request, so this one denies, and now that it doubles as the fallback IPermissionCatalog it renders an empty catalog rather than throwing, so a role-administration screen on an unconfigured host reads as "this host grants nothing yet" instead of failing (:225-228). [Rubric §13, Observability & Operability] assesses whether an operator can tell why: the log message spells out the remedy verbatim (:264-267, naming AddAuthorizationPolicies() / AddPermissions(...) and the required ordering before AddApplicationDecorators()). The second half of the doc comment (:12-17) is the more interesting teaching point and is an availability story rather than a security one: the two authorization decorators are registered unconditionally and take an IPermissionRegistry constructor dependency, so without any registration the whole pipeline fails to activate and a small app with no Identity module answers 500 on every read, not only the gated ones. This type turns a total activation failure into a correct, noisy denial on the subset of requests that actually declare a permission.
  • Walkthrough: two fields, two catalog properties, and three methods.
    • private static readonly HashSet<string> None = [] (:221) is the single empty grant set every permission call returns, and private int _warned (:223) is the one-time-warning latch.
    • IReadOnlyList<string> Roles => [] (:229) and IReadOnlyList<string> Permissions => [] (:232) are the IPermissionCatalog members: both always empty, so an unconfigured host's role editor renders no roles and no permissions to pick from rather than erroring.
    • GetPermissions(string role) (:235-239) warns then returns None.
    • HasPermission(IEnumerable<string> roles, string permission) (:242-249) argument-guards both parameters (:244-245) before warning and returning false, so a caller bug still surfaces as an ArgumentException rather than being swallowed by the stub.
    • WarnOnce() (:256-262) uses Interlocked.Exchange(ref _warned, 1) == 0 (:258) so concurrent requests produce exactly one log line. The comment (:251-255) explains why the warning is deferred to the first permission check instead of emitted at startup: a host with no permission-gated request is correctly configured and simply never needs a registry, so warning at boot would cry wolf. Reading the catalog properties never triggers the warning, only GetPermissions/HasPermission do.
    • LogNoPermissionsConfigured (:264-267) is a [LoggerMessage] source-generated Warning, which is why the class is partial.
  • Why it's built this way: it is registered with TryAddSingleton from inside AddApplicationDecorators() (MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.cs:154), and the surrounding comment (:119-123) states both halves of the rule: TryAdd so a host that already declared its grants (via AddAuthorizationPolicies() or AddPermissions(...), both of which run before this call) keeps its own registry and never constructs this type, and here rather than in AddApplication() so the registration lands exactly where the decorators that need it are wired. Adding IPermissionCatalog to the same fallback type, rather than a second stub class, means the one TryAddSingleton call keeps both ports covered from the same no-op instance.
  • Where it's used: reached through the IPermissionRegistry dependency of the authorization command and query decorators in the CQRS pipeline (see group 05), and through the IPermissionCatalog dependency of IRoleAdministrationService's GetCatalogAsync on a host that never configured a registry.
  • Caveats / not-in-source: internal, so it is not part of the framework's public API and cannot be referenced or asserted against from a consumer's code.

ILoginProtectionService

MMCA.Common.Application · MMCA.Common.Application.Auth · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/ILoginProtectionService.cs:10 · Level 3 · interface

  • What it is: the application-layer contract for brute-force and rate-limit protection on authentication endpoints: lockout checks, failed-attempt increments, successful-login resets, and registration rate-limiting per IP address.

  • Depends on: Result from MMCA.Common.Shared.Abstractions (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/ILoginProtectionService.cs:1).

  • Concept introduced: rate limiting as a first-class application concern. [Rubric §11, Security] assesses brute-force protection on auth flows, and [Rubric §12, Performance & Scalability] assesses whether such a policy is extracted to a port so the application layer can reason about it without coupling to a specific store (the doc comment at :7-8 names both a distributed and an in-memory cache as valid backers). Returning Result from CheckLockoutAsync (:18) and CheckRegistrationRateLimitAsync (:42) makes "account is locked out" a normal control-flow branch rather than a thrown exception.

  • Walkthrough: five async methods in two scopes.

    • Email-scoped (failed-login lockout): CheckLockoutAsync (:18) returns a failure result when the email is currently locked; IncrementFailedAttemptsAsync (:26) records a failure and, per the doc comment (:20-22), applies exponential-backoff lockout once the maximum is exceeded; ResetFailedAttemptsAsync (:33) clears the counter after a successful login.
    • IP-scoped (registration flood): CheckRegistrationRateLimitAsync (:42) and IncrementRegistrationCountAsync (:49) throttle account creation per client IP. Both accept a nullable ipAddress and skip the check when it is null, so a host that cannot resolve the caller IP degrades to no limit rather than blocking everyone; CheckRegistrationRateLimitAsync returns Result.Success() in that case (doc comment, :36-37).

    All five take a CancellationToken with a default argument, per convention.

  • Why it's built this way: keeping the protection policy behind an interface lets the shared authentication workflow compose it in while the concrete cache mechanics stay in the implementation; the null-IP skip keeps the limiter from becoming an availability hazard (ADR-029).

  • Where it's used: injected into AuthenticationServiceBase<TUser> (constructor parameter at MMCA.Common/Source/Core/MMCA.Common.Application/Auth/AuthenticationServiceBase.cs:81), which calls all five across its login and registration flows: CheckLockoutAsync (:184), IncrementFailedAttemptsAsync on both the unknown-email and wrong-password branches (:211, :221), ResetFailedAttemptsAsync on success (:281), CheckRegistrationRateLimitAsync (:329) and IncrementRegistrationCountAsync (:392). The concrete, cache-backed LoginProtectionService (tuned by LoginProtectionSettings, bound at MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:173-176) implements it, and the framework registers that pairing at :165.

IPasswordResetTokenService

MMCA.Common.Application · MMCA.Common.Application.Auth · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/IPasswordResetTokenService.cs:10 · Level 3 · interface

  • What it is: the two-method port behind the forgot-password workflow: issue a single-use reset token for an email address, and validate-then-consume a token presented back by the user. Implementations keep the token material outside the database, hashed at rest, and enforce both the per-email request throttle and the per-token validation-attempt cap (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/IPasswordResetTokenService.cs:5-9).

  • Depends on: Result and its generic form from MMCA.Common.Shared.Abstractions (:1), plus the UserIdentifierType alias. Its Infrastructure adapter is PasswordResetTokenService, backed by ICacheService and tuned by PasswordResetSettings.

  • Concept introduced: a single-use credential without a schema change. [Rubric §11, Security] assesses how a secondary credential is minted, stored, and retired; [Rubric §8, Data Architecture] assesses whether short-lived state earns a place in the durable store. A reset token is not durable data: it is valid for minutes and must stop working the instant it is redeemed. Putting it in columns on the user row costs a migration in every consumer and needs a sweeper to reap expired rows, because expiry is not something a table enforces; a self-contained signed payload needs no store but then cannot be single-use, since a signed token that has not expired stays valid however many times it is presented. This port takes the third path and hides the choice: the handlers see two Result-returning methods, and the cache substrate is entirely the implementation's business (ADR-091).

    The second teaching point is in the return shapes. ValidateAndConsumeAsync is documented to collapse unknown, expired, mismatched, and attempt-capped into one generic failure (:32-35), so the redeem endpoint cannot be used to distinguish a wrong token from an expired one from an address that was never issued a token. The issue path is throttled rather than refused loudly, for the same anti-enumeration reason the forgot-password handler answers success to every input.

  • Walkthrough: two members.

    • Task<Result<string>> IssueAsync(string email, UserIdentifierType userId, CancellationToken cancellationToken = default) (:23) returns the raw token to email, or a failure when the per-email request throttle has been exceeded. The doc comment (:12-15) states the replace semantics: issuing overwrites any token already outstanding for that address, so requesting a new link immediately stops the older one from working. The userId parameter is what the token resolves back to at redeem time, which is why the redeem call never has to trust an identifier supplied by the caller.
    • Task<Result<UserIdentifierType>> ValidateAndConsumeAsync(string email, string token, CancellationToken cancellationToken = default) (:36) validates the presented token against the outstanding record and consumes it on success, so a token never redeems twice (:25-28), returning the account the token belongs to.
  • Why it's built this way: taking email on both methods, rather than treating the token as self-describing, is what lets the implementation key its records by address and enforce the per-address throttle and the one-active-token rule at the same key. Returning Result<UserIdentifierType> rather than a boolean means the redeem handler gets the account identity from the token store itself. See PasswordResetTokenService for the mechanics the port hides: a 32-byte random token (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/PasswordResetTokenService.cs:41), only its digest stored, an attempt counter, and an address normalized through Email before it becomes a cache key (:34-45) so User@x.com and user@x.com cannot hold independent tokens for one account.

  • Where it's used: injected into the shared ForgotPasswordHandlerBase<TUser, TCommand> (constructor parameter at MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/ForgotPassword/ForgotPasswordHandlerBase.cs:65, called at :124, where a throttled issue is logged and still answered as success at :127-128) and into ResetPasswordHandlerBase<TUser, TCommand> (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/ResetPassword/ResetPasswordHandlerBase.cs:45, redeemed at :61-62). Both apps' sealed subclasses take the same dependency, for example ADC's ForgotPasswordHandler and ResetPasswordHandler. The framework registers the concrete as scoped at MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:183.

AuthSignInMetrics

MMCA.Common.Application · MMCA.Common.Application.Auth · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/AuthenticationServiceBase.cs:1101 · Level 3 · class (internal static)

  • What it is: the OpenTelemetry instrument for password sign-in outcomes: the MMCA.Common.Auth meter instance of the Application assembly, carrying one counter, mmca.auth.signin, tagged by a low-cardinality outcome. It is declared in the same file as AuthenticationServiceBase<TUser>, after the log companion (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/AuthenticationServiceBase.cs:1094-1101).
  • Depends on: System.Diagnostics.Metrics for Meter and Counter<long> (BCL, AuthenticationServiceBase.cs:2), Error and TwoFactorErrors (its TwoFactorRequiredCode) for classifying a second-factor failure. Nothing else.
  • Concept introduced: an outcome tag, never an identity, on a security metric. [Rubric §13, Observability] assesses whether the system exposes the signals an operator needs, and [Rubric §11, Security] assesses whether telemetry leaks personal data. The doc comment (:1094-1100) sets the rule in one line: tags carry only the low-cardinality outcome, never an address, a user id or a client IP. Seven fixed values keep the series count bounded however many accounts exist, and a rise in invalid_credentials or locked_out is visible without the metric pipeline ever holding who was attempted. The same comment records a packaging consequence: a host exports the meter by registering its name, the Aspire service defaults already do, and the name is duplicated there as a literal because MMCA.Common.Aspire has no reference to Application (:1095-1098).
  • Walkthrough: eleven internal members.
    • MeterName = "MMCA.Common.Auth" (:1104).
    • Seven outcome constants (:1107-1125): Success ("success", a token pair was issued), InvalidCredentials ("invalid_credentials": unknown address, wrong password, no password credential, or a request that failed validation), LockedOut ("locked_out"), SecondFactorRequired ("second_factor_required": the password verified and no code was supplied), SecondFactorFailed ("second_factor_failed"), EmailNotConfirmed ("email_not_confirmed") and Rejected ("rejected": the app gate or the issuance refused the account).
    • The Meter built from MeterName (:1130), internal rather than private because it is this assembly's one instance of the meter and AuthSecurityMetrics creates its counter on it (doc comment, :1127-1129), and the SignIns counter (:1133-1136), created as mmca.auth.signin with unit {attempt}, one count per LoginAsync call.
    • ForSecondFactorFailure(IEnumerable<Error> errors) (:1145-1146) maps a failed challenge to second_factor_required when any error carries TwoFactorErrors.TwoFactorRequiredCode (no code supplied) and to second_factor_failed for anything else, a wrong code, a replay, or a redemption that could not be persisted.
    • Record(string outcome) (:1150-1151) adds 1 to the counter with the single outcome tag.
  • Why it's built this way: a static class with a static meter matches how .NET metrics are meant to be created (one instrument per process, recorded from anywhere), and keeping it internal beside the workflow means the outcome vocabulary changes in the same file as the branches that emit it. Counting a validation failure as invalid_credentials rather than adding an eighth value keeps the tag set small and matches what the caller is told. Sharing the one Meter instance with the reuse counter keeps a second instance of the same name out of the assembly.
  • Where it's used: recorded only by AuthenticationServiceBase<TUser>'s LoginAsync, which records Success once the tokens are issued (AuthenticationServiceBase.cs:288) and routes every failure through the private SignInFailed helper (:978-986), which calls Record (:983) and then writes the matching Warning through AuthenticationServiceLog. The second-factor branch picks its tag through ForSecondFactorFailure (:248). Its Meter also backs AuthSecurityMetrics's counter (:1164). No usage outside the defining file; the background is ADR-041.

AuthSecurityMetrics

MMCA.Common.Application · MMCA.Common.Application.Auth · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/AuthenticationServiceBase.cs:1161 · Level 4 · class (internal static)

  • What it is: the refresh-token reuse counter, mmca.auth.refresh_reuse, created on the same MMCA.Common.Auth meter as AuthSignInMetrics's mmca.auth.signin. It is declared last in the same file as AuthenticationServiceBase<TUser> (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/AuthenticationServiceBase.cs:1154-1171).
  • Depends on: System.Diagnostics.Metrics for Counter<long> (BCL, AuthenticationServiceBase.cs:2) and the AuthSignInMetrics.Meter instance it creates its counter on (:1164). Nothing else.
  • Concept introduced: one meter name, several assemblies, no tags. [Rubric §13, Observability] assesses whether the security signals an operator needs are exported, and [Rubric §11, Security] whether they leak identity. The doc comment (:1154-1160) lays out the layout: the MMCA.Common.Auth meter name also carries mmca.auth.lockout (recorded by the Infrastructure login protection) and mmca.auth.admin_action (recorded by the API administration controllers), each declared in the assembly that records it, so an exporter subscribed to the one name sees all of them. The counter carries no tag at all: never an address, a user id or a client IP. A rise in reuse detections (a rotated refresh token presented again, BR-206) is a theft signal an operator can alert on without the pipeline knowing whose token it was.
  • Walkthrough: two internal members.
    • RefreshReuse (:1164-1167), a Counter<long> named mmca.auth.refresh_reuse with unit {event}, created on AuthSignInMetrics.Meter; its doc comment (:1163) defines the event: a presented refresh token had already been rotated, so its whole family was revoked.
    • RecordRefreshReuse() (:1170) adds 1 with no tag.
  • Why it's built this way: the reuse decision lives in the session issuer, not in the sign-in workflow, so it gets its own small holder rather than an eighth sign-in outcome; creating it on the existing Meter instance rather than a new Meter(MeterName) keeps one instance of the name per assembly. Keeping it internal keeps the metric vocabulary out of the public surface.
  • Where it's used: recorded once, by AuthSessionIssuer's private RevokeFamilyOnReuseAsync, after the family is revoked and saved and the reuse Warning is logged (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Sessions/AuthSessionIssuer.cs:699). Background: ADR-050 (rotation and reuse detection) and ADR-041.

AuthenticationServiceLog

MMCA.Common.Application · MMCA.Common.Application.Auth · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/AuthenticationServiceBase.cs:1053 · Level 5 · class (internal static partial)

  • What it is: the source-generated log-message companion of AuthenticationServiceBase<TUser>, declared in the same file after the base closes. It carries two messages, PasswordRehashRejected and SignInFailed, and the EmailLogHash helper that makes an address safe to put in the second (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/AuthenticationServiceBase.cs:1053-1092).
  • Depends on: Microsoft.Extensions.Logging for ILogger, LogLevel and the [LoggerMessage] generator (AuthenticationServiceBase.cs:6), System.Security.Cryptography and System.Text for the SHA-256 digest (:4-5), the Email value object for normalizing the address, and the solution-wide UserIdentifierType alias for the user-id parameter (:1059).
  • Concept: a non-generic log companion beside a generic base, and an address that never reaches a log. [Rubric §13, Observability] assesses structured, allocation-free logging with stable message templates, and [Rubric §15, Best Practices & Code Quality] covers keeping a public type's shape free of incidental requirements. The [LoggerMessage] source generator needs a partial method on a partial type. Putting it on the public abstract base would force that base to be partial and make the generated method generic over TUser; the doc comment (:1047-1050) names the alternative taken: "a separate non-generic companion so the public base does not have to be partial". The class is internal, so it is not part of the framework's public surface. [Rubric §11, Security] applies to the sign-in line: a failed sign-in is logged with a 12-hex-character (48-bit) prefix of the SHA-256 of the normalized address, never the address, and the comment (:1065-1071) gives both halves of the reasoning: it is the same digest the login-protection counters key on, so the two log streams correlate, and a 48-bit prefix matches too many addresses to name one.
  • Walkthrough: three members and one private constant.
    • EmailLogHashLength = 12 (:1054), private, the number of hex characters a log line carries.
    • PasswordRehashRejected(ILogger logger, UserIdentifierType userId, string errorCodes) (:1059) logs at LogLevel.Warning (:1057) with the template "Password rehash for user {UserId} was refused by the aggregate ({ErrorCodes}); the sign-in is unaffected and the stored hash is unchanged" (:1058). The template states the consequence for an operator reading it: the sign-in already succeeded and nothing was written.
    • SignInFailed(ILogger logger, string outcome, string emailHash) (:1062-1063) logs at Warning with "Password sign-in failed ({Outcome}) for address hash {EmailHash}", where Outcome is one of the AuthSignInMetrics tag values.
    • EmailLogHash(string? email) (:1074-1089) normalizes a blank address to the empty string (:1077-1080), otherwise takes Email.Create(email)'s normalized value and falls back to Trim().ToLowerInvariant() for a malformed address (:1084, under a scoped CA1308 suppression that names the RFC 5321 lowercase rule it matches, :1083), and returns the first 12 uppercase hex characters of the SHA-256 digest (:1088).
  • Why it's built this way: a refused rehash is a domain answer (the aggregate's RehashPassword returned a failure), not an exception, so it never reaches the best-effort wrapper's own failure log and metric; that message is what makes the branch visible. Logging the error codes joined with ", " rather than the error messages keeps the line free of any user-facing text. A failed sign-in needs a per-address handle for an investigation (the same address failing repeatedly) without writing personal data, which is what the truncated digest gives. The background is ADR-133 (the stored hash carries its work factor and is upgraded on sign-in), ADR-096 (best-effort side effects never fail the primary operation) and ADR-041.
  • Where it's used: PasswordRehashRejected is called once, from the private RehashPasswordIfNeededAsync of AuthenticationServiceBase<TUser> when IPasswordRehashableUser.RehashPassword fails (AuthenticationServiceBase.cs:1025-1032). SignInFailed and EmailLogHash are called together from the base's private SignInFailed helper (:982), which every failing branch of LoginAsync returns through. Both use the base's overridable Logger property as the sink, which defaults to NullLogger.Instance (:153), so the lines are emitted only by an app subclass that overrides Logger with an injected logger. No usage outside the defining file.

AuthenticationValidators

MMCA.Common.Application · MMCA.Common.Application.Auth · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/AuthenticationValidators.cs:33 · Level 5 · class (sealed)

  • What it is: a tiny parameter object that bundles the three FluentValidation validators the authentication workflow needs (login, registration, refresh), the authentication service's logger, the optional Terms of Service version registration requires, and, when the host registered one, the sign-in second-factor challenge, into one injectable dependency.
  • Depends on: FluentValidation's IValidator<T> (NuGet, :1) over the request DTOs LoginRequest, RegisterRequest, and RefreshTokenRequest (all in MMCA.Common.Shared.Auth), ILoggerFactory and ILogger from Microsoft.Extensions.Logging (:2) for the service's logger, IOptions<LegalAcceptanceOptions> and LegalAcceptancePolicy from MMCA.Common.Application.Auth.Legal for the terms check, and ITwoFactorAuthenticator for the optional challenge.
  • Concept introduced: the parameter object as a constructor-arity guardrail. [Rubric §1, SOLID] assesses whether a class stays a single, cohesive responsibility rather than sprawling into a god class, and [Rubric §15, Best Practices & Code Quality] assesses whether cross-cutting dependencies are grouped so a class can grow without exploding its constructor. The doc comment (:10-16) states the exact motive: collapsing three closely-related dependencies into one keeps the app's AuthenticationService below the application-service constructor-arity ceiling (a god-class analyzer guardrail) without giving up per-request validation. Because the request DTOs already live in MMCA.Common.Shared.Auth, the bundle is app-agnostic, which is why it could be hoisted out of the apps into the framework. The same move is now used three more times: the logger, the terms options and the second-factor authenticator ride in here, so each reaches every app's subclass through the container with no constructor change (the loggerFactory parameter doc, :20-25, says so for the logger: the failed sign-in Warnings are written by default). The pressure is real rather than theoretical: ADC's subclass already carries a long primary constructor (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/AuthenticationService.cs:52-69, the bundle at :56).
  • Walkthrough: two constructors, one constant and six get-only members.
    • The primary constructor (:33-38) takes the three IValidator<T> instances, a required ILoggerFactory loggerFactory, and an optional IOptions<LegalAcceptanceOptions>? legalAcceptance = null.
    • LoggerCategory (:41) is the public constant "MMCA.Common.Application.Auth.AuthenticationService", the category of the logger the bundle creates.
    • A second public constructor (:56-63) takes the same five arguments, legalAcceptance without a default, plus a required ITwoFactorAuthenticator twoFactor, chains to the primary and sets TwoFactor. Its doc comment (:42-55) gives the selection rule: the container picks it only when an ITwoFactorAuthenticator is registered (by AddTwoFactorAuthentication(configuration)), so a host that has not adopted two-factor resolves the primary constructor and is unchanged. The class-level RS0027 suppression (:32) records why the shipped constructor keeps its optional parameter: removing the default would break every call that omits it, and the longer overload has no optional parameter, so positional calls with four or five arguments bind unambiguously.
    • Login (:66), Register (:69) and Refresh (:72) surface the validators by name.
    • Logger (:78) is created once from the factory under LoggerCategory by the private CreateLogger (:93-97), which null-guards the factory. Its doc comment (:74-77) names what it carries: the failed password sign-in Warnings and the best-effort password rehash after a successful sign-in.
    • CurrentTermsVersion (:84) returns LegalAcceptancePolicy.ResolveCurrentVersion(legalAcceptance?.Value): the Terms of Service version registration requires, or null when acceptance is not configured.
    • TwoFactor (:91) is the sign-in challenge, or null when the host registered none. Its doc comment (:86-90) fixes precedence: AuthenticationServiceBase uses it only when its own twoFactor constructor argument is null, so an explicit argument wins. Beyond the resolver call and the logger creation the type has no logic.
  • Why it's built this way: a sealed grouping type with get-only properties is the cheapest way to fold cohesive dependencies into one constructor slot, so the workflow base can validate each request shape, log its failures, and challenge a second factor, without pushing its constructor or the app's over the arity limit; DI resolves the underlying services and composes them into this one object, choosing the constructor by what is registered. Two of the three validators (LoginRequestValidator, RefreshTokenRequestValidator) come from the framework assembly, while IValidator<RegisterRequest> is satisfied by the app's own RegisterRequestValidator, so the bundle is the point where framework and app validation meet.
  • Where it's used: injected into AuthenticationServiceBase<TUser> (constructor parameter at MMCA.Common/Source/Core/MMCA.Common.Application/Auth/AuthenticationServiceBase.cs:82), whose LoginAsync, RegisterAsync, and RefreshTokenAsync call validators.Login (:162), validators.Register (:302), and validators.Refresh (:402) respectively before doing any work, which re-exposes CurrentTermsVersion as a protected property (:145) that RegisterAsync tests (:311), whose SignInFailed helper and password rehash log through validators.Logger (:984, :1015, :1028), and whose ChallengeSecondFactorAsync resolves twoFactor ?? validators.TwoFactor (:864). It is registered by each app's Identity module rather than by the framework, since one of its dependencies is app-owned: MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/DependencyInjection.cs:36 and MMCA.Store/Source/Modules/Identity/MMCA.Store.Identity.Application/DependencyInjection.cs:42, both TryAddScoped<AuthenticationValidators>(). AddTwoFactorAuthentication registers the authenticator the longer constructor picks up (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Auth.cs:66, with the by-type registration precondition stated at :38-40), and the terms options are bound by the opt-in AddLegalAcceptance(configuration) (DependencyInjection.Auth.cs:148-154).

IAuthenticationService

MMCA.Common.Application · MMCA.Common.Application.Auth · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/IAuthenticationService.cs:12 · Level 5 · interface

  • What it is: the application-layer contract for the Identity module's authentication workflows: login, registration, token refresh, per-device and global session revocation, session and sign-in history listing, external (OAuth) login, and the two credential-proved sign-ins (a redeemed sign-in link and a verified passkey).

  • Depends on: LoginRequest, RefreshTokenRequest, RegisterRequest, AuthenticationResponse, RegistrationOutcome, RefreshSessionSummaryResponse, SignInSummaryResponse, SignInLinkErrors and PasskeyErrors (the defaults' failures), Result, Error, and the UserIdentifierType alias.

  • Concept introduced: default interface methods for optional capabilities. [Rubric §1, SOLID] (interface segregation and dependency inversion): three members ship a default implementation in the interface itself, so an implementation that has not adopted a capability inherits a safe answer and need not override anything. SignInVerifiedEmailOwnerAsync (:186-192) and SignInWithPasskeyAsync (:209-215) reject through SignInLinkErrors.NotSupported and PasskeyErrors.NotSupported, so an implementation that has not adopted sign-in links (ADR-116) or passkeys (ADR-139) keeps compiling and never opens a session through that path; and HasSignInMethodBesidesPasskeysAsync (:229-232) answers false, which the remarks (:226-227) justify as the recoverable direction: refusing to delete the last passkey can be undone, a locked-out account cannot. The counter-example is just as deliberate: ExternalLoginAsync (:163-170, ADR-036) has no default body, and the remarks (:144-149) say why: AuthenticationServiceBase declares it abstract, so an implementation whose signature drifts from the interface's fails to compile instead of being silently bypassed by a default. [Rubric §11, Security]: every sign-in member returns Result<AuthenticationResponse>, so auth outcomes flow as values and no exception leaks credential detail to the caller.

    The second concept the signatures teach is that a session is a device, not a user. LoginAsync, RegisterAsync and RefreshTokenAsync all take optional ipAddress and userAgent (:25-26, :41-42, :56-57) recorded on the session row, and the doc comments state the invariant each time: signing in opens a session for the calling device and leaves the user's other devices signed in (:15-16), and refreshing rotates the presenting device's session only (:46-47).

  • Walkthrough: twelve methods, all async, all ending in a CancellationToken.

    • LoginAsync(LoginRequest, string? ipAddress = null, string? userAgent = null, ...) returns Result<AuthenticationResponse> (:23-27).
    • RegisterAsync(RegisterRequest, string? ipAddress = null, string? userAgent = null, ...) (:39-43); the ipAddress does double duty, feeding ILoginProtectionService's registration rate limit and the new session row (:35). The summary (:30-32) adds one outcome to the contract: when the host requires a confirmed address and the new account is unconfirmed, the result is a success carrying RegistrationOutcome.ConfirmationPending and no session is opened.
    • RefreshTokenAsync(RefreshTokenRequest, string? ipAddress = null, string? userAgent = null, ...) (:54-58) exchanges an expired access token plus a valid refresh token for a rotated pair, recording the caller's IP and user agent on the rotated session.
    • RevokeTokenAsync(UserIdentifierType userId, string? refreshToken = null, ...) (:69-72) signs one device out. The documented fallback is the interesting part (:61-63): passing no token, or one that does not belong to this user, revokes every session the user holds, which the comment calls the safe reading of "log me out" from a caller that cannot produce its refresh token.
    • RevokeAllSessionsAsync(UserIdentifierType userId, ...) (:81-83) signs every device out: a password change, an admin lockout, or an explicit "sign out everywhere".
    • GetSessionsAsync(UserIdentifierType userId, Guid? currentSessionId = null, ...) (:98-101) lists live sessions newest first with the caller's own device marked. currentSessionId is the caller token's sid claim and is used only to set RefreshSessionSummaryResponse.IsCurrent; passing null marks no row (:92-94).
    • GetSignInsAsync(UserIdentifierType userId, Guid? currentSessionId = null, ...) (:115-118) lists the user's sign-in history: 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, over what the session store retains (RefreshSessions:RetentionDays, 30 by default) (:104-106). currentSessionId sets SignInSummaryResponse.IsCurrent the same way.
    • RevokeSessionByIdAsync(UserIdentifierType userId, Guid sessionId, ...) (:134-137) revokes one named device. The remarks (:124-128) fix two behaviors as contract: an unknown id and another account's id both return NotFound and are indistinguishable, so a caller cannot probe for another user's sessions; and revoking an already-revoked session changes nothing and also returns NotFound with the code Auth.SessionAlreadyRevoked (:126-128), so a device list can tell the user the device was already signed out instead of claiming this request signed it out.
    • ExternalLoginAsync(loginProvider, providerKey, email, firstName, lastName, bool emailVerified, ...) (:163-170), the OAuth path. emailVerified is whether the provider asserted the address as verified (its email_verified claim as the framework's provider registrations map it, false when it asserted nothing, :156-160), and the remarks (:144-149) make it the only proof of the address the call receives: an implementation marks a new account's address confirmed, and links the login to an existing account found by address, only when it is true; otherwise a new account starts unconfirmed and an existing account is never linked by the address alone.
    • SignInVerifiedEmailOwnerAsync(UserIdentifierType userId, string? ipAddress = null, string? userAgent = null, ...) (:186-192) opens a session for an account whose owner has just redeemed a single-use sign-in link; the caller has already spent the token, and this member applies the same account gates a password sign-in does and mints the pair (:173-175).
    • SignInWithPasskeyAsync(UserIdentifierType userId, ...) (:209-215) does the same after a verified passkey assertion, and the resulting access token carries mfa=passkey (:195-198).
    • HasSignInMethodBesidesPasskeysAsync(UserIdentifierType userId, ...) (:229-232) asks whether the account still has a password or an external login, before its last passkey is deleted (:218-220).

    The doc comment (:6-9) also records a scope decision: password change is not on this interface. It is dispatched directly through its own command handler at the controller layer.

  • Why it's built this way: concentrating the token-issuing and session-management workflows behind one port keeps the Identity controllers thin and lets the protection and rate-limit policy (ILoginProtectionService) compose in; the defaulted members keep the contract stable across hosts that do and do not enable sign-in links or passkeys, the abstract-in-the-base external login forces every app to answer social login explicitly (an implementation or a refusal), and every credential-proved sign-in routes through the same account gates and issuance. Encoding the anti-probing and idempotent-revoke rules in remarks rather than leaving them to an implementation makes them testable expectations of every implementer.

  • Where it's used: implemented by AuthenticationServiceBase<TUser> (which realises every member except ExternalLoginAsync, declared abstract there so the app supplies it) and, through it, by each app's sealed AuthenticationService; consumed by the API controller bases (AuthControllerBase, OAuthControllerBase, TwoFactorControllerBase), by RedeemSignInLinkHandlerBase for the sign-in link redemption, and by the passkey sign-in flow.

RefreshSessionSignIn

MMCA.Common.Application · MMCA.Common.Application.Auth · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/RefreshSessionSignIn.cs:19 · Level 5 · record (sealed)

  • What it is: one sign-in as the session store aggregates it: its identifier, the instant its earliest retained session was issued, and its newest session (the head), which carries the last activity, the device and how the sign-in ended (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/RefreshSessionSignIn.cs:5-9).
  • Depends on: RefreshSession from MMCA.Common.Domain.Auth (:1). Nothing else.
  • Concept introduced: a sign-in is a rotation chain, not a row. [Rubric §8, Data Architecture] assesses whether read shapes match what the data means, and [Rubric §12, Performance & Scalability] assesses whether a read stays bounded as data grows. Every refresh rotates a session into a new row, so a user who stayed signed in for a month owns hundreds of rows for one sign-in. This record is the unit a sign-in history needs: one entry per chain, its start, and only its newest row. SignInId is the chain's shared RefreshSession.SignInId, or, for a row written before that column existed, the row's own Id (:10-13), so older data still lists. Head is read-only: a store may return it untracked, so a mutation on it is never persisted (:15-18).
  • Walkthrough: a positional sealed record with three members (:19): Guid SignInId, DateTime StartedAt (the UTC issue instant of the earliest retained session, :14) and RefreshSession Head. Value equality and immutability come from the record; there is no behavior.
  • Why it's built this way: aggregating in the store, and handing back this small projection, is what lets IRefreshSessionStore's GetRecentSignInsAsync bound its read by the number of sign-ins requested rather than by the user's total row count, so a sign-in that rotated a thousand times costs one entry. Carrying the whole head rather than a flattened DTO leaves the response shaping (device, end reason, current marker) to the application layer.
  • Where it's used: returned by IRefreshSessionStore.GetRecentSignInsAsync (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/IRefreshSessionStore.cs:80-83); produced by EFRefreshSessionStore (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Auth/EFRefreshSessionStore.cs:96) and by the test double InMemoryRefreshSessionStore; consumed by SignInHistory (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Sessions/SignInHistory.cs:45), which sits behind the issuer's ListSignInsAsync that AuthenticationServiceBase<TUser>'s GetSignInsAsync calls. Background: ADR-097.

IRefreshSessionStore

MMCA.Common.Application · MMCA.Common.Application.Auth · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/IRefreshSessionStore.cs:21 · Level 6 · interface

  • What it is: persistence for RefreshSession rows, one hashed refresh session per signed-in device (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/IRefreshSessionStore.cs:5-6). Sessions are added, looked up by token hash or by id, listed per user (live, unrevoked, all, or aggregated into sign-ins), counted per user, rotated, and saved.

  • Depends on: RefreshSession from MMCA.Common.Domain.Auth (:1), RefreshSessionSignIn for the sign-in aggregate, and the UserIdentifierType alias. The shipped implementation is EFRefreshSessionStore; the test double is InMemoryRefreshSessionStore (MMCA.Common/Source/Hosting/MMCA.Common.Testing/Support/InMemoryRefreshSessionStore.cs:27).

  • Concept introduced: a repository whose contract is deliberately missing an Update. [Rubric §1, SOLID] assesses interface segregation, and [Rubric §8, Data Architecture] assesses whether the persistence contract expresses the aggregate's rules. The doc comment (:8-14) explains the shape: sessions are mutated only through RefreshSession.Revoke on instances this store returned, so an implementation that tracks its entities persists a revocation with no update method at all, and TryRotateAsync is the one exception because rotation is a claim, not a mutation. The requirement that makes that safe is stated as a contract obligation, not left implicit: implementations must return tracked instances from every lookup except FindByIdUntrackedAsync, which is untracked by design and for reading only, because a no-tracking read anywhere else would accept revocations and rotations and drop them silently at save time (:15-19). This is the same trap called out for composed EF queries elsewhere in the framework, promoted here to interface documentation.

    The second concept is lookup by hash, never by token (:8, :37). The store never sees plaintext: callers hash first with RefreshSession.HashToken and search on the digest, which is what lets the table hold only digests. [Rubric §11, Security] applies directly.

  • Walkthrough: twelve members, none with a default body.

    • AddAsync(RefreshSession session, ...) (:26) stages an insert.
    • FindByTokenHashAsync(string tokenHash, ...) (:37) finds by digest including revoked and expired rows, and the comment (:29-32) marks that as load-bearing: a rotated token that comes back is found on its revoked row, which is the BR-206 reuse signal, so a store that filtered revoked rows out would report a replay as "unknown token" and never revoke the family.
    • GetUnrevokedByUserAsync(UserIdentifierType userId, ...) (:45-47) returns the user's un-revoked sessions oldest first, expired ones included since they still occupy a row, which is what makes both family revocation and cap eviction deterministic (:40-41).
    • GetAllByUserAsync(UserIdentifierType userId, ...) (:59-61) returns every session row the user holds, revoked and expired included, oldest first, as tracked instances. Account erasure needs the whole set: a revoked row still carries the IP address and user agent captured at issue time, so anonymizing only the un-revoked rows would leave the rest behind (:50-54).
    • GetRecentSignInsAsync(UserIdentifierType userId, int maxSignIns, ...) (:80-83) returns the user's newest maxSignIns sign-ins as RefreshSessionSignIn entries, newest first by StartedAt, aggregated in the store: one entry per RefreshSession.SignInId with its earliest issue instant and only its newest row (:64-68). A row with no SignInId (written before the column existed) is its own sign-in unless it was rotated away, in which case its successor stands for it (:68-69). Two obligations follow (:71-73): the returned heads are for reading only (the shipped EF store reads them untracked), and an implementation must bound what it reads by maxSignIns, never by the user's total row count.
    • GetUserIdsWithLiveSessionsAsync(DateTime now, int limit, ...) (:96-99) returns each user holding at least one live session at now exactly once, at most limit of them, where live means not revoked and ExpiresAt strictly after now (RefreshSession.IsActiveAt). The query is evaluated and bounded in the store, and a caller that must know whether the set was cut asks for one more than it accepts (:86-90).
    • QueryUserIdsWithLiveSessions(Type userEntityType, DateTime now) (:114) returns the same set as an unexecuted IQueryable<UserIdentifierType>? that composes into a query over the user entity, so a roster filter runs as one subquery in the database instead of shipping every signed-in id to the server (:102-109). Composition is only valid when both tables sit behind the same context instance, so the store answers null whenever the user entity does not resolve to the same physical data source as the sessions (a database-per-service host can split them) or it cannot compose at all, and the caller falls back to the bounded id list. [Rubric §8, Data Architecture] applies: the contract states the one condition under which a cross-table query is legal.
    • CountLiveSessionsByUserAsync(IReadOnlyCollection<UserIdentifierType> userIds, DateTime now, ...) (:125-128) counts live sessions for many users in one grouped query, never one per user; a requested user with no live session is absent from the result and duplicates count once (:117-121). The EF store implements the three live-session members at MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Auth/EFRefreshSessionStore.cs:222, :243 and :264.
    • FindByIdAsync(Guid id, UserIdentifierType userId, ...) (:140-143) takes the owner as part of the query rather than as a check the caller performs afterwards. The comment (:131-134) gives the reason: a session id is a value a client hands back, so scoping the query to the owner is what makes another account's id indistinguishable from a nonexistent one. That is an authorization decision encoded in a signature.
    • FindByIdUntrackedAsync(Guid id, ...) (:159) re-reads a session as the database holds it now, bypassing any tracked copy, revoked and expired rows included (:146-154). The rotation loser needs it: its tracked instance was read before the winner's conditional update and still shows the row live, so only a fresh read can say when and why the row was revoked. The instance is for reading only, so a mutation on it is never persisted. A null answer is read by the caller as "cannot tell" and met with the conservative BR-206 family revocation (:151-154), so a store that can re-read answers with the row; the shipped EF store does so with a no-tracking query (EFRefreshSessionStore.cs:305).
    • SaveChangesAsync(...) (:164) persists staged inserts and revocations.
    • TryRotateAsync(RefreshSession presented, RefreshSession successor, DateTime revokedAt, ...) (:195-199) is the one exception to the no-update rule: it atomically claims the presented session for rotation (revoking it as RefreshSession.ReasonRotated, linked to the successor), then stages and persists the successor. The bool return is the whole point (:171-178): two requests presenting the same still-live token both read an un-revoked row, so a check-then-act rotation would mint two successors from one token and the presented row could never fire reuse detection again. Returning false tells the caller it lost the claim. The caller then re-reads the row through FindByIdUntrackedAsync to tell a sibling rotation inside the reuse grace (a 409 with nothing revoked) or a sign-out or cap eviction (that request fails alone) from a genuine replay (the family is revoked). The remarks (:179-184) put the arbitration where the rows live: the shipped EF store issues a conditional ExecuteUpdateAsync the database decides (EFRefreshSessionStore.cs:332, the update at :350), and an in-memory store revokes the one instance every reader shares. A revoke on a tracked copy followed by a save is explicitly not a claim, since two requests holding two copies both succeed at it, which is why the member carries no default body.
  • Why it's built this way: hashed-at-rest, per-device session rows are what turn refresh-token rotation into something a user can inspect and revoke per device, and what let reuse detection revoke a whole family (ADR-050, BR-205/206). Keeping the contract in Application means the workflow that uses it is independent of EF, so an extracted Identity service can bring its own store. Making rotation a claim rather than a mutation is the difference between a race that mints two live tokens and a race one side of which is answered as a replay. Pushing the sign-in aggregation into the store keeps a history page's cost proportional to the page, not to how often the user's tokens rotated.

  • Where it's used: registered as scoped against the EF implementation at MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:191, scoped, like the unit of work it shares a DbContext with, so a login and its session insert commit together. Consumed by AuthSessionIssuer, not by AuthenticationServiceBase (injected at MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Sessions/AuthSessionIssuer.cs:56) for the owner-scoped lookups behind targeted revocation (:323, :363), the unrevoked-session reads behind sign-out and family revocation (:267, :710), cap eviction (:735), the insert of a new session (:516), the rotation claim and the loser's untracked re-read (:559, :569) and the successor lookup of a lost-response recovery (:659). The sign-in aggregate is read by SignInHistory (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Sessions/SignInHistory.cs:45), the all-sessions read behind account erasure by RefreshSessionRevocation (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/RefreshSessionRevocation.cs:82), and the live-session reads by UserSessionsAdministrationService, which tries the composed query first (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Administration/UserSessionsAdministrationService.cs:95), falls back to the bounded id list asking for one more than it accepts (:105), and counts per-user devices in one grouped call (:135).

RefreshSessionRevocation

MMCA.Common.Application · MMCA.Common.Application.Auth · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/RefreshSessionRevocation.cs:22 · Level 6 · class (public static)

  • What it is: a shared static helper with two steps. RevokeAllAsync (public) revokes every un-revoked refresh session a user holds; RevokeAndAnonymizeAllAsync (internal) is the account-erasure step. Used wherever a credential-rotation path needs to make sure a stale token cannot keep authenticating after the event that should have invalidated it.

  • Depends on: IRefreshSessionStore (nullable: a host that never registered one, because refresh sessions are opt-in, is a no-op), RefreshSession (.Revoke, RefreshSession.ReasonSignedOut), and the BCL TimeProvider.

  • Concept introduced: a credential-rotation event is a call site, not a feature flag. [Rubric §11, Security] assesses whether changing a credential actually invalidates the sessions issued under the old one. Because refresh sessions are opt-in (RefreshSessionSettings.Enabled), a change-password or reset-password handler cannot assume a store exists; the doc comment states this directly (:23-26), and refreshSessions is null (:37-40) is checked first so the call degrades to a no-op rather than throwing, meaning the same handler code runs unchanged on a host that never enabled the feature.

  • Walkthrough: one static method, RevokeAllAsync(IRefreshSessionStore? refreshSessions, TimeProvider? timeProvider, UserIdentifierType userId, CancellationToken cancellationToken) (:31-35). It returns immediately on a null store (:37-40) or an empty session list (:44-47), otherwise stamps now from the supplied timeProvider or TimeProvider.System (:42), calls session.Revoke(now, RefreshSession.ReasonSignedOut) on every un-revoked session in a loop (:49-52), and saves once (:54).

    RevokeAndAnonymizeAllAsync (:69-90) is the erasure variant. It reads every session through IRefreshSessionStore.GetAllByUserAsync, revokes the un-revoked ones as RefreshSession.ReasonAccountDeleted, and calls Anonymize() on every row, revoked ones too, since each still carries the IP address and user agent captured at issue time (:57-64, :81-89). It saves nothing: the store returns tracked rows, so the caller's own unit-of-work save persists the changes together with the erasure. It is used by DeleteUserHandlerBase (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/DeleteUser/DeleteUserHandlerBase.cs:177).

  • Why it's built this way: a static class with no instance state keeps the helper a one-line call from any handler that needs it (RevokeAllAsync is public so an app-side IUserAdministrationService can run the same step after locking an account or changing its role instead of re-implementing it, class doc :16-19), and centralizing the null-store check here means every caller gets the same opt-in-safe behavior instead of re-deriving it.

  • Where it's used: the documented mechanism behind IUserAdministrationService<TUserDto>'s SetLockedAsync obligation (see that type); also ChangePasswordHandlerBase (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/ChangePassword/ChangePasswordHandlerBase.cs) and ResetPasswordHandlerBase (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/ResetPassword/ResetPasswordHandlerBase.cs).

AuthenticationServiceBase<TUser>

MMCA.Common.Application · MMCA.Common.Application.Auth · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/AuthenticationServiceBase.cs:78 · Level 8 · class (abstract)

  • What it is: the shared authentication workflow (password login, registration, refresh-token rotation, per-device and global revocation, session and sign-in history listing, and the sign-in-link and passkey sign-ins) hoisted once into the framework, generic over the app's User aggregate. It realises IAuthenticationService and leaves the genuinely app-specific decisions to a small set of abstract and virtual hooks a sealed subclass overrides (class doc comment, MMCA.Common/Source/Core/MMCA.Common.Application/Auth/AuthenticationServiceBase.cs:29-56).

  • Depends on: IUnitOfWork and IRepository<TEntity, TIdentifierType> (persistence, G07), IPasswordHasher, ILoginProtectionService, AuthenticationValidators and IAuthSessionIssuer (the five required constructor parameters, :79-83), and two optional ones: an ITwoFactorAuthenticator? and IOptions<EmailConfirmationSettings>? (:84-85, both default null so a subclass that adopts neither passes nothing), the IAuthUser credential contract, IEmailIdentifiedUser and AuditableAggregateRootEntity<TIdentifierType> as the TUser constraint (:86), UserEmailLookup for the sign-in lookup by address (class doc, :35-37) and, where a host adopts the matching feature, IEmailConfirmableUser (matched in CheckEmailConfirmed), IPasswordRehashableUser (matched in the sign-in rehash) and IUserPreferences (matched when seeding the registration culture), PasswordCredential (the stored-credential test), BestEffort, the companions AuthenticationServiceLog and AuthSignInMetrics, ITokenService (reached only through the issuer's TokenService property), TwoFactorOutcome, TwoFactorErrors and AuthClaimTypes (the mfa claim values), SignInLinkErrors and PasskeyErrors, RegistrationOutcome, Email (normalizing the login and register address), ClaimsPrincipalExtensions (principal.GetUserId(), principal.FindMultiFactorMethod() and principal.FindAuthTime()), Result and Error, and the request and response DTOs. The base itself takes no session store, no session settings, no clock and no logger (:78-85): the first three belong to the issuer, and the logger rides in on the validators bundle (AuthenticationValidators.Logger).

  • Concept introduced: the Template Method that de-duplicates a whole vertical slice. [Rubric §2, Design Patterns] assesses idiomatic pattern use: this is a textbook Template Method, the invariant sequence of an operation living in the base while the variable steps are deferred to subclass hooks, and the class doc comment lists the hooks with what each app supplies (:34-46). [Rubric §15, Best Practices & Code Quality] (DRY across services) and [Rubric §1, SOLID] also apply: a fix to the lockout order or the rotation logic is written once for every app. [Rubric §11, Security]: the base encodes the security posture directly, validate first, an ILoginProtectionService lockout and rate-limit gate (ADR-029), an untracked-then-tracked dual fetch (ADR-004), an opt-in upgrade of an outdated password hash on sign-in (ADR-133), a refusal of every interactive sign-in for a machine client's service account (ADR-140), and, through IAuthSessionIssuer, refresh-token rotation with reuse detection (ADR-050, BR-205/206). [Rubric §13, Observability]: every password sign-in is counted by outcome and every failure logged without the address. [Rubric §7, Microservices Readiness]: the workflow depends only on ports, so it runs unchanged whether the Identity module is in-monolith or its own service.

    The division of labour is the other concept to absorb before reading the code (:50-55): this class decides who is signed in, and IAuthSessionIssuer decides what they are handed. Once a caller is proved, the multi-device refresh sessions (hashed at rest), BR-205 rotation with BR-206 reuse detection, the per-user session cap, and the sid and mfa claims on the minted access token are the issuer's job, so this workflow never touches a RefreshSession row. Every session-shaped member below is a single delegation to the issuer; the reuse, replay, expiry and cap rules are taught on AuthSessionIssuer.

  • Walkthrough (members in teaching order):

    • Constructor, arming fields and protected accessors (:78-145): a primary constructor takes the five required collaborators plus the two optional ones; when twoFactor is null the challenge falls back to AuthenticationValidators.TwoFactor, and an explicit argument wins (parameter doc, :66-72). A private constant PasswordRehashOperation = "password-rehash" (:89) is the best-effort operation name and metric tag for the sign-in rehash. Two private fields arm the minted token for one request: _multiFactorMethod (:101), the second-factor method that satisfied this request (a plain field because the service is scoped and one request issues one token pair, remarks :97-100), and _authenticatedAt (:109), the sign-in instant (auth_time) a presented token carried, armed only by RefreshTokenAsync so the rotated token keeps it unchanged; a sign-in leaves it null and the issuer stamps the instant of the session it opens (:103-108). Protected read-only properties re-expose UnitOfWork (:112), TokenService (:124), which returns sessionIssuer.TokenService, the issuer's stamping instance, so minting through it is what puts sid on the token (remarks, :116-122), and a Repository resolved lazily as unitOfWork.GetRepository<TUser, UserIdentifierType>() (:127-128). A protected CurrentTermsVersion (:145) forwards validators.CurrentTermsVersion, so adopting Terms of Service acceptance adds no constructor dependency here or in the app's subclass; when it is non-null, RegisterAsync has already refused a request whose AcceptedTerms is false before CreateUser runs, so a CreateUser override stamps that version on the new user (doc comment :130-144). There is no logger member: the failed sign-in Warnings and the rehash lines go to validators.Logger, the bundle's logger under the AuthenticationValidators.LoggerCategory category, so every app writes them with no override and no constructor change. Token lifetimes and the session cap are not members of this class: they are configuration read by the issuer.

    • LoginAsync (:156-293): every call is counted once on the MMCA.Common.Auth meter by outcome, and every outcome but success writes one Warning through AuthenticationValidators.Logger carrying the outcome and a truncated hash of the normalized address (remarks, :147-155). Each failing branch returns through the private SignInFailed(outcome, request.Email, failure) helper (:978-986), which records the AuthSignInMetrics outcome and logs through AuthenticationServiceLog before handing the failure back unchanged. The sequence: validate the request (a failure counts as invalid_credentials, :162-169), check lockout (ADR-029 and BR-212, locked_out, :171-179), normalize the raw email into an Email value object (:183) so the EF predicate compares same-typed converted values (an invalid address yields a null value object that simply matches no user). Step 1 is an untracked fetch through the framework's own lookup, unitOfWork.GetReadRepository<TUser, UserIdentifierType>().FindUntrackedByEmailAsync(loginEmail, ...) (:187-190), which reads the app's IEmailIdentifiedUser.Email, to verify credentials without change-tracker overhead. The gate is CanSignInWithPassword(untracked) (:196, private helper at :943-944): the account must exist, must not be a machine client's service account (ADR-140), and must carry stored password material (HasStoredCredential, :937, through PasswordCredential.IsStored); an external-OAuth account (ADR-036) carries none. All three refusals answer the identical generic 401 after the identical BurnPasswordVerificationCost(request.Password) call (:198) and IncrementFailedAttemptsAsync (:199), so none of them can be told apart, by status or by timing, from an unknown address (comment, :192-195). passwordHasher.VerifyPassword runs next (:207) and fails the same way on a wrong password. Only after the password check does the app gate (ValidateLoginCandidateAsync, :221, outcome rejected) run, deliberately: reaching it proves the caller owns the account, so its distinct status message (for example a deactivated-account rejection) is told to the account's owner rather than to anyone sweeping addresses, and running it first would make account state readable with no credential at all and skip the failed-attempt counter (comment, :217-220). Two more gates follow the same rule, for the same reason: CheckEmailConfirmed(untracked) (:234, outcome email_not_confirmed, hook at :834-844), off unless the host both supplied EmailConfirmationSettings.RequireConfirmedEmail and the app's User implements IEmailConfirmableUser, and ChallengeSecondFactorCountingFailuresAsync(untracked.Id, request, cancellationToken) (:243-244, private helper at :878-891, outcome chosen by AuthSignInMetrics.ForSecondFactorFailure). That helper runs the overridable ChallengeSecondFactorAsync hook (:860-866) and counts a TwoFactorErrors.TwoFactorInvalidCode failure against the account through IncrementFailedAttemptsAsync exactly like a wrong password (:885-888), so the lockout at the top of the method throttles code guessing per account; a missing code is the ordinary first leg of the challenge and is not counted (:868-873). Step 2 is a tracked re-fetch by id (:257), purely about the instance the app's CreateAccessToken hook mints from, and the second lookup turns a race that deleted the account between the two steps into a clean 404, counted as invalid_credentials because it reads as an unknown address (:258-266). Then ResetFailedAttemptsAsync (:269), and _multiFactorMethod = MultiFactorMethodFor(secondFactor.Value) (:272, private helper at :899-908, mapping a verified TOTP or recovery code to the mfa claim value and any unrecognized outcome to null) arms the field in a try/finally around the private IssueTokensCoreAsync (:273-281), which does not repeat the challenge this request already ran (:275-276), so the claim lands only on this response and disarms whether or not the call throws. A refused issuance is counted as rejected (:283-286), a success is recorded (:288), and then RehashPasswordIfNeededAsync(issued, user, request.Password) (:290) runs before return issued (:292).

    • RegisterAsync (:296-393): validate (:302), refuse unaccepted terms when a version is configured (:311-314, returning LegalAcceptanceErrors.TermsNotAccepted), IP rate-limit (ADR-029 and BR-213, :317-321), reject a duplicate email through the EmailExistsAsync hook (:323-328), hash the password (:330), build the user through the CreateUser hook and unwrap it with TryGetValue (:331-335), seed the account's language from the request culture (SeedRegistrationCulture, :337-341, private helpers at :773-781 and :790-800), AddAsync and save (:343-348), run the OnUserRegisteredAsync post-commit hook to pick up the instance the first access token is minted from (:377), and increment the IP registration count (:380). The culture seed exists because the confirmation email is composed later, outside this request, in the recipient's stored culture (ADR-027); it applies only to a User that implements IUserPreferences and has no culture yet, and stores nothing for the invariant culture, the pseudo-locale or a culture that resolves to the default (doc comments, :766-772, :783-789). Next, registration opens no session exactly when sign-in would refuse the new account: if CheckEmailConfirmed(tokenUser) fails, the result is a success carrying RegistrationOutcome.ConfirmationPending (:385-388), and because the same virtual gate decides both, a subclass override moves them together. Otherwise the session is opened last (:392): it carries the user id, which a store-generated key only has once the insert has run.

      The save is wrapped in a deliberately broad catch (Exception) (:350) whose comment (:353-366) is the teaching material. The email lookup above is a check-then-act: two concurrent registrations for the same address both pass it, and the loser only fails on the insert, against the unique index every consumer puts on Email (ADC unfiltered, Store filtered on IsDeleted). Without the catch, that race surfaces as a generic 500 instead of the 409 a serialized pair would have produced. The catch cannot name DbUpdateException, because Application has no EF Core dependency by layer rule, so the re-check is what narrows it (:367-372): if the address exists now, the concurrent registration is the cause and the caller gets the same conflict the serial path returns through the shared EmailAlreadyExistsFailure() helper; anything else rethrows untouched and still reaches the exception middleware. The re-check passes CancellationToken.None on purpose: it has to run even when the caller's token is what aborted the save, or a cancelled save could never be classified.

    • RefreshTokenAsync (:396-468): validate (:402), pull claims from the expired JWT via TokenService.GetPrincipalFromExpiredToken (:410, the issuer's instance; signature still checked, only lifetime skipped), read the identifier with principal.GetUserId() (:420, rides the standard sub claim, also accepts the NameIdentifier form the bearer handler maps it to, and parses through IParsable so the identifier alias can change shape without editing this file), load the tracked user (:427, a missing user answered by CreateRefreshUserMissingError, :430), run the refresh app gate (:434), and hand the presented refresh token to sessionIssuer.RotateAsync (:455-461) together with a mint callback over CreateAccessTokenForSession. The issuer resolves the session behind the token (reuse detection included), rotates it, and answers with a token pair whose access token carries the successor's sid. Two claims ride the rotation, both read off the presented access token, whose signature was already validated, and both armed in one try/finally around the successor mint and cleared together (:463-467): the step-up the user already performed, _multiFactorMethod = principal.FindMultiFactorMethod() (:445; dropping it would quietly demote a signed-in session every access-token lifetime and make every role that requires a second factor unreachable without a fresh sign-in, comment :440-444), and the sign-in instant, _authenticatedAt = principal.FindAuthTime() (:450), carried unchanged because a refresh is not a sign-in, so a stolen refresh token cannot make its session look recently signed in; a token with no auth_time rotates into one with none (comment, :447-449, ADR-139).

    • RevokeTokenAsync (:471-485): load the user (a NotFound when absent), then delegate to sessionIssuer.SignOutAsync(userId, refreshToken, ...) (:482). Only a live session belonging to this user identifies the device to sign out; when the token is absent or identifies no live session of this user, the issuer revokes every live session instead, rather than reporting success for a revocation that reached nothing.

    • RevokeAllSessionsAsync (:488-501): the unconditional form of the same thing, through sessionIssuer.SignOutEverywhereAsync (:498).

    • GetSessionsAsync (:505-513) and GetSignInsAsync (:517-525): no user lookup, so each is one call to the issuer, sessionIssuer.ListActiveAsync (:510) for live devices and sessionIssuer.ListSignInsAsync (:522) for the sign-in history, wrapped in a success (remarks, :504, :516).

    • RevokeSessionByIdAsync (:533-537): an expression-bodied delegation to sessionIssuer.RevokeSessionAsync. Ownership is checked by the issuer's store query, so another account's id and a nonexistent id produce the same NotFound (remarks, :528-532); an already-revoked session writes nothing and returns NotFound with Auth.SessionAlreadyRevoked, matching the interface contract (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/IAuthenticationService.cs:126-128).

    • ExternalLoginAsync (:544-551): declared abstract here, with the interface's bool emailVerified parameter. The remarks (:540-543) and the class doc (:47-49) give the reason: OAuth linking is coupled to the app's User factory, so the app implements it, or refuses it explicitly when it offers no external sign-in, and a signature change is a compile error in every app rather than a silent fall-through to a default.

    • SignInVerifiedEmailOwnerAsync (:567-595): the sign-in-link path. A missing account or a service account reads as an invalid link (:574-579), the app gate runs (:581), and the second factor is challenged with no code (:587): any outcome other than NotEnrolled is refused with SignInLinkErrors.SecondFactorRequired (:588-592), because the link proves only mailbox access and honoring it would let that alone bypass an enrolled factor (remarks, :562-564). The email-confirmation gate is skipped on purpose: redeeming the link is the proof that gate asks for (:558-559). It then mints through IssueTokensCoreAsync (:594).

    • SignInWithPasskeyAsync (:613-642): the passkey path. A missing account or a service account answers PasskeyErrors.AssertionFailed (:620-625), the app gate runs (:627), and with no second-factor challenge _multiFactorMethod is armed to AuthClaimTypes.MultiFactorMethodPasskey around the issuance (:633-641): a passkey is possession of the authenticator plus its own user verification, so it satisfies the second factor itself, and RefreshTokenAsync carries mfa=passkey across rotations like otp (remarks, :606-610).

    • HasSignInMethodBesidesPasskeysAsync (:650-662): a vanished account answers false (:655-658); otherwise a non-empty stored password hash counts, and so does the virtual HasExternalLoginAsync (:660-661, hook at :673-674, default false).

    • IssueTokensAsync (:703-725): the protected open-and-respond an app-level sign-in that proves no factor (external login) mints through. It null-guards the user (:709) and, for anyone but a service account, runs the second-factor challenge with no code first, refusing an enrolled account with TwoFactorErrors.TwoFactorRequired and opening no session (:710-722; doc :688-696). It ends in the private IssueTokensCoreAsync (:737-755), the core every framework sign-in (password, registration, sign-in link, passkey) calls directly once it has settled the factor itself. The core refuses a service account with the generic Auth.InvalidCredentials 401 (:743-747), which makes it the backstop behind every path-specific refusal (doc :680-687), and otherwise delegates to sessionIssuer.IssueAsync(user.Id, sessionId => CreateAccessTokenForSession(user, sessionId), ...) (:749-754): the access token is a callback because it carries the session's id, which exists only once the issuer has opened the session.

    • The private mechanics are login-side only. ChallengeSecondFactorCountingFailuresAsync (:878-891) is the counting wrapper described under LoginAsync. MultiFactorMethodFor (:899-908) maps an unrecognized outcome to null, so an enum that grew cannot silently mint an mfa claim. HasStoredCredential (:937) delegates to PasswordCredential.IsStored, and CanSignInWithPassword (:943-944) adds the existence and service-account checks. BurnPasswordVerificationCost (:960-968) skips a blank password and otherwise calls the hasher's own passwordHasher.BurnVerificationCost(password) (:967), so a branch that never reaches the real check still pays the key-derivation cost. The remarks (:951-959) explain both choices: the burn costs what verifying the most expensive record the hasher can have stored costs (for the shipped hasher, the larger of its current and legacy work factors), so an unknown address costs the same as an account still on an older record, and it does not verify against fixed decoy material because a hasher that rejects wrong-sized material before deriving anything (the shipped one does) would answer a decoy instantly and silently reopen the timing gap. SignInFailed (:978-986) is the record-and-log helper above; it logs through validators.Logger (:984).

      RehashPasswordIfNeededAsync (:1006-1037) is the work-factor upgrade. It returns at once unless the issuance succeeded and the app's User opts in by implementing IPasswordRehashableUser (:1008-1011). Otherwise it runs inside BestEffort.ExecuteAsync(PasswordRehashOperation, validators.Logger, ..., CancellationToken.None) (:1013-1036): when passwordHasher.NeedsRehash(rehashable.PasswordHash) reports the stored hash is current it does nothing (:1018-1021); otherwise it hashes the verified plaintext and hands the new material to rehashable.RehashPassword(hash, salt) (:1023-1024), logs AuthenticationServiceLog.PasswordRehashRejected through validators.Logger with the joined error codes and returns if the aggregate refuses (:1025-1032), and saves through the unit of work on its own (:1034). The remarks (:994-1001) give the ordering its reason: it runs after the tokens are issued and saves separately, so the session save never carries the user row, and a refused invariant, a concurrency conflict or a dropped connection cannot fail a sign-in that has already succeeded; any non-domain failure is logged and counted by the best-effort wrapper, and the record is simply upgraded on a later sign-in. CancellationToken.None is deliberate: the sign-in is complete, and an abandoned request must not surface as a cancellation from this step. EmailAlreadyExistsFailure() (:1044-1046) is the 409 shared by the up-front check and the race recovery so the two paths are indistinguishable to a caller. Session resolution, rotation, family revocation and the cap are private to AuthSessionIssuer.

    • The hooks: four are abstract, so a subclass must supply them. EmailExistsAsync (:761) is written against the app's concrete User so EF translates the predicate against the app's own mapped columns, and explicitly leaves the app to decide whether soft-deleted accounts count (ignoreQueryFilters: true blocks re-registration of an erased address); CreateUser (:764) runs the app's domain factory; CreateAccessToken (:803) mints the app's claim set (for example speaker_id versus customer_id); and ExternalLoginAsync (:544) is the OAuth path above. The sign-in lookup by address is not a hook: the framework owns it over IEmailIdentifiedUser.Email (class doc, :35-37). Eight virtual methods can be overridden: CreateAccessTokenForSession (:823-824) calls sessionIssuer.MintForSession(sessionId, _multiFactorMethod, _authenticatedAt, () => CreateAccessToken(user)), so the issuer arms its stamping token service for the duration of the app hook and sid (plus mfa when this request verified a second factor, and auth_time, carried over unchanged on a refresh) is appended to whatever claim set the app passes, which is what keeps the claims additive with no change to CreateAccessToken's signature (remarks, :809-819); CheckEmailConfirmed (:834-844) is the email-confirmation gate, used by both sign-in and registration; ChallengeSecondFactorAsync (:860-866) runs the second-factor challenge through twoFactor ?? validators.TwoFactor (:864) and, with neither, answers TwoFactorOutcome.NotEnrolled with no extra query, which is what keeps the feature free for an app that has not adopted it; HasExternalLoginAsync (:673-674) reports an external login for the last-passkey check; ValidateLoginCandidateAsync (:911) and ValidateRefreshCandidateAsync (:915) add extra gates such as a deactivated-account check (the first also guards the sign-in-link and passkey paths); OnUserRegisteredAsync (:922) runs the post-commit side-effect; and CreateRefreshUserMissingError (:930-931) defaults the vanished-user case to 401 (a token for a missing user is indistinguishable from an invalid one) while letting an app return 404 where its public contract already promises it.

  • Why it's built this way: the untracked-then-tracked dual fetch keeps the common credential-verification path off the change tracker (cheaper, and soft-deleted accounts fall out via EF query filters returning the generic 401) while still giving a tracked instance to mint from (ADR-004). Per-device session rows with hashed tokens, rotation, family revocation on reuse, and a per-user cap are the BR-205/206 model (ADR-050), and keeping them behind IAuthSessionIssuer gives the sign-in decision and the session mechanics one owner each (:50-55). Routing every sign-in path, password or not, through one issuance core is what lets a single check refuse a service account everywhere (ADR-140) and lets the sign-in-link and passkey paths (ADR-116, ADR-139) reuse the app gate and the session mint unchanged. Password material flows through IAuthUser's PasswordHash and PasswordSalt (ADR-032). A successful sign-in is the only moment the verified plaintext is in hand, which is why the hash upgrade lives here, opt-in per app through IPasswordRehashableUser (ADR-133), and why it is best-effort rather than part of the sign-in's success (ADR-096). Taking the logger from the validators bundle rather than from an overridable property means the failure lines are on by default in every app without widening the constructor. The whole workflow depends only on abstractions, so it is identical whether the module runs in-process or as an extracted service.

  • Where it's used: subclassed by each app's sealed AuthenticationService, for example MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/AuthenticationService.cs:52, which binds TUser = User, adds the Attendee default role (BR-45) and the speaker_id claim (BR-209, claims builder documented at :558), takes the injected AuthenticationValidators and IAuthSessionIssuer (:56-57) and passes them through to the base, re-lists IAuthenticationService (:69) so it can re-implement RegisterAsync with new (:83), overrides the abstract ExternalLoginAsync (:290), and overrides HasExternalLoginAsync (:182). ADC's User opts into the sign-in rehash by implementing IPasswordRehashableUser (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Domain/Users/User.cs:38). MMCA.Store supplies its own subclass with a customer_id claim. Consumed by the Identity API controllers via the IAuthenticationService port.

  • Caveats / not-in-source: ExternalLoginAsync has no framework body at all: an app with no external sign-in still has to implement it, as an explicit refusal (class doc, :47-49). The failed sign-in Warnings and a refused rehash are written under the MMCA.Common.Application.Auth.AuthenticationService category (AuthenticationValidators.LoggerCategory) in every app, so log-level configuration for that category is what silences or surfaces them; the mmca.auth.signin counter records every attempt regardless, and a thrown rehash failure is also counted on the MMCA.Common.BestEffort meter.

EmailConfirmationSettings

MMCA.Common.Application · MMCA.Common.Application.Auth.EmailConfirmation · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/EmailConfirmation/EmailConfirmationSettings.cs:10 · Level 0 · class

  • What it is: the options class bound to the Authentication:EmailConfirmation configuration section (EmailConfirmationSettings.cs:28), controlling token lifetime, throttling, and whether an unconfirmed address blocks sign-in.
  • Depends on: nothing first-party; System.ComponentModel.DataAnnotations ([Range]) and System.Diagnostics.CodeAnalysis ([SuppressMessage]) validate the bound values.
  • Concept introduced: the config-bound settings-class shape (a SectionName constant plus init-only, range-validated properties with sane defaults) is the same one the sibling PasswordResetSettings uses elsewhere in this group; see it there for the general pattern rather than re-teaching it here. [Rubric §11, Security] (assesses whether authentication-adjacent behavior is safely configurable): every numeric knob here is range-constrained (EmailConfirmationSettings.cs:43,50,54,58), so a bad value in configuration fails validation instead of silently disabling throttling.
  • Walkthrough: ConfirmationUrl (EmailConfirmationSettings.cs:40) defaults to empty rather than being [Required], deliberately, per its own doc comment (EmailConfirmationSettings.cs:30-34): an unconfigured host still boots and degrades to a token-only, paste-in-by-hand flow. TokenLifetimeMinutes (line 44) defaults to 1440 (one day). MaxValidationAttempts (line 51) caps wrong-token guesses at 5 before the record is discarded. MaxRequestsPerEmail (line 55) and RequestWindowMinutes (line 59) throttle re-issuance per address. RequireConfirmedEmail (line 70) defaults to false.
  • Why it's built this way: the RequireConfirmedEmail default is called out as load-bearing in its own remarks (EmailConfirmationSettings.cs:49-54): turning it on locks out every account whose address was never confirmed, so a host backfills existing rows as confirmed before flipping it, and with it off the whole feature is additive. This is the opt-in shape recorded in ADR-116.
  • Where it's used: read by AuthenticationServiceBase and EmailConfirmationTokenService (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/AuthenticationServiceBase.cs, MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/EmailConfirmationTokenService.cs) and registered in MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs; ADC binds it via MMCA.ADC.Identity.Application/Users/AuthenticationServiceSettings.cs and consumes it in SendEmailConfirmationHandler.

LegalAcceptanceOptions

MMCA.Common.Application · MMCA.Common.Application.Auth.Legal · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Legal/LegalAcceptanceOptions.cs:12 · Level 0 · class (sealed)

  • What it is: the options class for terms-of-service acceptance, bound from the Legal section (SectionName, LegalAcceptanceOptions.cs:15). Its one setting, CurrentTermsVersion (:21), is the terms version every user must have accepted (for example 2026-10-01); changing it asks every signed-in user to accept again, and null or whitespace turns the feature off.
  • Depends on: nothing; it is a plain options bag.
  • Concept: a feature switch carried by configuration rather than a flag. "Not configured" is a legal state that disables the feature, and LegalAcceptancePolicy.ResolveCurrentVersion is the single place that turns the raw value into a trimmed version or null.
  • Why it's built this way: an opt-in host (ADR-116) that never sets the section changes nothing, so the registration only binds the section (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Auth.cs:153-154, inside AddLegalAcceptance at :104). Related: ADR-070, ADR-116.
  • Where it's used: injected as IOptions<LegalAcceptanceOptions> by LegalAcceptanceControllerBase (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Legal/LegalAcceptanceControllerBase.cs:48, read at :54) and, optionally, by AuthenticationValidators (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/AuthenticationValidators.cs:38,84), which exposes CurrentTermsVersion to the registration check.

MachineClientSettings

MMCA.Common.Application · MMCA.Common.Application.Auth.MachineClients · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/MachineClients/MachineClientSettings.cs:19 · Level 0 · class (sealed)

  • What it is: the options class for machine clients (OAuth client credentials), bound from the MachineClients section (SectionName, MachineClientSettings.cs:22) by AddMachineClients(configuration) and validated at startup.
  • Depends on: nothing first-party at runtime; its doc comment points at IServiceAccountProvisioner, which an enabled host must register.
  • Concept introduced: the config-bound settings shape is the one EmailConfirmationSettings already shows; what is new here is a lifetime cap derived from another mechanism's window. [Rubric §11, Security] (assesses whether credentials and their revocation are bounded): MaxAccessTokenMinutes is 15 (:33) because revocation works by the soft-deleted marker for the service account, which lives 20 minutes, and a token must lapse within that window minus the bearer handler's 5-minute clock skew (doc comment :27-32).
  • Walkthrough: MinAccessTokenMinutes is 1 (:25). Enabled (:36) defaults to false; while it is false the token endpoint and every administration endpoint answer 404 and the MachineClients table is in no model, so a host that never opts in sees no route and no migration (remarks :8-13). AccessTokenMinutes (:42) defaults to MaxAccessTokenMinutes; nothing renews the token, a program asks again. DataSourceName (:48) names the logical data source that owns the MachineClients table (the Identity database) and defaults to "Default".
  • Why it's built this way: off by default so the feature is additive, and turning it on needs consumer code (an IServiceAccountProvisioner over the app's own User aggregate, remarks :14-17). MachineClientSettingsValidator enforces both at startup: the 1 to 15 range (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/MachineClients/MachineClientSettingsValidator.cs:23-27) and, when enabled, a registered provisioner (:37-40). Recorded in ADR-140; the fail-at-startup shape is ADR-070.
  • Where it's used: bound in MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.MachineClients.cs:42-46 (inside AddMachineClients, :37); read by MachineClientService, by EFMachineClientStore (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/MachineClients/EFMachineClientStore.cs:32), and by ApplicationDbContext and DesignTimeDbContextHelper to decide whether the table is in the model.

ServiceAccount

MMCA.Common.Application · MMCA.Common.Application.Auth.MachineClients · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/MachineClients/ServiceAccount.cs:13 · Level 0 · record (sealed)

  • What it is: the facts a machine token is minted from, for one service account: user id (the token's sub), name, email and role (ServiceAccount.cs:13-17), the same standard claims a person's token carries.
  • Depends on: the UserIdentifierType alias and PiiAttribute on Name and Email (:15-16).
  • Concept: a plain positional record crossing the consumer boundary; no new concept. Role is the host's role name, and its permissions are read from the registry rather than carried here (doc comment :12).
  • Why it's built this way: Common has no user entity, so the consumer's IServiceAccountProvisioner returns this small projection instead of its User aggregate. See ADR-140.
  • Where it's used: returned by IServiceAccountProvisioner.FindAsync and consumed by MachineClientService.IssueTokenAsync (MachineClientService.cs:103-121); ADC builds it in MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/Administration/ServiceAccountProvisioner.cs.

EmailConfirmationErrors

MMCA.Common.Application · MMCA.Common.Application.Auth.EmailConfirmation · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/EmailConfirmation/EmailConfirmationErrors.cs:10 · Level 2 · class

  • What it is: the static Error-factory class for the email-confirmation flow: one factory for a sign-in refused because the address is unconfirmed, one for a valid token on a password-holding account whose request carried no proof of the account, and one for every failing token redemption.
  • Depends on: Error (the Result-pattern error type taught in the primer) and AuthErrorCodes (PasswordRequiredCode aliases AuthErrorCodes.EmailConfirmationPasswordRequired, "EmailConfirmation.PasswordRequired", MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/AuthErrorCodes.cs:60).
  • Concept: the same named-code-plus-factory-method convention used by every *Errors class in this codebase (see AuthErrorCodes for the general shape); no new concept here.
  • Walkthrough: three error codes: EmailNotConfirmedCode (EmailConfirmationErrors.cs:13), InvalidTokenCode (line 16) and PasswordRequiredCode (line 23). EmailNotConfirmed(source) (lines 33-36) returns Error.Unauthorized, distinct from Auth.InvalidCredentials so a UI can offer to resend the link. PasswordRequired(source) (lines 48-51) returns Error.Unauthorized when a valid token would confirm an account that holds a password and the caller proved neither the account (signed in as it, or its current password) nor a claim on it (a new password); nothing was changed and the token is still redeemable (doc comment lines 18-22). InvalidToken(source) (lines 56-59) is the single rejection every failing redemption (unknown, expired, mismatched, or attempt-capped token) collapses to.
  • Why it's built this way: the remarks on EmailNotConfirmed (lines 28-32) explain it is reachable only after the password has already been proved, so the message can safely tell the account owner what is wrong rather than help an address sweeper enumerate valid accounts. PasswordRequired follows the same reasoning (remarks lines 44-47): it is reachable only with a valid token, so it tells the mailbox owner, never a sweeper, that the account has a password, and the client then offers the current password or a new one. InvalidToken collapsing every failure mode to one message denies an attacker any signal about which reason a redemption failed for.
  • Where it's used: raised by ConfirmEmailHandlerBase (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/EmailConfirmation/ConfirmEmailHandlerBase.cs:112,121,306 for InvalidToken, :228 for PasswordRequired), by AuthenticationServiceBase.cs and ADC's AuthenticationService.cs (the sign-in refusal), and by EmailConfirmationTokenService.cs; asserted against in ConfirmEmailAccountProofTests.cs, EmailConfirmationHandlerBaseTests.cs, EmailConfirmationTokenServiceTests.cs, AuthErrorCodesAlignmentTests.cs, and ADC's ConfirmEmailHandlerTests.cs and AuthenticationServiceTests.cs.

LegalAcceptanceErrors

MMCA.Common.Application · MMCA.Common.Application.Auth.Legal · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Legal/LegalAcceptanceErrors.cs:11 · Level 2 · class (static)

  • What it is: the two validation errors of terms acceptance, as factory methods plus their code constants.
  • Depends on: Error (the primer's Result/Error pattern), AuthErrorCodes (TermsNotAcceptedCode aliases AuthErrorCodes.TermsNotAccepted, LegalAcceptanceErrors.cs:14) and LegalAcceptanceErrorCodes (VersionNotCurrentCode, :17).
  • Concept: error factories with stable codes, mirroring EmailConfirmationErrors; no new concept.
  • Walkthrough: TermsNotAccepted(source) (:22) is the registration refusal when a terms version is configured and the box was not ticked ("You must accept the Terms of Service to register."). VersionNotCurrent(source) (:33) refuses an acceptance of any version other than the configured one, including any acceptance while none is configured. Both build Error.Validation with the caller-supplied source.
  • Why it's built this way: the shared code constants let a client switch on a stable string without referencing the Application layer.
  • Where it's used: TermsNotAccepted is returned by AuthenticationServiceBase.RegisterAsync (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/AuthenticationServiceBase.cs:313); VersionNotCurrent by LegalAcceptancePolicy.EnsureAcceptsCurrentVersion (LegalAcceptancePolicy.cs:36).

MachineClientErrors

MMCA.Common.Application · MMCA.Common.Application.Auth.MachineClients · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/MachineClients/MachineClientErrors.cs:6 · Level 2 · class (static)

  • What it is: the error factories of the machine-client flow, plus the code constants the token endpoint switches on.
  • Depends on: Error (the primer's Result/Error pattern).
  • Concept: error factories with stable codes, mirroring EmailConfirmationErrors; no new concept. [Rubric §11, Security] (assesses whether failures leak information): one code covers every authentication failure.
  • Walkthrough: four public codes: InvalidClientCode (MachineClientErrors.cs:9), UnsupportedGrantTypeCode (:12), InvalidRequestCode (:15), RoleNotAllowedCode (:18). InvalidClient(source) (:27) is Error.Unauthorized for an unknown id, wrong secret, revoked or expired client, missing or non-service account, or a forbidden role, all deliberately indistinguishable (doc comment :20-24). UnsupportedGrantType (:33) and InvalidRequest (:39) are Error.Validation for a grant type other than client_credentials and a missing one. RoleNotAllowed (:49) refuses a role granting users:view-as, users:manage, roles:manage or clients:manage. PrivilegeCeiling (:59-64) is Error.Forbidden with target role for a client whose role grants a permission the caller does not hold, refusing both a create and a secret rotation; it reuses the users-administration code UserAdministration.PrivilegeCeiling (403) inline and names no permission (doc comment :52-56). RoleRequired (:69) and NotFound (:75, Error.NotFoundError) also use inline codes with no public constant.
  • Why it's built this way: the constants let the API map a refusal onto the RFC 6749 body without string literals: MachineTokenControllerBase.TokenError answers 400 for the two grant-type codes and 401 invalid_client for everything else (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/MachineClients/MachineTokenControllerBase.cs:115-130). Sharing the users-administration code for the ceiling means a client can switch on one string for "you cannot hand out more than you hold", whichever surface refused.
  • Where it's used: raised by MachineClientService and read by MachineTokenControllerBase (MachineTokenControllerBase.cs:117-121).

IEmailConfirmationTokenService

MMCA.Common.Application · MMCA.Common.Application.Auth.EmailConfirmation · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/EmailConfirmation/IEmailConfirmationTokenService.cs:15 · Level 3 · interface

  • What it is: the token-lifecycle abstraction for email confirmation: issue a token for an address, check one presented back without spending it, and validate and consume one.
  • Depends on: UserIdentifierType (the module's identifier-type alias), Result<T>.
  • Concept: an issue/validate-and-consume token contract, mirroring the shape IPasswordResetTokenService uses elsewhere in this group. What is added here is a non-consuming check, so a redemption that needs a second proof from the caller can stop without burning the link.
  • Walkthrough: IssueAsync(email, userId, cancellationToken) (IEmailConfirmationTokenService.cs:28) replaces any token already outstanding for that address, so there is one active token per address, and fails only when the per-address request throttle (EmailConfirmationSettings.MaxRequestsPerEmail/RequestWindowMinutes) has been exceeded. ValidateAsync(email, token, cancellationToken) (line 43) validates WITHOUT consuming, so a redemption that then needs more from the caller (a password proof) leaves the token redeemable; a wrong token still counts against the attempt cap exactly as it does on the consuming path (doc comment lines 30-34). ValidateAndConsumeAsync(email, token, cancellationToken) (line 59) validates against the outstanding token and consumes it on success, collapsing unknown/expired/mismatched/attempt-capped failures to the single EmailConfirmationErrors.InvalidToken error (returns doc lines 55-58). Sequential redemptions of one token succeed once; redemption takes no lock, so two CONCURRENT redemptions can both read the entry before either removes it and both succeed, which only confirms the same address twice, an idempotent outcome (doc comment lines 46-50).
  • Why it's built this way: consuming on success is what makes sequential redemption single-use, and the documented concurrent race is accepted rather than locked because its only effect is idempotent. Splitting the check from the spend lets the handler refuse with PasswordRequired and keep the link alive, while counting wrong guesses on both paths keeps the attempt cap honest. Collapsing every failure reason to one error denies an attacker signal about why a guess failed. The opt-in shape is ADR-116.
  • Where it's used: implemented by EmailConfirmationTokenService (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/EmailConfirmationTokenService.cs), registered with TryAddScoped in MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Auth.cs:91. ConfirmEmailHandlerBase calls ValidateAsync first (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/EmailConfirmation/ConfirmEmailHandlerBase.cs:107) and ValidateAndConsumeAsync once the account proof passes (:298); it is also consumed by SendEmailConfirmationHandlerBase.cs and by ADC's SendEmailConfirmationHandler.cs/ConfirmEmailHandler.cs, and named in MMCA.Common/Source/Core/MMCA.Common.Application/Auth/SignInLinks/ISignInLinkTokenService.cs.

ILegalAcceptanceService

MMCA.Common.Application · MMCA.Common.Application.Auth.Legal · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Legal/ILegalAcceptanceService.cs:21 · Level 3 · interface

  • What it is: the per-user storage contract behind terms acceptance: read the signed-in user's standing, and record that they accepted a version.
  • Depends on: LegalAcceptanceDTO, Result<T>, and the UserIdentifierType alias.
  • Concept: a deliberately thin consumer boundary. The controller base validates the request first (ILegalAcceptanceService.cs:14, via LegalAcceptancePolicy.EnsureAcceptsCurrentVersion) and re-derives every answer afterwards (:17, via Normalize), so an implementation only has to load and save the accepted version and instant.
  • Walkthrough: GetForCurrentUserAsync(currentUserId, currentVersion, ct) (:26) reads the caller's standing, or a failure such as NotFound. AcceptForCurrentUserAsync(currentUserId, version, ct) (:39) records the acceptance stamped with the implementation's own clock and returns the standing afterwards.
  • Why it's built this way: Common ships no implementation and AddLegalAcceptance deliberately registers none (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Auth.cs:137), because where the accepted version lives is the consumer's User aggregate (see ILegalAcceptingUser in MMCA.Common/Source/Core/MMCA.Common.Domain/Auth/ILegalAcceptingUser.cs). Recorded in ADR-116.
  • Where it's used: consumed by LegalAcceptanceControllerBase (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Legal/LegalAcceptanceControllerBase.cs:46); ADC implements it as LegalAcceptanceService (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/LegalAcceptanceService.cs), registers it in that module's DependencyInjection.cs, and subclasses the controller base as LegalAcceptanceController.

IMachineClientService

MMCA.Common.Application · MMCA.Common.Application.Auth.MachineClients · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/MachineClients/IMachineClientService.cs:11 · Level 3 · interface

  • What it is: the machine-client contract: the OAuth client credentials grant, and administration of the clients behind it.
  • Depends on: Result<T>, the response and request records in MMCA.Common.Shared.Auth.MachineClients (MachineTokenResponse, MachineClientResponse, MachineClientSecretResponse, CreateMachineClientRequest).
  • Concept: a service a program (not a person) authenticates against with an id and a secret, receiving a short-lived bearer token and no refresh token or session. The feature switch lives on the interface itself, so a controller can resolve it per action and answer 404 while it is off.
  • Walkthrough: IsEnabled (IMachineClientService.cs:14) mirrors MachineClients:Enabled. IssueTokenAsync(grantType, clientId, clientSecret, ct) (:28) runs the grant and fails with MachineClients.InvalidClient, UnsupportedGrantType or InvalidRequest. ListAsync (:37) lists every client, revoked ones included. CreateAsync(request, callerHoldsPermission, ct) (:55-58) provisions the service account, stores the client and returns the primary secret once. RotateAsync(clientId, callerHoldsPermission, ct) (:69-72) issues a secondary secret, returned once; both work until PromoteAsync (:78) makes it primary and the old one stops at once. RevokeAsync (:87) stops the secrets and writes the soft-deleted marker so tokens already held are rejected.
  • The privilege ceiling: CreateAsync and RotateAsync take an optional Func<string, bool>? callerHoldsPermission that answers whether the caller holds a given permission. Every permission the client's role grants must pass it, or the call is refused with UserAdministration.PrivilegeCeiling (param docs :44-49 and :62-66). null applies no ceiling and is meant for a trusted caller with no principal; the HTTP surface always supplies it (:48-49). [Rubric §11, Security] (assesses least privilege): an operator who can manage clients still cannot mint a credential that outranks them.
  • Why it's built this way: two secrets with an explicit promote let a caller rotate without downtime, and the ceiling applies to rotation as well as creation because a fresh secret on a stronger client is the same escalation as a new client. See ADR-140.
  • Where it's used: implemented by MachineClientService, registered by AddMachineClients (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.MachineClients.cs:54), resolved per request by MachineTokenControllerBase (MachineTokenControllerBase.cs:57) and MachineClientsControllerBase (MachineClientsControllerBase.cs:45-46), which passes its CallerHoldsPermission() predicate to create and rotate (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/MachineClients/MachineClientsControllerBase.cs:88,116), and checked by CloudAdapterTripwire.

IServiceAccountProvisioner

MMCA.Common.Application · MMCA.Common.Application.Auth.MachineClients · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/MachineClients/IServiceAccountProvisioner.cs:15 · Level 3 · interface

  • What it is: the consumer-implemented contract that creates and reads the service-account users behind machine clients.
  • Depends on: ServiceAccount, Result<T>, the UserIdentifierType alias.
  • Concept: the consumer-supplied-store shape of ADR-116 (compare ILegalAcceptanceService): Common has no user entity, so the app implements this over its own User aggregate. A service account is a user whose IAuthUser.IsServiceAccount is true: no password, no external login, never a person; the framework refuses it on every interactive sign-in path and as a view-as target (remarks IServiceAccountProvisioner.cs:10-14).
  • Walkthrough: CreateAsync(name, role, ct) (:24) creates a passwordless service-account user with the role and returns its id, or the app's own refusal (an unknown role, say). FindAsync(userId, ct) (:33) returns the account, or null when it does not exist, is deleted or locked, or is not a service account, so a token is never minted for a person.
  • Why it's built this way: an enabled host without a registration fails at startup naming it (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/MachineClients/MachineClientSettingsValidator.cs:37-40). Related: ADR-116, ADR-140.
  • Where it's used: called by MachineClientService at create and on every mint; ADC implements it as ServiceAccountProvisioner (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/Administration/ServiceAccountProvisioner.cs:25), registered at MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/DependencyInjection.cs:51.

LegalAcceptancePolicy

MMCA.Common.Application · MMCA.Common.Application.Auth.Legal · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Legal/LegalAcceptancePolicy.cs:10 · Level 3 · class (static)

  • What it is: the pure rules of terms acceptance, kept out of the controller and the consumer's service so they cannot drift.
  • Depends on: LegalAcceptanceOptions, LegalAcceptanceErrors, LegalAcceptanceDTO, Result.
  • Concept: server-authoritative version checking. [Rubric §11, Security] assesses whether consent is recorded against what the user actually saw: the client says which version it showed, and the server refuses unless it equals the configured one.
  • Walkthrough: ResolveCurrentVersion(options) (LegalAcceptancePolicy.cs:18) returns the trimmed configured version, or null for null options, null value or whitespace. EnsureAcceptsCurrentVersion(currentVersion, suppliedVersion, source) (:36) succeeds only when a version is configured and the trimmed supplied one matches it with an ordinal comparison; otherwise it fails with LegalAcceptanceErrors.VersionNotCurrent. Normalize(currentVersion, standing) (:50) re-derives the standing through LegalAcceptanceDTO.Evaluate, taking only the accepted version and instant from the consumer's answer, so the result never depends on a consumer filling CurrentVersion or IsCurrent correctly.
  • Why it's built this way: the ordinal match means a client holding stale terms cannot record consent to the new ones, and the no-version-configured failure means there is nothing to accept when the feature is off.
  • Where it's used: LegalAcceptanceControllerBase (LegalAcceptanceControllerBase.cs:54,83,110,125), AuthenticationValidators (AuthenticationValidators.cs:84), and LegalAcceptancePolicyTests.cs (MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Auth/Legal/).

IAccountClaimService

MMCA.Common.Application · MMCA.Common.Application.Auth.EmailConfirmation · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/EmailConfirmation/IAccountClaimService.cs:17 · Level 4 · interface

  • What it is: the account-proof steps an email confirmation needs when the unconfirmed account already holds a password: verify the current password under the sign-in lockout accounting, or let the mailbox owner claim the account with a new password (IAccountClaimService.cs:6-10).
  • Depends on: IAuthUser, IPasswordChangeableUser, Result, the UserIdentifierType alias.
  • Concept introduced: proof of the account, not just of the mailbox. A confirmation token proves only that the caller can read the address's mail; for an account that already has a password, the confirming handler additionally asks for that password or a new one, and a new one is a takeover by the mailbox owner, so it is made to cost every existing session and second factor. [Rubric §11, Security] (assesses whether account-recovery paths resist takeover and guessing): the current-password check goes through the same lockout counter as sign-in, so the confirmation endpoint is not a side door for password guessing, and a claim ends every session an earlier holder of the password could still be using.
  • Walkthrough: VerifyCurrentPasswordAsync(user, email, currentPassword, ct) (:30-34) verifies the password exactly as a password sign-in does: a locked address is refused before the check, a wrong password counts as a failed attempt, a right one changes nothing (doc :19-23), and the result is success, the lockout refusal, or Auth.InvalidCredentials (:29). ClaimWithNewPasswordAsync(userId, user, newPassword, ct) (:46-50) revokes every refresh session, removes any enrolled or pending second factor, then applies the already policy-validated password to the tracked account, stopping at the first failure (doc :36-45). ClearFailedAttemptsAsync(email, ct) (:56) clears the lockout counter as a successful sign-in does; the caller runs it only after its own write succeeds (doc :22-23).
  • Why it's built this way: the service changes the account aggregate but never saves it, so the caller owns the unit of work, while session revocation and second-factor removal persist through their own stores before the account changes, matching ResetPasswordHandlerBase (remarks :11-16). It is registered by AddEmailConfirmation, so an app that wires ConfirmEmailHandlerBase gets it with no registration of its own (:12-13). Opt-in shape: ADR-116.
  • Where it's used: implemented by AccountClaimService, registered with TryAddScoped (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Auth.cs:96), injected into ConfirmEmailHandlerBase (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/EmailConfirmation/ConfirmEmailHandlerBase.cs:68), which calls VerifyCurrentPasswordAsync (:244-245), ClaimWithNewPasswordAsync (:267-268) and ClearFailedAttemptsAsync (:181), and passed through by ADC's ConfirmEmailHandler (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/ConfirmEmail/ConfirmEmailHandler.cs:30); covered by ConfirmEmailAccountProofTests.cs, EmailConfirmationHandlerBaseTests.cs and ADC's ConfirmEmailHandlerTests.cs.

IMachineClientStore

MMCA.Common.Application · MMCA.Common.Application.Auth.MachineClients · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/MachineClients/IMachineClientStore.cs:10 · Level 5 · interface

  • What it is: persistence for MachineClient rows.
  • Depends on: MachineClient.
  • Concept: a narrow store interface rather than the generic repository; no new concept. Every caller sits behind MachineClients:Enabled, so it never queries a table the model does not carry (doc comment IMachineClientStore.cs:5-9).
  • Walkthrough: ListAsync (:15) returns every client, revoked ones included, oldest first. FindAsync(clientId, ct) (:21) returns a tracked instance, so SaveAsync(client, ct) (:33) persists changes made to it. AddAsync (:27) adds and saves a new client. RecordUseAsync(client, usedOn, ct) (:44) calls MachineClient.RecordUse and saves best effort: a concurrent issuance that saved first wins, because the last-used instant is informational and must never fail a token request.
  • Why it's built this way: the best-effort RecordUseAsync keeps a concurrency conflict on a diagnostic column off the token path. See ADR-140.
  • Where it's used: implemented by EFMachineClientStore over the Identity database, registered with TryAddScoped (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.MachineClients.cs:53), and consumed by MachineClientService.

MachineClientService

MMCA.Common.Application · MMCA.Common.Application.Auth.MachineClients · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/MachineClients/MachineClientService.cs:41 · Level 6 · class (sealed)

  • What it is: the framework's IMachineClientService: it runs the client credentials grant and administers clients.
  • Depends on: IMachineClientStore, IServiceAccountProvisioner, ITokenService, IPermissionRegistry, ICacheService, IOptions<MachineClientSettings>, TimeProvider (primary constructor, MachineClientService.cs:41-48); plus MachineClient, MachineClientSecret, AdministrationPermissions, AuthClaimTypes and SoftDeletedUserCache.
  • Concept introduced: a machine token is minted by the raw ITokenService, not the session-stamping wrapper the sign-in workflow uses, so it carries no sid, mfa or auth_time and opens no refresh session; it carries the service account's standard claims and role permissions as a person's token does, plus client_id and token_use=machine (remarks :16-20). [Rubric §11, Security] (assesses least privilege and revocation): four permissions are refused on the backing role, checked at create and again at every mint (remarks :23-25); create and rotate also apply the caller's privilege ceiling, so no operator hands a client more than they hold, the rule users and roles administration already apply (remarks :28-31); and revocation reuses the soft-deleted-user marker of ADR-047.
  • Walkthrough: ClientCredentialsGrantType is "client_credentials" (:51). ForbiddenPermissions (:58-64) lists ViewAsUsers, ManageUsers, ManageRoles and ManageClients: role and client management are included because a client could otherwise grant its own role anything or mint further clients for itself (:53-57). IssueTokenAsync (:72) refuses a missing or foreign grant type (:78-86), then collapses every other failure to one InvalidClient result: unparsable id or empty secret (:89), unknown client or Accepts false (:96), and an account that is missing, mismatched or holds a forbidden role, re-read on every mint (:103-104). It then mints with GenerateShortLivedAccessToken at AccessTokenMinutes (:109-121), records the use (:123) and returns a Bearer response (:125). CreateAsync(request, callerHoldsPermission, ct) (:142) requires a role (:149), refuses a role carrying a forbidden permission (:154), then applies the ceiling (:159, MachineClientErrors.PrivilegeCeiling), and validates the client row on a throwaway hash (:167), all BEFORE provisioning the account (:173), so a refused create leaves no orphaned account (remarks :136-141). RotateAsync(clientId, callerHoldsPermission, ct) (:190) answers NotFound for an unknown client, then, when a ceiling is supplied, reads the role from the client's service account and refuses with PrivilegeCeiling when the account cannot be read or the caller lacks one of its permissions (:201-208), before rotating and saving (:211-217). PromoteAsync (:222) delegates to the entity and saves. RevokeAsync (:248) saves the revoked row first (:256-257), then writes the marker for the service account with a duration from SoftDeletedUserCache.MarkerDurationFor over the longer of the machine and host access-token lifetimes (:260-263). IsForbiddenRole (:279) reads the role's permissions from the registry, and CallerHoldsEveryPermissionOf (:293-294) reads the same registry and requires the predicate to pass for every permission the role grants, returning true when no predicate is supplied (doc :285-292).
  • Why it's built this way: saving before marking means no new token is minted once revocation starts, and the marker then makes every service's SoftDeletedUserMiddleware answer 401 to tokens the client already holds (remarks :241-247). The duration assumes the default bearer clock skew, since this layer cannot read the host's JwtBearerOptions (:259). A rotation whose account can no longer be read is refused under a ceiling because it has no role to measure (remarks :186-189). See ADR-140.
  • Where it's used: registered by AddMachineClients (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.MachineClients.cs:54) and reached through the G12 controller bases; covered by MachineClientServiceRevocationMarkerTests.cs (MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Auth/MachineClients/), the API test host MachineClientTestHost.cs (MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/Controllers/MachineClients/) and ADC's MachineClientControllersTests.cs.

AccountClaimService

MMCA.Common.Application · MMCA.Common.Application.Auth.EmailConfirmation · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/EmailConfirmation/AccountClaimService.cs:20 · Level 8 · class (sealed)

  • What it is: the framework's IAccountClaimService, built over the same password hasher, lockout service and session revocation that password sign-in and ResetPasswordHandlerBase use (AccountClaimService.cs:8-11).
  • Depends on: IPasswordHasher, ILoginProtectionService, IRefreshSessionStore, an optional ITwoFactorStore and an optional TimeProvider (primary constructor, :20-25); plus RefreshSessionRevocation, IAuthUser and IPasswordChangeableUser.
  • Concept: the account-proof concept is taught on IAccountClaimService; this class shows it reuses the sign-in building blocks rather than duplicating them. twoFactorStore is null on a host that has not adopted two-factor authentication (:15-18), and timeProvider defaults to the system clock for the revocation stamp (:19), the optional-constructor-argument shape that keeps identity completions opt-in (ADR-116).
  • Walkthrough: VerifyCurrentPasswordAsync (:28) first returns the lockout refusal from CheckLockoutAsync when the address is locked (:36-40), then succeeds when VerifyPassword matches the stored hash and salt (:42-45); otherwise it calls IncrementFailedAttemptsAsync (:47) and fails with Error.Unauthorized("Auth.InvalidCredentials", "The password is incorrect.") (:48-49). ClaimWithNewPasswordAsync (:53) revokes every refresh session through RefreshSessionRevocation.RevokeAllAsync (:63-65), then, when a two-factor store is present and the account has an enabled factor or a pending secret, calls DisableAsync and returns its failure if it fails (:67-78), and finally hashes the new password and returns user.ChangePassword(newHash, newSalt) (:80-81). ClearFailedAttemptsAsync (:85-86) forwards to ResetFailedAttemptsAsync.
  • Why it's built this way: the revocation is persisted before the account changes, in the ResetPasswordHandlerBase order, so the store's save never carries a half-applied account and a failure leaves the password as it was (comment :61-62). Reusing the lockout service means a wrong current password on the confirmation path is counted exactly as on sign-in.
  • Where it's used: registered as the IAccountClaimService implementation with TryAddScoped (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Auth.cs:96) and reached through ConfirmEmailHandlerBase; covered by ConfirmEmailAccountProofTests.cs (MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Users/UseCases/EmailConfirmation/).
  • Caveats / not-in-source: RefreshSessionRevocation.RevokeAllAsync and the two-factor store's persistence are not shown in this file; that they save through their own stores rests on the interface remarks (IAccountClaimService.cs:14-15) and the inline comment, not on code read here.

IPermissionGrantCache

MMCA.Common.Application · MMCA.Common.Application.Auth.Permissions · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Permissions/IPermissionGrantCache.cs:21 · Level 0 · interface

  • What it is: the read side of the in-memory snapshot of stored (database-granted, as opposed to compiled-into-code) permissions, keyed by role.
  • Depends on: nothing first-party in its own signature; consumed alongside IPermissionRegistry.
  • Concept introduced: the cache-in-front-of-a-store pattern used across this group for data that is read on every authorization check but changes rarely. [Rubric §12, Performance & Scalability] (assesses whether hot paths avoid a database round trip): GetPermissions (IPermissionGrantCache.cs:29) is synchronous and reads the already-loaded snapshot, so it stays off the authorization hot path's I/O.
  • Walkthrough: GetPermissions(string role) (line 99) returns the role's stored permissions, matched case-insensitively, empty when the role has none or the cache has not loaded yet. RefreshAsync (line 107) reloads the whole snapshot from the store; called at startup, on a configured interval, and explicitly by IPermissionGrantCacheInvalidator after a grant changes.
  • Why it's built this way: separating the read interface from the invalidation interface (IPermissionGrantCacheInvalidator) lets LayeredPermissionRegistry, which only needs to read, depend on a narrower contract than the administration path that needs to force a reload.
  • Where it's used: implemented by PermissionGrantCache (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Auth/PermissionGrantCache.cs), read by LayeredPermissionRegistry (LayeredPermissionRegistry.cs) and StoredPermissionRoleAdministrationService, and registered in MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs.

IPermissionGrantCacheInvalidator

MMCA.Common.Application · MMCA.Common.Application.Auth.Permissions · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Permissions/IPermissionGrantCache.cs:53 · Level 0 · interface

  • What it is: the write-triggering half of the cache: forces a reload of one role's grants (or every role) after an administrative change.
  • Depends on: nothing first-party in its own signature.
  • Concept: same cache-invalidation split introduced at IPermissionGrantCache; no new concept here.
  • Walkthrough: InvalidateAsync(string? role = null, ...) (IPermissionGrantCache.cs:61) invalidates the cached grants and reloads them; null means every role.
  • Why it's built this way: kept on a separate, narrower interface from the read side so a caller that only grants or revokes (the administration surface) depends on exactly the capability it needs.
  • Where it's used: implemented alongside IPermissionGrantCache by PermissionGrantCache.cs, called by StoredPermissionRoleAdministrationService.cs after a grant or revoke, and registered in MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs.

PasskeyAttestation

MMCA.Common.Application · MMCA.Common.Application.Auth.Passkeys · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Passkeys/PasskeyAttestation.cs:9 · Level 0 · record

  • What it is: the verified result of a passkey registration: the credential id, the public key, the authenticator's starting signature counter and its transports.
  • Depends on: nothing first-party; BCL byte[], IReadOnlyList<string>.
  • Concept: a library-neutral output record, so the WebAuthn library's own types never cross into the core layers (see IPasskeyCeremony); no new concept.
  • Walkthrough: a single positional record line (PasskeyAttestation.cs:9): CredentialId, PublicKey, SignCount (uint) and Transports.
  • Why it's built this way: it carries exactly what PasskeyService needs to build a PasskeyCredential (PasskeyService.cs:100-107) and nothing of the verification library, which keeps Fido2NetLib confined to MMCA.Common.Passkeys (ADR-139, decision 1).
  • Where it's used: returned by IPasskeyCeremony.VerifyRegistrationAsync and produced by Fido2PasskeyCeremony (MMCA.Common/Source/Core/MMCA.Common.Passkeys/Fido2PasskeyCeremony.cs).

PasskeyChallenge

MMCA.Common.Application · MMCA.Common.Application.Auth.Passkeys · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Passkeys/PasskeyChallenge.cs:7 · Level 0 · record

  • What it is: the server-side half of a passkey ceremony in flight: which ceremony it is, which account it was issued to (registration only), and the options JSON exactly as sent to the browser.
  • Depends on: the UserIdentifierType alias (see the primer).
  • Concept: the stored challenge a completion must redeem; the single-use mechanics live in PasskeyChallenges.
  • Walkthrough: the positional record PasskeyChallenge(string Ceremony, UserIdentifierType? UserId, string OptionsJson) (PasskeyChallenge.cs:7) plus two ceremony constants: Register = "register" (line 10) and SignIn = "signin" (line 13). UserId is null for a sign-in, because a discoverable sign-in names no account before the assertion.
  • Why it's built this way: keeping the options verbatim lets the completion verify against what was actually issued, and recording the ceremony and account lets PasskeyService refuse a flow redeemed by the wrong ceremony or another account (PasskeyService.cs:80-84).
  • Where it's used: built by PasskeyService (PasskeyService.cs:66, :188), serialized and redeemed by PasskeyChallenges.

PasskeySettings

MMCA.Common.Application · MMCA.Common.Application.Auth.Passkeys · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Passkeys/PasskeySettings.cs:19 · Level 0 · class

  • What it is: the options class bound to the Passkeys section: the on/off switch, the WebAuthn relying party, the allowed browser origins, and the data source that owns the passkey table.
  • Depends on: nothing first-party.
  • Concept: the same config-bound settings shape as EmailConfirmationSettings; its validation is a separate validator, PasskeySettingsValidator, per the fail-fast configuration contract (ADR-070).
  • Walkthrough: SectionName (PasskeySettings.cs:22) is "Passkeys". Enabled (line 25) defaults to false. RelyingPartyId (line 31) is the registrable domain the passkeys belong to (example.com also covers app.example.com), required when enabled. RelyingPartyName (line 34) is the name the authenticator shows, required when enabled. Origins (line 40) lists the exact scheme, host and port the browser ceremonies may run on, at least one required when enabled. DataSourceName (line 46) defaults to "Default" and names the logical data source holding the PasskeyCredentials table (the Identity database).
  • Why it's built this way: passkeys are an opt-in, so the default is off and a disabled host carries no relying-party configuration at all (ADR-139, decision 2). DataSourceName follows the same gated-table shape as the permission grants (PermissionGrantSettings): the table is mapped only on the named source.
  • Where it's used: bound and validated by PasskeysServiceCollectionExtensions and PasskeySettingsValidator (MMCA.Common/Source/Core/MMCA.Common.Passkeys), read by Fido2PasskeyCeremony, PasskeyService (IsEnabled), EFPasskeyCredentialStore.cs, ApplicationDbContext.cs and DesignTimeDbContextHelper.cs (under MMCA.Common/Source/Core/MMCA.Common.Infrastructure); pinned by PasskeyModelGateTests.cs and AddPasskeysTests.cs.

PasskeyStepUp

MMCA.Common.Application · MMCA.Common.Application.Auth.Passkeys · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Passkeys/PasskeyStepUp.cs:17 · Level 0 · class

  • What it is: the rule that decides whether a signed-in caller may register a passkey: their interactive sign-in must be at most ten minutes old.
  • Depends on: BCL ClaimsPrincipal, TimeSpan, DateTimeOffset; the FindAuthTime() principal extension that reads the auth_time claim.
  • Concept introduced: step-up by sign-in age. A sensitive action (planting a new sign-in method on the account) asks "how long ago did this person actually sign in", not "how fresh is this token". [Rubric §11, Security] (assesses how authentication and authorization resist account takeover): the check reads auth_time, which a refresh carries over unchanged, so a stolen refresh token can never keep itself fresh enough to register its own passkey.
  • Walkthrough: MaxSignInAge (PasskeyStepUp.cs:20) is ten minutes. IsSatisfiedBy(principal, now) (lines 26-30) reads the sign-in instant with principal.FindAuthTime() (line 27); a principal with no auth_time never qualifies, and a sign-in stamped slightly in the future (clock skew between hosts, comment at line 29) counts as recent because only now - signedInAt <= MaxSignInAge is tested (line 30).
  • Why it's built this way: per ADR-139 decision 8, the alternatives ("a token under ten minutes old" or "a token carrying mfa") both ride every refresh, since a refresh resets iat and carries mfa; only auth_time measures the sign-in itself.
  • Where it's used: checked by both registration actions of PasskeysControllerBase.cs and by TwoFactorControllerBase.cs (under MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers); the refusal is PasskeyErrors.StepUpRequired; pinned by AuthTimeClaimTests.cs.

PasskeyStoredKey

MMCA.Common.Application · MMCA.Common.Application.Auth.Passkeys · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Passkeys/PasskeyStoredKey.cs:8 · Level 0 · record

  • What it is: what an assertion is verified against: the stored public key, the last signature counter, and the owning account's WebAuthn user handle.
  • Depends on: nothing first-party.
  • Concept: the input-side twin of PasskeyAttestation, keeping the ceremony contract free of the domain entity; no new concept.
  • Walkthrough: one positional record line (PasskeyStoredKey.cs:8): PublicKey, SignCount (uint), UserHandle.
  • Why it's built this way: PasskeyService builds it from a PasskeyCredential with the handle derived by UserHandleFor (PasskeyService.cs:255), so the verification library sees bytes, never the entity.
  • Where it's used: passed to IPasskeyCeremony.VerifyAssertionAsync, consumed by Fido2PasskeyCeremony.

PermissionGrantSettings

MMCA.Common.Application · MMCA.Common.Application.Auth.Permissions · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Permissions/PermissionGrantSettings.cs:9 · Level 0 · class

  • What it is: the options class bound to Authentication:PermissionGrants, controlling how long a cached grant snapshot is served, which logical data source owns the grant table, and which role names the administration surface lists.
  • Depends on: nothing first-party; System.ComponentModel.DataAnnotations ([Range], [Required]).
  • Concept: the same config-bound settings shape as EmailConfirmationSettings; no new concept.
  • Walkthrough: SectionName (PermissionGrantSettings.cs:12) is "Authentication:PermissionGrants". CacheSeconds (line 34) defaults to 30, is range-validated to 5-3600 (line 33), and its remarks (lines 17-32) spell out two things. First the trade-off (lines 18-26): this is the bound on how stale another replica may be after an edit, since invalidation is per process, and the stored grants are read by the token-minting Identity service, so any lag here is added on top of the access token's lifetime (15 minutes by default) before a revoke reaches every service. Second the failure behavior (lines 27-31): each cached entry lives three intervals, so the snapshot outlives the gap before the next reload and survives up to two failed reloads, after which it stops answering and stored grants fail closed. DataSourceName (line 42, [Required] at line 41) defaults to "Default", naming the logical data source a modular host points at its Identity database. KnownRoles (line 54) defaults to an empty list, and its remarks (lines 48-53) explain why it must be configured: neither IPermissionRegistry (which answers questions about a role but does not list roles) nor the grant table (which only knows roles that already have a grant) can enumerate roles on its own; left empty, the surface still works but lists nothing until the first grant exists.
  • Why it's built this way: the 30-second default keeps the revoke window close to the token lifetime itself, at the cost of one small query per Identity replica every 30 seconds and with no broker on the authorization path; raising it trades a longer revoke window for fewer database reads (PermissionGrantSettings.cs:24-26). The three-interval entry lifetime means a transient store outage costs nothing for two reload cycles, while a longer one degrades to denying stored grants (compiled permissions are unaffected, see LayeredPermissionRegistry) rather than serving an arbitrarily old snapshot.
  • Where it's used: read by PermissionGrantCache.cs, PermissionGrantRefreshService.cs, EFPermissionGrantStore.cs, StoredPermissionRoleAdministrationService.cs, ApplicationDbContext.cs, and DesignTimeDbContextHelper.cs (all under MMCA.Common/Source/Core/MMCA.Common.Infrastructure); registered in MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Auth.cs; pinned by PermissionGrantModelGateTests.cs and PermissionGrantCacheTests.cs in MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests.

LayeredPermissionRegistry

MMCA.Common.Application · MMCA.Common.Application.Auth.Permissions · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Permissions/LayeredPermissionRegistry.cs:30 · Level 1 · class

  • What it is: an IPermissionRegistry decorator that unions the compiled-into-code permission set with the stored (database-granted) set, so a role's effective permissions are "compiled OR granted", never a replacement of one by the other.
  • Depends on: IPermissionRegistry (the inner, compiled registry), IPermissionGrantCache (the stored-grant cache).
  • Concept introduced: the decorator pattern applied to a registry lookup. [Rubric §2, Design Patterns] (assesses whether a pattern is used idiomatically and solves a real problem): LayeredPermissionRegistry wraps inner without changing its contract, adding a second data source transparently to every caller of IPermissionRegistry.
  • Walkthrough: the type is a primary-constructor class taking inner and grants (LayeredPermissionRegistry.cs:30-32). GetPermissions(role) (lines 35-52) reads both layers; when the stored set is empty it returns the compiled set as-is (no allocation), and only when both layers contribute does it materialize a HashSet<string> union, per the comment at lines 45-47: this call is a reporting path (administration surface, diagnostics), not the hot authorization path. HasPermission(roles, permission) (lines 55-66) is that hot path: it short-circuits on the compiled registry first (inner.HasPermission), and only falls through to a per-role stored-grant lookup (grants.GetPermissions(role).Contains(permission)) when the compiled check fails; the caller's roles sequence is materialized once (line 62) because both passes would otherwise enumerate it twice.
  • Why it's built this way: separating the always-cheap compiled check from the stored-grant fallback keeps the common case (a permission granted in code) allocation-free and single-pass, per ADR-116, which records the opt-in database-grant layer as additive on top of the existing compiled registry.
  • Where it's used: registered as the IPermissionRegistry implementation in MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs (3 sites) when database grants are enabled; exercised directly in MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Auth/LayeredPermissionRegistryTests.cs.

PasskeyErrors

MMCA.Common.Application · MMCA.Common.Application.Auth.Passkeys · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Passkeys/PasskeyErrors.cs:10 · Level 2 · class

  • What it is: the catalogue of passkey refusals, each a stable code constant plus a factory returning a typed Error.
  • Depends on: Error.
  • Concept: the same per-feature error catalogue as TwoFactorErrors and SignInLinkErrors; the error kind on each factory picks the HTTP status (see the Result pattern in the primer).
  • Walkthrough: seven code constants (PasskeyErrors.cs:13-31), all prefixed Passkeys.; PasskeysNotSupportedCode is named apart from the sign-in-link constant because the error-resource scan resolves codes by name (comment at line 12). The factories, each taking an optional source: NotSupported (line 36, Error.Validation), ChallengeInvalid (line 42, Error.Validation: unknown, expired, used, or the wrong ceremony or account), RegistrationFailed (line 48, Error.Validation), AssertionFailed (line 54, Error.Unauthorized), StepUpRequired (line 63, Error.Forbidden, pointing at PasskeyStepUp), LastPasskey (line 69, Error.Conflict) and NotFound (line 75, Error.NotFoundError).
  • Why it's built this way: AssertionFailed is deliberately one vague message for every sign-in refusal (unknown credential, bad signature, counter); the specific reason goes only to a Warning log in PasskeyService, so a caller cannot probe which credentials exist (ADR-139, decision 7).
  • Where it's used: PasskeyService (8 sites), Fido2PasskeyCeremony, PasskeysControllerBase.cs, AuthenticationServiceBase<TUser> and IAuthenticationService (the not-supported default), and PasskeysPanel.razor.cs in MMCA.Common.UI.

IPasskeyCeremony

MMCA.Common.Application · MMCA.Common.Application.Auth.Passkeys · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Passkeys/IPasskeyCeremony.cs:19 · Level 3 · interface

  • What it is: the core contract for the WebAuthn cryptography: build creation and request options, verify an attestation, read a credential id from an assertion, verify an assertion.
  • Depends on: PasskeyAttestation, PasskeyStoredKey, Result; BCL JsonElement.
  • Concept introduced: a library boundary held by a core interface. [Rubric §32, Dependency & Supply-Chain] (assesses how third-party code is contained and pinned): every member speaks JSON strings, JsonElement and byte arrays, so the Fido2 package and its native dependencies live only in MMCA.Common.Passkeys, which a host opts into, and the core layers never load them.
  • Walkthrough: CreateRegistrationOptions(userHandle, userName, displayName, excludeCredentialIds) (IPasskeyCeremony.cs:27) returns creation options as JSON, excluding the account's existing credentials so an authenticator is not enrolled twice. VerifyRegistrationAsync(optionsJson, attestation, isCredentialIdUnique, ...) (lines 35-39) verifies against the options as issued and calls back to ask whether the credential id is unused. CreateSignInOptions() (line 43) builds request options naming no credential (a discoverable sign-in). ReadCredentialId(assertion) (line 48) returns the id or null when malformed. VerifyAssertionAsync(optionsJson, assertion, credential, ...) (lines 60-64) checks the signature, user handle and counter, and returns the counter the authenticator reported.
  • Why it's built this way: ADR-139 decision 1 keeps the WebAuthn library in one package behind this contract, guarded at build time (EnforcePasskeysBoundary) and test time (PasskeysIsolationTests.cs). The uniqueness callback lets the store answer without the ceremony depending on persistence.
  • Where it's used: implemented by Fido2PasskeyCeremony, registered by PasskeysServiceCollectionExtensions, consumed by PasskeyService; its absence while Passkeys:Enabled is true fails startup in CloudAdapterTripwire.cs (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Configuration).

IPasskeyService

MMCA.Common.Application · MMCA.Common.Application.Auth.Passkeys · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Passkeys/IPasskeyService.cs:12 · Level 3 · interface

  • What it is: the application-facing passkey surface: begin and complete a registration, list, rename and delete an account's passkeys, and begin and complete a passkey sign-in.
  • Depends on: PasskeyOptionsResponse, PasskeyRegisterRequest, PasskeyResponse, PasskeySignInRequest, AuthenticationResponse, IAuthenticationService, Result.
  • Concept: a two-step begin/complete ceremony, where begin stores a single-use challenge and complete must redeem it (see PasskeyChallenges); no further new concept.
  • Walkthrough: IsEnabled (IPasskeyService.cs:15) mirrors Passkeys:Enabled. BeginRegistrationAsync(userId, userName, displayName, ...) (lines 23-27) and CompleteRegistrationAsync(userId, request, ...) (lines 34-37) run registration for a signed-in account, which must be the one the flow was issued to. ListAsync (line 43) returns the passkeys oldest first; RenameAsync (lines 51-55) relabels one. DeleteAsync (line 65) removes one, the last only while the account still has a password or external login (remarks at lines 58-59, via IAuthenticationService.HasSignInMethodBesidesPasskeysAsync). BeginSignInAsync (line 70) starts an anonymous discoverable sign-in, and CompleteSignInAsync(request, ipAddress, userAgent, ...) (lines 81-85) verifies the assertion and mints the token pair through IAuthenticationService.SignInWithPasskeyAsync.
  • Why it's built this way: the sign-in ends in the app's own authentication service, so a passkey sign-in produces the same token pair, refresh session and sign-in history as any other, stamped mfa=passkey (ADR-139, decision 7).
  • Where it's used: implemented by PasskeyService, registered by PasskeysServiceCollectionExtensions, called by PasskeysControllerBase.cs (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Passkeys); pinned by AddPasskeysTests.cs and PasskeysIsolationTests.cs.

IPasskeyCredentialStore

MMCA.Common.Application · MMCA.Common.Application.Auth.Passkeys · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Passkeys/IPasskeyCredentialStore.cs:10 · Level 4 · interface

  • What it is: the persistence abstraction for stored passkeys: list an account's, find by row id or by WebAuthn credential id, add, update, remove.
  • Depends on: PasskeyCredential.
  • Concept: the same narrow store-behind-an-interface shape as IPermissionGrantStore; each write saves immediately rather than joining a unit of work.
  • Walkthrough: ListForUserAsync(userId, ...) (IPasskeyCredentialStore.cs:16) returns oldest first. FindAsync(userId, id, ...) (line 23) scopes by account, so another account's row reads as missing. FindByCredentialIdAsync(credentialId, ...) (line 29) searches across all accounts, which is what sign-in and the registration uniqueness check need. AddAsync (line 35), UpdateAsync (line 41, for a rename or a recorded use) and RemoveAsync (line 47) each save.
  • Why it's built this way: scoping FindAsync by account makes ownership a property of the query rather than a check every caller must remember. Removal is a hard delete: passkeys are flat bookkeeping with no soft-delete flag (ADR-139, decision 4).
  • Where it's used: implemented by EFPasskeyCredentialStore (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Auth/EFPasskeyCredentialStore.cs), registered in MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs, consumed by PasskeyService; faked in PasskeyTestHost.cs.

IPermissionGrantStore

MMCA.Common.Application · MMCA.Common.Application.Auth.Permissions · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Permissions/IPermissionGrantStore.cs:16 · Level 4 · interface

  • What it is: the persistence abstraction behind the stored-grant layer: read every grant, read one role's grants, grant a permission, revoke a permission.
  • Depends on: PermissionGrant (the persisted grant row), Result.
  • Concept: an idempotent grant/revoke pair, so a click repeated by an administration UI is not an error; no new concept beyond that idempotency guarantee.
  • Walkthrough: GetAllAsync(cancellationToken) (IPermissionGrantStore.cs:23) reads every stored row, used to build the in-memory snapshot the authorization path reads. GetPermissionsAsync(role, cancellationToken) (line 31) reads one role's stored permissions for the administration surface. GrantAsync(role, permission, grantedBy, cancellationToken) (lines 42-46) grants a permission, succeeding and writing nothing when the role already has it stored (doc comment lines 33-36). RevokeAsync(role, permission, cancellationToken) (line 60) removes a stored grant, also idempotent; its remarks (lines 51-55) are explicit that this removes only the STORED grant, never a compiled-into-code one, which is exactly what keeps a data edit from disabling an endpoint the code guarantees.
  • Why it's built this way: the "stored grant is additive, never subtractive over compiled permissions" rule enforced here is the same invariant LayeredPermissionRegistry.HasPermission implements: the compiled check always wins first, and revoking a stored grant can never take away a compiled-in permission.
  • Where it's used: implemented by EFPermissionGrantStore (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Auth/EFPermissionGrantStore.cs), read by PermissionGrantCache.cs (2 sites) to build the IPermissionGrantCache snapshot, called by IRoleAdministrationService's implementation StoredPermissionRoleAdministrationService.cs (2 sites), and registered in MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs.

PasskeyChallenges

MMCA.Common.Application · MMCA.Common.Application.Auth.Passkeys · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Passkeys/PasskeyChallenges.cs:21 · Level 5 · class

  • What it is: the single-use challenge store for passkey ceremonies, plus the per-account lock that serializes passkey deletions.
  • Depends on: ICacheService, IDistributedLock, PasskeyChallenge; BCL RandomNumberGenerator, JsonSerializer.
  • Concept introduced: read-and-burn under a distributed lock. A challenge must be redeemable exactly once across every replica, so redemption reads the shared store and removes the entry inside one lock, and a contended lock is itself treated as the replay. [Rubric §11, Security] (assesses replay and takeover resistance): a captured flow id cannot be redeemed twice, even by two requests racing on different replicas.
  • Walkthrough: Lifetime (PasskeyChallenges.cs:24) is five minutes. Keys are passkeys:challenge: plus a flow id of FlowIdLength 32 (lines 26-27); the lock lease and wait are 10 and 5 seconds (lines 31-32), sized like the OAuth exchange-code lock. IssueAsync (lines 38-47) generates the flow id from 16 random bytes as lower-case hex (line 42) and stores the serialized challenge for Lifetime (lines 43-44). RedeemAsync (lines 56-83) rejects anything not exactly 32 lower-case hex characters (line 58), takes lock: plus the key (line 64) and returns null when contended (lines 65-69), reads with GetFromSharedStoreAsync rather than a local copy (line 74) so a flow burned on another replica misses, then removes the entry and deserializes it (lines 80-81). LockAccountAsync(userId, ...) (lines 92-94) takes lock:passkeys:user:{userId}, returning null past the wait.
  • Why it's built this way: this is the OAuth exchange-code pattern applied to WebAuthn (ADR-139 decision 5, building on ADR-108 for the lock and ADR-077 for the cache). The account lock lives here because it uses the same lock primitive and timings.
  • Where it's used: consumed by PasskeyService (3 sites), registered in MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Caching.cs and by PasskeysServiceCollectionExtensions.

PasskeyService

MMCA.Common.Application · MMCA.Common.Application.Auth.Passkeys · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Passkeys/PasskeyService.cs:33 · Level 6 · class

  • What it is: the implementation of IPasskeyService: it orchestrates the challenge store, the WebAuthn ceremony, the credential store and the app's authentication service.
  • Depends on: PasskeySettings, IPasskeyCeremony, IPasskeyCredentialStore, PasskeyChallenges, IAuthenticationService, PasskeyCredential, PasskeyErrors; BCL TimeProvider, ILogger<T>.
  • Concept: orchestration over the contracts introduced at IPasskeyCeremony and PasskeyChallenges. [Rubric §13, Observability & Operability] (assesses whether failures are diagnosable): every refusal logs its specific reason at Warning through source-generated LoggerMessage methods (PasskeyService.cs:277-281) while the caller sees one generic error.
  • Walkthrough: a sealed partial primary-constructor class (PasskeyService.cs:33-40). IsEnabled (line 43) reads Enabled. UserHandleFor(userId) (lines 48-49) is the account id as UTF-8, opaque and free of personal data. BeginRegistrationAsync (lines 52-69) excludes the account's existing credential ids and issues a Register challenge. CompleteRegistrationAsync (lines 72-115) redeems the challenge and refuses it unless the ceremony is Register and the account matches (lines 80-84), verifies with a uniqueness callback over FindByCredentialIdAsync (lines 87-93), builds the entity with PasskeyCredential.Create (lines 100-107) and adds it (line 113). ListAsync (line 118) and RenameAsync (line 125) are thin. DeleteAsync (lines 153-179) takes the account lock (line 155), answering a Passkeys.Busy conflict when it cannot (line 158), and refuses LastPasskey when one passkey remains and the account has no other sign-in method (lines 170-173). BeginSignInAsync (line 182) issues a SignIn challenge with no account. CompleteSignInAsync (lines 194-218) redeems a SignIn challenge (line 203), verifies (line 209) and hands the user id to SignInWithPasskeyAsync (lines 215-216). The private VerifyAssertionAsync (line 236) reads the credential id (line 238), finds the credential across accounts (line 244), verifies against a PasskeyStoredKey (lines 251-257), then applies the counter rule itself with credential.RecordUse (line 266) before saving the use (line 273).
  • Why it's built this way: the signature-counter check runs here as well as in the library so the cloned-key rule does not depend on the library's own check (ADR-139, decision 6), and the count-then-delete inside the account lock stops two concurrent deletes of the last two passkeys from locking the user out (remarks at lines 148-152).
  • Where it's used: registered as IPasskeyService by PasskeysServiceCollectionExtensions; UserHandleFor is referenced from IPasskeyCeremony's documentation.

ISoftDeletedUserMarkerWriter

MMCA.Common.Application · MMCA.Common.Application.Auth.SoftDeletedUsers · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/SoftDeletedUsers/ISoftDeletedUserMarkerWriter.cs:9 · Level 0 · interface

  • What it is: the two-verb contract that writes and clears the soft-deleted user marker (ADR-047). Its summary (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/SoftDeletedUsers/ISoftDeletedUserMarkerWriter.cs:3-8) records that the marker now means "deleted or locked": an account erasure and an administrator's lock both write it, for as long as an already-issued access token on this host can still be accepted, and an unlock clears it.
  • Depends on: nothing first-party beyond the UserIdentifierType alias; Task and CancellationToken from the BCL. The cache and the token settings the marker needs are deliberately absent from the contract.
  • Concept introduced: a narrow writer that hides how a revocation is stored and how long it lasts. [Rubric §1, SOLID] assesses interface segregation and dependency inversion: whether a consumer depends only on what it uses. Writing the marker correctly needs two unrelated things (the shared cache it lives in, and the host's access-token lifetime that decides how long it must live), and the summary states the point of the abstraction directly: "neither workflow needs the cache nor the token settings itself" (ISoftDeletedUserMarkerWriter.cs:6-7). [Rubric §11, Security] assesses session revocation: a JWT stays valid until its exp, so a deleted or locked account's already-issued tokens must be refused by something other than the token. The marker is that something, and the second verb matters as much as the first: without ClearMarkerAsync, a token issued after an unlock would be refused on every host until the marker expired (doc at :19-22).
  • Walkthrough:
    • MarkDeletedAsync(userId, ct) (ISoftDeletedUserMarkerWriter.cs:17): marks the user as deleted or locked, so requests bearing an already-issued token are rejected (:11-13).
    • ClearMarkerAsync(userId, ct) (:26): removes the user's marker from the shared store, so a token issued after an unlock is accepted at once on every host (:19-22).
  • Why it's built this way: two workflows (account erasure and administrator lock/unlock) need the same marker with the same duration rule; putting the rule behind one writer keeps it in one place. The revocation model is recorded in ADR-047.
  • Where it's used: implemented by SoftDeletedUserMarkerWriter and registered as a scoped factory in MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.cs:63. Injected into UserAdministrationServiceBase<TUser, TUserDto> (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Administration/UserAdministrationServiceBase.cs:66, which writes the marker at :268 and clears it at :281) and into DeleteUserHandlerBase<TUser, TCommand> (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/DeleteUser/DeleteUserHandlerBase.cs:97, writing at :214). ADC passes it through its UserAdministrationService and DeleteUserHandler (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/).

IssuedSession

MMCA.Common.Application · MMCA.Common.Application.Auth.Sessions · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Sessions/AuthSessionIssuer.cs:752 · Level 0 · record (private sealed, nested)

  • What it is: the two-field result of opening or rotating a refresh session: the plaintext refresh token the client is handed, and the id of the session row it belongs to. It is a private sealed record nested inside AuthSessionIssuer (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Sessions/AuthSessionIssuer.cs:752), not part of the framework's public surface.
  • Depends on: nothing beyond the BCL (string, Guid). It is produced and consumed entirely inside its declaring class.
  • Concept introduced: the plaintext token exists in exactly one place, and it is a return value. [Rubric §11, Security] assesses how a bearer credential is stored. RefreshSession rows keep only a digest (RefreshSession.HashToken, used at AuthSessionIssuer.cs:200 and :285 to look up by hash), so once a session is persisted the raw token cannot be recovered from the store at all. The type comment says exactly this (AuthSessionIssuer.cs:747-751): the plaintext "exists nowhere else, since the store keeps only its hash". Modelling the hand-off as a small record rather than an out-parameter or a tuple is what keeps that fact readable: both methods that can produce a token return Result<IssuedSession>, so the compiler shows you the complete list of places raw token material is in flight. [Rubric §15, Best Practices & Code Quality] also applies: a positional record gives value equality and immutability for free, and Guid SessionId names what would otherwise be an anonymous second tuple element.
  • Walkthrough: one positional declaration, IssuedSession(string RefreshToken, Guid SessionId) (AuthSessionIssuer.cs:752). RefreshToken is what goes back to the caller in the AuthenticationResponse; SessionId is what the access token's sid claim carries, which is why the session must be opened before the token is minted (the comment at AuthSessionIssuer.cs:97-98).
  • Why it's built this way: the pairing is load-bearing rather than incidental. A caller that received only the token could not stamp sid, and a caller that received only the id could not answer the client. Returning both together removes the ordering mistake where a token is minted for a session that does not exist yet.
  • Where it's used: returned by OpenSessionAsync (AuthSessionIssuer.cs:494, constructed at :337) and RotateSessionAsync (:350, constructed at :390); unwrapped by IssueAsync (:84-85) and by RotateAsync (:120-121), each of which passes SessionId to the caller's mintAccessToken callback and puts RefreshToken into the response.

SignInLinkProfile

MMCA.Common.Application · MMCA.Common.Application.Auth.SignInLinks · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/SignInLinks/ISignInLinkTokenService.cs:75 · Level 0 · record (sealed)

  • What it is: the name an invitation creates the account with when the invited address has no account yet (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/SignInLinks/ISignInLinkTokenService.cs:72-75).
  • Depends on: PiiAttribute on both members; otherwise only string.
  • Concept: the personal-data marking is taught at PiiAttribute. The one detail worth seeing here is the [property: Pii] target: on a positional record parameter an unqualified attribute lands on the constructor parameter, so the explicit property: target is what puts the marker on the generated FirstName and LastName properties that tooling actually reflects over.
  • Walkthrough: one positional declaration, SignInLinkProfile(string FirstName, string LastName) (ISignInLinkTokenService.cs:75).
  • Where it's used: passed as the optional profile argument of ISignInLinkTokenService.IssueAsync (ISignInLinkTokenService.cs:38, supplied only for an invitation, doc :26-29), stored with the token by SignInLinkTokenService, and handed back on redemption as SignInLinkGrant.Profile, which RedeemSignInLinkHandlerBase<TUser, TCommand> reads to provision the account.

SignInLinkPurpose

MMCA.Common.Application · MMCA.Common.Application.Auth.SignInLinks · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/SignInLinks/ISignInLinkTokenService.cs:63 · Level 0 · enum

  • What it is: why a sign-in link was sent. Each purpose has its own lifetime and its own active token (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/SignInLinks/ISignInLinkTokenService.cs:62).
  • Depends on: nothing.
  • Concept: keying a single-use token by address AND purpose. The interface remarks (ISignInLinkTokenService.cs:12-17) give the reason: one active token per address and purpose, so asking for a sign-in link does not silently invalidate an outstanding invitation for the same address.
  • Walkthrough: SignIn = 0 (:62), the account owner asked for a link from the sign-in page, short-lived; Invite = 1 (:65), an organizer invited the address, long-lived, and may create the account. The explicit values pin the numbering.
  • Where it's used: selects the lifetime in SignInLinkSettings.LifetimeFor (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/SignInLinks/SignInLinkSettings.cs:58-59), is the second key of every token in SignInLinkTokenService (which enumerates both values at MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/SignInLinks/SignInLinkTokenService.cs:53), and comes back on redemption in SignInLinkGrant. SendSignInLinkHandlerBase issues SignIn; an invitation is issued as Invite through ISignInLinkTokenService directly (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/SignInLinks/SendSignInLinkHandlerBase.cs:43).

SessionStampingTokenService

MMCA.Common.Application · MMCA.Common.Application.Auth.Sessions · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Sessions/AuthSessionIssuer.cs:766 · Level 1 · class (private sealed, nested)

  • What it is: a pass-through ITokenService that appends up to three claims to every access token minted while it is armed (the current refresh session's sid, an mfa claim when a second factor verified this request, and an auth_time claim carrying the sign-in instant), the configured-lifetime and the short-lived kind alike, and behaves as the plain inner service the rest of the time (summary MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Sessions/AuthSessionIssuer.cs:754-760). It is a private sealed class nested inside AuthSessionIssuer (AuthSessionIssuer.cs:766).
  • Depends on: ITokenService (the contract it implements and the inner instance it wraps, AuthSessionIssuer.cs:766), AuthClaimTypes for the sid, mfa and auth_time claim names (:828, :833, :839), and the BCL (System.Security.Claims, System.Globalization.CultureInfo).
  • Concept introduced: a decorator used to make a new claim additive. [Rubric §2, Design Patterns] assesses idiomatic pattern use, and this is the Decorator pattern applied to a very specific compatibility problem. Access tokens need to name the session they belong to (and, when relevant, the second factor that satisfied a step-up and the instant the user actually signed in), but the claim set is produced by the app's own CreateAccessToken hook. The obvious fix, adding parameters to that hook, is a compile break in every consumer for claims the app has no decision to make about; the type's own remarks say exactly this (AuthSessionIssuer.cs:761-765). Wrapping the token service instead means the issuer arms the wrapper around the hook call and the claims appear in tokens minted by subclasses that were never edited. [Rubric §15, Best Practices & Code Quality] is the payoff: an additive protocol change with a zero-line consumer diff, three times over.
  • Walkthrough: a primary constructor takes the inner service (AuthSessionIssuer.cs:766).
    • Guid? CurrentSessionId { get; set; } (:769) is the session arming switch: a session id stamps, null mints unchanged.
    • string? CurrentMultiFactorMethod { get; set; } (:775) is the second-factor arming switch, set only when a second factor really verified for this request (doc :771-774).
    • DateTimeOffset? CurrentAuthTime { get; set; } (:778) is the sign-in-instant switch. The remarks on the issuer's arming method explain why plain mutable properties are safe for all three (:161-162): the issuer is resolved per request (scoped, like the store it saves through) and one request mints one token at a time.
    • AccessTokenLifetime (:781) and RefreshTokenLifetime (:784) forward straight to inner, so the lifetime callers read is still the JWT settings' value.
    • GenerateAccessToken(...) (:787-793) and GenerateShortLivedAccessToken(..., lifetime) (:796-803) both forward to inner with Stamp(additionalClaims) in place of the caller's claims, so a short-lived token minted through this instance while it is armed carries the same claims as a configured-lifetime one.
    • Stamp(additionalClaims) (:815-845) is the only member with behavior. When no switch is armed it hands the caller's sequence back unchanged (:817-820). Otherwise it copies the app's additionalClaims into a new List<Claim> (:822, so the caller's sequence is never mutated), then independently appends AuthClaimTypes.SessionId formatted as sessionId.ToString("D", CultureInfo.InvariantCulture) when CurrentSessionId is set (:824-829, the "D" format being the canonical hyphenated Guid form ClaimsPrincipalExtensions.FindSessionId parses back, see ClaimsPrincipalExtensions), AuthClaimTypes.MultiFactor set to the raw method string when CurrentMultiFactorMethod is set (:831-834), and AuthClaimTypes.AuthTime as Unix seconds typed ClaimValueTypes.Integer64 when CurrentAuthTime is set (:836-842), and returns the extended list (:844). The three claims are independent: a token can carry any combination of them.
    • GenerateRefreshToken() (:806) and GetPrincipalFromExpiredToken(string token) (:809-810) are plain forwards.
  • Why it's built this way: putting the stamping behind an ITokenService rather than inside the caller's own method keeps the app hook's signature and semantics untouched while still guaranteeing the claims on the tokens the framework's own flows mint. Routing both mint members through one private Stamp keeps the two token kinds from drifting apart. The escape hatch still applies: an app that mints from its own injected ITokenService reference produces a valid token with none of the three claims, and can restore them by overriding CreateAccessTokenForSession (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/AuthenticationServiceBase.cs:823-824).
  • Where it's used: constructed once per issuer instance (AuthSessionIssuer.cs:67) and exposed as IAuthSessionIssuer.TokenService (:77), which AuthenticationServiceBase<TUser> surfaces to subclasses as its protected TokenService property (AuthenticationServiceBase.cs:124). All three switches are armed and disarmed by the four-argument AuthSessionIssuer.MintForSession (AuthSessionIssuer.cs:173-190, with the finally at :184-189 guaranteeing all three disarm even when the hook throws), which the base calls from CreateAccessTokenForSession with its _multiFactorMethod and _authenticatedAt fields (AuthenticationServiceBase.cs:824; _authenticatedAt is read from the presented token's auth_time on a refresh, :450).
  • Caveats / not-in-source: the framework's own short-lived mints (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/MachineClients/MachineClientService.cs:115, MMCA.Common/Source/Core/MMCA.Common.Application/Auth/ViewAs/ViewAsService.cs:109) call GenerateShortLivedAccessToken on their own injected ITokenService, not on this nested wrapper, so the short-lived stamping applies only to a short-lived token minted through IAuthSessionIssuer.TokenService inside an armed MintForSession.

SignInLinkGrant

MMCA.Common.Application · MMCA.Common.Application.Auth.SignInLinks · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/SignInLinks/ISignInLinkTokenService.cs:80 · Level 1 · record (sealed)

  • What it is: what a redeemed sign-in token grants: the SignInLinkPurpose it was issued for and, for an invitation that carried one, the SignInLinkProfile to provision the account with (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/SignInLinks/ISignInLinkTokenService.cs:77-80).
  • Depends on: SignInLinkPurpose, SignInLinkProfile.
  • Concept: the redemption result carries the token's purpose rather than a bare success, so the caller decides what the link may do (sign in an existing account, or also create one) from what was actually issued, never from what the redeeming client claims.
  • Walkthrough: one positional declaration, SignInLinkGrant(SignInLinkPurpose Purpose, SignInLinkProfile? Profile) (ISignInLinkTokenService.cs:80).
  • Where it's used: the success value of ISignInLinkTokenService.ValidateAndConsumeAsync (ISignInLinkTokenService.cs:56), produced by SignInLinkTokenService (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/SignInLinks/SignInLinkTokenService.cs:99) and read by RedeemSignInLinkHandlerBase<TUser, TCommand> after the consume at MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/SignInLinks/RedeemSignInLinkHandlerBase.cs:101.

SignInLinkSettings

MMCA.Common.Application · MMCA.Common.Application.Auth.SignInLinks · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/SignInLinks/SignInLinkSettings.cs:10 · Level 1 · class (sealed)

  • What it is: the options class for sign-in links (ADR-116), bound from the Authentication:SignInLinks configuration section (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/SignInLinks/SignInLinkSettings.cs:6-13). It carries the master switch, the page the link opens, the two lifetimes, the throttles, and the two small pieces of behavior that depend on them.
  • Depends on: SignInLinkPurpose; System.ComponentModel.DataAnnotations ([Range]) and System.Diagnostics.CodeAnalysis ([SuppressMessage]).
  • Concept introduced: a capability that is registered but off. [Rubric §11, Security] assesses whether a security-sensitive feature fails closed. Enabled defaults to false (SignInLinkSettings.cs:20), so registering the capability changes nothing until a host turns it on, and turning it off again makes every outstanding link inert without waiting for it to expire (doc :15-19). The second security decision lives in ComposeLink: the address and the token ride in the URL fragment, which is never sent to a server, so the live token stays out of access logs, request telemetry and Referer headers, and a mail scanner that prefetches the link with a GET never sees, and so never spends, the token (remarks :68-73). The shape follows the same fail-fast stance: every numeric knob is range-validated, and the registration validates on start (see Where it's used), matching the fail-fast contract of ADR-070.
  • Walkthrough:
    • SectionName = "Authentication:SignInLinks" (:13).
    • Enabled (:20), default false.
    • SignInUrl (:31), default empty, deliberately not required (matching EmailConfirmationSettings.ConfirmationUrl, see EmailConfirmationSettings) so an unconfigured host still boots; with it empty no link can be composed and nothing is sent (doc :22-26). The CA1056 suppression (:27-30) explains why it is a string: the empty default is not a valid System.Uri.
    • SignInLifetimeMinutes (:35), [Range(1, 1440)], default 15; InviteLifetimeMinutes (:39), [Range(1, 43200)], default 20160 (14 days).
    • MaxValidationAttempts (:45), [Range(1, 100)], default 5: wrong tokens tolerated for one address before its outstanding tokens are discarded.
    • MaxRequestsPerEmail (:49), [Range(1, 100)], default 3, within RequestWindowMinutes (:53), [Range(1, 1440)], default 60.
    • LifetimeFor(purpose) (:58-59): the invite lifetime for Invite, the sign-in lifetime otherwise.
    • ComposeLink(email, token) (:74-77): null when SignInUrl is blank, otherwise {SignInUrl}#email=...&token=... with both values passed through Uri.EscapeDataString.
  • Why it's built this way: the defaults make the cheap mistake safe (an unconfigured host boots and sends nothing; an unlisted host never issues links), and the fragment rule is the same one the password-reset link uses (ForgotPasswordHandlerBase.ComposeResetLink, cited in the remarks at :69-70), so both emailed-token flows keep the token off the wire. Recorded in ADR-116.
  • Where it's used: bound by AddSignInLinks with .Bind(...), .ValidateDataAnnotations() and .ValidateOnStart() (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Auth.cs:117-120); injected as IOptions<SignInLinkSettings> into SignInLinkTokenService (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/SignInLinks/SignInLinkTokenService.cs:48), SendSignInLinkHandlerBase<TUser, TCommand> (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/SignInLinks/SendSignInLinkHandlerBase.cs:67) and RedeemSignInLinkHandlerBase<TUser, TCommand> (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/SignInLinks/RedeemSignInLinkHandlerBase.cs:66). ADC's architecture tests pin the invitation lifetime (MMCA.ADC/Tests/Architecture/MMCA.ADC.Architecture.Tests/Privacy/InvitationLifetimeTests.cs).

SignInLinkErrors

MMCA.Common.Application · MMCA.Common.Application.Auth.SignInLinks · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/SignInLinks/SignInLinkErrors.cs:9 · Level 2 · class (static)

  • What it is: the failures the sign-in-link workflow returns, declared once so the redeem handler, the authentication service and a client all match on the same literals (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/SignInLinks/SignInLinkErrors.cs:5-8).
  • Depends on: Error.
  • Concept: an error catalog (a static class of codes plus factory methods) is the same shape as EmailConfirmationErrors. What is specific here is the deliberate collapse: InvalidLink is "the single rejection every failing redemption collapses to" (:20), so a caller probing addresses or tokens cannot tell unknown from expired from mismatched from spent from disabled. [Rubric §11, Security] assesses that non-disclosure; the one distinct refusal, SecondFactorRequired, is reachable only after a valid token was spent, so it tells the mailbox owner, not a sweeper (remarks :34).
  • Walkthrough:
    • InvalidLinkCode = "Authentication.InvalidSignInLink" (:12) and InvalidLink(source) (:23-26): Error.Unauthorized, "The sign-in link is invalid or has expired. Please request a new one."
    • SecondFactorRequiredCode = "Authentication.SignInLinkSecondFactorRequired" (:15) and SecondFactorRequired(source) (:35-38): Error.Unauthorized. A link proves only that the caller reads the mailbox, so honoring it for an account with a second factor would let the mailbox alone bypass that factor (doc :28-31).
    • NotSupportedCode = "Authentication.SignInLinkNotSupported" (:18) and NotSupported(source) (:43-46): Error.Validation, "Sign-in links are not supported.", returned by an authentication service that has not adopted sign-in links; its XML <returns> names the 400 and the code (:42).
  • Where it's used: NotSupported is the default body of the sign-in-link member on IAuthenticationService (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/IAuthenticationService.cs:192); AuthenticationServiceBase<TUser> returns InvalidLink and SecondFactorRequired from SignInVerifiedEmailOwnerAsync (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/AuthenticationServiceBase.cs:578, :591); RedeemSignInLinkHandlerBase<TUser, TCommand> returns InvalidLink from each failing branch (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/SignInLinks/RedeemSignInLinkHandlerBase.cs:145, :200, :234, :311, :363); and SignInLinkTokenService returns it from ValidateAndConsumeAsync (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/SignInLinks/SignInLinkTokenService.cs:144).

IAuthSessionIssuer

MMCA.Common.Application · MMCA.Common.Application.Auth.Sessions · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Sessions/IAuthSessionIssuer.cs:27 · Level 3 · interface

  • What it is: the contract that issues, rotates and revokes the access/refresh token pair behind a signed-in device. Its summary (IAuthSessionIssuer.cs:8-13) lists what it owns: the multi-device RefreshSession rows (hashed at rest), BR-205 rotation with BR-206 reuse detection, the per-user live-session cap, and the sid/mfa claims stamped on the access token minted for a session. It also lists the user's sign-in history and records a native client's device metadata on a live session.
  • Depends on: ITokenService, AuthenticationResponse, RefreshSessionSummaryResponse, SignInSummaryResponse, DeviceMetadata, RefreshSessionSettings (referenced from the docs), Result/Result<T> (the Result pattern taught in the primer), and the UserIdentifierType alias.
  • Concept introduced: splitting "who is signed in" from "what they are handed". [Rubric §1, SOLID] assesses whether each type has one reason to change. The remarks (IAuthSessionIssuer.cs:16-20) draw the line explicitly: credentials, lockout, the second factor and the app's own gates stay with AuthenticationServiceBase<TUser>, which calls the issuer only once a caller has been proved, and the base's own summary states the same split from the other side (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/AuthenticationServiceBase.cs:51-52: "This class decides who is signed in; IAuthSessionIssuer decides what they are handed"). The access token's claim set still belongs to the app, so the issuer takes it as a Func<Guid, string> mintAccessToken callback: the session id the token must carry exists only once the session has been opened or rotated. [Rubric §11, Security] assesses credential lifecycle handling; the rotation and reuse rules are stated on the contract itself, not left to an implementation. [Rubric §15, Best Practices & Code Quality] shows in how the contract is held: the auth_time overload of MintForSession is abstract, with no default body, so every implementation has to stamp auth_time rather than silently leaving passkey registration refused on its host (remarks IAuthSessionIssuer.cs:100-103).
  • Walkthrough:
    • TokenService (IAuthSessionIssuer.cs:35): the ITokenService an app mints through. While the issuer is minting for a session it appends sid (and mfa when a second factor verified); at any other time it is the plain registered service (doc at :29-34).
    • IssueAsync(userId, mintAccessToken, ipAddress, userAgent, ct) (:47): opens a new session, evicting the oldest live one when the per-user cap is full, persists it and returns the pair; the user's other sessions are untouched (:37-40).
    • RotateAsync(userId, refreshToken, mintAccessToken, ipAddress, userAgent, ct) (:71): BR-205 rotation. An unknown or expired token fails alone, and so does a token whose session was revoked by a sign-out or evicted by the session cap (that device simply lost its session). A token already rotated, already flagged as reuse, or rotated first by a concurrent request is the BR-206 reuse signal and revokes every live session the user holds; a revoked row with any other or no recorded reason is treated as reuse too. Every rejection carries the same Auth.InvalidRefreshToken error (:54-62).
    • MintForSession(sessionId, multiFactorMethod, mintAccessToken) (:87): runs the callback with TokenService armed to stamp sid and, when not null, mfa (:79-82).
    • MintForSession(sessionId, multiFactorMethod, authenticatedAt, mintAccessToken) (:104): the same, also stamping auth_time: authenticatedAt when given (a refresh carrying the presented token's sign-in instant over unchanged), otherwise the instant of the sign-in IssueAsync is opening, and none outside it (:89-93). It is an abstract member: an implementation that minted no auth_time would leave passkey registration (which requires one) refused on its host, so every implementation stamps it (remarks :100-103).
    • SignOutAsync(userId, refreshToken, ct) (:115): revokes the one live session behind the presented token when it belongs to the user; when the token is absent or identifies no live session of this user, every live session is revoked instead (:107-109).
    • SignOutByRefreshTokenAsync(refreshToken, ct) (:126): signs one device out with the refresh token as the only proof, so it takes no user id. It revokes the session whose token hash matches when that session is live; an empty, unknown or already-revoked token is a no-op, never a fall-back to the user's other sessions, which is the deliberate contrast with SignOutAsync (:117-122).
    • SignOutEverywhereAsync(userId, ct) (:132): revokes every live session and saves.
    • ListActiveAsync(userId, currentSessionId, ct) (:142): live sessions newest first, with expired-but-unrevoked rows left out because a device list must not offer a device that can no longer authenticate (:134-137).
    • ListSignInsAsync(userId, currentSessionId, ct) (:156): the sign-in history, one row per sign-in (a rotation chain, however many times it rotated), live and ended alike, newest first, capped at the newest 50, each with how it ended, covering what the store retains (RefreshSessionSettings.RetentionDays) (:147-151).
    • RevokeSessionAsync(userId, sessionId, ct) (:171): another account's session id and a never-existing id both answer Auth.SessionNotFound; an already-revoked session writes nothing and answers the not-found failure Auth.SessionAlreadyRevoked, so the client can say the device was already signed out (:161-166).
    • RecordDeviceAsync(userId, sessionId, device, ct) (:185): records the DeviceMetadata a native client reported on its own session (named by the access token's sid), replacing what was there, and saves; rotation carries it to every successor. Another account's id, a missing id, and a revoked or expired session all answer Auth.SessionNotFound and write nothing (:173-179).
  • Why it's built this way: the remarks (IAuthSessionIssuer.cs:23-24) give the lifetime rule: scoped, like the session store it writes through, so a sign-in and its session insert share the request's unit of work. Keeping the session rules behind one interface means the authentication workflow never touches a session row. The multi-device session model is recorded in ADR-097 and the rotation scheme in ADR-050.
  • Where it's used: implemented by AuthSessionIssuer; registered TryAddScoped in MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:206; injected into AuthenticationServiceBase<TUser> (AuthenticationServiceBase.cs:83), which delegates to it from TokenService (:124), refresh (RotateAsync, :455), sign-out (:482, :498), session listing (:510), sign-in history (:522), revocation (:537), issuance (IssueAsync, :749) and CreateAccessTokenForSession (the four-argument MintForSession, :824). AuthControllerBase takes it as a [FromServices] parameter in two actions: the anonymous EndSessionAsync (POST session/end, always 204 No Content) calls SignOutByRefreshTokenAsync (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/AuthControllerBase.cs:201-215, call at :213), the path the Blazor web head uses server-to-server when the browser drops its session cookies (summary :183-189), and the device-report action calls RecordDeviceAsync (:327, :346). ADC's AuthenticationService takes it as a constructor argument and passes it to the base (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/AuthenticationService.cs:57,66).

ISignInLinkTokenService

MMCA.Common.Application · MMCA.Common.Application.Auth.SignInLinks · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/SignInLinks/ISignInLinkTokenService.cs:18 · Level 3 · interface

  • What it is: the contract that issues and redeems the single-use tokens behind sign-in links (ADR-116), on the design IEmailConfirmationTokenService uses: the token material lives outside the database, hashed at rest, with a per-address request throttle and a per-token validation-attempt cap (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/SignInLinks/ISignInLinkTokenService.cs:6-11).
  • Depends on: SignInLinkPurpose, SignInLinkProfile, SignInLinkGrant, Result<T> from the primer.
  • Concept introduced: a token keyed by address, not by account. [Rubric §11, Security] assesses how emailed bearer tokens are issued and spent. The remarks (ISignInLinkTokenService.cs:12-17) explain the key choice: an invitation is issued to an address that may have no account yet, and redeeming it is what creates one, so the token cannot be keyed by a user id. One active token per address and purpose means a new link of one purpose replaces only the outstanding link of that purpose. Redemption is validate-and-consume in one call, so sequential redemptions of one token succeed once, and every failure collapses to one generic error (:52-55). The contract is explicit that this is not a lock: two concurrent redemptions can both read the entry before either removes it and both succeed (:41-48).
  • Walkthrough:
    • IssueAsync(email, purpose, profile = null, ct) (:35): issues a token for the normalized address, replacing any token of the same purpose already outstanding (:20-23). profile is supplied only for an invitation; a plain sign-in link never creates an account (:26-29). Returns the raw token to email, or a failure when the per-address request throttle is exceeded (:31-34).
    • ValidateAndConsumeAsync(email, token, ct) (:56): validates the token against the address's outstanding tokens and consumes the one it matches, returning the SignInLinkGrant; unknown, expired, mismatched and attempt-capped all collapse to the same error (:52-55). Under a concurrent double redemption, an existing account gets two sessions for the owner the link proved, and an invitation to an address with no account has its losing account insert turned into an email conflict by the redeem workflow (:41-48).
  • Why it's built this way: reusing the email-confirmation token design keeps one reviewed shape for every emailed single-use token in the framework. Leaving redemption lock-free is a stated trade-off in the implementation's remarks: a double tap on the link asks for exactly the second session the race produces, and the invitation race is already settled at account provisioning (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/SignInLinks/SignInLinkTokenService.cs:31-38). Recorded in ADR-116.
  • Where it's used: implemented by SignInLinkTokenService and registered TryAddScoped by AddSignInLinks (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Auth.cs:123; the remarks at :112-113 note that registering it issues nothing until the app wires the handlers and a controller and sets Authentication:SignInLinks:Enabled). Injected into SendSignInLinkHandlerBase<TUser, TCommand> (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/SignInLinks/SendSignInLinkHandlerBase.cs:64) and RedeemSignInLinkHandlerBase<TUser, TCommand> (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/SignInLinks/RedeemSignInLinkHandlerBase.cs:64, consumed at :101). ADC issues invitations through it directly in SendSignInLinkInternalCommandHandler (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/SendSignInLink/).

RefreshSessionDevice

MMCA.Common.Application · MMCA.Common.Application.Auth.Sessions · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Sessions/RefreshSessionDevice.cs:11 · Level 5 · class (internal static)

  • What it is: one extension method that shapes the device columns of a RefreshSession into the DeviceMetadata the session responses carry, shared by the device list, the sign-in history and the administrator's view so the three cannot drift (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Sessions/RefreshSessionDevice.cs:6-10).
  • Depends on: RefreshSession, DeviceMetadata.
  • Concept: a single mapping owned in one place, the same reason the primer gives for shared helpers. The detail worth noticing is how "nothing recorded" is detected: a private static Empty instance of seven nulls (:13) is compared with == (:33), which works because DeviceMetadata is a sealed record (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/DeviceMetadata.cs:24) and so compares by value.
  • Walkthrough: ToDeviceMetadata(this RefreshSession session) (RefreshSessionDevice.cs:22) builds a DeviceMetadata from DeviceId, DeviceName, DeviceModel, DeviceManufacturer, DevicePlatform, DeviceFormFactor and DeviceType (:24-31), and returns null when it equals Empty (:33), so a response says "no device" for every browser session and every row anonymized for an erasure rather than carrying an object of seven nulls (doc :15-19).
  • Where it's used: AuthSessionIssuer.ListActiveAsync (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Sessions/AuthSessionIssuer.cs:282), SignInHistory (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Sessions/SignInHistory.cs:163) and UserSessionsAdministrationService (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Administration/UserSessionsAdministrationService.cs:61).

SoftDeletedUserMarkerWriter

MMCA.Common.Application · MMCA.Common.Application.Auth.SoftDeletedUsers · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/SoftDeletedUsers/SoftDeletedUserMarkerWriter.cs:13 · Level 6 · class (sealed)

  • What it is: the framework's ISoftDeletedUserMarkerWriter: writes the deleted-or-locked marker for SoftDeletedUserCache.MarkerDurationFor of the host's access-token lifetime, and removes it on an unlock (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/SoftDeletedUsers/SoftDeletedUserMarkerWriter.cs:6-10).
  • Depends on: ICacheService (the shared store the marker lives in) and ITokenService (for AccessTokenLifetime), both primary-constructor parameters (:13); SoftDeletedUserCache for the key, the duration rule and the write and remove operations.
  • Concept: the abstraction is taught at ISoftDeletedUserMarkerWriter. This class shows how thin the implementation can be once the duration rule and the cache key live in SoftDeletedUserCache: two one-line delegations.
  • Walkthrough:
    • MarkDeletedAsync (:16-21): SoftDeletedUserCache.MarkDeletedForAsync(cache, userId, SoftDeletedUserCache.MarkerDurationFor(tokenService.AccessTokenLifetime), ct), so the marker outlives any access token this host could still accept.
    • ClearMarkerAsync (:24-25): SoftDeletedUserCache.ClearMarkerAsync(cache, userId, ct).
  • Why it's built this way: the summary records the one assumption: the default bearer clock skew, because this layer cannot read the host's (:8-9). It is registered through a factory rather than a type registration (MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.cs:60-65); the comment there explains that a Development host validates every registration at build, and only a factory defers the writer's dependencies to the moment it is resolved, so a host that issues no tokens (and never resolves this) still starts. See ADR-047.
  • Where it's used: resolved wherever ISoftDeletedUserMarkerWriter is injected (see that section). Covered by SoftDeletedUserMarkerWriterTests (MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Auth/SoftDeletedUsers/).

SignInHistory

MMCA.Common.Application · MMCA.Common.Application.Auth.Sessions · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Sessions/SignInHistory.cs:20 · Level 7 · class (internal static)

  • What it is: the reader that turns a user's refresh-session rows into a sign-in history: the store aggregates the rotation chains and this shapes each one into a SignInSummaryResponse. Shared by the self-service list and the administrator's, so both read a history the same way (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Sessions/SignInHistory.cs:7-13).
  • Depends on: IRefreshSessionStore (GetRecentSignInsAsync, FindByIdAsync), RefreshSessionSignIn, RefreshSession, SignInSummaryResponse, SignInEndReasons, SignInHistoryEntryKind, optionally IViewAsGrantStore and ViewAsGrant; RefreshSessionDevice for the device column.
  • Concept introduced: a history row is a rotation chain, not a row. [Rubric §12, Performance & Scalability] assesses whether a read is bounded. Every refresh rotates the session into a new row, so a naive history would list one entry per refresh and grow with activity. Here a sign-in is the chain: it starts at its earliest retained row and was last active at its newest row's issue instant, and the newest row (the head) decides how it ended (remarks :14-19). The store does the aggregation and caps it at MaxEntries (:23, 50), so the read is bounded by sign-ins, never by how many times each rotated. [Rubric §11, Security] applies to the view-as rows: each support view of the account appears in the holder's own history, without the staff user's device or address (:59-62).
  • Walkthrough:
    • MaxEntries = 50 (:23).
    • ReadAsync(store, userId, now, currentSessionId, ct, viewAsGrants = null) (:37): reads the capped aggregate (:45), resolves which sign-in the caller is in (:46), shapes it (:49), and when a view-as grant store is present reads the account's recent grants with the same cap (:55) and merges them (:56).
    • Merge(history, grants, now) (:68): pure; concatenates the shaped grants, orders by StartedAt then SignInId descending, and takes MaxEntries (:72-78).
    • SummarizeViewAs (:80): a grant row spans the grant; ended grants report SignInEndReasons.ViewAsEnded (:84-87), past-expiry ones SignInEndReasons.Expired (:88-91); IP and user agent are null, IsCurrent is false, and the kind is SignInHistoryEntryKind.ViewAs (:93-102).
    • Summarize(signIns, now, currentSignInId) (:110): pure; shapes each chain and applies the same ordering and cap (:114-120).
    • ResolveCurrentSignInAsync (:127): the caller's sid is normally its chain's head, since each rotation mints the token for the successor, so it is matched against the heads with no read (:139-143); otherwise (an access token minted before a sibling rotated) one user-scoped primary-key lookup finds it and returns its SignInId, or its own Id for a chain's first row (:145-146, doc :122-126).
    • Summarize(signIn, now, currentSignInId) (:149): last-active is the head's CreatedAt, IP and user agent come from the head, IsCurrent matches the resolved sign-in (:162), and Device comes from head.ToDeviceMetadata() (:163).
    • DescribeEnd(head, now) (:166): a revoked head reports its instant and recorded reason as-is, because the session reasons and SignInEndReasons share their values (:168-173); otherwise a head past ExpiresAt reports Expired, and a live one reports no end (:175).
  • Why it's built this way: the shaping functions are pure and take now as a parameter, so the history is testable without a clock or a store, and the one shared reader keeps the self-service and administrator views identical. The model is recorded in ADR-097; the view-as rows in ADR-137.
  • Where it's used: AuthSessionIssuer.ListSignInsAsync (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Sessions/AuthSessionIssuer.cs:296) and UserSessionsAdministrationService (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Administration/UserSessionsAdministrationService.cs:76). ADC's E2E view-as tests exercise the "Viewed by support" rows (MMCA.ADC/Tests/E2E/MMCA.ADC.E2E.Tests/Workflows/Identity/Administration/ViewAsTests.cs).

AuthSessionIssuer

MMCA.Common.Application · MMCA.Common.Application.Auth.Sessions · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Sessions/AuthSessionIssuer.cs:54 · Level 8 · class (sealed, partial)

  • What it is: the framework's IAuthSessionIssuer: multi-device refresh sessions, hashed at rest (AuthSessionIssuer.cs:14-16). Every issue opens its own RefreshSession, so signing in on a second device leaves the first one signed in (:19-20).
  • Depends on: ITokenService (mints both tokens), IRefreshSessionStore (the session rows), IOptions<RefreshSessionSettings> (the per-user cap, the reuse grace and the lost-response window), TimeProvider (every session instant), an optional ILogger<AuthSessionIssuer> and an optional IViewAsGrantStore, all primary-constructor parameters (AuthSessionIssuer.cs:54-60, doc :42-53); RefreshSession, AuthenticationResponse, RefreshSessionSummaryResponse, SignInSummaryResponse, DeviceMetadata and Error/Result from the primer. Its private helpers are IssuedSession and SessionStampingTokenService; it reads history through SignInHistory and device columns through RefreshSessionDevice, and counts each reuse event through AuthSecurityMetrics. The class is partial because its two log methods are [LoggerMessage] source-generated (:670-683).
  • Concept introduced: refresh-token rotation with family revocation on reuse, a grace window for races, and an opt-in recovery for lost responses. [Rubric §11, Security] assesses how bearer credentials are issued, stored and revoked. The class remarks (AuthSessionIssuer.cs:17-41) state the model: the store holds only RefreshSession.HashToken digests; rotation revokes the presented session and links it to its successor; presenting an already-rotated token lands on that revoked row, which is the reuse signal that revokes the user's whole live family (BR-206); two requests presenting the same live token at once are covered by the same rule because the rotation is claimed atomically through IRefreshSessionStore.TryRotateAsync; and an expired session is not a reuse signal. Both paths share one carve-out (:26-29): a token rotated less than RefreshSessionSettings.ReuseGraceSeconds ago (default 10) is a rotation race between sibling requests, answered 409 Conflict (Auth.RefreshSuperseded) with nothing revoked; past the grace it is a replay, unless lost-response recovery is configured (RefreshSessionSettings.LostResponseRecoveryMinutes, off by default) and the presented row's successor was never presented, in which case that successor is rotated in its place (:29-31). A token whose row was revoked by a sign-out, a session-cap eviction or an earlier reuse sweep is not a new theft signal either: that device simply lost its session, so only that request fails. A swept row is dead by construction, so revoking the family again on it would only sign the user out of the sessions they re-established, on demand of anyone holding a swept token (:416-419); a genuine replay lands on a rotated row and still revokes the family. The practical effect: a stolen-and-replayed token costs the attacker the session and costs the user only a re-sign-in, while a double-fired refresh from two tabs, or a refresh whose response never reached the client, does not sign anyone out.
  • Walkthrough:
    • Fields (:67, :74): the nested SessionStampingTokenService wrapped around the injected token service, exposed as TokenService (:77), and _signInInstant, armed only while IssueAsync mints a new session's first access token so that token carries auth_time (doc :69-73).
    • Lifetimes (:79-83): AccessTokenLifetime and RefreshTokenLifetime read the token service and fall back to 15 minutes and 7 days when the value is non-positive, so the expiry reported to clients matches the JWT's actual exp; a host that binds JwtSettings through AddCommonAuthentication fails startup on such a value, so the fallback covers test doubles and token services configured outside that binding (:35-39).
    • IssueAsync (:86): opens the session first (OpenSessionAsync, :99), unwraps it with TryGetValue (:100), saves (:105), then sets _signInInstant to now (:109) and calls mintAccessToken(issued.SessionId) (:113) inside a try whose finally clears it (:117-120). The comment at :97-98 says why the order matters: the token carries the session's id in sid, and a session has an id only once created; the comment at :107-108 says why the instant is stamped here: opening a session is an interactive sign-in, and every refresh carries it over.
    • OpenSessionAsync (:494): generates a refresh token, creates the row through RefreshSession.Create with now + RefreshTokenLifetime (:501-508), runs EnforceSessionCapAsync (:515), stages the insert without saving (:516) and returns an IssuedSession (:518).
    • EnforceSessionCapAsync (:732): reads the user's un-revoked rows, keeps the ones active now, orders oldest first (CreatedAt, then Id), and revokes from the front with ReasonSessionCap until there is room for one more (loop at :741). Its summary (:723-731) records the default cap of 10, the 1-1000 startup range, and that expired-but-unrevoked rows do not count and age out through RefreshSessionCleanupService.
    • RotateAsync (:124): ResolveRotatableSessionAsync (:135), then RotateSessionAsync (:143), each result unwrapped with TryGetValue, then the mint with the successor's id (:154), so the client's current-device marker follows the rotation (comment :150-152).
    • ResolveRotatableSessionAsync (:423): a blank token, an unknown hash, or a row of another user fails alone (:429-441). A revoked row (:443-482) splits four ways: if IsReuseSignal is false (signed out, cap-evicted, or already swept by an earlier reuse event) it fails alone (:445-452); if it was rotated inside the grace (IsWithinRotationGrace) it answers RefreshSupersededError with nothing revoked (:454-459); if FindRecoverableSuccessorAsync finds a never-presented live successor, that successor is logged and returned as the session to rotate (:461-470), and if a sibling just recovered it the answer is RefreshSupersededError (:472-477); otherwise RevokeFamilyOnReuseAsync revokes the family before failing (:479-481). An expired row fails alone (:484-486). Its summary (:407-422) explains why the unknown-hash case must not revoke the family (otherwise anyone holding one of this user's expired access tokens could sign them out everywhere by posting a random token) and why a swept row must not either.
    • FindRecoverableSuccessorAsync (:644): returns nothing unless recovery is configured, the presented row was revoked as Rotated inside the window and has a successor hash (:649-657); looks the successor up by hash and requires the same user (:659-663); a still-live successor is the recovery, and a non-live one counts as superseded only when it was itself rotated within the grace (:665-667). A successor that was ever presented would itself be revoked, which is exactly the two-holders signal that must keep revoking the family (summary :634-643).
    • RotateSessionAsync (:535): builds the successor through session.CreateSuccessor, which continues the presented session's SignInId so the sign-in history folds a rotation chain into one row (:543-551), then asks the store to claim the rotation via TryRotateAsync (:558-560). A lost claim (:562-590) means a concurrent request spent this token first, but the tracked copy was read before that claim and still looks live, so the row is re-read untracked through IRefreshSessionStore.FindByIdUntrackedAsync (:568-570): a sign-out, cap eviction or reuse sweep of the same row fails alone (:571-577), a rotation inside the grace answers RefreshSupersededError (:579-582), and anything else (rotated longer ago than the grace, or unreadable) gets the replay answer through RevokeFamilyOnReuseAsync and Auth.InvalidRefreshToken (:587-589). Rotation replaces one session with one, so the cap is not re-evaluated (:523).
    • IsReuseSignal (:604) and IsWithinRotationGrace (:624): the first treats a revoked row as reuse when it has a successor hash (:606-609) or any reason other than signed-out, session-cap or reuse-detected (:611-613), the conservative answer for rows the code does not recognize; the second is true only for the Rotated reason, with a positive grace and now - RevokedAt under it (:626-631). A row flagged as reuse, signed out or evicted never reaches the grace check, because IsReuseSignal fails it alone first, however recent.
    • RevokeFamilyOnReuseAsync (:692) and RevokeLiveSessionsAsync (:704): the second revokes every un-revoked row with the given reason and returns how many it revoked (:710-720); the first uses it with ReasonReuseDetected, saves, logs the user id and the count, and counts the event once on the mmca.auth.refresh_reuse metric through AuthSecurityMetrics.RecordRefreshReuse() (:694-699, summary :685-691). Both reuse paths end here, so each event logs and counts exactly once. The log message deliberately omits the client IP and user agent, which are personal data and would put a device fingerprint into every log sink (comment :678-679).
    • InvalidRefreshTokenError (:390) and RefreshSupersededError (:401): Error.Unauthorized("Auth.InvalidRefreshToken", ...) is what every failing branch returns except the races, so a caller cannot tell unknown from expired from replayed (doc :384-389); a race answers Error.Conflict("Auth.RefreshSuperseded", ...) so the client keeps its session and retries with the winner's token (:396-405).
    • MintForSession (:164 and :173): the three-argument overload forwards with authenticatedAt: null (:164-165); the four-argument one arms the nested SessionStampingTokenService with the session id, the second-factor method, and authenticatedAt ?? _signInInstant (:177-179), runs the callback, and disarms all three in a finally (:184-189). A null authenticatedAt outside IssueAsync mints no auth_time rather than inventing a sign-in (remarks :168-172).
    • SignOutAsync (:193): revokes only a live session of this user found by token hash (:197-214); anything else degrades to revoking every live session rather than reporting success for a revocation that reached nothing (comment :203-206, fallback :217-218).
    • SignOutByRefreshTokenAsync (:222): the anonymous, token-only sign-out. A blank token returns at once (:224-227); otherwise the row is looked up by token hash with no user check (:229-231), and only a session still active now is revoked as signed out and saved (:237-243). An unknown token and an already-revoked or expired row are left untouched, so this path never falls back to the user's other sessions and never acts as a reuse signal (comment :234-236). SignOutEverywhereAsync (:247) always revokes everything.
    • ListActiveAsync (:261): one query for un-revoked rows, then an in-memory filter to the active ones, newest first, flagging the caller's own session and attaching its device metadata through ToDeviceMetadata (:269-283).
    • ListSignInsAsync (:292): delegates to SignInHistory.ReadAsync with the clock's current instant and the optional view-as grant store (:296-302); the read is bounded by the 50-sign-in cap, never by how many times each sign-in rotated (remarks :287-291).
    • RevokeSessionAsync (:318): the ownership check is the user-scoped FindByIdAsync query (:323), so another account's id and a missing id produce the same Auth.SessionNotFound (:324-331); an already-revoked row writes nothing and answers the not-found failure Auth.SessionAlreadyRevoked (:333-340), so the client can say the device was already signed out; the session is the caller's own, so the answer reveals nothing about another account (remarks :305-317).
    • RecordDeviceAsync (:355): the same user-scoped lookup (:363); a missing, revoked or expired session answers Auth.SessionNotFound (:364-371), since a client reporting on a dead session has nothing left to describe (remarks :349-354); otherwise session.RecordDevice(device) (:373), a failure returned as-is, then save (:379).
  • Why it's built this way: every timestamp comes from the injected TimeProvider, so rotation, expiry, the grace window and the recovery window are testable without a clock, and every user-visible failure on the refresh path collapses to one error (the exceptions being the deliberate, retryable 409s) so the endpoint leaks nothing about which rule fired. A lost concurrent rotation is re-read and judged by the same two predicates as a direct lookup, which keeps one rule for one observable situation. The auth_time stamping exists for step-up checks such as passkey registration (ADR-139). The multi-device model, rotation and reuse detection are recorded in ADR-097 and ADR-050; the view-as rows in ADR-137.
  • Where it's used: registered as the scoped IAuthSessionIssuer in MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:206; consumed through that interface by AuthenticationServiceBase<TUser> and AuthControllerBase (whose anonymous EndSessionAsync is the caller of SignOutByRefreshTokenAsync, MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/AuthControllerBase.cs:213). Constructed directly in the Common test suites, among them AuthSessionIssuerSignInHistoryTests.cs, AuthSessionIssuerTokenSignOutTests.cs, AuthSessionIssuerDeviceTests.cs, AuthSessionIssuerLostResponseRecoveryTests.cs and AuthSessionIssuerReuseGraceTests.cs (MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Auth/Sessions/), AuthenticationServiceBaseTests.cs, AuthenticationServiceIdentityCompletionsTests.cs and AuthenticationServiceLegalAcceptanceTests.cs (MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Auth/), PasskeyTestHost.cs (MMCA.Common/Tests/Core/MMCA.Common.Passkeys.Tests/) and AuthControllerBaseSessionDeviceTests.cs (MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/Controllers/Auth/), and in ADC's AuthenticationServiceTests.cs (MMCA.ADC/Tests/Modules/Identity/MMCA.ADC.Identity.Application.Tests/Users/).

RecoveryCodeSet

MMCA.Common.Application · MMCA.Common.Application.Auth.TwoFactor · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/TwoFactor/ITwoFactorService.cs:97 · Level 0 · record

  • What it is: a two-field record pairing a freshly generated set of plaintext recovery codes with their stored hashes.
  • Depends on: nothing first-party.
  • Concept: a plaintext/hash pair returned once, at generation time only, so the plaintext never has to be persisted or re-derived.
  • Walkthrough: Codes (ITwoFactorService.cs:98) is the plaintext shown to the user once; Hashes (line 86) is what the store keeps.
  • Why it's built this way: keeping the plaintext out of any store means a database compromise cannot recover usable recovery codes, only their hashes.
  • Where it's used: returned by ITwoFactorService.GenerateRecoveryCodes(), consumed by TotpTwoFactorService.cs and exercised in MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Users/TwoFactorHandlerBaseTests.cs.

TwoFactorOutcome

MMCA.Common.Application · MMCA.Common.Application.Auth.TwoFactor · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/TwoFactor/ITwoFactorAuthenticator.cs:73 · Level 0 · enum

  • What it is: the result of a second-factor challenge: NotEnrolled = 0, VerifiedTotp = 1, VerifiedRecoveryCode = 2 (ITwoFactorAuthenticator.cs:76,79,82).
  • Depends on: nothing first-party.
  • Concept: same explicitly-numbered, wire-stable outcome-enum shape used throughout the domain event taxonomy (see DomainEntityState in group-02); NotEnrolled = 0 is the default/no-op value, matching that convention.
  • Walkthrough: three values; NotEnrolled means the account has no active second factor so nothing was challenged, VerifiedTotp means a time-based code from the authenticator app verified, VerifiedRecoveryCode means a single-use recovery code verified and was spent.
  • Why it's built this way: collapsing the challenge result to one enum lets AuthenticationServiceBase decide, in one switch, whether to continue sign-in unchanged (NotEnrolled) or stamp an mfa claim on the issued token (the two verified cases).
  • Where it's used: returned by ITwoFactorAuthenticator.ChallengeAsync, read by AuthenticationServiceBase.cs (7 sites) and TwoFactorAuthenticator.cs (7 sites), and by the disable/regenerate handler bases.

TwoFactorSettings

MMCA.Common.Application · MMCA.Common.Application.Auth.TwoFactor · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/TwoFactor/TwoFactorSettings.cs:15 · Level 0 · class

  • What it is: the options class bound to Authentication:TwoFactor, controlling the TOTP parameters (issuer, digits, period, clock-skew window) and the recovery-code and secret sizing.
  • Depends on: nothing first-party; System.ComponentModel.DataAnnotations ([Range], [Required], [StringLength]).
  • Concept: the same config-bound settings shape as EmailConfirmationSettings; no new concept.
  • Walkthrough: SectionName (TwoFactorSettings.cs:18) is "Authentication:TwoFactor". Issuer (line 26) defaults to "MMCA" and labels the account in the authenticator app; its summary (lines 20-23) says a host sets its own application name there. Digits (line 30) defaults to 6. PeriodSeconds (line 34) defaults to 30. VerificationWindowSteps (line 46) defaults to 1, and its remarks (lines 40-44) explain the trade-off: one step widens acceptance to roughly ninety seconds to tolerate clock skew, while a larger window multiplies how many codes are live at once for an attacker guessing. RecoveryCodeCount (line 50) defaults to 10. RecoveryCodeByteLength (line 57) defaults to 10 bytes (eighty bits). SecretByteLength (line 61) defaults to 20 bytes, the RFC 4226 recommendation.
  • Why it's built this way: every size and window is a documented security/usability trade-off rather than an arbitrary constant, per ADR-116.
  • Where it's used: bound and validated by AddTwoFactorAuthentication(configuration) (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Auth.cs:50-51), read by TotpTwoFactorService and TwoFactorAuthenticator (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/TwoFactor/).

ViewAsSettings

MMCA.Common.Application · MMCA.Common.Application.Auth.ViewAs · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/ViewAs/ViewAsSettings.cs:34 · Level 0 · class

  • What it is: the options class bound to the ViewAs section that switches read-only view-as support access on and decides which host owns the grant table, how long grant rows are kept, and which data source holds them.
  • Depends on: nothing first-party; System.ComponentModel.DataAnnotations ([Range], [Required]).
  • Concept: the same config-bound, startup-validated settings shape as TwoFactorSettings (ADR-070). The feature it configures, a staff user seeing the app as one account sees it through a short-lived read-only token, is described by ADR-137 and walked through at ViewAsService.
  • Walkthrough: SectionName (ViewAsSettings.cs:37) is "ViewAs". Enabled (line 40) defaults to false; the class remarks (lines 10-15) list what "off" means: the grant and end endpoints answer 404, the always-present guard middleware refuses any view-as token with 401, the grant table is in no model (so no migration appears), and sign-in history shows no view-as rows. Lines 17-20 list what a host that turns it on must also do: register an IViewAsSubjectResolver, grant users:view-as to its staff role, add the ViewAsGrants migration on the Identity database, and disclose staff access in its privacy notice. HostsGrantStore (line 49) defaults to true; in a multi-service host only the Identity service keeps it, and the others set it false and learn that a grant ended from a marker in the shared ICacheService (remarks lines 23-31, which also state that a service unable to read that cache refuses view-as requests, failing closed). RetentionDays (line 56, [Range(1, 3650)] at line 55) defaults to 90, matching the field-level audit trail's retention. DataSourceName (line 63) defaults to "Default".
  • Why it's built this way: off by default with no table mapped means a host that never opts in carries neither the endpoints nor the schema, and the explicit HostsGrantStore split keeps the grant table in one database per ADR-137.
  • Where it's used: bound in MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:217-218, read by ViewAsService (the retention sweep), EFViewAsGrantStore, ApplicationDbContext, DesignTimeDbContextHelper, and the AuthControllerBase, UsersAdminControllerBase and ViewAsGrantsAdminControllerBase controllers in MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/.

ViewAsSubject

MMCA.Common.Application · MMCA.Common.Application.Auth.ViewAs · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/ViewAs/ViewAsSubject.cs:15 · Level 0 · record

  • What it is: the facts about one account that a view-as token is minted from, plus the two flags that make an account unviewable.
  • Depends on: UserIdentifierType; the [Pii] attribute on its personal fields.
  • Concept: a small app-supplied read model that lets Common stay ignorant of the consumer's user entity; the consumer fills it through IViewAsSubjectResolver.
  • Walkthrough: positional members UserId, Email, Role, FullName, IsDeleted (ViewAsSubject.cs:16-20), with Email (line 17) and FullName (line 19) marked [property: Pii]. IsServiceAccount (line 27) flags the service account behind a machine client (ADR-140), which has no person to support. IsLocked (line 34) flags a locked account: a lock writes the soft-deleted-user marker (ADR-047), so every host would refuse the token on its first call. Both are init properties that default to false.
  • Why it's built this way: carrying the refusal facts on the subject lets ViewAsService decide every refusal in one place before any grant row is written.
  • Where it's used: returned by IViewAsSubjectResolver.FindAsync, consumed by ViewAsService (the refusal checks and the token claims), built in ADC by MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/Administration/ViewAsSubjectResolver.cs.

ITwoFactorService

MMCA.Common.Application · MMCA.Common.Application.Auth.TwoFactor · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/TwoFactor/ITwoFactorService.cs:16 · Level 1 · interface

  • What it is: the TOTP/authenticator-app abstraction: mints secrets, builds the provisioning URI, verifies codes, and generates/hashes/matches recovery codes.
  • Depends on: RecoveryCodeSet (return type of GenerateRecoveryCodes).
  • Concept introduced: a service interface that isolates the cryptographic mechanics of TOTP (RFC 6238-style time-based codes) from the account-state orchestration that lives in ITwoFactorAuthenticator. [Rubric §1, SOLID] (assesses single-responsibility separation): this interface only knows about codes and secrets, never about a user account or a store.
  • Walkthrough: GenerateSecret() (ITwoFactorService.cs:22) mints a fresh Base32 secret. BuildProvisioningUri(secret, accountName) (line 37) builds the otpauth://totp/... URI an authenticator app scans as a QR code; it is deliberately returned as string rather than System.Uri (the [SuppressMessage] at lines 33-36 explains that round-tripping through Uri would re-normalize the percent-encoding the app parses). VerifyCode(secret, code) (line 46) checks a code within the configured number of time steps on each side of the current one. The overload VerifyCode(secret, code, out matchedStep) (line 59) verifies exactly the same way and also reports which time step matched (Unix seconds divided by the period, or 0 when nothing matched), so a caller that keeps per-account state can refuse a replay of a code it already accepted inside the same window. GenerateRecoveryCodes() (line 66) returns a fresh RecoveryCodeSet. HashRecoveryCode(code) (line 74) hashes one plaintext code the way the store keeps it. TryMatchRecoveryCode(code, storedHashes, out matchedHash) (line 83) compares in fixed time to avoid a timing side-channel on which stored hash matched.
  • Why it's built this way: keeping code verification, secret generation, and recovery-code hashing behind one narrow interface means ITwoFactorAuthenticator and the handler bases never touch a raw cryptographic primitive directly. Replay protection stays out of this interface too: the service only reports the matched step, and the stateful "accept each step once" rule lives in the caller.
  • Where it's used: implemented by TotpTwoFactorService (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/TwoFactor/TotpTwoFactorService.cs:60 for the step-reporting overload), consumed by the enrollment/regeneration handler bases in MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/TwoFactor/ and by TwoFactorAuthenticator, which calls the step-reporting overload (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/TwoFactor/TwoFactorAuthenticator.cs:81) and then rejects any step at or below the last one it cached for that user (TwoFactorAuthenticator.cs:198). Registered as a singleton in MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Auth.cs:58.

IViewAsSubjectResolver

MMCA.Common.Application · MMCA.Common.Application.Auth.ViewAs · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/ViewAs/IViewAsSubjectResolver.cs:8 · Level 1 · interface

  • What it is: the one-method extension point through which the consuming app reads an account's ViewAsSubject.
  • Depends on: ViewAsSubject, UserIdentifierType.
  • Concept: a consumer-implemented port: Common owns the view-as workflow, the app owns its user table.
  • Walkthrough: FindAsync(userId, cancellationToken) (IViewAsSubjectResolver.cs:14) returns the subject, or null when no such account exists.
  • Why it's built this way: Common does not register an implementation (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:216 says the account reader is the consumer's), and ViewAsService takes it as an optional constructor argument, so an enabled host that forgot it gets a ViewAs.NotConfigured failure rather than a DI error.
  • Where it's used: called by ViewAsService.StartAsync; implemented in ADC by ViewAsSubjectResolver (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/Administration/ViewAsSubjectResolver.cs:24) and registered in that module's DependencyInjection.cs.

TwoFactorErrors

MMCA.Common.Application · MMCA.Common.Application.Auth.TwoFactor · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/TwoFactor/TwoFactorErrors.cs:15 · Level 2 · class

  • What it is: the static Error-factory class for the two-factor flow: challenge-required, challenge-invalid, not-enrolled, enrollment-missing, and recent-sign-in-required.
  • Depends on: Error.
  • Concept: same convention as EmailConfirmationErrors; no new concept.
  • Walkthrough: five codes (TwoFactorErrors.cs:18,21,24,27,33). TwoFactorRequired(source) (lines 38-41) is Error.Unauthorized, asking the caller to supply a code or a recovery code. TwoFactorInvalid(source) (lines 51-54) is also Error.Unauthorized; its remarks (lines 46-50) note it is deliberately the same message for a wrong TOTP code and a wrong recovery code, since telling them apart would leak whether a presented value was recovery-code shaped. TwoFactorNotEnrolled(source) (lines 59-62) and TwoFactorEnrollmentMissing(source) (lines 67-70) are both Error.Conflict, for an action attempted on an account with no active factor and on an enrollment that was never started, respectively. RecentSignInRequired(source) (lines 80-83) is Error.Forbidden with code Authentication.TwoFactorRecentSignInRequired (line 33): starting or confirming enrollment from a session whose interactive sign-in (auth_time) is older than the recent-sign-in window. Its remarks (lines 75-79) explain that enrollment adds a way into the account, so it asks for the same recent sign-in as registering a passkey, and that a refresh never renews auth_time, so only a new sign-in clears it.
  • Why it's built this way: Conflict versus Unauthorized is used to distinguish "your account state does not support this action" from "your credentials did not verify", and Forbidden marks "you are signed in, but not recently enough for this", matching the semantics the rest of the auth surface uses for those error kinds.
  • Where it's used: raised by ConfirmTwoFactorEnrollmentHandlerBase.cs, DisableTwoFactorHandlerBase.cs and RegenerateRecoveryCodesHandlerBase.cs (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/TwoFactor/), by TwoFactorAuthenticator and AuthenticationServiceBase.cs; RecentSignInRequired is raised by TwoFactorControllerBase (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/TwoFactor/TwoFactorControllerBase.cs:136,170). Asserted in TwoFactorHandlerBaseTests.cs, TwoFactorAuthenticatorTests.cs, TwoFactorControllerBaseTests.cs and AuthErrorCodesAlignmentTests.cs.

ITwoFactorAuthenticator

MMCA.Common.Application · MMCA.Common.Application.Auth.TwoFactor · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/TwoFactor/ITwoFactorAuthenticator.cs:24 · Level 3 · interface

  • What it is: the account-level orchestration for the second-factor challenge at sign-in, one level above ITwoFactorService's pure cryptographic operations.
  • Depends on: UserIdentifierType, TwoFactorOutcome, TwoFactorErrors, Result<T>.
  • Concept: the service-orchestrates-over-a-crypto-primitive layering also seen with IEmailConfirmationTokenService versus its store; no new concept.
  • Walkthrough: ChallengeAsync(userId, code, cancellationToken) (ITwoFactorAuthenticator.cs:40-43) returns TwoFactorOutcome.NotEnrolled when the account has no active second factor (sign-in continues unchanged, no mfa claim), the verified outcome when a code satisfies the challenge, or a failure: TwoFactorErrors.TwoFactorRequiredCode when a code was needed and none arrived, TwoFactorErrors.TwoFactorInvalidCode when one arrived and did not verify (doc comment lines 32-39).
  • Why it's built this way: returning an outcome enum rather than a bare boolean lets AuthenticationServiceBase distinguish "no second factor configured" from "verified", which matters for whether it stamps an mfa claim on the issued token.
  • Enrollment confirmation: VerifyEnrollmentCodeAsync(userId, secret, code, cancellationToken) (ITwoFactorAuthenticator.cs:65-69) returns a plain bool and verifies a code against the account's PENDING secret under the same single-use time-step guard as ChallengeAsync (doc comment lines 45-64). The secret it receives (param doc lines 57-61) is the pending secret as ITwoFactorStore holds it, in the protected form ITwoFactorSecretProtector.Protect produced; the shipped implementation unprotects it before verifying. ChallengeAsync answers TwoFactorOutcome.NotEnrolled until the factor is active, so the confirm step cannot use it. There is deliberately no recovery-code fallback, because confirming must prove the authenticator app holds the secret. The accepted step is remembered, so the code that confirmed enrollment cannot be replayed against the first challenge inside its window. Implemented at TwoFactorAuthenticator.cs:90.
  • Where it's used: implemented by TwoFactorAuthenticator (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/TwoFactor/TwoFactorAuthenticator.cs), called from AuthenticationServiceBase.cs (2 sites), from ConfirmTwoFactorEnrollmentHandlerBase.cs:83 (VerifyEnrollmentCodeAsync), and by the disable and recovery-code regeneration handler bases, and registered in MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Auth.cs.

ITwoFactorSecretProtector

MMCA.Common.Application · MMCA.Common.Application.Auth.TwoFactor · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/TwoFactor/ITwoFactorSecretProtector.cs:13 · Level 3 · interface

  • What it is: protects an account's two-factor shared secret at rest, so the app's ITwoFactorStore only ever holds the protected form.
  • Depends on: Result<T>.
  • Concept: encryption at rest behind a two-method port. Per the interface summary (ITwoFactorSecretProtector.cs:5-12), the enrollment workflow protects the freshly minted secret before it reaches the store, and the shipped ITwoFactorAuthenticator unprotects the stored value when it verifies a code.
  • Walkthrough: Protect(secret) (line 18) turns the plaintext Base32 secret into its stored form. Unprotect(protectedSecret) (line 23) returns Result<string> and never throws: a failure means this host's key ring cannot read the value.
  • Why it's built this way: a database leak alone then yields no usable TOTP secret. The default uses the host's data-protection key ring (summary lines 9-10), so a multi-replica host needs a shared key ring, and the Result return turns a key-ring mismatch into a handled failure instead of an exception in the sign-in path.
  • Where it's used: implemented by DataProtectionTwoFactorSecretProtector (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/TwoFactor/DataProtectionTwoFactorSecretProtector.cs:15) and registered as a singleton in MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Auth.cs:62; called by BeginTwoFactorEnrollmentHandlerBase.cs (protect) and TwoFactorAuthenticator (unprotect); exercised end to end in TwoFactorSecretProtectionEndToEndTests.cs.

ITwoFactorStore

MMCA.Common.Application · MMCA.Common.Application.Auth.TwoFactor · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/TwoFactor/ITwoFactorStore.cs:24 · Level 3 · interface

  • What it is: the persistence abstraction for one account's two-factor state: enrollment lifecycle, recovery-code replacement, and single recovery-code consumption.
  • Depends on: UserIdentifierType, ITwoFactorUserState (the read shape, taught elsewhere in this group), Result.
  • Concept: a two-phase enrollment (start, then complete) so an abandoned setup cannot lock an account out; the same two-phase shape a reader has already seen in other enrollment-style flows in this group.
  • Walkthrough: GetAsync(userId, cancellationToken) (ITwoFactorStore.cs:34) returns null only when the account itself does not exist; an account that never enrolled still returns a state with IsTwoFactorEnabled = false. StartEnrollmentAsync(userId, secret, cancellationToken) (line 47) stores a freshly minted secret WITHOUT activating the factor, per its summary (lines 36-39), so an abandoned enrollment cannot lock the user out. The secret (param doc lines 41-44) arrives already in its protected form (ITwoFactorSecretProtector); the store keeps it as given and returns it unchanged from GetAsync. CompleteEnrollmentAsync(userId, recoveryCodeHashes, cancellationToken) (lines 57-60) activates the factor and stores the first recovery-code hashes, called only after a code from the stored secret has verified. DisableAsync(userId, cancellationToken) (line 69) turns the factor off and clears the secret and recovery codes, so a later re-enrollment starts from a fresh secret. ReplaceRecoveryCodesAsync(userId, recoveryCodeHashes, cancellationToken) (lines 79-82) replaces the whole set, never appends, since regeneration exists to invalidate a list the user believes compromised. ConsumeRecoveryCodeAsync(userId, recoveryCodeHash, cancellationToken) (lines 96-99) removes one hash to spend it, and its remarks (lines 87-91) flag this as security-critical: it must persist before the sign-in it authorized is answered, or the same code could sign in twice.
  • Why it's built this way: splitting StartEnrollmentAsync/CompleteEnrollmentAsync prevents a half-finished enrollment from ever becoming an active, un-verified second factor.
  • Where it's used: implemented by the consuming app, not by Common: AddTwoFactorAuthentication deliberately registers no ITwoFactorStore (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Auth.cs:32), and registering one alongside that call arms the sign-in challenge (line 37). Called by TwoFactorAuthenticator, by the enrollment/disable/regenerate handler bases in MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/TwoFactor/, and by TwoFactorControllerBase and UsersAdminControllerBase in MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/.

IViewAsService

MMCA.Common.Application · MMCA.Common.Application.Auth.ViewAs · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/ViewAs/IViewAsService.cs:10 · Level 3 · interface

  • What it is: the view-as workflow contract: start a grant and mint its token, end a grant, and check whether a token's grant is still live.
  • Depends on: ViewAsGrantResponse, UserIdentifierType, Result.
  • Concept: read-only support access (ADR-137): a staff user gets a short-lived token whose sub is the viewed account, while the act_sub and vag claims name the staff user and the grant row behind it.
  • Walkthrough: StartAsync(staffUserId, targetUserId, reason, cancellationToken) (IViewAsService.cs:22-26) grants and mints; its summary (lines 12-16) lists the refusals (the caller themselves, a missing or soft-deleted account, an account that itself holds users:view-as) and the reason must be 10 to 500 characters. EndAsync(grantId, staffUserId, cancellationToken) (line 33) ends the staff user's grant so its token is refused on the next request, answering not found when the staff user holds no such grant. IsGrantActiveAsync(grantId, staffUserId, targetUserId, cancellationToken) (lines 44-48) is true while the grant exists, names this staff user and this account, was not ended, and has not expired.
  • Why it's built this way: every view-as request is re-checked against the grant row, so ending a grant takes effect immediately rather than when the token expires.
  • Where it's used: implemented by ViewAsService, registered in MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:222; IsGrantActiveAsync is called per request by ViewAsGuardMiddleware (MMCA.Common/Source/Presentation/MMCA.Common.API/Middleware/ViewAsGuardMiddleware.cs:137), and the start and end endpoints live on UsersAdminControllerBase and AuthControllerBase.

IViewAsGrantStore

MMCA.Common.Application · MMCA.Common.Application.Auth.ViewAs · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/ViewAs/IViewAsGrantStore.cs:11 · Level 4 · interface

  • What it is: the persistence port for ViewAsGrant rows, the audit record of every staff view.
  • Depends on: ViewAsGrant, ViewAsGrantListRequest, UserIdentifierType.
  • Concept: a purpose-built store interface rather than the generic repository, because the grant table is mapped only on the host that holds it (see ViewAsSettings).
  • Walkthrough: AddAsync(grant, ...) (IViewAsGrantStore.cs:17) inserts and saves. FindAsync(grantId, ...) (line 23) reads one row by the token's vag id. EndAsync(grantId, staffUserId, endedAt, ...) (line 34) puts the staff user in the lookup so one staff user cannot end another's grant, and returns true when the grant was found, ended now or before. GetRecentForTargetAsync(targetUserId, maxCount, ...) (lines 41-44) returns the newest grants on one account. DeleteIssuedBeforeAsync(cutoff, ...) (line 50) is the retention sweep and returns the row count. ListAsync(request, now, ...) (lines 62-65) pages the whole support access log newest first; its summary (lines 52-57) notes the status filter is evaluated at now, email filters compare case-insensitively against the display snapshots, and the page size is clamped to ViewAsGrantListRequest.MaxPageSize. ForgetUserAsync(userId, ...) (line 76) is the account-erasure step that blanks the display snapshot on every grant naming the account and, per lines 67-72, saves nothing itself: the erasure's own unit-of-work save persists it.
  • Why it's built this way: keeping the erasure step unsaved lets it commit atomically with the rest of the account deletion.
  • Where it's used: implemented by EFViewAsGrantStore (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Auth/EFViewAsGrantStore.cs:36, registered at MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:221) and the test double InMemoryViewAsGrantStore (MMCA.Common/Source/Hosting/MMCA.Common.Testing/Support/InMemoryViewAsGrantStore.cs:13). Called by ViewAsService, SignInHistory (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Sessions/SignInHistory.cs:55), DeleteUserHandlerBase (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/DeleteUser/DeleteUserHandlerBase.cs:184) and ViewAsGrantsAdminControllerBase (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Administration/ViewAsGrantsAdminControllerBase.cs:76).

ViewAsGrantLogQuery

MMCA.Common.Application · MMCA.Common.Application.Auth.ViewAs · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/ViewAs/ViewAsGrantLogQuery.cs:12 · Level 4 · class

  • What it is: a static helper that applies the support-access-log filters to any IQueryable<ViewAsGrant>.
  • Depends on: ViewAsGrant, ViewAsGrantListRequest, ViewAsGrantStatus.
  • Concept: one filter definition shared by the EF store and the in-memory test double, so the two cannot drift.
  • Walkthrough: Filter(grants, request, now) (ViewAsGrantLogQuery.cs:26) null-checks and composes the three private steps with AND (line 31), returning an unordered query. ByEmail (line 34) folds each needle with ViewAsGrant.NormalizeDisplay and applies a contains match against StaffDisplay and TargetDisplay. ByWindow (line 49) keeps GrantedAt >= From and GrantedAt < To (inclusive start, exclusive end). ByStatus (line 64) derives Live (not ended, ExpiresAt > now), Ended (EndedAt set) and Expired (not ended, ExpiresAt <= now) at lines 67-69, mirroring ViewAsGrant.StatusAt; no status means no filter.
  • Why it's built this way: expressing the status as a translatable predicate keeps the filter in SQL on the EF path instead of materializing the log.
  • Where it's used: EFViewAsGrantStore.ListAsync (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Auth/EFViewAsGrantStore.cs:131) and InMemoryViewAsGrantStore (MMCA.Common/Source/Hosting/MMCA.Common.Testing/Support/InMemoryViewAsGrantStore.cs:73).

ViewAsService

MMCA.Common.Application · MMCA.Common.Application.Auth.ViewAs · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/ViewAs/ViewAsService.cs:42 · Level 9 · class

  • What it is: the shipped IViewAsService: validates and audits a view-as grant, mints its token, ends it, and answers the per-request liveness check.
  • Depends on: IViewAsGrantStore, ITokenService, IPermissionRegistry, ViewAsSettings, TimeProvider, and the optional IViewAsSubjectResolver and ICurrentUserService (ViewAsService.cs:43-49).
  • Concept introduced: impersonation without identity theft. The minted token is an ordinary access token for the viewed account plus two claims, AuthClaimTypes.ViewAsActor and ViewAsGrant (lines 104-108); the command pipeline's ViewAs decorator and the guard middleware use them to keep the session read-only and tied to a live grant (ADR-137). [Rubric §11, Security] (assesses how the design limits and audits privileged access): every view is bounded in time, written to an audit row before a token exists, and refused for accounts that would give lateral or machine access.
  • Walkthrough: Lifetime (lines 55-58) is the configured access-token lifetime when it is positive and below ViewAsGrant.MaxLifetime, otherwise MaxLifetime (the summary says 15 minutes), so a view never outlives an ordinary sign-in token. StartAsync (line 66) first validates self-view and the reason through ViewAsGrant.Create (line 76), returns ViewAs.NotConfigured as an Error.Unexpected (a host wiring fault, not a caller mistake) when no resolver is registered (lines 82-87), then reads the subject (line 89) and runs Refuse (line 90). It rebuilds the grant with the display snapshots (line 99: the staff email from StaffEmail, the viewed email from the subject), sweeps rows older than RetentionDays (line 101) and adds the grant (line 102) BEFORE minting the token with GenerateShortLivedAccessToken (lines 109-115). EndAsync (line 121) answers ViewAs.GrantNotFound when the store found nothing (line 128). IsGrantActiveAsync (line 132) requires the row to exist, match both user ids and be active at now (lines 140-143). StaffEmail (line 153) reads the email claim (mapped ClaimTypes.Email, then raw email, line 161) only when the current user IS the staff user (line 155). Refuse (line 165) answers in order: not found (line 169), deleted (lines 172-174), service account per ADR-140 (lines 178-180), locked (lines 187-189), and an account whose role holds AdministrationPermissions.ViewAsUsers (lines 193-194), so there is no lateral access.
  • Why it's built this way: the remarks (lines 61-65) state the two ordering choices: the row is written before the token so no token exists without its audit record, and the retention sweep rides on grants (which are rare) instead of a hosted service in every process.
  • Where it's used: registered scoped in MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:222; tested in MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Auth/ViewAs/ViewAsServiceTests.cs, ViewAsTokenTests.cs and ViewAsGuardMiddlewareTests.cs.
  • Caveats / not-in-source: ViewAsGrant.MaxLifetime is 15 minutes (MMCA.Common/Source/Core/MMCA.Common.Domain/Auth/ViewAsGrant.cs:30), matching the summary at lines 51-54.

IPasswordHasher

MMCA.Common.Application · MMCA.Common.Application.Interfaces.Infrastructure.Auth · MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Auth/IPasswordHasher.cs:6 · Level 0 · interface

  • What it is: the password-security port. Two required methods: hash a plaintext password into a separated (byte[] Hash, byte[] Salt) pair, and verify a plaintext against a stored hash plus salt. Two defaulted members follow: NeedsRehash lets the caller ask whether a hash that has just verified was derived with older parameters, and BurnVerificationCost spends one throwaway derivation on a sign-in branch that never reaches a real verification.
  • Depends on: nothing first-party, BCL only (byte[]). Its Infrastructure adapter is PasswordHasher.
  • Concept introduced: hash and salt kept apart. [Rubric §11, Security] assesses credential handling. Returning the hash and the salt as two distinct byte[] members (MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Auth/IPasswordHasher.cs:11) rather than one concatenated blob keeps the storage contract explicit: the caller persists two columns, and VerifyPassword (:18) is unambiguous about what it re-derives and compares. Because the algorithm and its parameters live entirely behind this interface, they can be strengthened without touching a single Application handler (ADR-032 sets the current hashing policy, applied inside PasswordHasher).
  • Walkthrough: (byte[] Hash, byte[] Salt) HashPassword(string password) (:11) returns a named value tuple the caller stores as two fields. bool VerifyPassword(string password, byte[] hash, byte[] salt) (:18) re-derives from the supplied salt and compares. bool NeedsRehash(byte[] hash) => false (:28) is a default interface method: it answers whether the stored hash was derived with a format or work factor other than the one HashPassword uses now, and the false default keeps a custom hasher compiling without ever triggering a rehash. void BurnVerificationCost(string password) => _ = HashPassword(password) (:40) is the second default member, and its doc comment (:30-38) names the attack it closes: an unknown address or an account with no password never reaches VerifyPassword, so without a burn those branches would answer measurably faster than a wrong password. The burn costs what verifying a record at the current parameters costs (:31-32), the shape of every new, changed, reset or rehashed record (:34-35); the comment rules out burning at an older, higher work factor because that would make the unknown address the slow one (:35-36). The default (one HashPassword, discarded) is exactly that cost. PasswordHasher implements the member explicitly (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/PasswordHasher.cs:117), deriving at BurnIterations over a fresh salt (:121), and BurnIterations is defined as the current Iterations (:67). [Rubric §11, Security] applies directly: this is user-enumeration resistance by timing, expressed as a contract member rather than left to each caller. The interface still declares no iteration count, algorithm identifier, or format version: the concrete decides what "current" means (PasswordHasher overrides NeedsRehash at MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/PasswordHasher.cs:130; ADR-133 records the versioned work factor).
  • Why it's built this way: a small port is the [Rubric §1, SOLID] dependency-inversion story in miniature. Swapping the key-derivation function or raising the iteration count is an Infrastructure change, invisible to the register, login, and change-password use cases that only ever see this contract. NeedsRehash closes the loop on such a change: existing records upgrade on their next successful sign-in, while the verified plaintext is still in hand, instead of staying on the old parameters forever.
  • Where it's used: a primary-constructor dependency of AuthenticationServiceBase<TUser>, which calls VerifyPassword on the login path (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/AuthenticationServiceBase.cs:207), HashPassword on registration (:330), BurnVerificationCost on the branches that have no credential to verify (:967), and, after tokens are issued, NeedsRehash then HashPassword in its best-effort rehash step (:1018 and :1023) when the app's User implements IPasswordRehashableUser; into the shared ChangePasswordHandlerBase<TUser, TCommand>, which verifies the current password (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/ChangePassword/ChangePasswordHandlerBase.cs:108) before hashing the new one (:117); into ResetPasswordHandlerBase<TUser, TCommand>, which hashes the replacement after the token redeems (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/ResetPassword/ResetPasswordHandlerBase.cs:110); and into the per-app Identity services, handlers and seeders that derive from those, for example ADC's AuthenticationService (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/AuthenticationService.cs:54), its ChangePasswordHandler (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/ChangePassword/ChangePasswordHandler.cs:26) and its module seeder (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/IdentityModuleSeeder.cs:34, which needs the hasher because seed data carries plaintext credentials).

ISoftDeletedUserValidator

MMCA.Common.Application · MMCA.Common.Application.Interfaces.Infrastructure.Auth · MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Auth/ISoftDeletedUserValidator.cs:7 · Level 0 · interface

  • What it is: a single-method port that answers "has this account been soft-deleted?", called after JWT authentication to reject a soft-deleted user who still holds a valid, unexpired token (BR-133, named in the type comment at MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Auth/ISoftDeletedUserValidator.cs:4).
  • Depends on: BCL plus the solution-wide UserIdentifierType alias (:15). See primer §2 for the alias convention and ADR-005 for soft-delete versus erasure. The generic implementation is SoftDeletedUserValidator<TUser>.
  • Concept introduced: closing the stateless-token window. [Rubric §11, Security] assesses whether revocation is timely. A JWT is stateless: once signed it stays valid until exp, even if the account behind it was deleted a minute later. This port lets middleware re-ask the question on every authenticated request and fail the request when the answer is yes, with no per-handler code. The comment at :5 states the second motive: the interface is declared in Application and implemented against the app's own User aggregate precisely so the middleware never takes a cross-module domain reference. That is the same dependency inversion as the other ports in this group, applied to a cross-module read.
  • Walkthrough: one member, Task<bool> IsUserSoftDeletedAsync(UserIdentifierType userId, CancellationToken cancellationToken = default) (:15). One question, one answer, cancellable.
  • Where it's used: SoftDeletedUserMiddleware resolves it lazily from the request scope (MMCA.Common/Source/Presentation/MMCA.Common.API/Middleware/SoftDeletedUserMiddleware.cs:117 calls context.RequestServices.GetService<ISoftDeletedUserValidator>(), so a host that registers no implementation simply skips the check; the reason is stated at :43) and queries it on a cache miss (:113-115). Both apps register the shared generic against their own user type: MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/DependencyInjection.cs:37 and MMCA.Store/Source/Modules/Identity/MMCA.Store.Identity.Application/DependencyInjection.cs:43, both as TryAddScoped<ISoftDeletedUserValidator, SoftDeletedUserValidator<User>>().

ITokenService

MMCA.Common.Application · MMCA.Common.Application.Interfaces.Infrastructure.Auth · MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Auth/ITokenService.cs:8 · Level 0 · interface

  • What it is: the token-minting port called by the login and refresh use cases. It builds a signed JWT access token from explicit identity facts (with a short-lived variant whose lifetime the caller chooses), generates an opaque refresh token, publishes the two token lifetimes, and recovers the ClaimsPrincipal from an expired-but-validly-signed access token.
  • Depends on: System.Security.Claims (BCL, :1) and the UserIdentifierType alias. Its Infrastructure adapter is TokenService, which signs with the RSA key surfaced by IJwksProvider; SessionStampingTokenService is a second, internal implementation that decorates the first.
  • Concept introduced: token creation as an Infrastructure detail. [Rubric §3, Clean Architecture] assesses whether library-specific types stay out of the inner layers: the handlers call this contract and never see System.IdentityModel.Tokens.Jwt. GetPrincipalFromExpiredToken (MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Auth/ITokenService.cs:72) is the linchpin of the refresh flow: it validates the signature while deliberately ignoring lifetime, so an expired access token can still identify the user whose tokens are being rotated, returning null when the token is invalid (:71).
  • Walkthrough: GenerateAccessToken(UserIdentifierType userId, string email, string role, string fullName, IEnumerable<Claim>? additionalClaims = null) (:17-22) takes the minimum claim set as typed parameters rather than a ready-made principal, with an escape hatch for module-specific claims. GenerateShortLivedAccessToken(..., IEnumerable<Claim>? additionalClaims, TimeSpan lifetime) (:42-48) is the same mint with an explicit expiry, written for the read-only view-as token, which must never outlive its 15-minute grant (ADR-137, summary at :24-28). It is a required member with no default body, and the remarks (:29-34) say why: every implementation must honor lifetime, because minting with the configured lifetime instead would hand out a view-as token that outlives its grant. The view-as guard also checks the grant's own expiry on every request, so such a token would still be refused once its grant (ViewAsGrant) expires, but the remarks call that only a second line. GenerateRefreshToken() (:52) returns a cryptographically random base64 string. Two required get-only properties publish the lifetimes: AccessTokenLifetime { get; } (:58) and RefreshTokenLifetime { get; } (:64), the latter the absolute refresh-token lifetime of BR-205. The comments at :54-57 and :60-63 state the rule: an implementation derives both from the same settings it mints with (and stamps sessions with), so the expiry reported to a client matches the token's actual exp. That derivation is visible in the concrete: TimeSpan.FromMinutes(_jwtSettings.AccessTokenExpirationMinutes) and TimeSpan.FromDays(_jwtSettings.RefreshTokenExpirationDays) (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/TokenService.cs:197 and :200), with its short-lived mint at :123. The 15-minute and 7-day baselines live in the caller instead: AuthSessionIssuer falls back to them when an implementation reports a non-positive lifetime (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Sessions/AuthSessionIssuer.cs:79-83). GetPrincipalFromExpiredToken(string token) (:72) closes the set.
  • Why it's built this way: the explicit-parameter overload is a [Rubric §11, Security] guardrail. The token's contents are a deliberate list, not whatever claims happened to ride in on an inbound principal. Surfacing the lifetimes through the same port removes the duplication where a caller would hard-code an expiry that could drift from the signed exp. Declaring GenerateShortLivedAccessToken and both lifetimes as required members, with no default bodies, makes the compiler ask every implementer and test double the security-relevant question: no implementation can silently mint a view-as token at the configured lifetime, or report a lifetime other than the one it signs with, by inheriting a default.
  • Where it's used: AuthenticationServiceBase<TUser> reads the expired principal on refresh (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/AuthenticationServiceBase.cs:410) through its TokenService property, which exposes a wrapped instance to subclasses. AuthSessionIssuer mints the refresh token when it opens a session (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Sessions/AuthSessionIssuer.cs:501) and when it rotates one (:545), and its wrapping implementation, the private SessionStampingTokenService (:766), forwards both lifetimes (:781, :784), stamps its armed claims into the short-lived mint before forwarding it (:796-803), and forwards GenerateRefreshToken and GetPrincipalFromExpiredToken to the inner service (:806, :809-810). The short-lived mint has two callers: ViewAsService for the view-as token (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/ViewAs/ViewAsService.cs:109, its lifetime capped at ViewAsGrant.MaxLifetime, :56-58) and MachineClientService for the client-credentials token (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/MachineClients/MachineClientService.cs:115, ADR-140). Each app's Identity service mints access tokens from the base's TokenService property, for example MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/AuthenticationService.cs (access token plus the speaker_id claim). The rotated pair produced here is what CookieSessionRefresher later exchanges on the browser's behalf.

ITwoFactorUserState

MMCA.Common.Domain · MMCA.Common.Domain.Auth · MMCA.Common/Source/Core/MMCA.Common.Domain/Auth/ITwoFactorUserState.cs:27 · Level 0 · interface

  • What it is: the two-factor enrollment surface an Identity module's User aggregate exposes: whether the second factor is active, the shared secret the codes are derived from (in protected form), and the hashes of the account's unspent recovery codes (MMCA.Common/Source/Core/MMCA.Common.Domain/Auth/ITwoFactorUserState.cs:29-43).
  • Depends on: nothing first-party beyond the BCL IReadOnlyCollection<string> (:1).
  • Concept introduced: two-factor state read through a capability interface, not the concrete User. [Rubric §1, SOLID] assesses interface segregation: a shared handler that needs to know whether TOTP is enrolled never needs the rest of the app's User shape, so it depends on this narrow contract instead. [Rubric §11, Security] assesses the shape of the stored secret itself: TwoFactorSecret (:37) is nullable, meaning "no enrollment started" is representable without a sentinel value, and it is never the plaintext Base32 key: it holds the protected form the framework handed the store (:32-36), so a read of the users table does not yield a working authenticator seed. TwoFactorRecoveryCodeHashes (:43) likewise holds hashes, not the plaintext codes a user was shown once at generation time.
  • Walkthrough: bool IsTwoFactorEnabled (:30) gates whether a code is demanded at sign-in. string? TwoFactorSecret (:37) is the protected shared secret, null until enrollment begins; the protection is applied by ITwoFactorSecretProtector before the secret reaches the store (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/TwoFactor/BeginTwoFactorEnrollmentHandlerBase.cs:28, :44; the store contract repeats it at MMCA.Common/Source/Core/MMCA.Common.Application/Auth/TwoFactor/ITwoFactorStore.cs:42). IReadOnlyCollection<string> TwoFactorRecoveryCodeHashes (:43) is empty both before enrollment and after every recovery code has been spent, which the doc comment (:40-41) states is a state the user recovers from by regenerating rather than an error condition.
  • Why it's built this way: keeping this state on its own interface, separate from IAuthUser and IPasswordChangeableUser, lets an app opt into two-factor without every existing User aggregate needing new members it never populates. See ADR-116 for the opt-in model this interface belongs to.
  • Where it's used: the generic constraint on BeginTwoFactorEnrollmentHandlerBase<TCommand> (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/TwoFactor/BeginTwoFactorEnrollmentHandlerBase.cs:65, :80, where a missing state is reported as NotFound targeting this interface), and it is the state ITwoFactorStore returns from GetAsync (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/TwoFactor/ITwoFactorStore.cs:34) against the concrete User. MMCA.Store's User lists it among its capability interfaces (MMCA.Store/Source/Modules/Identity/MMCA.Store.Identity.Domain/Users/User.cs:30), and AuditTrailSaveChangesInterceptor reads it to redact the two-factor material from audit rows.

IAuthUser

MMCA.Common.Domain · MMCA.Common.Domain.Auth · MMCA.Common/Source/Core/MMCA.Common.Domain/Auth/IAuthUser.cs:15 · Level 0 · interface

  • What it is: the deliberately minimal credential surface an Identity module's User aggregate exposes to the shared AuthenticationServiceBase<TUser> workflow. Two properties of password material, plus one defaulted flag that marks a machine client's service account. It is the contract that lets the framework's authentication plumbing verify and replace a password without knowing anything app-specific about the user (MMCA.Common/Source/Core/MMCA.Common.Domain/Auth/IAuthUser.cs:3-8).
  • Depends on: nothing first-party; the BCL only (byte[]). Implemented transitively through IPasswordChangeableUser by each app's User aggregate (see User).
  • Concept introduced: the inverted user contract. Rather than the shared auth workflow depending on a concrete User class, User implements a small interface the framework owns. Profile fields, roles, linked aggregates, and claim sources stay app-specific: the shared workflow reaches those only through per-app hooks (CreateAccessToken, CreateUser), never through this contract (MMCA.Common/Source/Core/MMCA.Common.Domain/Auth/IAuthUser.cs:6-8). [Rubric §1, SOLID] assesses interface segregation and dependency inversion, and this is a textbook case: the interface is exactly the credential surface and nothing more. [Rubric §11, Security] assesses credential handling, and the whole security-relevant surface of a User aggregate is readable in a dozen lines.
  • Concept: what the contract deliberately leaves out. The <para> block (MMCA.Common/Source/Core/MMCA.Common.Domain/Auth/IAuthUser.cs:9-13) records what is deliberately absent: refresh tokens. They are rows in RefreshSession, one per signed-in device, hashed at rest and reached through IRefreshSessionStore, so no usable bearer credential sits in the users table and this interface covers passwords only (ADR-097). [Rubric §15, Best Practices & Code Quality] applies: documenting an absence on the contract itself stops a later change from "helpfully" putting a token column back on the user.
  • Walkthrough: three members, all read-only.
    • byte[] PasswordHash (MMCA.Common/Source/Core/MMCA.Common.Domain/Auth/IAuthUser.cs:19), the PBKDF2 hash produced by IPasswordHasher, documented as either the versioned shape or the header-less legacy shape (:18, ADR-032, ADR-133).
    • byte[] PasswordSalt (:22), the salt paired with it.
    • Both sit inside a scoped #pragma warning disable CA1819 (:17, restored on :23) that knowingly returns arrays, to mirror IPasswordHasher's byte[] tuple and the EF-mapped varbinary columns rather than force a defensive copy on every read. The suppression's justification is written on the disable line itself, which is the convention this codebase uses everywhere it takes an analyzer exception.
    • bool IsServiceAccount => false (:32) is a default interface member marking the service account behind a machine client rather than a person (ADR-140). Its doc comment (:25-31) states the policy: such an account obtains tokens only through the client-credentials grant, so password sign-in, sign-in links, external login and passkeys refuse it, and it can never be viewed as. The false default means an app that has not adopted machine clients implements nothing.
    • There is no mutator. Writing new material is the separate capability IPasswordChangeableUser adds, so an aggregate that only ever authenticates never exposes a way to change its own password.
  • Why it's built this way: keeping the contract in Domain and keeping it small is what makes the shared auth workflow reusable across Store and ADC (both User aggregates satisfy it) while each aggregate stays free to model everything else its own way. See ADR-032 for the password-material policy, ADR-004 for the dual-fetch auth model this contract feeds, and ADR-097 for the refresh-token move.
  • Where it's used: it is part of the generic constraint on the shared login and registration workflow, where TUser : AuditableAggregateRootEntity<UserIdentifierType>, IAuthUser, IEmailIdentifiedUser (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/AuthenticationServiceBase.cs:86, the last being IEmailIdentifiedUser), which passes both password properties to VerifyPassword on the login path (:219) and refuses a service account on its sign-in branches (:573, :619, :942). It is also the base of IPasswordChangeableUser, and the shape hand-written test doubles copy. ADC's User overrides the flag with a stored IsServiceAccount { get; private set; } (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Domain/Users/User.cs:150, set to true only when a service account is provisioned, :373), and ViewAsService refuses to view one (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/ViewAs/ViewAsService.cs:178-180, ViewAs.TargetIsServiceAccount).

IPasswordChangeableUser

MMCA.Common.Domain · MMCA.Common.Domain.Auth · MMCA.Common/Source/Core/MMCA.Common.Domain/Auth/IPasswordChangeableUser.cs:11 · Level 3 · interface

  • What it is: the password-rotation surface an Identity module's User aggregate exposes to the shared ChangePasswordHandlerBase<TUser, TCommand> workflow. It is one method on top of IAuthUser (MMCA.Common/Source/Core/MMCA.Common.Domain/Auth/IPasswordChangeableUser.cs:5-9).
  • Depends on: IAuthUser (its base interface, :11) and Result from MMCA.Common.Shared.Abstractions (:1).
  • Concept: capability interfaces layered by workflow. [Rubric §1, SOLID] assesses interface segregation, and this is the pattern applied twice over: a User that only ever authenticates satisfies IAuthUser; a User whose app offers self-service password change implements this one and gets PasswordHash and PasswordSalt along with it, because the workflow must verify the current credential before writing the new one (the XML comment states exactly this reason, :7-9). Inheritance here encodes a real dependency between capabilities rather than a taxonomy. [Rubric §4, DDD] also applies: the method returns Result, so the aggregate can refuse the change (an invariant failure) instead of the handler assuming success.
  • Walkthrough: one member, Result ChangePassword(byte[] newPasswordHash, byte[] newPasswordSalt) (:19). The aggregate receives already-hashed material, never a plaintext password: hashing is the handler's job via IPasswordHasher, so no plaintext ever reaches the Domain layer or an EF change tracker.
  • Why it's built this way: keeping the hash-and-salt pair as the parameter shape mirrors IAuthUser's two properties and IPasswordHasher's tuple return, so the whole chain from handler to aggregate speaks one vocabulary. See ADR-032.
  • Where it's used: as the generic constraint where TUser : AuditableAggregateRootEntity<UserIdentifierType>, IPasswordChangeableUser on the shared change-password workflow (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/ChangePassword/ChangePasswordHandlerBase.cs:62), which verifies the current password (:55), hashes the new one (:61), and calls ChangePassword with the result (:62). The forgot-password sibling, ResetPasswordHandlerBase<TUser, TCommand>, calls the same member on the redeem path after IPasswordResetTokenService has identified the account (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/ResetPassword/ResetPasswordHandlerBase.cs:110-111). Both apps' User aggregates declare it (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Domain/Users/User.cs:36-37, MMCA.Store/Source/Modules/Identity/MMCA.Store.Identity.Domain/Users/User.cs:29-30), which is also how they pick up IAuthUser.

IPasswordRehashableUser

MMCA.Common.Domain · MMCA.Common.Domain.Auth · MMCA.Common/Source/Core/MMCA.Common.Domain/Auth/IPasswordRehashableUser.cs:16 · Level 3 · interface

  • What it is: the opt-in surface that lets the shared AuthenticationServiceBase<TUser> sign-in flow upgrade a stored password hash to the hasher's current format and work factor while it still holds the verified plaintext. An Identity module's User that does not implement it keeps its stored hash exactly as it is (MMCA.Common/Source/Core/MMCA.Common.Domain/Auth/IPasswordRehashableUser.cs:5-9).
  • Depends on: IAuthUser (its base interface, :16, which supplies the PasswordHash the sign-in flow inspects) and Result from MMCA.Common.Shared.Abstractions (:1).
  • Concept introduced: a re-derivation is not a password change. The <para> block (:10-14) is the reason this interface exists beside IPasswordChangeableUser rather than reusing its ChangePassword: a rehash keeps the same password, so it must not raise the aggregate's password-changed domain event, or anything else a real change triggers, such as revoking sessions or notifying the owner. [Rubric §1, SOLID] assesses interface segregation, and here two members with the same parameter shape are kept apart because their side effects differ. [Rubric §11, Security] assesses credential storage over time: a hash written under an older work factor stays at that cost until something re-derives it, and the only moment the plaintext is available to do so is a successful sign-in (ADR-133).
  • Walkthrough: one member, Result RehashPassword(byte[] newPasswordHash, byte[] newPasswordSalt) (:25), documented as replacing the stored material with a re-derivation of the same password without raising a password-changed event (:18-21). Like ChangePassword it receives already-hashed material, never the plaintext, and returns success or the aggregate's invariant failure (:24).
  • Why it's built this way: the upgrade is opt-in twice over. The caller pattern-matches user is not IPasswordRehashableUser rehashable and returns when the aggregate does not implement it (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/AuthenticationServiceBase.cs:1008), and IPasswordHasher's NeedsRehash is a default interface member that returns false (MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Auth/IPasswordHasher.cs:28), so a custom hasher that never overrides it never triggers a rewrite. The work runs after tokens are issued and saves on its own, so a refused invariant or a failed save cannot fail a sign-in that already succeeded (AuthenticationServiceBase.cs:995-1001). See ADR-032 for the password-material policy and ADR-133 for the versioned work factor.
  • Where it's used: RehashPasswordIfNeededAsync in AuthenticationServiceBase<TUser> is the only caller, invoked on the login path right after IssueTokensAsync (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/AuthenticationServiceBase.cs:290). Inside a best-effort wrapper it checks NeedsRehash against the stored hash (:688), hashes the verified password (:693), calls RehashPassword (:694), logs PasswordRehashRejected through AuthenticationServiceLog on a refused invariant (:697), and otherwise saves through the unit of work (:704). The ADC User aggregate implements it (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Domain/Users/User.cs:35), validating the hash and salt with the same UserInvariants checks as a password change and assigning both without adding a domain event (:442-457), in contrast to ChangePassword, which raises UserPasswordChanged (:429). The MMCA.Store User implements it too (MMCA.Store/Source/Modules/Identity/MMCA.Store.Identity.Domain/Users/User.cs:30). The flow is covered by AuthenticationServicePasswordRehashTests (MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Auth/AuthenticationServicePasswordRehashTests.cs).

IUserPreferences

MMCA.Common.Domain · MMCA.Common.Domain.Auth · MMCA.Common/Source/Core/MMCA.Common.Domain/Auth/IUserPreferences.cs:10 · Level 3 · interface

  • What it is: the stored UI-preference surface an Identity module's User aggregate exposes to the shared preference read and write workflows: preferred culture, preferred theme, and a single method that replaces both (MMCA.Common/Source/Core/MMCA.Common.Domain/Auth/IUserPreferences.cs:5-8).
  • Depends on: Result from MMCA.Common.Shared.Abstractions (:1). Nothing else; it is deliberately not tied to IAuthUser, because preferences are orthogonal to credentials.
  • Concept: null as "not chosen". [Rubric §27, i18n] assesses whether locale is a first-class, persisted user choice rather than a per-session guess, and [Rubric §19, State Management] assesses where such UI state lives. Both properties are nullable, and the contract states that null means the user has not chosen that preference (:7-8), which is what lets the UI fall back to a browser or host default without needing a separate "is set" flag. See ADR-027 for the culture model and ADR-028 for the theme model.
  • Walkthrough: string? PreferredCulture (for example "es", :13) and string? PreferredTheme ("light" or "dark", :16) are read-only. Result UpdatePreferences(string? preferredCulture, string? preferredTheme) (:25) replaces both at once. The subtlety is documented at :18-21: because the method is a whole-object replace, the shared workflow always passes the currently stored value for any field the request left null, so writing one preference never silently clears the other. That read-then-merge is visible in the caller (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/ChangePreferences/ChangePreferencesHandlerBase.cs:53).
  • Why it's built this way: one replace method keeps the aggregate's invariant check in a single place, and pushing the merge into the workflow keeps the null-means-unchanged policy out of every app's User. Returning Result lets the aggregate reject an unsupported culture or theme value.
  • Where it's used: the read workflow constrains where TUser : AuditableBaseEntity<UserIdentifierType>, IUserPreferences and projects both properties into a response (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/GetPreferences/GetUserPreferencesHandlerBase.cs:21, :44); the write workflow constrains where TUser : AuditableAggregateRootEntity<UserIdentifierType>, IUserPreferences (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/ChangePreferences/ChangePreferencesHandlerBase.cs:26). Both are cross-linked as GetUserPreferencesHandlerBase<TUser> and ChangePreferencesHandlerBase<TUser, TCommand>, and both apps' User aggregates implement the interface.

IEmailConfirmableUser

MMCA.Common.Domain · MMCA.Common.Domain.Auth · MMCA.Common/Source/Core/MMCA.Common.Domain/Auth/IEmailConfirmableUser.cs:22 · Level 3 · interface

  • What it is: the email-confirmation surface an Identity module's User aggregate exposes: whether the address has been proved, and a method that marks it confirmed (MMCA.Common/Source/Core/MMCA.Common.Domain/Auth/IEmailConfirmableUser.cs:24-32).
  • Depends on: Result from MMCA.Common.Shared.Abstractions.
  • Concept introduced: idempotent confirmation by contract. [Rubric §4, DDD] assesses whether an aggregate enforces its own invariants rather than trusting the caller, and ConfirmEmail()'s doc comment (:26-30) states the requirement directly: implementations should be idempotent, so redeeming a second token for an address that is already confirmed is an ordinary duplicate outcome, not a fault. That reading matters because a user can legitimately click an old confirmation link twice (a second tab, a forwarded email), and the workflow must not turn that into an error.
  • Walkthrough: bool IsEmailConfirmed (:24) is the current state. Result ConfirmEmail() (:32) returns a success result, or the aggregate's own invariant failure, and takes no parameters: the token itself is verified upstream by IEmailConfirmationTokenService before this method is ever called.
  • Why it's built this way: keeping confirmation as its own capability interface, alongside ITwoFactorUserState and IUserPreferences, lets an app that does not require email confirmation skip implementing it, consistent with the opt-in model of ADR-116.
  • Where it's used: the generic constraint on SendEmailConfirmationHandlerBase<TUser, TCommand> and ConfirmEmailHandlerBase<TUser, TCommand>, and by AuthenticationServiceBase<TUser>, which reads IsEmailConfirmed on the login path.

ILegalAcceptingUser

MMCA.Common.Domain · MMCA.Common.Domain.Auth · MMCA.Common/Source/Core/MMCA.Common.Domain/Auth/ILegalAcceptingUser.cs:21 · Level 3 · interface

  • What it is: the terms-acceptance surface an Identity module's User aggregate exposes: which terms version the user last accepted, when, and a method that records a new acceptance (MMCA.Common/Source/Core/MMCA.Common.Domain/Auth/ILegalAcceptingUser.cs:21-38).
  • Depends on: Result from MMCA.Common.Shared.Abstractions. Nothing else; like IUserPreferences it is not tied to IAuthUser.
  • Concept: idempotent acceptance by contract. [Rubric §4, DDD] assesses whether an aggregate enforces its own invariants, and the AcceptTerms doc comment states that implementations should be idempotent for the same version: accepting the version already on record is an ordinary repeat, not a fault (:34-37). This mirrors IEmailConfirmableUser, so a double-submitted acceptance form does not surface as an error.
  • Walkthrough: string? AcceptedTermsVersion (:29) and DateTime? TermsAcceptedOn (:32, UTC) are read-only and null when the user never accepted. Result AcceptTerms(string version, DateTime acceptedOn) (:42) takes a non-blank version and the UTC instant, and returns success or the aggregate's invariant failure.
  • Why it's built this way: a separate capability interface lets an app that does not gate on legal terms skip it, consistent with the opt-in model of ADR-116. The clock is passed in rather than read inside the aggregate, so the caller owns time.
  • Where it's used: AuthenticationServiceBase<TUser> documents the user.AcceptTerms(CurrentTermsVersion, now) call on an ILegalAcceptingUser (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/AuthenticationServiceBase.cs:140), and ILegalAcceptanceService names it as the typical aggregate shape (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Legal/ILegalAcceptanceService.cs:8). The ADC User aggregate implements it (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Domain/Users/User.cs:37).

PasskeyCredential

MMCA.Common.Domain · MMCA.Common.Domain.Auth · MMCA.Common/Source/Core/MMCA.Common.Domain/Auth/PasskeyCredential.cs:20 · Level 3 · class (sealed)

  • What it is: one registered passkey, a WebAuthn public-key credential bound to one account: the public half of a key pair whose private half never leaves the user's authenticator (MMCA.Common/Source/Core/MMCA.Common.Domain/Auth/PasskeyCredential.cs:5-7, ADR-139).
  • Depends on: Result and Error from MMCA.Common.Shared.Abstractions (:1) and the UserIdentifierType alias. Persisted through IPasskeyCredentialStore by EFPasskeyCredentialStore, mapped by PasskeyCredentialModelBuilderExtensions, and driven by PasskeyService.
  • Concept introduced: a stored credential that is not a secret. [Rubric §11, Security] assesses what a database read yields. The class comment (:15-17) states it plainly: the credential id and the public key only verify signatures, so a dump of this table cannot sign anyone in, which is why neither is hashed the way RefreshSession hashes its token. What this row must protect against instead is a cloned authenticator, and the signature counter is the tool: IsSignCountAcceptable(long stored, uint presented) (:123-124) accepts a counter that goes up, or zero on both sides (an authenticator that does not count, which is what synced passkeys do, :52-55), and refuses one that stays put or goes down, because that means two copies of the key are in use.
  • Concept: framework bookkeeping, not an aggregate. Like RefreshSession, it is a flat record with no audit stamps, no soft-delete flag and no concurrency token: inserted at registration, touched on each sign-in, renamed, and deleted outright (:9-13). It is mapped only where a host opts in (AddPasskeys with Passkeys:Enabled), in the Identity database alone (:12-13), consistent with ADR-006.
  • Walkthrough
    • Width constants published for the EF mapping: CredentialIdMaxLength = 1023 (the longest id WebAuthn allows, :23), PublicKeyMaxLength = 2048 (an RSA-4096 COSE key fits, :26), NameMaxLength = 100 (:29), TransportsMaxLength = 100 (:32), and DefaultName = "Passkey" (:35).
    • State: Id defaults to a fresh Guid and is what rename and delete address (:38); UserId is required (:41). CredentialId and PublicKey are required byte[] (:45, :48) inside a scoped #pragma warning disable CA1819 (:43-49) whose justification cites EF's varbinary shape and the IAuthUser precedent. SignCount (:55), Name (:64) and LastUsedOn (:70) have private setters; Transports (:61) holds comma-separated hints such as internal or hybrid, and CreatedOn (:67) is init-only.
    • Create(...) (:83) returns Result<PasskeyCredential>. It rejects an empty or oversized credential id (Passkeys.CredentialIdInvalid) or public key (Passkeys.PublicKeyInvalid) and a name over 100 characters (ValidateMaterial, :163), copies both byte arrays so the caller's buffers cannot mutate the row (:105-106), and turns a blank name into DefaultName (:109). Transport hints are best effort: an empty or oversized list is dropped to null rather than refusing the passkey (:182-187).
    • RecordUse(uint presentedSignCount, DateTime usedOn) (:133) applies the counter rule and returns Passkeys.SignCountInvalid as an Unauthorized error (:137-140) without touching the row, otherwise stores the new counter and the instant.
    • Rename(string? name) (:151) trims and requires 1 to 100 characters, failing with Passkeys.NameInvalid (:189-190).
  • Why it's built this way: keeping the counter rule as a static pure function on the Domain type lets the sign-in path and the tests evaluate it without a row, while RecordUse guarantees the rule is applied before any write. Validation lives in the factory so an oversized value surfaces as a [Rubric §4, DDD]-shaped Result failure instead of a database constraint violation.
  • Where it's used: PasskeyService creates the row after a verified registration (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Passkeys/PasskeyService.cs:100), renames it (:137) and records each sign-in (:266). ADC's Identity database carries the table through the AddPasskeyCredentials migration (MMCA.ADC/Source/Hosting/MMCA.ADC.Migrations.SqlServer.Identity/Migrations/20261112192534_AddPasskeyCredentials.Designer.cs). The rules are covered by PasskeyCredentialTests (MMCA.Common/Tests/Core/MMCA.Common.Domain.Tests/Auth/PasskeyCredentialTests.cs).

PermissionGrant

MMCA.Common.Domain · MMCA.Common.Domain.Auth · MMCA.Common/Source/Core/MMCA.Common.Domain/Auth/PermissionGrant.cs:24 · Level 3 · class (sealed)

  • What it is: one row granting a single area:capability permission to a single role, with an audit trail of when and by whom it was created (MMCA.Common/Source/Core/MMCA.Common.Domain/Auth/PermissionGrant.cs:24-94).
  • Depends on: Result and Error, both from MMCA.Common.Shared.Abstractions. Persisted through IPermissionGrantStore and its EF adapter, and read into IPermissionCatalog/IPermissionRegistry at runtime.
  • Concept introduced: two comparison conventions pinned by comment, not by type. [Rubric §11, Security] assesses authorization correctness, and this class carries the two rules an authorization decision depends on directly on the properties: Role (:188) is compared case-insensitively everywhere it is read, matching PermissionRegistry and RoleValue; Permission (:194) is compared ordinally, matching the compiled registry. Getting either comparison wrong would make a grant silently not match the token it was meant to authorize.
  • Walkthrough: RoleMaxLength = 64 (:176) and PermissionMaxLength = 128 (:179) are published column widths. Id (:182) defaults to a fresh Guid. Role and Permission (:188, :194) are required init-only strings. GrantedAt (:197) is required; GrantedBy (:203) is optional and documented as informational only, never part of an authorization decision, so a row written by a migration with no principal is still honored. Create(string role, string permission, DateTime grantedAt, string? grantedBy = null) (:213-242) is the only constructor path: it fails validation with PermissionGrant.RoleInvalid when the role is blank or over 64 characters (:219-225), and PermissionGrant.PermissionInvalid when the permission is blank or over 128 (:227-233), then trims both before storing.
  • Why it's built this way: validating length and blankness in the factory rather than trusting the caller keeps an oversized or empty value from reaching the database as a constraint violation instead of a [Rubric §4, DDD]-shaped Result failure. Grouping the two comparison conventions on the type that stores the data, rather than leaving them implicit in the store or the registry, is what keeps every reader consistent.
  • Where it's used: written and read by EFPermissionGrantStore and StoredPermissionRoleAdministrationService, mapped by PermissionGrantModelBuilderExtensions, and its RoleMaxLength/PermissionMaxLength constants are cited by SetUserRolesRequestValidator and SetRolePermissionsRequestValidator (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Validation/AdministrationRequestValidators.cs:22-23, :41-42) when validating admin requests that set roles or permissions.

ViewAsGrant

MMCA.Common.Domain · MMCA.Common.Domain.Auth · MMCA.Common/Source/Core/MMCA.Common.Domain/Auth/ViewAsGrant.cs:18 · Level 3 · class (sealed)

  • What it is: one read-only view-as grant: a staff user was allowed to see the app as another account for a bounded time, for a stated reason. The row is itself the audit record of that access (there is no separate audit-event API), and it is what the viewed account's sign-in history shows as "Viewed by support" (MMCA.Common/Source/Core/MMCA.Common.Domain/Auth/ViewAsGrant.cs:6-9, ADR-137).
  • Depends on: Result and Error from MMCA.Common.Shared.Abstractions (:1), the ViewAsGrantStatus enum from MMCA.Common.Shared.Auth.Responses (:2), and the UserIdentifierType alias. Persisted through IViewAsGrantStore by EFViewAsGrantStore, mapped by ViewAsGrantModelBuilderExtensions, and issued by ViewAsService.
  • Concept introduced: a bounded, justified, recorded impersonation. [Rubric §11, Security] assesses support access to user data. Three limits are enforced in the factory, not left to the caller: a staff user cannot view as themselves (ViewAs.Self, :109-113); the reason must be 10 to 500 characters after trimming, so "x" cannot stand in for a justification (ReasonMinLength/ReasonMaxLength, :21, :24; ViewAs.ReasonInvalid, :118-123); and the lifetime is clamped to MaxLifetime, 15 minutes, whatever the access-token lifetime is (:30, clamp at :126-129). The grant's Id travels in the view-as token as its vag claim (:33), with StaffUserId as act_sub and TargetUserId as sub (:36, :39), so every request can be checked against a live row.
  • Concept: framework bookkeeping, not an aggregate. Like RefreshSession, a flat record with no audit stamps, no soft-delete flag and no concurrency token: inserted, possibly ended once, and swept after the retention window. No global query filter may hide one from the per-request liveness check (:11-15).
  • Walkthrough
    • Constants: ReasonMinLength = 10 (:21), ReasonMaxLength = 500 (:24), DisplayMaxLength = 256 (an email address fits, :27), MaxLifetime = 15 minutes (:30).
    • State: Id (:33), StaffUserId (:36), TargetUserId (:39), the required Reason (:42), GrantedAt and ExpiresAt (:45, :48) are init-only; EndedAt (:51), StaffDisplay (:59) and TargetDisplay (:66) have private setters.
    • Two Create overloads: the five-argument form (:78) records no display snapshot and forwards to the seven-argument form (:100), which also snapshots both parties' emails so the support access log stays readable without a user lookup. A non-positive or oversized lifetime becomes MaxLifetime, and ExpiresAt = grantedAt + lifetime (:137).
    • NormalizeDisplay(string?) (:151) is both the storage form and the search-needle form: trimmed, lower-cased character by character with the invariant culture (so a match does not depend on a database collation), cut to 256 characters, and null when blank.
    • Lifecycle: IsActiveAt(now) (:172) is "not ended and not expired"; StatusAt(now) (:181) derives Ended, Live or Expired; End(now) (:193) is EndedAt ??= now, so ending an ended grant changes nothing.
    • Erasure: ForgetDisplayOf(userId) (:202) blanks the erased account's email snapshot on whichever side (staff, viewed, or both) it sits, and keeps the ids and the reason, so the access stays on record without the personal data (ADR-005).
  • Why it's built this way: making the grant row the audit record, rather than writing a separate event, means the evidence of access and the thing that authorizes access cannot diverge. Clamping the lifetime on the Domain type keeps the 15-minute ceiling true even if a caller asks for more, and ITokenService's short-lived mint is capped at the same MaxLifetime.
  • Where it's used: ViewAsService validates a request with the five-argument factory (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/ViewAs/ViewAsService.cs:76), creates the snapshotting grant (:99), and answers the per-request liveness question through IsActiveAt (:143), which ViewAsGuardMiddleware relies on. ViewAsGrantLogQuery folds its search needles with NormalizeDisplay (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/ViewAs/ViewAsGrantLogQuery.cs:36, :41); EFViewAsGrantStore runs ForgetDisplayOf during erasure (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Auth/EFViewAsGrantStore.cs:161); and ViewAsGrantsAdminControllerBase projects StatusAt into the admin log (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Administration/ViewAsGrantsAdminControllerBase.cs:90).

RefreshSession

MMCA.Common.Domain · MMCA.Common.Domain.Auth · MMCA.Common/Source/Core/MMCA.Common.Domain/Auth/RefreshSession.cs:46 · Level 4 · class (sealed)

  • What it is: one refresh-token session, meaning a single device's right to mint access tokens for one user, held as a hash of the issued refresh token. A user has as many rows as they have signed-in devices, so signing in on a phone no longer signs the same account out of a laptop (BR-205/206, MMCA.Common/Source/Core/MMCA.Common.Domain/Auth/RefreshSession.cs:9-12). It implements IAnonymizable (:39) so the device metadata it captures has an erasure path.
  • Depends on: Result and Error (:5), PiiAttribute (:3), IAnonymizable (:4), the UserIdentifierType alias, and from the BCL System.Security.Cryptography.SHA256, System.Text.Encoding, and Convert.ToHexString (:1-2). Persisted by EFRefreshSessionStore behind IRefreshSessionStore, mapped by RefreshSessionModelBuilderExtensions, swept by RefreshSessionCleanupService, tuned by RefreshSessionSettings.
  • Concept introduced: a refresh token is a credential, so store its digest and make reuse detectable. [Rubric §11, Security] assesses how a long-lived credential is stored, rotated, and revoked, and this one class carries four separate properties that are each worth understanding on their own.
    • Hash at rest. The plaintext refresh token exists only in the response that hands it to the client; the row keeps TokenHash (:72), so a database read cannot mint tokens (:14-16). That forces one design consequence the comment calls out explicitly: because lookups are by hash, the digest must be unsalted and deterministic. A per-row salt would make the token unfindable. This is the opposite trade-off from PasswordHasher, and legitimately so: a refresh token is 64 random bytes from a CSPRNG rather than a human-chosen password, so there is no dictionary to run against it and no value in slowing the digest down.
    • Rotation leaves a chain. Using a session revokes it and records its successor in ReplacedByTokenHash (:19-22, :83-87). The point is not bookkeeping: presenting an already-rotated token lands on a revoked row rather than on nothing, and that difference is the signal that a token was replayed. A stolen-and-replayed token therefore triggers revocation of the whole family instead of failing quietly (BR-206 reuse detection, ADR-050).
    • Framework bookkeeping, not an aggregate. The class comment (:24-31) is explicit that this is a flat record like OutboxMessage and AuditTrailEntry: no audit stamps, no soft-delete flag, no concurrency token. The reason matters for [Rubric §8, Data Architecture]: rows are never deleted or edited except to be revoked, and no global query filter may hide a revoked row, because the reuse check depends on finding it. It is also mapped only where a consumer opts in (ApplyRefreshSessionConfiguration), since sessions belong to the Identity module's database rather than to every data source (ADR-006 database-per-service).
    • Personal data is separable from the credential. The class comment (:32-37) splits the row in two: IpAddress and UserAgent identify the data subject's device and network, so both carry [Pii] and Anonymize clears them for an erasure request (ADR-005), while the token hashes, timestamps and revocation chain carry no personal data and are kept. That split is what lets reuse detection keep working on an anonymized row. It also satisfies the framework's PII convention, under which any domain entity with a [Pii]-marked property must implement IAnonymizable (MMCA.Common/Source/Hosting/MMCA.Common.Testing.Architecture/Rules/Governance/ArchitectureRules.Governance.cs:10).
  • Walkthrough
    • Width and reason constants (MMCA.Common/Source/Core/MMCA.Common.Domain/Auth/RefreshSession.cs:49-79): TokenHashLength = 64 (the width of a hex-encoded SHA-256 digest, :46), IpAddressMaxLength = 45 (sized to fit an IPv4-mapped IPv6 literal, :49), UserAgentMaxLength = 512 (:52), ReasonRevokedMaxLength = 64 (:55), and the five revocation reasons ReasonRotated (:58), ReasonSignedOut (:61), ReasonReuseDetected (:64), ReasonSessionCap (:67, value "SessionCapExceeded"), and ReasonAccountDeleted (:70, value "AccountDeleted", recorded when a session is revoked because its account was deleted and erased). Publishing the widths as public const on the Domain type is what lets the EF configuration derive every column width from the same numbers (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Auth/RefreshSessionModelBuilderExtensions.cs:63, :52, :56-58) rather than repeating magic numbers in a mapping file.
    • State (:73-112): Id defaults to a fresh Guid (:73); UserId, TokenHash, CreatedAt and ExpiresAt are required and init-only (:76-85), so a session cannot be constructed without them and cannot be rewritten afterwards. Three revocation members carry private set and change only through Revoke: RevokedAt (:88), ReplacedByTokenHash (:94), ReasonRevoked (:97). IpAddress (:105) and UserAgent (:112) are optional capture, each marked [Pii] (:104, :111) and also private set: they are written once by Create and afterwards only cleared by Anonymize, never set from outside. The UserAgent comment (:100-103) gives the reason for its marking: alongside the IP it fingerprints the data subject's device. The comment on IpAddress (:92-96) is a good example of documenting what a field is not for: it identifies a session in a "your devices" list and gives an audit trail for a revocation, and it is never part of a validation decision, so a mobile client changing networks is not signed out.
    • Derived state: IsRevoked => RevokedAt is not null (:115) and IsActiveAt(DateTime utcNow) => !IsRevoked && ExpiresAt > utcNow (:119). Passing the instant in rather than reading a clock keeps the type free of ambient time, which is what makes it directly unit-testable (see RefreshSessionTests).
    • Create(...) (:132-165), the factory returning Result<RefreshSession> in the framework's standard shape (see the primer on factory methods and the Result pattern). Two guards: a blank token fails with RefreshSession.TokenRequired (:140-146), and an expiry at or before creation fails with RefreshSession.ExpiryInPast (:148-154), both Error.Validation. On success it hashes the token on the way in (:159), so the plaintext never reaches a property, and truncates the two optional capture fields to their column widths (:162-163). Truncating in the factory rather than trusting the caller is what keeps an oversized User-Agent header from turning a login into a database error.
    • HashToken(string refreshToken) (:180-184): Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(refreshToken))), guarded by ArgumentException.ThrowIfNullOrWhiteSpace (:182). The <remarks> (:171-177) is the one piece of this file to read twice: the encoding is part of the contract, not an implementation detail, because a consumer's data migration has to reproduce it exactly to carry existing tokens over. It even gives the T-SQL equivalent, CONVERT(char(64), HASHBYTES('SHA2_256', CONVERT(varchar(max), Token)), 2), and explains both halves of why it matches: style 2 emits upper-case hex with no 0x prefix, and the varchar conversion is what makes the hashed bytes UTF-8 rather than SQL Server's default UTF-16. [Rubric §8, Data Architecture] and [Rubric §34, Architecture Governance & Documentation] both apply here: a hash format that a migration must reproduce is a published contract, and it is documented as one.
    • Revoke(DateTime revokedAt, string reason, string? replacedByTokenHash = null) (:194-209): the only mutator of session state. It is idempotent by refusal (:187-188), returning Error.Invariant("RefreshSession.AlreadyRevoked", ...) when the session is already revoked (:196-202) rather than silently overwriting, so the first reason and instant recorded are the ones kept. That matters for forensics: a session revoked by reuse detection must not have that reason overwritten by a later sign-out or by the account-erasure step. On success it stamps the instant, the truncated reason, and the successor hash (:204-206).
    • Anonymize() (:217-222): the IAnonymizable member. It nulls IpAddress and UserAgent and returns Result.Success(). Unlike Revoke it is idempotent by acceptance (:211-215): an already-anonymized session stays as it is and the call still succeeds, because erasing absent data is not an error. It deliberately leaves the session's validity untouched; revoking is the sign-out path's job, so anonymizing a row and ending it remain two separate decisions.
    • Truncate (:224-225) is the shared private helper, returning the value unchanged when it is null, empty, or already short enough.
  • Why it's built this way: ADR-097 records the move from one plaintext refresh-token column on the user row to a session table, and ADR-050 the rotation-and-reuse-detection model the chain implements. Keeping the class free of audit stamps and soft-delete is deliberate rather than an omission, and keeping Create/Revoke/Anonymize as the only ways in and out means every row in the table was validated, every revoked row carries a reason, and personal data can be erased without breaking the chain.
  • Where it's used: AuthSessionIssuer is the main consumer. It hashes a presented token to look the session up (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Sessions/AuthSessionIssuer.cs:200, :285), creates one per login (:320) and per rotation (:360), revokes on sign-out (:166, :172, :180) and on a by-id revoke from the device list (:247), revokes the live family on reuse detection (:295, :383), and evicts the oldest session with ReasonSessionCap when a user is at RefreshSessions:MaxActiveSessionsPerUser (:427, documented at :409; default 10 at MMCA.Common/Source/Core/MMCA.Common.Application/Auth/RefreshSessionSettings.cs:35). Its ListActiveAsync filters with IsActiveAt and projects IpAddress and UserAgent into RefreshSessionSummaryResponse for the "your devices" list (AuthSessionIssuer.cs:205-214). RefreshSessionRevocation also revokes with ReasonSignedOut (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/RefreshSessionRevocation.cs:52). The erasure path is RefreshSessionRevocation.RevokeAndAnonymizeAllAsync (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/RefreshSessionRevocation.cs:70-92): for every session the user holds it revokes the un-revoked ones with ReasonAccountDeleted (:87) and calls Anonymize on all of them (:90), revoked rows included, since each still carries the captured IP address and user agent. Rotation itself is a claim rather than a plain mutation: IRefreshSessionStore.TryRotateAsync revokes with ReasonRotated and links the successor (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/IRefreshSessionStore.cs:195; the EF implementation does it as a conditional ExecuteUpdate, MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Auth/EFRefreshSessionStore.cs:353, :142). The table is mapped through ApplyRefreshSessionConfiguration (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Auth/RefreshSessionModelBuilderExtensions.cs:50), which the internal RefreshSessionModelContributor applies only when RefreshSessions:Enabled is set and the source is the one RefreshSessions:DataSourceName names (RefreshSessionModelBuilderExtensions.cs:140-152), and the account-deletion path calls that erasure step before its single save (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/DeleteUser/DeleteUserHandlerBase.cs:171-199), so the revocation and anonymization commit or roll back together with the user's own erasure. The refresh flow's soft-delete query filter already stops an erased account's sessions from working; the revocation records why (:153-154).

IErasableUser

MMCA.Common.Domain · MMCA.Common.Domain.Auth · MMCA.Common/Source/Core/MMCA.Common.Domain/Auth/IErasableUser.cs:22 · Level 4 · interface

  • What it is: the erasure surface an Identity module's User aggregate exposes to the shared DeleteUserHandlerBase<TUser, TCommand> workflow: soft-delete the row, then irreversibly anonymize the personal data it still holds (MMCA.Common/Source/Core/MMCA.Common.Domain/Auth/IErasableUser.cs:6-9).
  • Depends on: IAnonymizable (its base, contributing Result Anonymize(), :1 and :30) and Result (:2).
  • Concept introduced: why a Delete() that already exists on the base entity is redeclared here. This is the most instructive comment in the file and it is worth reading in full (:11-29). AuditableBaseEntity<TIdentifierType> already has a Delete(). But an app's User may hide it (public new Result Delete()) to couple account-specific behavior to deletion. A hidden method is not an override, and C# member lookup on a generic type parameter prefers the members of its class constraint, so a shared workflow writing user.Delete() would bind to the base implementation and silently skip the app's version. Because the app User lists this interface in its own base list, the interface map resolves to the most derived Delete() declared on the app type, so invoking it through the interface forces interface dispatch and reaches exactly the member the app intended. [Rubric §1, SOLID] (Liskov: the hidden method is exactly the substitutability hazard this closes) and [Rubric §15, Best Practices & Code Quality] both apply, and this is a case where a language rule, not a style preference, dictates the design. The second paragraph (:25-28) adds the compile-time guarantee: the base entity deliberately does not implement this interface, so a consumer that forgets to declare it fails the generic constraint at compile time rather than losing behavior at run time.
  • Walkthrough: one declared member, Result Delete() (:37), documented as soft-delete plus whatever the app couples to deletion (:32-34), returning a failure when the account is already deleted (:36). Inherited from IAnonymizable is Result Anonymize(), which must be idempotent. The two-step order is visible in the caller: cast once to the interface (IErasableUser erasable = user;, MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/DeleteUser/DeleteUserHandlerBase.cs:150, with the reason spelled out at :88-92), erasable.Delete() first (:94), the app's own tail hook next (OnAfterSoftDeleteAsync, :101), then erasable.Anonymize() (:108), each short-circuiting on failure.
  • Why it's built this way: soft-delete alone hides a row but retains its personal data, so it does not satisfy an erasure request; anonymize-in-place overwrites the personal fields while keeping the row so foreign keys and the audit trail survive (ADR-005). Splitting the two into separate members lets the workflow run app-specific work between them, which the handler documents as the only point where an app can both read the personal data and know the delete succeeded (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/DeleteUser/DeleteUserHandlerBase.cs:49-50). [Rubric §30, Compliance, Privacy & Data Governance] assesses exactly this: an erasure path that does not destroy referential integrity.
  • Where it's used: the generic constraint where TUser : AuditableAggregateRootEntity<UserIdentifierType>, IErasableUser on the shared delete-user workflow (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/DeleteUser/DeleteUserHandlerBase.cs:103), implemented by each app's User aggregate (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Domain/Users/User.cs:36-37, MMCA.Store/Source/Modules/Identity/MMCA.Store.Identity.Domain/Users/User.cs:29-30).
  • Caveats / not-in-source: the interface's own comment says an app typically hides Delete() to revoke the refresh token (MMCA.Common/Source/Core/MMCA.Common.Domain/Auth/IErasableUser.cs:16, :34). That phrasing predates the move to RefreshSession rows and no longer describes either app. ADC is the only consumer that hides the method, and its version calls base.Delete() and raises a UserDeleted domain event (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Domain/Users/User.cs:529-538), with the XML comment there stating outright that sessions are not touched and do not need to be. MMCA.Store does not hide Delete() at all. The load-bearing lesson (interface dispatch over a possibly-hidden base member) is unchanged; the example in the comment is stale.

ICurrentUserService

MMCA.Common.Application · MMCA.Common.Application.Interfaces.Infrastructure.Auth · MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Auth/ICurrentUserService.cs:10 · Level 8 · interface

  • What it is: the Application layer's read-only window onto the authenticated caller: the raw ClaimsPrincipal, a strongly-typed UserId, the caller's first role, the full role set, a generic typed-claim reader, and a role-membership helper. It answers "who is calling?" without any handler ever touching HttpContext.
  • Depends on: System.Security.Claims and IParsable<T> (BCL, :1) plus the solution-wide UserIdentifierType alias (:16); see primer §2. It reads role claims through ClaimsPrincipalExtensions (MMCA.Common.Shared.Auth, imported at :2). Its adapter is CurrentUserService in Infrastructure.
  • Concept introduced: the caller-identity port with behavior on the interface. [Rubric §3, Clean Architecture] assesses whether inner layers stay free of transport types, and [Rubric §1, SOLID] (interface segregation) whether a contract exposes only what its clients need. A handler must know the caller to run ownership checks and to stamp audit fields, but it must not depend on IHttpContextAccessor, which would drag ASP.NET Core into the Application project. This interface is that inversion, and the adapter is the only place the accessor appears (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Context/CurrentUserService.cs:17, :25). What makes it worth studying is the use of default interface members: Roles (:46-61) and IsInRole (:83-84) ship real implementations on the contract, so every implementer and every hand-written test double inherits correct multi-role behavior instead of re-deriving it.
  • Walkthrough: ClaimsPrincipal User (:13) exposes the full principal for advanced inspection. UserIdentifierType? UserId (:16) is the typed identifier, nullable because an unauthenticated request has no user. string? Role (:23) is documented as the first role claim only, with the remarks at :19-22 steering callers to Roles or IsInRole for membership checks. Roles (:46-61) is the interesting member: it reads every role claim through User.GetRoleValues() (:52), the framework's one role-claim predicate (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/ClaimsPrincipalExtensions.cs:60), which accepts each claim type the JWT middleware may produce (ClaimTypes.Role when inbound claim mapping is on, or the raw role / roles claim when it is off, ClaimsPrincipalExtensions.cs:92-94) and returns an empty sequence for a null principal (ClaimsPrincipalExtensions.cs:61-62), so User is null-guarded even though the property is declared non-nullable (comment at :50-51). It then falls back to a single-element list built from Role when the principal yields nothing (:59). Sharing that predicate means the current-user service cannot drift from what the authorization handler treats as a role (ClaimsPrincipalExtensions.cs:73-75). The long remarks at :28-45 justify both accommodations from the nature of a default interface member: it runs against every implementation, including a hand-written double or a mock that stubs only Role, where reading claims alone would have reported no roles and silently turned an authorization check into a denial, and dereferencing a null principal would have turned it into a NullReferenceException. Claims win when present, so a genuine multi-role principal is still read in full. T? GetClaimValue<T>(string claimType) where T : struct, IParsable<T> (:70-71) parses a named claim into any parsable value type and returns null when the claim is missing or unparseable, which is how a module reads its own claim (the doc names speaker_id, :65) without Common ever knowing that claim exists. IsInRole(string roleName) (:83-84) is Roles.Any(role => string.Equals(role, roleName, StringComparison.OrdinalIgnoreCase)).
  • Why it's built this way: the remarks at :79-82 record the reasoning behind IsInRole checking every claim rather than comparing against Role. Comparing against the first role alone matched only whichever role happened to be listed first, which is latent today because tokens carry a single role, and would have surfaced silently as an authorization denial the moment a second role was added. Typing UserId as the per-app alias instead of a generic parameter keeps the interface concrete and easy to mock while staying correct for each app. [Rubric §11, Security] and [Rubric §15, Best Practices & Code Quality] both apply.
  • Where it's used: registered as scoped against CurrentUserService at MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:398. It supplies the Roles set the CQRS authorization decorators check permissions against (MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Decorators/AuthorizationCommandDecorator.cs:30, and its query twin; see group 05); it is how audit fields get their actor, since DbContextFactory passes _currentUserService.UserId into every save (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/Factory/DbContextFactory.cs:69, used at :297, :340, :370, :431 and :482); and it backs the ownership check in OwnerOrAdminFilter and the framework's account controllers.
  • Caveats / not-in-source: Role deliberately reports only the first role claim; treat it as a display value and use Roles or IsInRole for any decision.

MachineClientSecret

MMCA.Common.Domain · MMCA.Common.Domain.Auth.MachineClients · MMCA.Common/Source/Core/MMCA.Common.Domain/Auth/MachineClients/MachineClientSecret.cs:15 · Level 0 · class (static)

  • What it is: the machine-client secret format: 32 random bytes handed out once as base64url, stored only as their SHA-256 hash, and compared in constant time (MMCA.Common/Source/Core/MMCA.Common.Domain/Auth/MachineClients/MachineClientSecret.cs:6-9,15-45).
  • Depends on: nothing first-party; System.Security.Cryptography (RandomNumberGenerator, SHA256, CryptographicOperations) and System.Text.Encoding (BCL, MachineClientSecret.cs:1-2).
  • Concept introduced, a high-entropy secret needs a fast hash, not a password hash. [Rubric §11, Security] assesses whether credentials are stored and compared safely. A user password is low-entropy, so it goes through the slow PasswordHasher; this secret is 256 bits of RandomNumberGenerator output, so "there is nothing for a slow hash to protect against, and the token endpoint stays cheap under a burst of requests" (MachineClientSecret.cs:10-14). What the type does keep from password handling is that the plaintext is never stored and that comparison runs in constant time, so response timing cannot leak how many bytes of a guess matched.
  • Walkthrough:
    • SecretByteLength = 32 (:18) and HashByteLength = 32 (:21, the SHA-256 output size); the second is the length every stored hash is checked against.
    • Generate() (:25) draws SecretByteLength bytes from RandomNumberGenerator.GetBytes and base64url-encodes them through the private Base64UrlEncode (:43-44: standard base64 with = padding trimmed and +// swapped for -/_), so the secret is safe in a URL or a form body.
    • Hash(string) (:30-34) throws on null, then returns SHA256.HashData over the secret's UTF-8 bytes. The same call hashes a freshly generated secret for storage and a presented secret for comparison.
    • Matches(ReadOnlySpan<byte>, byte[]?) (:40-41) returns false for an empty slot or a stored hash of the wrong length, and otherwise defers to CryptographicOperations.FixedTimeEquals.
  • Why it's built this way: ADR-140 (the OAuth client credentials grant for machine clients) names this format; the type's own summary cites it (MachineClientSecret.cs:7). A static class with no state keeps generation, hashing and comparison in one place the domain entity, the application service and the EF mapping all share.
  • Where it's used: MachineClient validates hash lengths against HashByteLength (MMCA.Common/Source/Core/MMCA.Common.Domain/Auth/MachineClients/MachineClient.cs:79,138) and calls Hash plus Matches in Accepts (MachineClient.cs:116-118); MachineClientService calls Generate and Hash on create and rotate (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/MachineClients/MachineClientService.cs:165-166,210-211); MachineClientModelBuilderExtensions sizes both hash columns with HashByteLength (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/MachineClients/MachineClientModelBuilderExtensions.cs:44-45).

MachineClient

MMCA.Common.Domain · MMCA.Common.Domain.Auth.MachineClients · MMCA.Common/Source/Core/MMCA.Common.Domain/Auth/MachineClients/MachineClient.cs:21 · Level 4 · class (sealed)

  • What it is: a program allowed to obtain access tokens through the OAuth client credentials grant, backed one to one by its own service-account user whose role decides what the tokens may do (MMCA.Common/Source/Core/MMCA.Common.Domain/Auth/MachineClients/MachineClient.cs:6-9,21).
  • Depends on: AuditableBaseEntity<TIdentifierType> (base, keyed by Guid), MachineClientSecret, Result and Error; the UserIdentifierType alias for the service-account key (ADR-048).
  • Concept introduced, secret rotation without downtime on a revoke-never-delete entity. [Rubric §11, Security] assesses whether non-human credentials can be rotated, expired and revoked. The entity holds two hash slots: PrimarySecretHash always holds one, SecondarySecretHash holds a rotated secret until it is promoted, and "both are accepted meanwhile so a program can switch without downtime" (MachineClient.cs:10-14). A revoked client "keeps its row (and its audit stamps) and refuses every secret from then on" (:15-19). [Rubric §4, DDD] assesses whether invariants live on the entity: every state change goes through a method returning Result, with private setters and a private constructor (:26-28), following the Result pattern taught in the primer.
  • Walkthrough:
    • State: NameMaxLength = 100 (:24); Name (:31), ServiceAccountUserId (:34), PrimarySecretHash (:38, defaulting to an empty array) and the nullable SecondarySecretHash (:41), both byte[] under a scoped CA1819 suppression because that is EF Core's native varbinary shape (:36,42); SecretExpiresOn, RevokedOn and LastUsedOn (:45,48,51), all nullable UTC instants; and the computed IsRevoked => RevokedOn is not null (:54).
    • Create (:63-99): throws on a null hash, trims the name and fails MachineClients.NameInvalid when it is empty or over 100 characters (:73-77), fails MachineClients.SecretHashInvalid when the hash is not HashByteLength bytes (:79-83), and fails MachineClients.SecretExpiryInvalid when an expiry is not after utcNow (:85-89). On success it assigns Id = Guid.NewGuid() and copies the hash with a collection spread, so the caller's array cannot later mutate the entity (:91-98).
    • Accepts(string?, DateTime) (:109-122): false for a null or empty secret; otherwise hashes it once and runs Matches against BOTH slots before evaluating anything else (:116-118), so the short-circuit over IsRevoked and the expiry check (:121) "leaks no timing" (:120). The expiry is exclusive: the secret works only while utcNow < expiry.
    • Rotate(byte[]) (:130-146): fails MachineClients.Revoked on a revoked client, fails SecretHashInvalid on a wrong-length hash, else stores a copy in the secondary slot. A second rotation before promotion replaces the waiting secret (:125-126).
    • Promote() (:150-166): fails Revoked, or the conflict MachineClients.NoSecondarySecret when there is nothing to promote (:157-161); otherwise moves the secondary hash into the primary slot and clears the secondary, so the old primary stops working (:163-165).
    • Revoke(DateTime) (:173) is RevokedOn ??= utcNow: idempotent, keeping the first instant. RecordUse(DateTime) (:177) stamps LastUsedOn. The private Revoked helper builds the shared MachineClients.Revoked conflict error (:179-180).
  • Why it's built this way: ADR-140 records the machine-client model this entity implements. Per the type's own summary, the entity is mapped only where a host opts in (AddMachineClients with MachineClients:Enabled), in the Identity database alone (MachineClient.cs:17-18).
  • Where it's used: MachineClientService calls Accepts before minting a token (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/MachineClients/MachineClientService.cs:96), runs Create twice on create, first with a default service-account id purely to validate the name and expiry before any account is provisioned, then for real (MachineClientService.cs:167,179), and calls Rotate, Promote and Revoke (:182,201,227). IMachineClientStore is its persistence contract; EFMachineClientStore calls RecordUse (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/MachineClients/EFMachineClientStore.cs:74) and MachineClientModelBuilderExtensions maps it. In ADC the table first appears in the Identity migration 20261112192549_AddMachineClients (MMCA.ADC/Source/Hosting/MMCA.ADC.Migrations.SqlServer.Identity/Migrations/).
  • Caveats / not-in-source: Not determinable from source within this type: whether the store ever physically deletes a revoked row; the "revoked, never deleted" rule is stated in the summary (MachineClient.cs:16) but enforced, if at all, by the store and service, not here.

EmailConfirmationEntry

MMCA.Common.Infrastructure · MMCA.Common.Infrastructure.Auth · MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/EmailConfirmationTokenService.cs:212 · Level 0 · record (internal sealed)

  • What it is: the cached confirmation record behind the email-confirmation flow: what EmailConfirmationTokenService writes into the cache when a confirmation token is issued, and reads back when one is redeemed. It is internal sealed, declared as a second type at the bottom of its service's file (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/EmailConfirmationTokenService.cs:212-216).
  • Depends on: nothing first-party except the UserIdentifierType alias (the per-module global using identifier alias, ADR-048). Four positional parameters, all BCL primitives.
  • Concept: the same cache-DTO rule PasswordResetEntry demonstrates: a value round-tripped through System.Text.Json in a distributed cache must be a JSON primitive, so the token digest travels as Base64 text (TokenHashBase64, :170) rather than as byte[], and the expiry as Unix seconds (ExpiresAtUnixSeconds, :173) rather than as DateTimeOffset. [Rubric §11, Security] applies through the same member name convention: TokenHashBase64, never Token, so the record cannot hold the redeemable secret it guards.
  • Walkthrough: four members, the same shape as PasswordResetEntry:
    • string TokenHashBase64 (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/EmailConfirmationTokenService.cs:213): the SHA-256 digest of the issued token, Base64-encoded. Validation re-hashes the presented token and compares digests.
    • UserIdentifierType UserId (:171): the account the token confirms.
    • int FailedAttempts (:172): wrong tokens presented against this record so far.
    • long ExpiresAtUnixSeconds (:173): when the record expires; a failed-attempt rewrite recaches with the remaining lifetime computed from this field so a wrong guess cannot extend how long the token stays redeemable (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/EmailConfirmationTokenService.cs:176-189).
  • Why it's built this way: being a record gives the with expression the attempt-counter rewrite relies on (entry with { FailedAttempts = attempts }, MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/EmailConfirmationTokenService.cs:193). Being internal keeps the cache layout out of the package's public API.
  • Where it's used: written by IssueAsync (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/EmailConfirmationTokenService.cs:79-85), read by ValidateAndConsumeAsync (:85), and rewritten by RecordFailedAttemptAsync (:148-151). It appears nowhere else.

IJwksProvider

MMCA.Common.Infrastructure · MMCA.Common.Infrastructure.Auth · MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/IJwksProvider.cs:11 · Level 0 · interface

  • What it is: the abstraction that returns the active JsonWebKeySet served at /.well-known/jwks.json. Implementations materialize the public signing key(s) in the JWK format that other services consume to validate access tokens (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/IJwksProvider.cs:5-10).
  • Depends on: Microsoft.IdentityModel.Tokens.JsonWebKeySet (NuGet, :1). Implemented by RsaJwksProvider; configured by JwksSettings and served by JwksEndpointExtensions.
  • Concept introduced: publishing a public key instead of sharing a secret. [Rubric §11, Security] assesses key management and blast radius, and [Rubric §7, Microservices Readiness] assesses whether a module can be lifted out without a rewrite. In an extracted-service topology, symmetric HS256 would require every service to hold the same secret, so any one compromised service can mint tokens for all of them. The asymmetric alternative (ADR-004) keeps the RSA private key inside the Identity service and publishes only the public key at a well-known URL; peers fetch it and validate signatures without ever being able to sign. IJwksProvider is how the Identity API obtains that public key set to serve.
  • Walkthrough: a single synchronous member, JsonWebKeySet GetJsonWebKeySet() (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/IJwksProvider.cs:19). Synchronous is the deliberate shape because key material is resolved once and cached in-process by the implementation. The doc comment sets a contract that the implementation must honor: return an empty key set rather than throwing when no signing key is configured (:13-17), so /.well-known/jwks.json stays a valid, pollable URL even in a host where JWKS publishing is off.
  • Why it's built this way: an interface here lets tests inject a pre-built key set with no file IO, and the empty-set contract makes the endpoint safe to map unconditionally instead of behind a feature check.
  • Where it's used: registered as services.TryAddSingleton<IJwksProvider, RsaJwksProvider>() (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:256) immediately after the JwksSettings options binding (:240-243); the JWKS minimal-API endpoint calls it, and consuming services fetch the resulting document through AddForwardedJwtBearer at startup (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/IJwksProvider.cs:9).

JwtSigningAlgorithm

MMCA.Common.Infrastructure · MMCA.Common.Infrastructure.Auth · MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/JwtSigningAlgorithm.cs:23 · Level 0 · enum

  • What it is: a four-value enum selecting which algorithm access tokens are signed with, and so which key type the configured key is read as: symmetric HMAC (HS256) or one of three asymmetric algorithms (RS256, PS256, ES384) (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/JwtSigningAlgorithm.cs:3-6).
  • Depends on: nothing. Referenced by JwtSettings, JwksAdditionalKey, JwtAlgorithms, TokenService, RsaJwksProvider, and the API-layer authentication wiring.
  • Concept introduced: the deployment shape, and the key, encoded as one configuration value. [Rubric §11, Security] assesses key management: HS256 requires every validator to hold the signing key, which is acceptable only while issuer and validators share a process. The asymmetric values split the pair: the Identity service signs with its private key and every other service validates against the JWKS endpoint, so no peer ever holds the signing key (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/JwtSigningAlgorithm.cs:8-11, ADR-004). RS256 and PS256 read an RSA key, ES384 an ECDSA key on P-384 (:11-12). [Rubric §7, Microservices Readiness]: making this a configuration value rather than a compile-time choice is what lets the same binaries run both topologies. The doc then states the crypto-agility rule: the algorithm belongs to the key, every asymmetric validator accepts all three asymmetric values, and each JWKS key publishes its own alg, so a rotation can move to a new algorithm by staging the new key and keeping the old one as an additional validation key (:12-14, ADR-149). The operational consequence of the other boundary is stated just as plainly: switching a running deployment between HS256 and an asymmetric algorithm invalidates every existing token, a hard cutover (:19-20).
  • Walkthrough: HS256 = 0 (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/JwtSigningAlgorithm.cs:26), RS256 = 1 (:29, RSA PKCS#1 v1.5 with SHA-256, the default), PS256 = 2 (:32, RSA-PSS with SHA-256 over the same RSA key pair) and ES384 = 3 (:35, ECDSA on P-384 with SHA-384 over EcPrivateKeyPem + EcPublicKeyPem), all with explicit ordinals.
    • The default is RS256, and where that default lives is worth being precise about. The enum's zero value is HS256, so a configuration binder that saw an invalid value would land there; but a host that simply omits Jwt:SigningAlgorithm never has the property set at all, and JwtSettings's own initializer holds (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/JwtSettings.cs:37). The default is a property initializer, not the enum ordinal.
    • The enum carries no behavior of its own. JwtAlgorithms maps it: IsAsymmetric answers true for every value except HS256 (MMCA.Common/Source/Build/Auth/JwtAlgorithms.cs:38), UsesEcKey true for ES384 only (:43), ToSecurityAlgorithm returns the JOSE alg name (:49-56), and AcceptedFor returns the asymmetric list or the HS256-only list (:61-62).
    • TokenService branches on the value once, in its constructor, and caches the resulting credentials (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/TokenService.cs:93-109), with the asymmetric and HMAC builders at :274 and :265. Each fails with a named InvalidOperationException when its key material is missing: the asymmetric builder names EcPrivateKeyPem or RsaPrivateKeyPem and the selected algorithm (:283-287), the HMAC builder throws through JwtSettings.DecodeHmacSigningKey (:269).
    • The API layer branches on the same value when configuring in-process JWT bearer validation: BuildValidationParameters takes the asymmetric path for any of RS256, PS256 or ES384 (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/WebApplicationBuilderExtensions.Authentication.cs:227-250), accepting the whole asymmetric list (:247), and, when the public key of the algorithm's key type is absent, throws a message that points the reader at AddForwardedJwtBearer for services that fetch the key through JWKS at runtime instead (:231-235).
  • Why it's built this way: the values encode deployment shape and key type rather than a compatibility level (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/JwtSigningAlgorithm.cs:4-6). A single-process monolith that will never be split skips key-pair management entirely; everything else picks an asymmetric algorithm, and because validators accept all three, moving between them is a key rotation rather than a cutover.
  • Where it's used: JwtSettings.SigningAlgorithm (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/JwtSettings.cs:37) and its conditional validation (:114, :121, :128), JwksAdditionalKey.Algorithm (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/JwksSettings.cs:219), RsaJwksProvider.CurrentKeyAlgorithm (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/RsaJwksProvider.cs:37-40), TokenService, and BuildValidationParameters in the API startup extensions (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/WebApplicationBuilderExtensions.Authentication.cs:226).

LoginProtectionSettings

MMCA.Common.Infrastructure · MMCA.Common.Infrastructure.Auth · MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/LoginProtectionSettings.cs:9 · Level 0 · class (sealed)

  • What it is: strongly typed, [Range]-validated configuration for brute-force login lockout and registration rate limiting, bound from the LoginProtection configuration section (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/LoginProtectionSettings.cs:5-7).
  • Depends on: System.ComponentModel.DataAnnotations for [Range] (BCL, :1). Consumed by LoginProtectionService through IOptions<LoginProtectionSettings>.
  • Concept: [Rubric §11, Security] assesses whether brute-force defenses exist and are tunable, and this settings class is where the policy numbers live rather than being hard-coded into a handler. [Rubric §15, Best Practices & Code Quality] also applies in a small way: five init-only properties with defaults mean an app that configures nothing still gets a safe policy, and an app that configures one value inherits the rest.
  • Walkthrough: const string SectionName = "LoginProtection" (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/LoginProtectionSettings.cs:12) names the bound section. Two concerns follow.
    • Account lockout: MaxFailedAttempts (default 5, [Range(1, 100)], MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/LoginProtectionSettings.cs:17-18), MaxLockoutSeconds (default 300, [Range(1, 3600)], :23-24), FailedAttemptWindowMinutes (default 30, [Range(1, 1440)], :30-31). The window comment (:26-29) is load-bearing for understanding the service: the attempt counter resets by cache expiration, not by a sweep job.
    • Registration rate limiting: MaxRegistrationsPerIpPerHour (default 10, [Range(1, 10000)], MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/LoginProtectionSettings.cs:36-37) and RegistrationRateLimitWindowMinutes (default 60, [Range(1, 1440)], :42-43).
  • Why it's built this way: sealed with init-only properties gives an immutable options object. Every property carries a [Range], and the registration wires .ValidateDataAnnotations().ValidateOnStart() (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:173-176), so an obviously unsafe value such as MaxFailedAttempts = 0 fails the host at startup instead of quietly disabling lockout until someone notices in production. The MaxLockoutSeconds upper bound of 3600 is also what lets LoginProtectionService reason about its shift-clamp safely.
  • Where it's used: bound and validated in AddInfrastructure (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:173-176) immediately before LoginProtectionService is registered (:165). Its sibling PasswordResetSettings is bound in exactly the same shape two lines later (:167-170), as is RefreshSessionSettings (:175-178).

PasswordResetEntry

MMCA.Common.Infrastructure · MMCA.Common.Infrastructure.Auth · MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/PasswordResetTokenService.cs:204 · Level 0 · record (internal sealed)

  • What it is: the cached reset record behind the forgot-password flow: what PasswordResetTokenService writes into the cache when a reset token is issued, and reads back when one is redeemed. It is internal sealed, declared as a second type at the bottom of its service's file (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/PasswordResetTokenService.cs:204-208).
  • Depends on: nothing first-party except the UserIdentifierType alias (the per-module global using identifier alias taught in the primer, ADR-048). Four positional parameters, all BCL primitives.
  • Concept introduced: a cache DTO is constrained by its serializer, not by your domain. [Rubric §8, Data Architecture] assesses whether each store is given a shape it can actually round-trip, and this four-line record is a compact lesson in that. The XML comment states the rule directly (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/PasswordResetTokenService.cs:195-199): the cache round-trips values through System.Text.Json, so every member is a JSON primitive. A value object such as Email or a raw byte[] here would not survive a distributed backing store, which is why the token digest is carried as Base64 text (:172) and the expiry as Unix seconds (:175) rather than as byte[] and DateTimeOffset. [Rubric §11, Security] also applies through one member name: TokenHashBase64, not Token. The record is structurally incapable of holding the secret it guards.
  • Walkthrough: four members, in the order they matter.
    • string TokenHashBase64 (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/PasswordResetTokenService.cs:205): Base64 of the SHA-256 of the issued token, never the token itself (:167). Validation re-hashes the presented token and compares digests, so the cache never holds redeemable material.
    • UserIdentifierType UserId (:173): the account the token redeems to (:168). Storing the id in the record is what lets redemption resolve the user without a second lookup by email.
    • int FailedAttempts (:174): wrong tokens presented against this record so far (:169), the counter the attempt cap is enforced against.
    • long ExpiresAtUnixSeconds (:175): when the record expires (:170). This one exists for a specific reason explained at the rewrite site: when a failed attempt bumps the counter, the record is re-cached with the remaining lifetime computed from this field, so a wrong guess cannot extend how long the token stays redeemable (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/PasswordResetTokenService.cs:132, :146-152).
  • Why it's built this way: being a record gives the non-destructive with expression that the attempt-counter update relies on (entry with { FailedAttempts = attempts }, MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/PasswordResetTokenService.cs:183), so the rewrite is a copy rather than a mutation. Being internal keeps a cache-layout detail out of the package's public API: nothing outside the Infrastructure assembly should be able to construct or read one. See ADR-091 for why the reset lifecycle lives in the cache at all.
  • Where it's used: written by IssueAsync (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/PasswordResetTokenService.cs:89-95), read by ValidateAndConsumeAsync (:100), and rewritten by RecordFailedAttemptAsync (:148-152). It appears nowhere else.

JwtSettings

MMCA.Common.Infrastructure · MMCA.Common.Infrastructure.Auth · MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/JwtSettings.cs:20 · Level 1 · class (sealed)

  • What it is: the Jwt section: issuer, audience, signing algorithm, the key material for whichever algorithm is selected (an HMAC secret, an RSA pair or a P-384 EC pair), the RSA key-size floor, and the two token lifetimes. It adds the piece attributes cannot express, algorithm-aware validation of the key material (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/JwtSettings.cs:6-19).
  • Depends on: JwtSigningAlgorithm (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/JwtSettings.cs:37), which is what puts it at Level 1, plus System.ComponentModel.DataAnnotations for [Required], [Range] and, critically, for the IValidatableObject interface (:1, :20), and System.Globalization for the invariant-culture failure message (:2, :168).
  • Concept introduced: IValidatableObject for conditional requirements. Attributes describe a property in isolation, so they cannot say "this one is required only when that one has a particular value". IValidatableObject is the options-validation extension point for exactly that case: the type implements a single Validate method that yields one ValidationResult per failure, and .ValidateDataAnnotations() runs it alongside the attribute checks. The class doc gives that as the reason it implements the interface: key-material validation is conditional on the selected algorithm (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/JwtSettings.cs:17-18). [Rubric §11, Security] assesses credential handling. The HS256 branch does not merely check that a secret is present: it decodes SecretForKey as Base64 and requires at least 32 bytes, the 256-bit output size of HMAC-SHA256 (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/JwtSettings.cs:25-26, :150-170). Each failure has its own message (missing, not Base64, or too short with the actual bit count), and Validate appends advice to replace the placeholder with a real secret from user-secrets or environment variables (:114-119). The same private check sits behind the public DecodeHmacSigningKey (:144-147), and its doc names the three readers that call it: the startup validation, the token issuer and the in-process validator (:136-140). So the key a host boots with is exactly the key TokenService signs with (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/TokenService.cs:269) and the in-process bearer handler verifies with (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/WebApplicationBuilderExtensions.Authentication.cs:260), and a short or shipped-placeholder HMAC key fails the boot instead of reaching production silently. The asymmetric keys get a strength floor of their own: MinimumRsaKeySizeBits applies to the signing key, the validation key and every JWKS key, and outside Development a shorter RSA key, or an EC key not on P-384, fails host startup while Development logs a warning (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/JwtSettings.cs:15-16, :74-79); that check is read by JwtKeyStrengthValidator in the API layer rather than by Validate. [Rubric §15, Best Practices & Code Quality] assesses fail-fast posture. Registration pairs the bind with .ValidateDataAnnotations().ValidateOnStart() (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/WebApplicationBuilderExtensions.Authentication.cs:144-147), so both the attribute checks and Validate run at boot, not on the first token issued (ADR-070).
  • Walkthrough: one static field, one constant, eleven init properties, two public methods and one private helper.
    • SectionName = "Jwt" (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/JwtSettings.cs:23) and MinimumHmacKeyBytes = 32 (:26), whose comment gives the reason: an HMAC-SHA256 key should be at least as long as its 256-bit output (:25).
    • SigningAlgorithm (:37): defaults to JwtSigningAlgorithm.RS256, and the remarks give the reason (:31-36): asymmetric signing is what lets a validator verify a token without holding the key that mints one, so a host that never sets Jwt:SigningAlgorithm gets the algorithm that survives extraction. A single-host monolith opts into HS256 explicitly.
    • SecretForKey (:44), documented as a Base64-encoded HMAC key that belongs in user-secrets or environment variables, never a checked-in appsettings.json (:39-43); RsaPrivateKeyPem (:51) and RsaPublicKeyPem (:59), read under RS256 and PS256 (:46-50, :53-58); EcPrivateKeyPem (:65) and EcPublicKeyPem (:72), the P-384 pair read under ES384 (:61-64, :67-71). None carries [Required], because whether it is required is decided in Validate. The docs are specific about the split: the private key is what an issuer signs with, the public key is what an in-process validator verifies with, and a service that fetches the key through JWKS at runtime leaves the public key unset (:56-58, :69-71).
    • MinimumRsaKeySizeBits (:81), default 3072, with [Range(2048, int.MaxValue)] (:80) so a value below 2048 is itself a configuration error (:74-79).
    • Issuer (:85) and Audience (:89): both [Required] (:84, :88), because they matter in every mode.
    • AccessTokenExpirationMinutes (:97), default 15; RefreshTokenExpirationDays (:104), default 7. The short-access-plus-long-refresh split of ADR-050, expressed as defaults. Both carry [Range(1, int.MaxValue)] (:96, :103): a zero or negative lifetime would mint a token whose expiry is not after its not-before (or a session expired at issue), so it fails host startup under .ValidateDataAnnotations().ValidateOnStart() instead of failing every sign-in.
    • Validate(ValidationContext) (:112-134): an iterator method with three independent checks. Under HS256, any reason CheckHmacSigningKey returns yields a failure naming SecretForKey (:114-119); under RS256 or PS256, a null or whitespace RsaPrivateKeyPem yields a failure naming RsaPrivateKeyPem and the selected algorithm (:121-126); under ES384, a null or whitespace EcPrivateKeyPem yields a failure naming EcPrivateKeyPem (:128-133). Note the asymmetry: the private key is enforced here, the public key is not, because a service that only validates fetches it through JWKS.
    • DecodeHmacSigningKey(string) (:144-147): returns the decoded key bytes, or throws InvalidOperationException carrying the same reason the startup check reports.
    • CheckHmacSigningKey(string?, out byte[]) (:150-170): the private helper both public methods share. It returns a reason string, or null with the decoded bytes: null or whitespace (:153-156), a FormatException from Convert.FromBase64String (:158-165), or fewer than MinimumHmacKeyBytes decoded bytes, reported in bits (:167-169).
    • The in-process validator enforces the public-key half at wiring time instead: BuildValidationParameters (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/WebApplicationBuilderExtensions.Authentication.cs:224) throws when an asymmetric algorithm is selected with no public key of that algorithm's key type (EcPublicKeyPem for ES384, RsaPublicKeyPem otherwise), and the message points at AddForwardedJwtBearer for services that should fetch the key at runtime (:231-235).
  • Why it's built this way: keeping the conditional rule in code next to the properties it constrains, rather than in the registration call, means every host that binds this section gets the same guarantee without repeating it, and routing every HS256 reader through one decode-and-length check means the three cannot disagree about what a valid key is. Switching between HS256 and an asymmetric algorithm is a hard cutover that invalidates every existing token (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/JwtSigningAlgorithm.cs:19-20), so failing the boot on a half-configured section is much cheaper than discovering it at the first sign or the first validation.
  • Where it's used: bound in AddCommonAuthentication (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/WebApplicationBuilderExtensions.Authentication.cs:144-147), which then re-reads the section eagerly to build the token validation parameters at wiring time (:158, :165); consumed by TokenService through IOptions<JwtSettings>, which branches on the algorithm once in the constructor and caches the credentials (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/TokenService.cs:74-110), and optionally by RsaJwksProvider to learn the current key's algorithm (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/RsaJwksProvider.cs:24, :37-40).

PasswordHasher

MMCA.Common.Infrastructure · MMCA.Common.Infrastructure.Auth · MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/PasswordHasher.cs:22 · Level 1 · class

  • What it is: the framework's one credential hasher. It derives a hash for a new password, verifies a candidate password against a stored (hash, salt) pair, and reports whether a stored hash should be re-derived, all with PBKDF2-HMAC-SHA512. New hashes are derived at 210,000 iterations and written in a self-describing 69-byte format that carries their own work factor; the older header-less 64-byte format (always 600,000 iterations) still verifies. It also burns one throwaway derivation on demand, for sign-in branches that never reach a real verification. PBKDF2 is the only algorithm in the type (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/PasswordHasher.cs:8-21).
  • Depends on: IPasswordHasher, the Application-layer port it implements (imported at MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/PasswordHasher.cs:4, declared at MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Auth/IPasswordHasher.cs:6, whose NeedsRehash member defaults to false so a custom hasher never triggers a rehash, MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Auth/IPasswordHasher.cs:28, and whose BurnVerificationCost member defaults to one discarded HashPassword, :39). Externals are BCL only: System.Buffers.Binary (BinaryPrimitives), System.Security.Cryptography (Rfc2898DeriveBytes, RandomNumberGenerator, CryptographicOperations) and System.Text.Encoding (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/PasswordHasher.cs:1-3).
  • Concept introduced: a password is stored as a deliberately slow, salted one-way derivation that records its own cost. [Rubric §11, Security] assesses credential-at-rest protection, and this type is where the framework makes its whole stance on it. Five decisions are visible in source and each one answers a specific threat. A per-credential 32-byte salt drawn from a CSPRNG (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/PasswordHasher.cs:25, :74) means two users who pick the same password get different stored hashes, so a precomputed rainbow table buys an attacker nothing. A 210,000-iteration work factor (:34, the OWASP Password Storage Cheat Sheet figure for PBKDF2-HMAC-SHA512, with 600,000 being its figure for PBKDF2-HMAC-SHA256, :9-11) makes each guess in an offline cracking run cost real CPU time, which is the only defense once a dump has left the building. The work factor is stored inside every hash it writes (:77-80), so raising the constant later re-derives records on their next sign-in rather than breaking them (:30-33). FixedTimeEquals (:109) compares the full buffer regardless of where the first byte differs, so the duration of a failed login carries no information about how close the guess was. And VerifyPassword accepts only the two shapes this hasher ever wrote before comparing anything (:99-102): the inline comment records that the check closes a real hole (:92-98), an account created through external OAuth (ADR-036) carries an empty hash and salt, and earlier code derived an empty hash from an empty salt and compared two empty spans, which FixedTimeEquals answers true for. The stored count is itself bounded to [100_000, 2_000_000] (:52, :58, enforced at :154), so a tampered row can neither lower the cost of guessing its password nor turn a sign-in into a CPU denial of service (:48-57). Timing is closed on the other side too: a sign-in for an unknown or credential-less account burns one derivation at BurnIterations (:67), which is the current work factor Iterations, so it costs what verifying a current-format account costs (:113-116). The constant's doc records why it is not the legacy factor: burning at 600,000 made an unknown address about three times slower than every current account, the very membership oracle the burn exists to close (:60-66). [Rubric §15, Best Practices & Code Quality] applies to the shape rather than the crypto: one algorithm, no per-app copy, so the question "which primitive authenticated this login" has exactly one answer everywhere.
  • Walkthrough
    • Private constants carry the whole policy: SaltSize = 32 (256 bits, MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/PasswordHasher.cs:25), HashSize = 64 (512 bits, :28), Iterations = 210_000 (:34), LegacyIterations = 600_000 (:37, the count every header-less hash was derived with), FormatVersion = 0x01 (:40), HeaderSize = 5 (:43, one version byte plus a 4-byte big-endian count), VersionedHashSize = HeaderSize + HashSize (:46, 69 bytes), and the accepted stored-count bounds MinIterations = 100_000 (:52) and MaxIterations = 2_000_000 (:58). One constant is internal rather than private: BurnIterations (:67), set to Iterations (210,000 today), so the burn cost follows the current work factor if it moves (:60-66).
    • HashPassword(string password) (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/PasswordHasher.cs:70) rejects null, empty and whitespace-only input up front with ArgumentException.ThrowIfNullOrWhiteSpace (:72), draws a fresh salt from RandomNumberGenerator.GetBytes(SaltSize) (:74, the cryptographic RNG and not Random), derives 64 bytes at the current Iterations (:75), then lays out the versioned hash: the version byte, the iteration count via BinaryPrimitives.WriteInt32BigEndian, then the derived bytes after the header (:77-80), and returns the (Hash, Salt) named tuple (:82). The salt is generated here rather than accepted from the caller, so no call site can accidentally reuse one.
    • VerifyPassword(string password, byte[] hash, byte[] salt) (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/PasswordHasher.cs:86) guards the password for null/empty/whitespace and the two arrays for null (:88-90), then returns false immediately unless the salt is exactly SaltSize bytes and TryReadIterations recognizes the hash (:99-102). It takes the trailing HashSize bytes as the expected digest (:104), recomputes the derivation over the stored salt at the stored work factor (:105), and returns CryptographicOperations.FixedTimeEquals(computedHash, expected) (:109).
    • IPasswordHasher.BurnVerificationCost(string password) (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/PasswordHasher.cs:117-122) is an explicit interface implementation, so it is reachable only through the port. It guards the password (:119) and discards one ComputePbkdf2Hash over a fresh salt at BurnIterations (:121). The remarks give the sizing rule (:113-116): the cost equals verifying a current-format record, the shape every account moves to on its first sign-in. That is the same work factor the port's default (one discarded HashPassword) would burn (MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Auth/IPasswordHasher.cs:30-40); the override ties the burn to the named BurnIterations constant and skips building the versioned buffer.
    • NeedsRehash(byte[] hash) (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/PasswordHasher.cs:130-136) answers true for a recognized legacy 64-byte hash and for a versioned hash whose stored count differs from Iterations (:134-135); unrecognized material answers false, because it never verifies and so there is no sign-in to upgrade it on (:125-129).
    • TryReadIterations(byte[] hash, out int iterations) (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/PasswordHasher.cs:143-159) is the one format reader: a 64-byte hash yields LegacyIterations (:145-149); a 69-byte hash whose first byte is FormatVersion yields its big-endian count, accepted only inside the bounds (:151-155); anything else is rejected (:157-158).
    • ComputePbkdf2Hash(string password, byte[] salt, int iterations) (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/PasswordHasher.cs:162-168) is the single expression-bodied derivation all three paths route through (hash, verify, burn), always at HashSize output, which is what keeps the write path and the verify path from drifting apart.
  • Why it's built this way: ADR-102 removed an older HMAC-SHA512 verification branch and supersedes ADR-032, so PBKDF2 is the only primitive that runs. ADR-133 records the versioned format: storing the work factor in each hash is what lets the iteration constant move without invalidating existing credentials, because verification reads the count from the row rather than from the constant, and NeedsRehash tells the sign-in flow when to upgrade. The remaining shape (no per-app hasher, no algorithm parameter on the port) is what lets [Rubric §11, Security] be assessed once for every application.
  • Where it's used: registered as services.TryAddSingleton<IPasswordHasher, PasswordHasher>() (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:407); the type is stateless, so a singleton is safe. Consumers reach it through the port: AuthenticationServiceBase<TUser> takes it as a constructor parameter (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/AuthenticationServiceBase.cs:80), verifies on login (:219, and a failure there increments the brute-force counter at :221), hashes on registration (:342), burns one derivation's cost for an unknown, credential-less or service account so it is indistinguishable from a wrong password (:204-210, through the private BurnPasswordVerificationCost at :958-966, which calls the port's BurnVerificationCost at :965), and after a successful sign-in calls RehashPasswordIfNeededAsync (:302), which re-derives and saves the hash only when the user implements IPasswordRehashableUser and NeedsRehash answers true (:1004-1035, check at :1016); ChangePasswordHandlerBase<TUser, TCommand> verifies the current password then hashes the new one (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/ChangePassword/ChangePasswordHandlerBase.cs:57, :108, :117); and ResetPasswordHandlerBase<TUser, TCommand> only hashes (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/ResetPassword/ResetPasswordHandlerBase.cs:44, :110), because possession of the reset token stands in for knowledge of the old password.
  • Caveats / not-in-source: the upgrade happens only on a successful password sign-in, and only for an app whose User opts in through IPasswordRehashableUser (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/AuthenticationServiceBase.cs:1008), so a credential whose owner never signs in again keeps its older format and work factor indefinitely. The rehash is best-effort and runs after tokens are issued, through BestEffort with CancellationToken.None (:995-999, :1011-1034): a failure there is logged and the record is upgraded on a later sign-in. Because the burn matches a current-format record, an account still on a legacy 600,000-iteration record verifies roughly three times slower than an unknown address until its first sign-in re-derives it, the residual the BurnIterations doc names (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/PasswordHasher.cs:65-66); in an app that does not opt into the rehash, that gap lasts as long as the legacy record does.

JwksKeyMaterial

MMCA.Common.Infrastructure · MMCA.Common.Infrastructure.Auth · MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/JwksSettings.cs:249 · Level 3 · class (internal static)

  • What it is: the key-material rules shared by the current JWKS key and every additional key. Three internal helpers, declared as the third type in the JwksSettings.cs file: ResolvePem(pem, path) turns an inline-PEM-or-path pair into PEM text, the algorithm-aware ResolvePem(algorithm, rsaPem, rsaPath, ecPem) picks the material that algorithm reads, and CreatePublicKey(algorithm, pem, keyId) turns PEM text into a public-only AsymmetricSecurityKey (RSA or ECDSA) stamped with a kid (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/JwksSettings.cs:249-292).
  • Depends on: JwtSigningAlgorithm, JwtAlgorithms (UsesEcKey, MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/JwksSettings.cs:277) and JwtKeyMaterial (:291), the last at Level 2, which is what puts this type at Level 3; the two shared helpers come in through the MMCA.Common.Auth import (:5). BCL File, and AsymmetricSecurityKey from Microsoft.IdentityModel.Tokens (:4).
  • Concept: one loader for every key that is published or accepted. [Rubric §11, Security] assesses whether the publisher and the validators agree on what a key is. RsaJwksProvider loads the current key through these helpers (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/RsaJwksProvider.cs:51-52, :59) and JwksAdditionalKey loads each additional key through them (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/JwksSettings.cs:239, :244), so the JWKS document and the local validators that consume CreateAdditionalValidationKeys cannot drift onto different PEM rules. The import itself sits one level lower, in JwtKeyMaterial, which keeps only the exported public parameters (MMCA.Common/Source/Build/Auth/JwtKeyMaterial.cs:81, :87), so a private PEM supplied by mistake still yields only the public half (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/JwksSettings.cs:287) and nothing private can reach the published key set; an EC key not on P-384 is refused with a CryptographicException (MMCA.Common/Source/Build/Auth/JwtKeyMaterial.cs:51-55).
  • Walkthrough
    • ResolvePem(string? pem, string? path) (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/JwksSettings.cs:255-264): a non-blank inline PEM wins (:257-260); otherwise a blank path answers null and a set path answers File.ReadAllText(path) (:263). The comment at :262 justifies the synchronous read: every caller materializes its keys once and caches them.
    • ResolvePem(JwtSigningAlgorithm, string? rsaPem, string? rsaPath, string? ecPem) (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/JwksSettings.cs:275-283): for RS256 and PS256 it falls through to the two-argument overload (:277-280); for ES384 it answers the inline EC PEM, or null when that is blank (:282). There is no EC path form: an EC key is configured inline only.
    • CreatePublicKey(JwtSigningAlgorithm, string pem, string keyId) (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/JwksSettings.cs:290-291): an expression-bodied delegate to JwtKeyMaterial.CreatePublicKey, which imports into a using-scoped RSA or P-384 ECDsa and wraps the exported public parameters (MMCA.Common/Source/Build/Auth/JwtKeyMaterial.cs:74-96). An RsaSecurityKey holds parameters and needs no disposal; an ECDsaSecurityKey owns a fresh public-only ECDsa instance (:80-81), which is why JwksSettings.LoadFailure disposes it after a probe (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/JwksSettings.cs:164-168) and RsaJwksProvider disposes it after converting it to a JWK (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/RsaJwksProvider.cs:74-81).
  • Why it's built this way: internal keeps the PEM rules a single implementation inside the Infrastructure assembly without adding them to the package's public API; the two public entry points are the types that call it. Delegating the import to JwtKeyMaterial, which is linked into the issuer, the JWKS publisher and the in-process validator (MMCA.Common/Source/Build/Auth/JwtKeyMaterial.cs:9-11), extends the same guarantee past this file: every site loads a key the same way.
  • Where it's used: RsaJwksProvider.BuildKeySet for the current key (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/RsaJwksProvider.cs:51-52, :59) and JwksAdditionalKey.CreateValidationKey for each additional key (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/JwksSettings.cs:239-244).

JwksAdditionalKey

MMCA.Common.Infrastructure · MMCA.Common.Infrastructure.Auth · MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/JwksSettings.cs:204 · Level 4 · class (sealed)

  • What it is: one public key published in the JWKS document alongside the current signing key and accepted by every local validator; nothing is ever signed with it (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/JwksSettings.cs:188-190). Each entry carries its own signing algorithm. It is the element type of JwksSettings.AdditionalKeys (:81), declared as the second type in the same file.
  • Depends on: JwksKeyMaterial (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/JwksSettings.cs:239, :244), which is what puts it at Level 4; JwtSigningAlgorithm for Algorithm (:219); JwtAlgorithms for the key-type check in the failure message (:240); System.ComponentModel.DataAnnotations for [Required] and [StringLength] (:1); AsymmetricSecurityKey from Microsoft.IdentityModel.Tokens (:4).
  • Concept introduced: a signing-key rotation without a 401 wave. [Rubric §11, Security] assesses key management, and [Rubric §7, Microservices Readiness] whether extracted services keep validating through a change. A forwarded validator caches the JWKS document, so a key it has never seen fails every token signed with it until its next refresh. The type's own doc gives the sequence that avoids that (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/JwksSettings.cs:192-194): stage the next key here before switching to it, so validators that cache the document already know it; switch; then keep the previous key here until every token it signed has expired. Because each entry publishes its own alg and every asymmetric validator accepts all three asymmetric algorithms, the same sequence can also change the signing algorithm (:24-27, ADR-149). Removal is not instant everywhere: in-process validators build their key list once and drop a removed key at restart, while forwarded validators drop it on their next JWKS metadata refresh (:74-80).
  • Walkthrough
    • KeyId (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/JwksSettings.cs:212): [Required] and [StringLength(64)] (:210-211), defaulting to string.Empty. It is published as the JWK kid and must be unique across the current key and every additional key, because a validator selects the key by this value (:206-209).
    • Algorithm (:219): defaults to RS256, is published as the JWK alg, and must be asymmetric; RS256 and PS256 read the RSA material, ES384 reads EcPublicKeyPem (:214-218).
    • RsaPublicKeyPem (:222), which wins over RsaPublicKeyPath (:225) for the RSA algorithms, the same precedence the current key follows; EcPublicKeyPem (:228), the inline P-384 key read under ES384.
    • CreateValidationKey() (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/JwksSettings.cs:237-245): resolves the PEM through the algorithm-aware JwksKeyMaterial.ResolvePem and throws an InvalidOperationException naming the kid and the material that algorithm reads when it is not set (:239-242), then returns JwksKeyMaterial.CreatePublicKey(Algorithm, pem, KeyId) (:244). The result is an AsymmetricSecurityKey: an RsaSecurityKey or an ECDsaSecurityKey. Only public parameters are kept, so a private PEM supplied by mistake still yields only the public half (:230-236); an ECDSA result owns its ECDsa instance, which the callers that keep nothing dispose.
  • Why it's built this way: the remarks state the one deliberate difference from the current key (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/JwksSettings.cs:197-203): a current key with no material yields an empty key set, but a listed additional key without the material its Algorithm reads can only be a mistake, so it is a configuration error. Attributes on list elements are not reached by the parent's .ValidateDataAnnotations(), which is why JwksSettings.Validate re-checks the key id, rejects duplicates, rejects a non-asymmetric algorithm and missing material, and loads every entry through CreateValidationKey at startup (:91-126, :135-152, :160-176) (ADR-070).
  • Where it's used: JwksSettings.CreateAdditionalValidationKeys maps every entry through CreateValidationKey (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/JwksSettings.cs:183-184), and that list feeds the refresh-flow validation in TokenService (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/TokenService.cs:104) and the in-process bearer validation parameters in the API layer (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/WebApplicationBuilderExtensions.Authentication.cs:246). RsaJwksProvider calls CreateValidationKey per entry itself, so it can publish each key under its own Algorithm (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/RsaJwksProvider.cs:63-66). See ADR-004.

EmailIdentity

MMCA.Common.Infrastructure · MMCA.Common.Infrastructure.Auth · MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/EmailIdentity.cs:14 · Level 5 · class (internal static)

  • What it is: the one shared helper that turns an email address into the address segment of every cache key this module builds. internal static string KeySegment(string? email) returns a 64-character hex SHA-256 of the normalized address (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/EmailIdentity.cs:16-26), and internal static string Normalize(string? email) produces that normalized address: it runs the supplied value through Email.Create, and a malformed address (which never matches a user but can still mint a key) falls back to the same trim-and-lowercase shape so its attempts collapse onto one key too (:28-46).
  • Depends on: the Email value object (:41), plus the BCL SHA256, Convert.ToHexString and Encoding.UTF8 (:26).
  • Concept introduced: one key segment, normalized and then hashed. [Rubric §15, Best Practices & Code Quality] assesses whether a proven idiom is reused or reinvented per call site, and [Rubric §11, Security] whether personal data leaks into places it does not belong. LoginProtectionService, PasswordResetTokenService and EmailConfirmationTokenService all build their keys through EmailIdentity.KeySegment, so the normalization rule (and the scoped #pragma warning disable CA1308 that documents why lowercasing is safe here) exists in exactly one file. Normalizing first means every spelling of one account still lands on one key; hashing second means the address itself never appears in a key. The doc comment gives the reason for the hash: a key travels further than the entry it names (Redis key names, the two-level cache's read-fault warnings, and Redis client exception messages, which quote the key), and none of those places may carry an email address (:16-22).
  • Walkthrough
    • KeySegment(string? email) (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/EmailIdentity.cs:25-26) is expression-bodied: Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(Normalize(email)))).
    • Normalize(string? email) (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/EmailIdentity.cs:36-45) returns string.Empty for a null, empty or whitespace-only input (:38-39); otherwise it calls Email.Create(email) (:41) and returns the normalized Value when TryGetValue succeeds, or email.Trim().ToLowerInvariant() on failure (:43), under #pragma warning disable CA1308 (:42-44) because that fallback intentionally matches Email's own RFC 5321 lowercase normalization.
  • Why it's built this way: internal static keeps the helper out of the package's public API, since it exists purely to keep the three token/lockout services' cache keys consistent with each other and with the Email value object's own normalization, not to be a general-purpose utility. Hashing in the helper rather than at each call site means no key builder can forget to.
  • Where it's used: the key builders in LoginProtectionService (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/LoginProtectionService.cs:82, :49), PasswordResetTokenService (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/PasswordResetTokenService.cs:55, :55) and EmailConfirmationTokenService (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/EmailConfirmationTokenService.cs:168, :137) all call KeySegment; unit-tested directly by EmailIdentityTests (MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Auth/EmailIdentityTests.cs), and AuthCacheKeyPrivacyTests (MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Auth/AuthCacheKeyPrivacyTests.cs) exercises the three services' keys.

JwksSettings

MMCA.Common.Infrastructure · MMCA.Common.Infrastructure.Auth · MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/JwksSettings.cs:30 · Level 5 · class (sealed)

  • What it is: the Jwks section that controls whether an Identity service publishes a JSON Web Key Set at /.well-known/jwks.json, where its current public key comes from (an RSA key inline or by path, or an inline P-384 key when Jwt:SigningAlgorithm is ES384), and which further public keys are published beside it for a rotation (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/JwksSettings.cs:9-29). It implements IValidatableObject (:30) so the list of additional keys is checked at startup, which property attributes alone cannot reach.
  • Depends on: JwksAdditionalKey, the element type of AdditionalKeys (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/JwksSettings.cs:81), which is what puts it at Level 5; JwtAlgorithms for the per-key algorithm checks (:137, :142), imported from MMCA.Common.Auth (:5). From the BCL and libraries: System.ComponentModel.DataAnnotations for [StringLength] and IValidatableObject (:1), System.Globalization for the invariant member names in failure messages (:2, :98), System.Security.Cryptography for the CryptographicException the load check catches (:3, :172), and AsymmetricSecurityKey and ECDsaSecurityKey from Microsoft.IdentityModel.Tokens (:4, :165, :183). Consumed by RsaJwksProvider and TokenService through IOptions<JwksSettings>.
  • Concept introduced: key distribution as configuration. [Rubric §11, Security] assesses how trust is established between services. In a single-process monolith the issuer and the validator can share one symmetric secret. Once a module is extracted, the validator must obtain the issuer's public key without sharing anything secret, which is what a JWKS document is for (ADR-004, ADR-008). [Rubric §7, Microservices Readiness]: the framework ships the endpoint always and the key set empty, so nothing about a deployment changes until a host flips Enabled. The kid contract is the subtle part: KeyId is published as the JWK kid and must match the kid header on tokens the issuer signs (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/JwksSettings.cs:20-21, restated on the property itself at :41-45), otherwise a validator holding a correct key set still cannot pick the right key. TokenService closes that loop by taking these same options and stamping KeyId onto every asymmetric token it signs (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/TokenService.cs:68-73, :98, :296). The same contract is why Validate rejects a repeated key id across the current key and every additional key (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/JwksSettings.cs:106-111): a validator selects a key by its id, so two keys sharing one would make the choice ambiguous. The alg follows the key: the current key is published with the algorithm of Jwt:SigningAlgorithm, since it is the key tokens are signed with, and each additional key with its own (:17-19, :24-27), so a rotation can also change the signing algorithm (ADR-149).
  • Walkthrough:
    • SectionName = "Jwks" (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/JwksSettings.cs:33).
    • Enabled (:39), defaulting to false with the rationale spelled out inline (:35-38): existing HMAC-only deployments must not start advertising a key set by accident.
    • KeyId (:47), [StringLength(64)] (:46), defaulting to "default".
    • RsaPublicKeyPem (:54) and RsaPublicKeyPath (:60), documented as mutually exclusive (:49-53, :56-59); the path form exists for keys mounted as a secret rather than inlined in configuration. EcPublicKeyPem (:66) is the inline P-384 key published as the current key when Jwt:SigningAlgorithm is ES384, and is ignored for the RSA algorithms (:62-65).
    • AdditionalKeys (:81), an IReadOnlyList<JwksAdditionalKey> defaulting to empty: public keys published after the current one and accepted by every local validator, never used to sign (:68-73). The remarks state when a removal takes effect (:74-80): in-process validators build their key list once, so at the next restart; forwarded validators on their next JWKS metadata refresh.
    • Validate(ValidationContext) (:91-126): seeds a set of seen ids with the current KeyId (:93), then for each entry yields a failure when the id is missing or longer than 64 characters (:100-105) or repeats one already seen (:106-111), when ConfigurationFailure reports a problem (:113-116), or otherwise when the key cannot be loaded (:117-124). The comment on that last branch gives the reason (:119-120): parsing here makes ValidateOnStart fail the host at startup, rather than sign-in, refresh and every authenticated request failing at first use of the key set.
    • ConfigurationFailure(JwksAdditionalKey, string) (:135-152): rejects an entry whose Algorithm is not asymmetric, because a published key never validates HS256 (:137-140); for ES384 requires EcPublicKeyPem (:142-147); for RS256 and PS256 requires RsaPublicKeyPem or RsaPublicKeyPath (:149-151).
    • LoadFailure(JwksAdditionalKey) (:160-176): loads the key the way every validator will, through JwksAdditionalKey.CreateValidationKey, disposes the ECDsa instance an ECDSA probe owns because the probe keeps nothing (:164-168), and returns the exception message for the IO, access, argument, cryptographic, not-supported and invalid-operation failures it filters on (:172), or null when the key loads.
    • CreateAdditionalValidationKeys() (:183-184): one AsymmetricSecurityKey per additional key (RSA or ECDSA, by its algorithm), in order, stamped with its key id; the doc names its callers as every local validator (:178-182).
    • The consuming logic, worth reading alongside: RsaJwksProvider builds its key set once behind a Lazy<JsonWebKeySet> in PublicationOnly mode (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/RsaJwksProvider.cs:31-32), returns an empty set when Enabled is false (:44-47), resolves the current PEM by the current key's algorithm through JwksKeyMaterial (:51-52), publishes the current key under KeyId first (:59) and every additional key after it (:63-66), and sets each JWK's alg from that key's own algorithm (:88).
  • Why it's built this way: default-off plus an empty key set means the endpoint is safe to map unconditionally, and two RSA key sources cover both "inline it in configuration" and "mount it as a secret" without a second code path in the provider. Publishing additional keys next to the current one is what lets a signing key rotate without a 401 wave, and checking every listed key at boot keeps a mistyped PEM or a wrong algorithm from surfacing as a run of failed sign-ins (ADR-070).
  • Where it's used: bound with .ValidateDataAnnotations().ValidateOnStart() in AddInfrastructure (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:252-255), immediately followed by the IJwksProvider registration (:256). TokenService takes it as an optional constructor dependency, falls back to new JwksSettings().KeyId when it is absent (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/TokenService.cs:98), and accepts the additional keys in the refresh flow (:104). The in-process bearer validation parameters accept them too (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/WebApplicationBuilderExtensions.Authentication.cs:246), and JwksKeyStrengthValidator reads it for the startup key-strength check.

EmailConfirmationTokenService

MMCA.Common.Infrastructure · MMCA.Common.Infrastructure.Auth · MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/EmailConfirmationTokenService.cs:42 · Level 6 · class (sealed)

  • What it is: the IEmailConfirmationTokenService implementation: the email-confirmation token lifecycle, issue a single-use token for an address, throttle how often one address can ask, hash the token at rest, cap wrong guesses, and either check the token without spending it or consume it on a successful redeem (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/EmailConfirmationTokenService.cs:12-25, :91-102). The class remarks add why its keys carry their own emailconfirm: prefix: a key shared with the reset service would make issuing a confirmation link silently invalidate an outstanding password-reset link for the same address (:27-31).
  • Depends on: IEmailConfirmationTokenService (the Application port it implements, MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/EmailConfirmationTokenService.cs:46); EmailConfirmationSettings via IOptions<> (:45, snapshotted at :50); ICacheService (:43), which holds the token record; ICounterStore (:44), which holds the per-address request throttle (:39); TimeProvider (:46), the clock for the expiry stamp and the remaining-lifetime check (:41); EmailConfirmationEntry, its cached record; EmailConfirmationErrors for the failure; Result and Error; EmailIdentity, the shared key-segment helper, at the two key builders (:168, :170); and from the BCL SHA256, RandomNumberGenerator, CryptographicOperations, and System.Buffers.Text.Base64Url.
  • Concept introduced: the same cache-backed token pattern, applied a third time. [Rubric §11, Security] assesses credential issuance and redemption; [Rubric §15, Best Practices & Code Quality] assesses whether a proven idiom is reused or reinvented per flow. This type is structurally the same shape as PasswordResetTokenService: hash the token at rest, throttle issuance per address, cap validation attempts, and consume both the token and the request counter together on success. The TokenKey doc comment says so directly, citing PasswordResetTokenService as the precedent for normalizing the cache key the same way Email normalizes the lookup value (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/EmailConfirmationTokenService.cs:160-168), and both key builders call EmailIdentity.KeySegment instead of a private copy of the same helper (:168, :170), so the address reaches the key only as a hex SHA-256 of its normalized form. The throttle counts in ICounterStore rather than the cache, the same split LoginProtectionService and PasswordResetTokenService use: the comment at the top of IssueAsync calls it an atomic fixed-window throttle whose window opens on the first request and is never extended (:58), and a throttled request is answered as a 429 with a Retry-After bound, like the lockout. One place it departs from its password-reset sibling: redemption reads through GetFromSharedStoreAsync but takes no distributed lock, and the class remarks say why (:33-35): two concurrent redemptions of one token only confirm the same address twice, an idempotent outcome, so the lock PasswordResetTokenService takes under IDistributedLock would buy nothing here.
  • Walkthrough
    • TokenByteLength = 32 (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/EmailConfirmationTokenService.cs:48) is the only constant; _settings is the snapshotted EmailConfirmationSettings (:50). The primary constructor takes ICacheService, ICounterStore, IOptions<EmailConfirmationSettings> and TimeProvider (:42-46).
    • IssueAsync(string email, UserIdentifierType userId, CancellationToken) (:53-88): increments the per-email request counter in the counter store with the configured RequestWindowMinutes window (:59-62) and, once the count exceeds MaxRequestsPerEmail, fails with Error.TooManyRequests("Authentication.ConfirmationThrottled", ...) whose RetryAfter is the full request window (:64-74); the comment gives the reason for the full window: the counter exposes no remaining lifetime (:66). It then mints 32 CSPRNG bytes rendered with Base64Url.EncodeToString (:76), builds an EmailConfirmationEntry holding the Base64 digest of the token, the user id, a zero attempt count, and the absolute expiry as Unix seconds computed from the injected clock (:79-83), caches it under the token key with the configured lifetime (:85), and returns the raw token to the caller (:87); the raw token is never written anywhere else.
    • ValidateAsync (:91-95) and ValidateAndConsumeAsync (:98-102), each (string email, string token, CancellationToken), both delegate to the private ValidateCoreAsync with consume: false and consume: true. Its doc states the split (:104-112): a wrong token counts against the attempt cap either way, and a right one is consumed only when consume is set.
    • ValidateCoreAsync (:113-158): loads the entry with GetFromSharedStoreAsync (:123), whose comment gives the reason (:121-122): a token consumed on another replica must be a miss here, never a stale local copy that would let it be redeemed twice. It returns InvalidToken() when there is none (:124-127); a FormatException decoding the stored Base64 removes the unreadable record rather than leaving it to expire (:129-139); the comparison is CryptographicOperations.FixedTimeEquals over the two digests (:141), with token ?? string.Empty so a null token hashes rather than throwing; a mismatch records a failed attempt and returns the same generic failure (:141-145). On a match without consume it returns the entry's UserId and leaves the token live (:147-150). On a match with consume it removes the token key from the cache and resets the address's request counter in the counter store (:152-155), so a confirmed address is not left throttled out of a later legitimate request, and returns the entry's UserId (:157).
    • TokenKey, RequestKey, HashToken (:160-173): TokenKey and RequestKey each call EmailIdentity.KeySegment (:168, :170), producing emailconfirm:token:{hex SHA-256} and emailconfirm:req:{hex SHA-256} keys; HashToken is the shared SHA-256 helper for the token itself (:172-173).
    • RecordFailedAttemptAsync (:175-196): computes attempts = entry.FailedAttempts + 1 and the remaining lifetime from ExpiresAtUnixSeconds against the injected clock (:180-181). At MaxValidationAttempts, or once the remaining lifetime is non-positive, it deletes the record (:183-187); otherwise it rewrites the entry with entry with { FailedAttempts = attempts } at the remaining TTL, not a fresh one (:189-195).
    • InvalidToken() (:198-200) is the single failure factory built from EmailConfirmationErrors.InvalidToken, so unknown, expired, mismatched and attempt-capped tokens collapse to one error rather than giving an oracle for which addresses have an outstanding confirmation.
  • Why it's built this way: reusing the pattern PasswordResetTokenService established, rather than a bespoke implementation, is what keeps a third token lifecycle (login lockout, password reset, email confirmation) auditable as one idiom instead of three. ADR-116 frames identity-completion flows like this one as opt-in per host, and ADR-077 is the cache substrate whose shared-store read the redemption relies on. Taking TimeProvider rather than reading DateTimeOffset.UtcNow lets a test move the clock past the expiry without waiting.
  • Where it's used: registered services.TryAddScoped<IEmailConfirmationTokenService, EmailConfirmationTokenService>() (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Auth.cs:91), after the EmailConfirmationSettings binding (:83).
  • Caveats / not-in-source: the request throttle is atomic in the counter store, but the failed-attempt rewrite is still a read-modify-write on the cache entry, and because redemption is not serialized, concurrent wrong guesses can undercount it against the attempt cap. Two concurrent correct redemptions can both succeed; the class remarks accept that as idempotent (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/EmailConfirmationTokenService.cs:33-35). A token checked through ValidateAsync stays redeemable until it is consumed, expires or exhausts its attempt cap (:147-150).

LoginProtectionService

MMCA.Common.Infrastructure · MMCA.Common.Infrastructure.Auth · MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/LoginProtectionService.cs:42 · Level 6 · class (sealed, partial)

  • What it is: the brute-force and rate-limiting service: exponential-backoff account lockout after repeated login failures, plus a per-IP registration rate limit (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/LoginProtectionService.cs:15-41). The counters live in an atomic, fixed-window counter store and the lockout flag and its expiry in the cache (:16-17). It fails open on a cache outage: when the cache throws, a check answers success and an increment or reset does nothing, each with a warning log, so an unreachable cache suspends the lockout instead of failing every sign-in and registration (:26-29). A lockout also carries its remaining time, which the API answers as a Retry-After header (:34-39), and the registration limit answers the same way with its window as the bound. Each account entering lockout is counted once on the mmca.auth.lockout metric.
  • Depends on: ILoginProtectionService (the Application port, MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/LoginProtectionService.cs:47); LoginProtectionSettings via IOptions<> (:45, snapshotted at :69); ICacheService (:43) for the lockout flag and its expiry; ICounterStore (:44) for the attempt and registration counters; an optional ILogger<LoginProtectionService> defaulting to NullLogger (:46, :70); an optional TimeProvider defaulting to TimeProvider.System (:47, :71); Result and Error (:10); EmailIdentity, the shared key-segment helper, at the three email key builders (:82, :84, :91) and the log-key hash (:302); ClientAddressKey, the per-IP partition key (:9, :287); System.Diagnostics.Metrics for the lockout counter (:1); and from the BCL SHA256 and Encoding for the IP key segment (:2-3).
  • Concept introduced: counter keys must be normalized the same way the lookup is, and must not carry the identity they count. [Rubric §11, Security] assesses brute-force protection, rate limiting and keeping personal data out of infrastructure surfaces; [Rubric §12, Performance & Scalability] assesses whether it is one shared service rather than logic copied per endpoint. Two mechanisms in this file deserve close reading.
    • Key normalization and hashing (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/LoginProtectionService.cs:82-91, documented at :73-81): LockoutKey, AttemptsKey and LockoutUntilKey each call EmailIdentity.KeySegment(email) (:82, :84, :91) rather than carrying a private copy of the normalizer. Without normalization, the counter keys would be built from raw request input while the user lookup runs against the normalized value object, so User@x.com, user@x.com and " user@x.com " resolve to one account but get independent attempt counters, and an attacker defeats the ADR-029 backoff just by varying capitalization; a malformed address (which never matches a user but still increments a counter) falls back to the same trim-and-lowercase shape so its attempts collapse onto one key too. KeySegment then hashes the normalized address, so the key holds a hex SHA-256 rather than the address. The registration key gets the same treatment for the client address, with one extra step: IpKeySegment hashes ClientAddressKey.For(ipAddress), the partition key every per-IP limiter uses, so an IPv6 address counts as its /64 and an IPv4-mapped address as its IPv4 form, and rotating addresses inside one /64 does not buy a fresh registration allowance (:277-287). The partition is applied here rather than where the controller reads the address, because that same address is stored on the session record that sign-in history shows (:280-282). The hash exists because a key travels further than the entry it names (Redis key names, the two-level cache's read-fault warnings, Redis client exception text) and none of those places may carry a client address (:271-276). Logs go one step further: LogKeyHash keeps only the first LogKeyHashLength = 12 hex characters (48 bits) of the segment (:50, :302), enough to correlate repeated lockouts of one account but too few to reverse a guessable address by trying candidates (:296-301).
    • The lockout curve (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/LoginProtectionService.cs:166-181): excessAttempts = newCount - MaxFailedAttempts, clamped to int.MaxValue (:168), drives lockoutSeconds = Math.Min(1 << Math.Min(excessAttempts, 30), MaxLockoutSeconds) (:174), doubling the lockout per excess failure (1s, 2s, 4s, and so on) up to the configured cap. The inner Math.Min(excessAttempts, 30) clamps the shift exponent, and the comment explains why (:170-173): C# masks an int shift count to five bits, so 1 << 31 is negative and 1 << 32 wraps back to 1, which would silently shrink the lockout for a sufficiently persistent attacker. Since 1 << 30 already exceeds the [Range(1, 3600)] cap on LoginProtectionSettings.MaxLockoutSeconds, deep excess always lands on the cap.
  • Walkthrough
    • Key builders: LockoutKey produces login:lockout:{hex SHA-256 of the normalized address} (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/LoginProtectionService.cs:82), AttemptsKey produces login:attempts:{...} (:84), LockoutUntilKey produces login:lockout-until:{...} (:91), and RegistrationKey produces registration:ip:{hex SHA-256 of the client's partition key} (:284, via IpKeySegment at :286-287). The expiry lives under its own key rather than in a richer lockout value, because a flag already cached as true must keep reading as locked and the shared-store read drops an entry it cannot deserialize (:86-90).
    • Metrics: AuthMeterName = "MMCA.Common.Auth" (:57), the meter shared with the sign-in, refresh-reuse and administrative-action counters declared in the Application and API assemblies, duplicated here as a literal because each assembly declares the instruments it records (:52-56); Lockouts is the mmca.auth.lockout counter, unit {event}, incremented once per account entering lockout and never tagged with an address, a key hash or a client IP (:61-67).
    • CheckLockoutAsync(string email, CancellationToken) (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/LoginProtectionService.cs:94-130): reads the boolean lockout key through GetFromSharedStoreAsync (:104), never the replica's L1 copy, because a reset clears only the resetting replica's L1 and a local read would keep another replica locking the account out after the lockout was lifted (:101-103). Only for a locked account does it also read the lockout-until key and turn it into a remaining time (:106-112), so an unlocked sign-in costs one read. A cache miss is treated as not locked out (?? false), and a cache outage is caught by the IsCacheOutage filter (:114), logged, and answered with Result.Success() (:116-117), so the check fails open rather than locking everyone out. When locked, it returns Error.TooManyRequests("Auth.TooManyAttempts", ...) with RetryAfter set to that remaining time (:125-129).
    • RemainingLockout(long?) (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/LoginProtectionService.cs:137-146): null when no expiry was stored or it has already passed, because a zero hint would tell the client to retry into the lockout (:132-136).
    • IncrementFailedAttemptsAsync (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/LoginProtectionService.cs:149-198): increments the attempts key in the counter store with the FailedAttemptWindowMinutes window (:155-158); the comment states the increment is atomic, so a burst of genuinely concurrent guesses counts every one, and the window is fixed by the first failure (:151-152). Each failure writes an Information line carrying the truncated key hash and the count (:160-164). Once the count reaches MaxFailedAttempts it writes the lockout flag and the lockout-until instant with the exponential TTL (:166-181), and only the attempt that first reaches the threshold logs the lockout Warning and adds one to mmca.auth.lockout (:183-191), so a credential-stuffing run that keeps guessing adds one line and one increment per locked account. A cache outage is logged and swallowed (:194-197).
    • ResetFailedAttemptsAsync (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/LoginProtectionService.cs:201-213): on a successful login, resets the attempts counter in the counter store and removes the lockout flag and its expiry from the cache (:205-207), with the same log-and-swallow handling of a cache outage (:209-212).
    • CheckRegistrationRateLimitAsync(string? ipAddress, ...) (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/LoginProtectionService.cs:216-247): a null or empty IP is unrestricted (:218-221); otherwise it reads the per-IP count from the counter store (:227) and, once it reaches MaxRegistrationsPerIpPerHour, fails with Error.TooManyRequests("Auth.RegistrationRateLimitExceeded", ...) whose RetryAfter is the full RegistrationRateLimitWindowMinutes window (:238-246). The comment gives both halves of that choice (:235-237): a rate limit is a 429 with a Retry-After, as the lockout is, never a 401 a client would read as an expired session, and the counter store exposes no remaining lifetime, so the hint is the full window. A cache outage returns Result.Success() (:229-233).
    • IncrementRegistrationCountAsync (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/LoginProtectionService.cs:250-269): no-ops on a missing IP (:252-255) and otherwise increments the per-IP counter with the RegistrationRateLimitWindowMinutes window (:260-263), a fixed window anchored to the first registration from that address (:257), logging and swallowing a cache outage (:265-268).
    • Outage handling and logging helpers: IsCacheOutage (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/LoginProtectionService.cs:293-294) treats every cache fault as an outage except the caller's own cancellation, which keeps propagating; a cancellation the caller did not request (a store-side timeout) counts as an outage (:289-292). Three source-generated [LoggerMessage] methods follow: LogCacheUnavailable, a warning that logs the operation name, never the key (:304-306); LogFailedAttemptRecorded at Information (:308-310); and LogLockoutTripped at Warning (:312-314), the last two carrying only the truncated key hash.
  • Why it's built this way: reusing ICacheService (Redis in production, in-memory fallback) for the lockout flag and ICounterStore for the counts, instead of a bespoke store, keeps the service thin and lets both expire naturally by TTL rather than needing a sweep job; IOptions<> keeps every threshold configurable per environment (ADR-029). Registered scoped (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:177), after the LoginProtectionSettings binding (:173-176).
  • Where it's used: injected into AuthenticationServiceBase<TUser> (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/AuthenticationServiceBase.cs:81), which calls all five port members across its login and registration flows: the lockout check (:184), an increment on both the unknown-or-credential-less branch and the wrong-password branch (:211, :221), the reset on success (:281), and the registration rate-limit check and increment (:329, :392); a further increment sits at :885. Incrementing on the unknown-user branch as well as the wrong-password branch is what keeps the endpoint from becoming a user-enumeration oracle by timing or by lockout behavior. Use-case handlers also take it as a constructor parameter (for example MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/ResetPassword/ResetPasswordHandlerBase.cs:46).
  • Caveats / not-in-source: the counter store does not throw on a Redis fault; it counts in the local process instead, so through an outage the attempt and registration counts keep running per replica rather than across the fleet (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/LoginProtectionService.cs:29-31). When the cache itself throws, the lockout write fails with everything else in the try block and is swallowed (:194-197), so no lockout applies until the cache is back. Both windows are fixed, not sliding: a failure or registration late in a window does not extend it (:151-152, :257). Because the registration Retry-After is the full window rather than the time left in it, a client can be told to wait longer than it needs to.

PasswordResetTokenService

MMCA.Common.Infrastructure · MMCA.Common.Infrastructure.Auth · MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/PasswordResetTokenService.cs:34 · Level 6 · class (sealed)

  • What it is: the IPasswordResetTokenService implementation, and the whole forgot-password token lifecycle in one file: issue a single-use token for an address, throttle how often one address can ask, hash the token at rest, cap wrong guesses, and consume the token exactly once on a successful redeem (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/PasswordResetTokenService.cs:12-28).
  • Depends on: IPasswordResetTokenService (the Application port, :5, :39); PasswordResetSettings via IOptions<> (:37, snapshotted at :47); ICacheService (:6, :35), which holds the hashed token record (:29); ICounterStore (:36), which holds the per-email request throttle (:30); IDistributedLock (:38), which serializes redemptions of one token (:32); TimeProvider (:39), the clock for the expiry stamp and the remaining-lifetime check (:33); PasswordResetEntry (its cached record); Result and Error (:7); EmailIdentity, the shared key-segment helper, at the two key builders (:55, :57); and from the BCL SHA256, RandomNumberGenerator, CryptographicOperations, and System.Buffers.Text.Base64Url (:1-3).
  • Concept introduced: a reset token is a bearer credential, so treat it like a password. [Rubric §11, Security] assesses credential issuance and redemption; [Rubric §8, Data Architecture] assesses picking the right store for the right lifetime. Five properties are designed in, and the class doc lists all five up front (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/PasswordResetTokenService.cs:15-27).
    • Hashed at rest. Only SHA256.HashData(...) of the token is stored (:59-60, :90), so a cache dump does not hand out working reset links. Like RefreshSession and unlike a password, a reset token is high-entropy (32 random bytes, :41, :86) and short-lived, which is why a plain digest is sufficient here where PasswordHasher needs 210,000 PBKDF2 iterations: there is no dictionary to run against a 256-bit random value.
    • One active token per email. The key is derived purely from the address (:55), so SetAsync overwrites (:95) and an older link stops working the moment a newer one is requested.
    • Attempt cap. Wrong tokens are counted on the record and the record is discarded at MaxValidationAttempts (:173-177), which turns the token into a credential you cannot grind at.
    • Single redemption. The read, compare and remove run as one critical section under an IDistributedLock on the token key (:24-26, :108-122), so two concurrent redemptions of one token cannot both succeed, and a redemption that cannot take the lock is answered as invalid rather than as a second success. The lookup itself reads the shared store, so a token consumed on another replica is a miss rather than a stale local copy (:131-133).
    • No schema change, no sweeper. The token record rides ICacheService and the request throttle rides ICounterStore, so expiry is a TTL rather than a background job over a table (ADR-091). Compare LoginProtectionService, which reaches the same conclusion for lockout counters.
  • Walkthrough
    • Primary constructor takes ICacheService cacheService, ICounterStore counterStore, IOptions<PasswordResetSettings> settings, IDistributedLock distributedLock and TimeProvider timeProvider (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/PasswordResetTokenService.cs:34-39), snapshotting settings.Value into _settings (:47). TokenByteLength = 32 (:41) is the one constant; two static timeouts govern the redeem lock, RedeemLockTimeToLive of 10 seconds (:43) and RedeemLockWait of 5 seconds (:45).
    • TokenKey and RequestKey (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/PasswordResetTokenService.cs:55-57) each call EmailIdentity.KeySegment(email) rather than carrying a private normalizer, and the doc comment cites LoginProtectionService as the origin of the rule (:49-54): keys built from raw request input would give User@x.com and user@x.com independent tokens and independent request counters while resolving to one account. TokenKey produces pwdreset:token:{hex SHA-256 of the normalized address} (:55) and RequestKey produces pwdreset:req:{...} (:57), so the address itself never appears in a key. HashToken is the shared SHA-256 helper (:59-60).
    • IssueAsync(string email, UserIdentifierType userId, CancellationToken) (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/PasswordResetTokenService.cs:63-98): throttle first. It increments the per-email request counter in the counter store with the RequestWindowMinutes window (:69-72), an atomic fixed window that opens on the first request and is never extended (:68), and once the count exceeds MaxRequestsPerEmail fails with Error.TooManyRequests("Auth.ResetThrottled", ...) whose RetryAfter is the full request window, because the counter exposes no remaining lifetime (:74-84, comment at :76). Only then does it mint the token: 32 CSPRNG bytes rendered with Base64Url.EncodeToString (:86, URL-safe because the token travels in a query string), builds a PasswordResetEntry holding the Base64 digest, the user id, a zero attempt count and the absolute expiry as Unix seconds computed from the injected clock (:89-93), caches it under the token key with the configured lifetime (:95), and returns the raw token to the caller to email (:97). The raw token exists only in that return value: it is never written anywhere.
    • ValidateAndConsumeAsync(string email, string token, CancellationToken) (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/PasswordResetTokenService.cs:101-123): builds the token key (:106), then tries to acquire the distributed lock lock:{key} with the 10-second TTL and a 5-second wait (:111-113). A null handle (contended or unavailable) returns InvalidToken() (:114-117); otherwise it runs RedeemAsync inside an await using over the handle, so the lock is released however the redemption ends (:119-122). The comment at :108-110 states the reason: without the critical section, two callers that both read before either removes would both succeed.
    • RedeemAsync (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/PasswordResetTokenService.cs:125-163): loads the entry with GetFromSharedStoreAsync (:133) and returns InvalidToken() when there is none (:134-137). A FormatException decoding the stored Base64 removes the unreadable record rather than leaving it to expire (:139-149). The comparison is CryptographicOperations.FixedTimeEquals over the two digests (:151), the same timing-side-channel defense PasswordHasher uses, with token ?? string.Empty so a null token hashes rather than throwing. A mismatch records a failed attempt and returns the same generic failure (:151-155). On a match it removes the token key from the cache and resets the address's request counter in the counter store (:159-160), so a successful reset does not leave the user throttled out of a later legitimate request (:157-158), and returns the entry's UserId (:162).
    • RecordFailedAttemptAsync (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/PasswordResetTokenService.cs:165-186): computes attempts = entry.FailedAttempts + 1 and the remaining lifetime from ExpiresAtUnixSeconds against the injected clock (:170-171). At MaxValidationAttempts, or once the remaining lifetime is non-positive, it deletes the record (:173-177). Otherwise it rewrites the entry with entry with { FailedAttempts = attempts } and a TTL of the remaining seconds, not a fresh lifetime (:179-185), because a wrong guess must not be able to extend how long the token stays redeemable.
    • InvalidToken() (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/PasswordResetTokenService.cs:188-192) is the single failure factory: unknown, expired, mismatched, attempt-capped and lock-contended all collapse to one Auth.InvalidResetToken error with one message. That uniformity is deliberate: distinct errors would make the endpoint an oracle for which addresses have an outstanding reset.
  • Why it's built this way: ADR-091 records the decision. It extends ADR-029 (the cache-backed protection idiom reused here) and sits beside ADR-032, which decided how a password is stored but not how a user who has lost one gets a new one. Keeping the token out of the database is what makes the feature additive: no migration, no new table, and nothing to reap. The redeem lock is the ADR-108 primitive, and the shared-store read leans on the ADR-077 cache substrate. Taking TimeProvider rather than reading DateTimeOffset.UtcNow lets a test move the clock past the expiry without waiting.
  • Where it's used: registered services.TryAddScoped<IPasswordResetTokenService, PasswordResetTokenService>() (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:183), after the PasswordResetSettings binding (:179-182). ForgotPasswordHandlerBase<TUser, TCommand> calls IssueAsync and emails the resulting link (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/ForgotPassword/ForgotPasswordHandlerBase.cs:124); ResetPasswordHandlerBase<TUser, TCommand> calls ValidateAndConsumeAsync (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/ResetPassword/ResetPasswordHandlerBase.cs:77-78) before the save, because leaving the token live until the write succeeds would open a replay window, and a token burned by a later invariant failure only costs the user one more reset request (:74-76). It is unit-tested by PasswordResetTokenServiceTests.
  • Caveats / not-in-source: the per-email request throttle is atomic in the counter store, so every concurrent request is counted. The redeem lock serializes redemptions, so the failed-attempt rewrite (a read-modify-write on the cache entry) does not race another redemption of the same token on a host whose lock is shared; the lock's own cross-replica strength depends on which IDistributedLock the host registers, which is not determinable from this file.

RsaJwksProvider

MMCA.Common.Infrastructure · MMCA.Common.Infrastructure.Auth · MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/RsaJwksProvider.cs:24 · Level 6 · class (sealed)

  • What it is: the production IJwksProvider. It builds a JsonWebKeySet from the PEM-encoded public keys configured via JwksSettings, the current key first and then every additional key, each published with its own alg, kty and key-type members (n/e for RSA, crv/x/y for EC), and returns an empty set when publishing is disabled (the default) or no current key is configured (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/RsaJwksProvider.cs:7-17). Despite the name it publishes ECDSA keys as well as RSA keys.
  • Depends on: IJwksProvider; JwksSettings via IOptions<JwksSettings>, which is what puts it at Level 6, and an optional IOptions<JwtSettings> read only for the current key's algorithm (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/RsaJwksProvider.cs:24, documented at :19-23); JwksKeyMaterial, JwksAdditionalKey, JwtSigningAlgorithm and JwtAlgorithms (:3, :38, :88); and Microsoft.IdentityModel.Tokens (JsonWebKeySet, AsymmetricSecurityKey, RsaSecurityKey, ECDsaSecurityKey, JsonWebKeyConverter) (:2).
  • Concept: this reinforces the JWKS story introduced on IJwksProvider ([Rubric §11, Security], [Rubric §7, Microservices Readiness], ADR-004) and adds one lesson of its own about caching failure. The PEM parse cost is paid once and memoized in a Lazy<JsonWebKeySet> (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/RsaJwksProvider.cs:31-32), but the mode is LazyThreadSafetyMode.PublicationOnly, not the default ExecutionAndPublication. The comment above it (:26-30) explains why, and it is worth internalizing: the default Lazy<T> caches a factory exception forever, so a single transient IO failure reading the PEM file would brick /.well-known/jwks.json (and with it cross-service auth) until the process restarts. PublicationOnly caches only a successful result and lets a later call retry; concurrent factory runs are harmless here because BuildKeySet is pure and keeps no key instance. That is [Rubric §29, Resilience] reasoning applied to one field declaration. A second, smaller point: the current key's alg is taken from JwtSettings.SigningAlgorithm, not from the JWKS section, because the current key is the one tokens are signed with (:12-13), which is what keeps the published alg and the token header in agreement (ADR-149).
  • Walkthrough
    • The primary constructor takes IOptions<JwksSettings> options and an optional IOptions<JwtSettings>? jwtOptions (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/RsaJwksProvider.cs:24), and the Lazy<JsonWebKeySet> captures both (:31-32); GetJsonWebKeySet() is just _cachedKeySet.Value (:35).
    • CurrentKeyAlgorithm(JwtSettings?) (:37-40): the configured algorithm when it is asymmetric, otherwise RS256, so a provider constructed without JwtSettings, or behind an HS256 issuer, publishes the current key as RS256 (:20-22).
    • BuildKeySet(JwksSettings, JwtSigningAlgorithm) (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/RsaJwksProvider.cs:42-69) short-circuits to an empty JsonWebKeySet when !settings.Enabled (:44-47) or when the PEM resolved for the current algorithm is blank (:51-56). Those are the two paths that satisfy the IJwksProvider never-throw contract. The comment at :49-50 notes that a path-configured key file is read on the first request, cached on success and re-read after a failure. With a key present it publishes the current key through JwksKeyMaterial.CreatePublicKey(currentAlgorithm, pem, settings.KeyId) (:59), then each additional key from additional.CreateValidationKey() under additional.Algorithm (:63-66); the comment gives the ordering rule (:61-62): signing never uses an additional key, and a validator that ignores kid and takes the first key still gets the one tokens are signed with today.
    • ToJwk(AsymmetricSecurityKey, JwtSigningAlgorithm) (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/RsaJwksProvider.cs:71-90): an ECDsaSecurityKey is converted with JsonWebKeyConverter.ConvertFromECDsaSecurityKey inside a using over its ECDsa, because the JWK carries the public point and the instance is not kept (:74-81); anything else is converted with ConvertFromRSASecurityKey (:84). The JWK is marked Use = "sig" (:87) and Alg = JwtAlgorithms.ToSecurityAlgorithm(algorithm) (:88), so consumers know each key's purpose and algorithm.
  • Why it's built this way: building every key through JwksKeyMaterial, which keeps only public parameters, guarantees the private key can never reach the JWKS document even by accident. The inline-PEM-or-path pair for RSA supports both secrets-manager injection (env var or config) and a volume-mounted key file, which are the two deployment shapes the framework's samples use. sealed, and registered singleton (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:256) so the cache is process-wide.
  • Where it's used: the JWKS minimal-API endpoint calls GetJsonWebKeySet() per request; see JwksEndpointExtensions.

TokenService

MMCA.Common.Infrastructure · MMCA.Common.Infrastructure.Auth · MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/TokenService.cs:29 · Level 6 · class (sealed partial)

  • What it is: the JWT issuer. It mints signed access tokens carrying the user id, email, role and display name (plus any extra claims a caller supplies), either at the configured lifetime or at a caller-chosen shorter one, generates opaque random refresh tokens, projects both configured lifetimes as TimeSpans, and re-reads an already-expired access token during the refresh flow. It signs with RS256, PS256, ES384 or HS256, decided once at construction from configuration (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/TokenService.cs:93-109). The class is partial only so the source-generated [LoggerMessage] method at its foot can be emitted (:343-344).
  • Depends on: ITokenService (the port it implements) and IDisposable (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/TokenService.cs:29); JwtSettings, JwtSigningAlgorithm and JwksSettings, the two options bound through IOptions<T> (:75, :79), with JwksSettings (Level 5) being what puts this type at Level 6; JwtAlgorithms for the accepted-algorithm list and the JOSE alg name (:93, :297) and JwtKeyMaterial for PEM import (:326-327); IPermissionRegistry, a required constructor dependency (:32, :76) that supplies the role-to-permission map baked into every access token; and an ILogger<TokenService> (:34, :78) used for exactly one log line. Externals: System.IdentityModel.Tokens.Jwt (JwtSecurityToken, JwtSecurityTokenHandler), Microsoft.IdentityModel.Tokens (SigningCredentials, SecurityKey, RsaSecurityKey, ECDsaSecurityKey, TokenValidationParameters), System.Security.Cryptography (AsymmetricAlgorithm, RSA, ECDsa, RandomNumberGenerator), Microsoft.Extensions.Logging, and TimeProvider for the clock.
  • Concept introduced: asymmetric issuance, and one deliberate hole in validation. [Rubric §11, Security] assesses token issuance and algorithm-confusion defense, and two choices here are worth reading slowly. First, GetPrincipalFromExpiredToken sets ValidateLifetime = false on purpose (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/TokenService.cs:218) under a narrowly scoped #pragma warning disable CA5404 (:217, restored at :219) whose comment states why: the refresh flow's whole job is reading claims out of a token that has already expired. Every other check stays on (:214-216). Second, the algorithm is pinned twice: ValidAlgorithms limits validation to the list this issuer's key type accepts (:224), and the token header's alg is re-checked against the same list with an ordinal comparison after validation succeeds (:233-237). The list comes from JwtAlgorithms.AcceptedFor (:93): all three asymmetric algorithms for an asymmetric issuer, HS256 alone for an HMAC issuer, and the two lists never mix (:90-92, MMCA.Common/Source/Build/Auth/JwtAlgorithms.cs:12-14). That separation is the defense against algorithm substitution, where an attacker takes the public key (which is published on purpose) and presents it as an HMAC shared secret: the resulting HS256 token is refused by an asymmetric issuer (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/TokenService.cs:206-208). Accepting all three asymmetric algorithms rather than only the configured one is deliberate: a key rotation may change the algorithm, and a token the previous key signed stays valid while that key is published (:90-92, ADR-149). [Rubric §7, Microservices Readiness] applies to the algorithm switch itself: an asymmetric algorithm (RS256 is the default) lets an extracted service validate a token without ever holding the issuer's private key, because it fetches the public key from the JWKS document that RsaJwksProvider publishes (ADR-004). Under an asymmetric algorithm the refresh flow also accepts the additional keys JwksSettings publishes (:100-104, passed at :223), so a token signed with the key in force before a rotation still refreshes while signing stays on the current key. HS256 remains available for a single-process monolith, where issuer and validator are the same host and a shared secret costs nothing (:106-109). [Rubric §14, Testability] shows up in the constructor: the clock is an injected, required TimeProvider with no TimeProvider.System fallback (:77, :87), resolved from whatever DI registration adds it in the container's AddServices call (the parameter doc says so at :58-61), so a test passes its own and can assert iat/nbf/exp without waiting for wall-clock time to pass. A third, [Rubric §20, Policy and Enforcement Points] concept sits in the shared Mint helper: every access token carries one AuthClaimTypes.Permission claim per permission IPermissionRegistry grants the token's role (:164-176), so a client can gate its own surface on a capability rather than a role name it would otherwise have to know. A host that declared no grants resolves UnconfiguredPermissionRegistry, which grants nothing, and its tokens simply carry no permission claims (:51-57, the constructor's own doc comment on the parameter). A fourth, [Rubric §13, Observability], is the split catch in GetPrincipalFromExpiredToken (:241-255): ordinary rejections stay silent, but anything else is logged before it is refused, so a fault in the validation path cannot hide behind an ordinary 401.
  • Walkthrough
    • Fields (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/TokenService.cs:31-43): the settings snapshot (:31), the injected IPermissionRegistry (:32), the TimeProvider (:33), the ILogger<TokenService> (:34), the SigningCredentials used to sign and the SecurityKey used to validate (:35-36), the list of additional validation keys defaulting to empty (:37), the list of algorithms validation accepts (:38), and two nullable owned AsymmetricAlgorithm handles, each an RSA or an ECDsa (:42-43). The comment at :40-41 explains why IDisposable is on the class at all: the security-key wrappers do not dispose the instances they wrap, so something has to.
    • The constructor (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/TokenService.cs:74-110) takes IPermissionRegistry permissionRegistry and ILogger<TokenService> logger as required parameters, null-guarded alongside jwtOptions (:81-83) and assigned to _permissionRegistry and _logger (:86, :88). TimeProvider timeProvider is likewise a required parameter with no default (:77), assigned straight to _timeProvider with no fallback (:87); it is not null-guarded. The logger's parameter doc states its whole job (:62-67): record the one validation failure that is not an ordinary rejection. The constructor materializes all key material exactly once, so no token operation re-parses a PEM. It first fixes the accepted algorithm list (:93). For any asymmetric algorithm (:95) it builds the credentials through BuildAsymmetricCredentials; the key id it passes is jwksSettings?.Value.KeyId falling back to a default JwksSettings instance (:97-98), which is how the same kid ends up on both the token and the published JWK (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/RsaJwksProvider.cs:59). It then loads the published additional keys through CreateAdditionalValidationKeys (:104), and the comment gives the reason (:100-103): the refresh flow validates a token this service signed, possibly with the key in force before a rotation. Otherwise it builds HMAC credentials (:106-109).
    • GenerateAccessToken(userId, email, role, fullName, additionalClaims) (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/TokenService.cs:113-119) and GenerateShortLivedAccessToken(..., TimeSpan lifetime) (:122-133) both delegate to the private Mint. The first passes AccessTokenExpirationMinutes (:119); the second rejects a zero or negative lifetime with ArgumentOutOfRangeException (:131) and otherwise honors the caller's lifetime exactly, the remarks leaving the cap to the caller (:122).
    • Mint (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/TokenService.cs:135-187) reads the clock once (:143), then builds six claims (:149-157): sub (the user id, formatted with CultureInfo.InvariantCulture), jti (a fresh GUID, so a token is individually identifiable), iat as Unix seconds, and the standard name, email and role claims. The comment at :145-148 is a design note worth internalizing: sub is the only carrier of the user id. A duplicate custom claim used to ride alongside it, which meant two values that could disagree and two claim names every reader had to know; readers now go through ClaimsPrincipalExtensions instead. Caller-supplied claims are appended (:159-162). Then, before the token is assembled, permission claims are added (:164-176): alreadyClaimed collects any Permission claim value already present in claims (:168-171), and every permission _permissionRegistry.GetPermissions(role) returns that is not already in that set is appended, ordered ordinally for a deterministic token per role (:173-176). A JwtSecurityToken is then assembled with issuer, audience, notBefore from the injected clock and expires at now + lifetime (:178-184), and serialized (:186).
    • GenerateRefreshToken() (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/TokenService.cs:190-194) returns 64 CSPRNG bytes Base64-encoded. It is not a JWT and carries no claims: it is an opaque bearer string whose only property is being unguessable, and the store it is compared against is what gives it meaning.
    • AccessTokenLifetime and RefreshTokenLifetime (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/TokenService.cs:197, :200) project the configured minutes and days, so callers computing an expiry timestamp never re-read settings and never disagree with the token just minted.
    • GetPrincipalFromExpiredToken(string token) (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/TokenService.cs:210-256) builds the validation parameters described above (:212-225), with the current key as IssuerSigningKey and the additional keys as IssuerSigningKeys (:222-223), validates (:231), applies the post-validation alg re-check and returns null when the token is not a JwtSecurityToken or the header's alg is not in the accepted list (:233-237). The failure path is two catches. A SecurityTokenException or ArgumentException (bad signature, wrong issuer or audience, malformed input) returns null without a log line, because a client presenting a bad token is not an event (:241-246). Any other exception is treated as a fault in the validation path: it is logged at warning level through the source-generated LogUnexpectedValidationFailure (:253, declared at :343-344) and still answered with null (:247-255), so the method fails closed either way. A malformed, forged, or wrong-issuer token therefore produces a plain "no principal" answer rather than a parser exception leaking to the caller.
    • Dispose() (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/TokenService.cs:259-263) releases both owned key handles.
    • BuildHmacCredentials (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/TokenService.cs:265-272) decodes SecretForKey through JwtSettings.DecodeHmacSigningKey (:269), the same decode-and-length check the startup validation applies (the comment at :267-268), so a missing, non-Base64 or shorter-than-32-byte key throws InvalidOperationException here too. The decoded bytes become one SymmetricSecurityKey used for both signing and validation (:269-271).
    • BuildAsymmetricCredentials (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/TokenService.cs:274-324) picks the EC pair for ES384 and the RSA pair otherwise (:278-281), throws naming the missing EcPrivateKeyPem or RsaPrivateKeyPem and the selected algorithm (:283-287), and imports the private key through ImportKey (:289), which calls JwtKeyMaterial.ImportP384 or ImportRsa (:326-327), so an ES384 key that is not on P-384 is refused (MMCA.Common/Source/Build/Auth/JwtKeyMaterial.cs:51-55). It wraps the key with WrapKey, which stamps the key id on an ECDsaSecurityKey or an RsaSecurityKey (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/TokenService.cs:296, :329-334), so every asymmetric token carries a kid header, and signs with JwtAlgorithms.ToSecurityAlgorithm(algorithm) (:297). The comment at :292-295 gives the reason for the kid: a validator reading the published JWKS selects the key by name, and without one it has to try every published key, which stops working the moment a rotation publishes two. The validation key prefers the configured public PEM and otherwise derives the public half of the signing key through PublicHalfOf (:302-304, :336-341), so an issuer configured with only a private key still validates its own tokens during refresh; it carries the same key id (:310). Both nested try/catch blocks dispose the partially built key before rethrowing (:313-317, :319-323), so a bad PEM does not leak a native handle. Because all of this runs in the constructor, missing or malformed key material fails at host startup, not on the first login.
  • Why it's built this way: ADR-004 records the asymmetric-issuance rationale and ADR-149 the choice of algorithms. The DI lifetime deserves its own read at the registration site (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:399-405): the comment there records that a scoped lifetime disposed the underlying RSA at end-of-request while the static CryptoProviderCache in Microsoft.IdentityModel.Tokens still held the cached AsymmetricSignatureProvider wrapping it (:387-390), throwing ObjectDisposedException on the next RS256 sign. Singleton is correct because the constructor depends only on singletons (the JWT and JWKS options, the permission registry, TimeProvider and a logger) and the service is stateless after construction (:390-392). Baking permission claims into the token itself, rather than having a client call back to look them up, is the same shape ADR-020 establishes for permission-based authorization: the permission set travels with the credential.
  • Where it's used: registered as services.TryAddSingleton<ITokenService, TokenService>() (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:406), which resolves IPermissionRegistry and the logger from the container alongside the JWT options. Consumed through the port in two places. AuthSessionIssuer mints the tokens: its AccessTokenLifetime reads this service's lifetime with a 15-minute floor when the setting is non-positive (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Sessions/AuthSessionIssuer.cs:79-80), and refresh tokens are minted at :476 and :520. The same file wraps this service in the private SessionStampingTokenService pass-through (:737), which appends the AuthClaimTypes.SessionId (sid) claim through the additionalClaims parameter (:776), so per-device session identity is layered on without this type knowing about sessions at all. AuthenticationServiceBase<TUser> reads the expired token in the refresh flow (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/AuthenticationServiceBase.cs:410). The sub claim it writes is what CurrentUserService and ClaimBasedUserIdProvider read back.
  • Caveats / not-in-source: nothing here rotates or reloads key material. The keys, including the additional validation keys, are read once in the constructor (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/TokenService.cs:74-110) and the instance is a singleton, so a key change takes a host restart. Refresh-token storage, rotation and revocation are not in this file either: it only produces the random string.

AuditHistoryEntryDTO

MMCA.Common.Shared · MMCA.Common.Shared.Auditing · MMCA.Common/Source/Core/MMCA.Common.Shared/Auditing/AuditHistoryEntryDTO.cs:12 · Level 0 · record (sealed)

  • What it is: one recorded change in an entity's history, the read-side shape returned by IAuditTrailReader and served by the audit-history endpoint (MMCA.Common/Source/Core/MMCA.Common.Shared/Auditing/AuditHistoryEntryDTO.cs:3-5,12).
  • Depends on: nothing first-party beyond the solution-wide UserIdentifierType alias (ChangedBy, AuditHistoryEntryDTO.cs:42); BCL Guid and DateTime.
  • Concept introduced, a deliberately minimal projection of an infrastructure row. [Rubric §30, Compliance/Privacy/Data Governance] assesses whether changes to data are traceable and whether personal data stays protected while being traced; [Rubric §9, API & Contract Design] assesses whether a public contract carries only what its consumer needs. The remarks call the type "deliberately minimal in v1": it carries what a "who changed what, and when" view needs "and nothing an infrastructure table happens to also store" (AuditHistoryEntryDTO.cs:6-11). Values are the invariant string forms recorded at capture time, and a value that belonged to a property marked as personal data reads as the redaction placeholder on both sides (:9-10), so the history view does not become a way around PII redaction. The trail itself is ADR-075.
  • Walkthrough: a sealed record of init-only properties, the mandatory ones marked required.
    • Id (:15), the identifier of the trail row.
    • EntityType (:18), the full CLR type name of the changed entity, and EntityKey (:21), the invariant string form of its primary key.
    • PropertyName (:27), nullable: null on the summary row of a create or delete (:23-26).
    • OldValue (:30) and NewValue (:33), both nullable strings.
    • Operation (:36), one of Added, Modified or Deleted.
    • ChangedBy (:42), nullable: null when the save carried no identity, such as a background service or a seeder (:38-41).
    • ChangedOn (:45), the UTC instant the change was recorded, and CorrelationId (:48), the trace identifier it was recorded under, when there was one.
  • Why it's built this way: the reader contract lives in Application, the endpoint in API and the panel in the UI; placing the shape in Shared lets all of them, and a Blazor client, share it without a reference on Infrastructure, where the trail row lives (AuditTrailEntry).
  • Where it's used: declared as the return of IAuditTrailReader.GetForEntityAsync (MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/IAuditTrailReader.cs:40) and projected by AuditTrailReader (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/AuditTrail/AuditTrailReader.cs:48,80); served as a bare JSON array by AuditHistoryControllerBase (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Administration/AuditHistoryControllerBase.cs:31,94,99); fetched by AuditHistoryService (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auditing/AuditHistoryService.cs:27) and rendered by AuditHistoryPanel (MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Auditing/AuditHistoryPanel.razor.cs:24,42). In ADC, the Conference module's event and session detail pages (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.UI/Pages/Events/EventDetail.razor.cs, .../Pages/Sessions/SessionDetail.razor.cs) reference it for their history panels.
  • Caveats / not-in-source: it sits in the authentication group by the inventory's assignment, but it is an auditing contract; nothing in it relates to authentication beyond ChangedBy naming a user.

AuthClaimTypes

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

  • What it is: the claim-type name constants the framework's own token vocabulary rests on, sitting alongside the standard System.Security.Claims.ClaimTypes values (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/AuthClaimTypes.cs:5-9).
  • Depends on: nothing first-party at runtime. Its doc comments point at IPermissionRegistry for the role-derived half of the permission model (AuthClaimTypes.cs:14) and at the ClaimsPrincipalExtensions readers FindUserIdValue, HasMultiFactor, HasMultiFactorWithheldRole and IsViewAs (AuthClaimTypes.cs:31,57,86,119).
  • Concept introduced, a claim vocabulary owned by the framework rather than by each reader. [Rubric §11, Security] assesses how authentication and authorization are modeled and which facts a principal is allowed to carry; [Rubric §15, Best Practices & Code Quality] assesses single points of change. A claim type is just a string, so writer and reader agreeing on it is a convention with no compiler behind it. Putting every name in one const holder is what makes the token issuer and every reader provably agree.
    • Permission (AuthClaimTypes.cs:24, value "permission") carries a single granted capability, honored in addition to the permissions a role confers through IPermissionRegistry (AuthClaimTypes.cs:11-14). The doc comment states that TokenService itself is the emitter (AuthClaimTypes.cs:15-22): every access token it mints carries one Permission claim per permission the role's registry entry grants, sorted ordinally so the same role always produces the same token shape. That is what lets a client decide what to show (a navigation entry gating on a required permission) without knowing any role name, while server-side checks still go through the registry, so a host that mints tokens some other way loses nothing. This makes the model in ADR-020 backward compatible with plain role checks: a token still authorizes correctly if a reader ignores the claim entirely.
    • Subject (AuthClaimTypes.cs:34, value "sub") is the single authoritative carrier of the user identifier in every token the framework mints. The doc comment states the trap that follows (AuthClaimTypes.cs:26-33): one value reaches readers under two different claim types, because the JWT bearer handler maps inbound sub onto ClaimTypes.NameIdentifier while a handler that materializes an identity straight from a token's claims leaves the raw sub in place.
    • SessionId (AuthClaimTypes.cs:47, value "sid") is the RFC 7519 / OpenID Connect session id: the identifier of the refresh session the access token was minted for, which is to say the device behind the token (AuthClaimTypes.cs:36-40). It is additive, never required (AuthClaimTypes.cs:41-45): rotation mints a new session and therefore a new sid, a token issued before the claim shipped simply carries none, and nothing validates it. A missing or unparsable value degrades to "no current session known", never to a rejected token.
    • MultiFactor (AuthClaimTypes.cs:63, value "mfa") is an RFC 8176 (amr)-style claim asserting that the access token was minted after a second authentication factor was presented (AuthClaimTypes.cs:49-62). Presence is the assertion, not the value: readers ask whether the claim exists (ClaimsPrincipalExtensions.HasMultiFactor), the value exists for audit and for UI copy such as "you signed in with a recovery code". A token issued for an account with no second factor carries no mfa claim at all, which is why a role that requires a second factor denies such a caller rather than degrading to a plain role check. The value is one of three method names: MultiFactorMethodTotp (AuthClaimTypes.cs:66, value "otp"), MultiFactorMethodRecoveryCode (AuthClaimTypes.cs:69, value "recovery") and MultiFactorMethodPasskey (AuthClaimTypes.cs:76, value "passkey"). A passkey counts as multi-factor by itself, being possession of the device plus the authenticator's own user verification, and a refresh carries the value over like the other two (AuthClaimTypes.cs:71-75).
    • MultiFactorWithheldRole (AuthClaimTypes.cs:89, value "mfa_withheld_role") and MultiFactorWithheldPermission (AuthClaimTypes.cs:96, value "mfa_withheld_permission") are markers, not grants. The API adds one to a validated bearer principal for each role it withheld because the role is listed under Authorization:MultiFactor:RequiredForRoles and the session carries no mfa claim, and one for each Permission claim it removed with that role and did not keep for a role the principal still holds. The token still carries the role; only the request's principal goes without it. The marker lets a reader tell "signed in, role withheld until a second factor" from "no such role", and it never grants anything (AuthClaimTypes.cs:78-95).
    • AuthTime (AuthClaimTypes.cs:111, value "auth_time") is the OpenID Connect sign-in instant, in Unix seconds, stamped when an interactive sign-in opens a session and carried unchanged across every refresh, so unlike iat it does not move when a refresh mints a new access token; a view-as token carries none (AuthClaimTypes.cs:98-104). It is what "recently signed in" is judged by: registering a passkey requires an auth_time within the last ten minutes (ADR-139), so a stolen refresh token cannot keep a session fresh enough to plant one, and a token without the claim reads as not recent (AuthClaimTypes.cs:105-109).
    • ViewAsActor (AuthClaimTypes.cs:122, value "act_sub") names the staff user behind a view-as token, whose sub is the user being viewed (ADR-137). Presence makes the request read-only: every command is refused and every non-safe HTTP method is rejected while it is present (AuthClaimTypes.cs:113-121). ViewAsGrant (AuthClaimTypes.cs:128, value "vag") is the id of the grant the token was minted for, checked on every view-as request so ending the grant ends the token before it expires (AuthClaimTypes.cs:124-127).
    • ClientId (AuthClaimTypes.cs:134, value "client_id", RFC 9068) names the machine client a token was issued to through the client credentials grant, whose sub is the client's service-account user. TokenUse (AuthClaimTypes.cs:140, value "token_use") is carried only by a machine token, with the value TokenUseMachine (AuthClaimTypes.cs:146, value "machine"); a token without it was issued to a person. A machine token has no refresh token, no sid, no auth_time and no mfa (AuthClaimTypes.cs:130-145, ADR-140).
  • Walkthrough: fifteen public const string fields and nothing else (AuthClaimTypes.cs:24-146). const rather than static readonly so the values are usable in attribute arguments and in patterns that require compile-time constants, the same reason RoleNames uses const.
  • Why it's built this way: ADR-020 makes the permission layer opt-in, ADR-097 adds the per-device session identity that sid names, the opt-in two-factor completion (ADR-116) adds mfa and its first two method values, ADR-139 adds the passkey method and auth_time, ADR-137 adds the view-as pair, and ADR-140 adds the machine-client pair. Keeping the claim types as shared constants means the writer and the reader cannot drift apart on a string.
  • Where it's used:
    • Permission is written by TokenService itself, one claim per permission the injected IPermissionRegistry grants the token's role, sorted ordinally and deduplicated against any permission claim the caller already supplied (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/TokenService.cs:164-176), and is read by PermissionAuthorizationHandler and the CQRS AuthorizationGate, both through ClaimsPrincipalExtensions.HasPermissionClaim (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/PermissionAuthorizationHandler.cs:31, MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Decorators/AuthorizationGate.cs:47).
    • Subject is written by TokenService as JwtRegisteredClaimNames.Sub (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/TokenService.cs:151) and read through ClaimsPrincipalExtensions by CurrentUserService, ClaimBasedUserIdProvider, the IdempotencyFilter, and the rate-limit partitioner.
    • SessionId, MultiFactor and AuthTime are stamped by AuthSessionIssuer (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Sessions/AuthSessionIssuer.cs:828,833,839). The method value comes from AuthenticationServiceBase<TUser>, which maps a verified TwoFactorOutcome to otp or recovery and a passkey sign-in to passkey (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/AuthenticationServiceBase.cs:626,901-902). sid is read back by FindSessionId for the "my sessions" endpoint (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/AuthControllerBase.cs:296).
    • The withheld markers are written by MultiFactorRoleWithholding (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/MultiFactor/MultiFactorRoleWithholding.cs:87-88) and read by MultiFactorRoleAuthorizationHandler (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/MultiFactor/MultiFactorRoleAuthorizationHandler.cs:67-69).
    • The view-as pair is written by ViewAsService (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/ViewAs/ViewAsService.cs:106-107) and checked by ViewAsGuardMiddleware (MMCA.Common/Source/Presentation/MMCA.Common.API/Middleware/ViewAsGuardMiddleware.cs:127-128).
    • The machine-client pair is written by MachineClientService (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/MachineClients/MachineClientService.cs:112-113) and refused by RefuseMachineClientsAttribute (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/RefuseMachineClientsAttribute.cs:44).
  • Caveats / not-in-source: the Permission claim is written by every token the framework mints (TokenService.cs:164-176); a reader depending on Permission being absent from real tokens would be wrong. The registry lookup remains the authoritative check either way, since the claim path is additive.

AuthErrorCodes

MMCA.Common.Shared · MMCA.Common.Shared.Auth · MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/AuthErrorCodes.cs:12 · Level 0 · class (static)

  • What it is: the caller-facing error-code strings for registration, sign-in, email confirmation, two-factor enrollment and the multi-factor gate, held in Shared so a client can branch on a refusal without a reference on Application (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/AuthErrorCodes.cs:12-67).
  • Depends on: nothing first-party; consumed as an Error code string. Its doc comment points at AuthClaimTypes.MultiFactor (AuthErrorCodes.cs:29).
  • Concept introduced, one code for every path that means the same thing to the caller. [Rubric §15, Best Practices & Code Quality] assesses whether a caller-facing contract stays stable across an implementation detail; [Rubric §9, API & Contract Design] assesses whether error contracts are explicit. EmailAlreadyExists is returned by both the up-front existence check and the unique-index race recovery during registration, so the two paths stay indistinguishable to the caller (AuthErrorCodes.cs:14-17), and MultiFactorRequired is returned by the HTTP permission check for a role the host lists under Authorization:MultiFactor:RequiredForRoles (AuthErrorCodes.cs:27-33). Several constants mirror codes that Application types also define, and the copies are pinned together by tests rather than by a reference (MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Auth/SignIn/AuthErrorCodesAlignmentTests.cs:16-47): TwoFactorRequired, TwoFactorInvalid and TwoFactorRecentSignInRequired must equal TwoFactorErrors's codes (AuthErrorCodesAlignmentTests.cs:37-40 for the last), EmailNotConfirmed must equal EmailConfirmationErrors's, and MultiFactorRequired must stay the literal "Authorization.MultiFactorRequired". The direction is reversed for EmailConfirmationPasswordRequired: EmailConfirmationErrors.PasswordRequiredCode is defined as a reference to it (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/EmailConfirmation/EmailConfirmationErrors.cs:23).
  • Walkthrough: eight public const string fields.
    • EmailAlreadyExists (AuthErrorCodes.cs:19, "Auth.EmailAlreadyExists"): registration refused because the address already belongs to an account; the registration UI keys its "sign in instead" guidance on it.
    • TermsNotAccepted (:25, "Auth.TermsNotAccepted"): registration refused because the host requires Terms of Service acceptance and the request did not carry it; returned only when a current terms version is configured (:21-24).
    • MultiFactorRequired (:34, "Authorization.MultiFactorRequired"): the operation needs a session that signed in with a second factor and the token carries no mfa claim, because the caller's role is listed under Authorization:MultiFactor:RequiredForRoles. A client sends the user to set up two-factor authentication or to sign in again with a code (:27-33).
    • TwoFactorRequired (:41, "Authentication.TwoFactorRequired"): the account has a second factor and the sign-in carried no code. The password has been proved at that point, so a client prompts for the code and retries the same credentials with it (:36-40).
    • TwoFactorInvalid (:47, "Authentication.TwoFactorInvalid"): the second-factor code did not verify; a client keeps the code step and asks for a new one (:43-46).
    • EmailNotConfirmed (:53, "Authentication.EmailNotConfirmed"): the host requires a confirmed address and the account's is not confirmed; a client offers to resend the link (:49-52).
    • EmailConfirmationPasswordRequired (:60, "EmailConfirmation.PasswordRequired"): the confirmation token is valid, but the account holds a password and the request proved neither the account nor a claim on it. Nothing changed and the token is still redeemable, so a client asks for the current password or a new one and posts the same token again (:55-59).
    • TwoFactorRecentSignInRequired (:66, "Authentication.TwoFactorRecentSignInRequired"): starting or confirming a two-factor enrollment was refused because the session's interactive sign-in is older than the recent-sign-in window; a client sends the user to sign in again first (:62-65).
  • Why it's built this way: a race between the registration pre-check and the database's unique constraint is possible under concurrent attempts, and returning the same code from both paths means the caller-facing behavior does not depend on which path lost. The prefixes follow the producing concern (Auth. for registration, Authentication. for sign-in and two-factor enrollment, EmailConfirmation. for confirmation, Authorization. for the gate), and a client matches on the full string.
  • Where it's used: registration codes are returned by AuthenticationServiceBase (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/AuthenticationServiceBase.cs), and TermsNotAccepted is re-exposed as LegalAcceptanceErrors.TermsNotAcceptedCode (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Legal/LegalAcceptanceErrors.cs:14); see LegalAcceptanceErrors. MultiFactorRequired is emitted by MultiFactorRoleAuthorizationHandler (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/MultiFactor/MultiFactorRoleAuthorizationHandler.cs:59) and by MultiFactorRefusalResultHandler (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/MultiFactor/MultiFactorRefusalResultHandler.cs:66), and detected on the client by AuthDelegatingHandler (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/AuthDelegatingHandler.cs:335). The three sign-in codes map to login-page refusals in LoginRefusals (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/TwoFactor/LoginRefusals.cs:51-53). EmailConfirmationPasswordRequired is what the confirmation page branches on to ask for a password (MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/ConfirmEmail.razor.cs:266), and TwoFactorRecentSignInRequired is what the two-factor account page and enrollment panel branch on (MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/TwoFactor/TwoFactorAccount.razor.cs:355, MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/TwoFactor/TwoFactorEnrollmentPanel.razor.cs:102).

Base32

MMCA.Common.Infrastructure · MMCA.Common.Infrastructure.Auth.TwoFactor · MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/TwoFactor/Base32.cs:13 · Level 0 · class (internal static)

  • What it is: RFC 4648 section 6 Base32 over the upper-case A-Z2-7 alphabet, the encoding an authenticator app expects a TOTP secret in (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/TwoFactor/Base32.cs:3-6,13).
  • Depends on: BCL only (ReadOnlySpan<byte>, ArgumentException).
  • Concept introduced, owning a small codec instead of taking a package for it. [Rubric §32, Dependency & Supply-Chain] assesses whether third-party dependencies earn their place. The codec is under a hundred lines of bit shifting with no external dependency, internal to Infrastructure, so neither the framework's public surface nor its consumers take a package for it. [Rubric §14, Testability] applies too: the Infrastructure tests exercise it through RFC vectors (MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Auth/TwoFactor/TotpRfcVectorTests.cs).
  • Walkthrough:
    • Alphabet (Base32.cs:15), the 32 characters in value order.
    • Encode(ReadOnlySpan<byte>) (:21-57) throws on empty input (:23-26), sizes the output to a multiple of eight characters ((length + 4) / 5 * 8, :28), and feeds each byte into a bit buffer masked to twelve bits, emitting a character every time five bits are available (:34-44). Leftover bits are left-aligned into one last character (:46-49) and the rest is = padding (:51-54).
    • Decode(string) (:65-88) throws on null or empty (:67), trims trailing = (:69), sizes the output as length * 5 / 8 bytes (:70), and emits a byte every time eight bits are buffered (:75-85). Leftover low bits of the last character are ignored, and fewer than eight bits decode to an empty array.
    • ValueOf(char) (:90-96) accepts upper- and lower-case letters and the digits 2-7, and throws for anything else, which includes whitespace and a = that is not trailing.
  • Why it's built this way: the remarks state the leniency policy (Base32.cs:7-12): encoding always pads, while decoding tolerates missing padding and either letter case, because that is how authenticator secrets are typed and stored; anything else is rejected rather than guessed at.
  • Where it's used: TotpTwoFactorService encodes new secrets and recovery codes with it and decodes the stored secret before verifying (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/TwoFactor/TotpTwoFactorService.cs:40,71,108).
  • Caveats / not-in-source: its exceptions are not part of any public contract; TotpTwoFactorService.VerifyCode catches ArgumentException and answers false (TotpTwoFactorService.cs:73-79).

DeviceMetadata

MMCA.Common.Shared · MMCA.Common.Shared.Auth · MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/DeviceMetadata.cs:24 · Level 0 · record (sealed, positional)

  • What it is: what a native client reports about the device it runs on, recorded on the caller's current refresh session so a "signed-in devices" list and a sign-in history can name the device in its owner's words. The same shape is the body of PUT auth/sessions/current/device and the Device member of the session responses (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/DeviceMetadata.cs:3-7).
  • Depends on: nothing; seven string? positional members.
  • Concept introduced: none new; it is the device half of the per-device refresh session model taught at RefreshSession (ADR-097). [Rubric §11, Security] applies in one sentence: every member is informational only, so nothing validates a session against it, and the server truncates each value to its column width and stores a blank one as null (DeviceMetadata.cs:8-12).
  • Walkthrough: DeviceId, a per-install identifier the client generates (a random GUID, since iOS exposes no stable device id; not a hardware serial, :14-17); DeviceName, the owner's name for the device when the platform exposes it (:18); DeviceModel (:19); DeviceManufacturer (:20); DevicePlatform, such as Android, iOS or WinUI (:21); DeviceFormFactor, such as Phone, Tablet or Desktop (:22); and DeviceType, Physical or Virtual (:23). The record is declared at :24-31.
  • Why it's built this way: browser clients report nothing and are described from the user-agent instead (DeviceMetadata.cs:10-11); a native client knows more about itself than a user-agent string says, so it reports a structured shape and the server stores it on the session row.
  • Where it's used: sent by MauiDeviceMetadataReporter (MMCA.Common/Source/Presentation/MMCA.Common.UI.Maui/Services/MauiDeviceMetadataReporter.cs:34) and accepted by AuthControllerBase (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/AuthControllerBase.cs:326); passed through AuthSessionIssuer (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Sessions/AuthSessionIssuer.cs:358) to RefreshSession.RecordDevice (MMCA.Common/Source/Core/MMCA.Common.Domain/Auth/RefreshSession.cs:273); read back by RefreshSessionDevice.ToDeviceMetadata (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Sessions/RefreshSessionDevice.cs:22) into RefreshSessionSummaryResponse and SignInSummaryResponse (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Responses/RefreshSessionSummaryResponse.cs:35, .../SignInSummaryResponse.cs:50); and labeled in the UI by UserAgentSummary.

PasswordComplexity

MMCA.Common.Shared · MMCA.Common.Shared.Auth · MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/PasswordComplexity.cs:18 · Level 0 · class (static partial)

  • What it is: the one definition of the strong-password rule: the two length bounds, four source-generated character-class regexes, and an Evaluate predicate that combines them (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/PasswordComplexity.cs:5-18).
  • Depends on: nothing first-party; BCL System.Text.RegularExpressions and the [GeneratedRegex] source generator (PasswordComplexity.cs:1,34).
  • Concept introduced, one rule evaluated on both sides of the wire. [Rubric §24, Forms, Validation & UX Safety] assesses validation parity: the client form must give the verdict the API would. The doc comment states the purpose directly (PasswordComplexity.cs:5-10): the server validator (StrongPasswordRules<T> in MMCA.Common.Application) and the client attribute (PasswordComplexityAttribute in MMCA.Common.UI) both read this type, so they cannot disagree on the same input. It lives in Shared because Shared is the one project both of those layers may reference (UI depends on Shared only). The character classes are Unicode-aware (PasswordComplexity.cs:11-16): an accented or CJK letter counts as a letter, never as the "special" character.
  • Walkthrough: MinimumLength is 8 (PasswordComplexity.cs:28) and MaximumLength is 128 (PasswordComplexity.cs:31), both const int measured in UTF-16 code units, so they are usable in attribute arguments. Four public static partial Regex properties are source-generated by [GeneratedRegex], each with a 1000 ms match timeout: Uppercase (\p{Lu}, PasswordComplexity.cs:34-35), Lowercase (\p{Ll}, :38-39), Digit (\p{Nd}, :42-43), and SpecialCharacter ([^\p{L}\p{Nd}], anything that is neither a letter nor a decimal digit, :49-50). Evaluate(string? password) (PasswordComplexity.cs:52-57) returns true only when the input is non-null, at least MinimumLength long, and matches all four regexes. It deliberately does not check MaximumLength: the upper bound is a separate rule with its own message on both sides (PasswordComplexity.cs:52-56).
  • Why it's built this way: a client rule and a server rule written separately are two copies of one policy that drift independently. Exposing the regexes (not only Evaluate) lets the server's FluentValidation chain keep one message per failed class, while the client attribute asks the single yes/no question. Source-generated regexes avoid runtime regex construction, and the match timeout bounds evaluation of untrusted input.
  • Where it's used: StrongPasswordRules<T> feeds both length constants and all four regexes into its rule chain (MMCA.Common/Source/Core/MMCA.Common.Application/Validation/CommonValidationRules.cs:255-260); PasswordComplexityAttribute calls Evaluate, leaving empty input to [Required] (MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/PasswordComplexityAttribute.cs:25); RegisterModel and ResetPasswordModel pair that attribute with [StringLength(PasswordComplexity.MaximumLength)] to supply the separate upper-bound rule (MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/RegisterModel.cs:27-28, MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/ResetPasswordModel.cs:25-26); pinned by MMCA.Common/Tests/Core/MMCA.Common.Shared.Tests/Auth/PasswordComplexityTests.cs.
  • Caveats / not-in-source: the server's length messages interpolate MinimumLength and MaximumLength (CommonValidationRules.cs:255-256), but the attribute's default message still hard-codes "at least 8 characters" (PasswordComplexityAttribute.cs:19); changing the lower bound means editing that string too. No plain password-rules sibling remains in CommonValidationRules.cs: StrongPasswordRules<T> (CommonValidationRules.cs:248) is the only password validator there.

SetRequest

MMCA.Common.Infrastructure · MMCA.Common.Infrastructure.Auth.Administration · MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/Administration/StoredPermissionRoleAdministrationService.cs:379 · Level 0 · record (private sealed, nested)

  • What it is: the private parameter object that carries one stored-permission set, as the caller submitted it, from SetStoredPermissionsAsync into the locked, transactional unit that applies it (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/Administration/StoredPermissionRoleAdministrationService.cs:373-384).
  • Depends on: nothing first-party; BCL Func<string, bool> and IReadOnlyList<string>. It is nested inside StoredPermissionRoleAdministrationService.
  • Concept introduced: none of its own; it is the hand-off value for the per-role edit unit that PermissionRoleEditUnit introduces.
  • Walkthrough: five positional members (:379-384): Role (the caller's spelling, kept for the error target), CanonicalRole (the spelling every read, write, lock and invalidation uses), Permissions (the desired stored set), CallerHoldsPermission (the privilege-ceiling predicate, or null for none) and ChangedBy (the audit label stamped on granted rows) (:373-378). ApplySetAsync deconstructs it in one line on entry (StoredPermissionRoleAdministrationService.cs:188).
  • Why it's built this way: the set body runs as a delegate handed to PermissionRoleEditUnit.RunAsync (StoredPermissionRoleAdministrationService.cs:158-163), so the five caller values travel as one record built inside the lambda rather than as five captured parameters on a private method.
  • Where it's used: constructed once per set in SetStoredPermissionsAsync (:162) and consumed only by ApplySetAsync (:183-188); no usage outside the defining file.

Totp

MMCA.Common.Infrastructure · MMCA.Common.Infrastructure.Auth.TwoFactor · MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/TwoFactor/Totp.cs:24 · Level 0 · class (internal static)

  • What it is: RFC 6238 time-based one-time passwords over HMAC-SHA1 with RFC 4226 dynamic truncation, "the variant every authenticator app implements" (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/TwoFactor/Totp.cs:8-11,24).
  • Depends on: BCL only: HMACSHA1.HashData, BinaryPrimitives, CryptographicOperations.FixedTimeEquals and MemoryMarshal from System.Security.Cryptography, System.Buffers.Binary and System.Runtime.InteropServices.
  • Concept introduced, a one-time code is an HMAC of the clock. [Rubric §11, Security] assesses whether credentials are verified without side channels. A TOTP code is the HMAC of a shared secret over a counter, where the counter is "the whole Unix seconds of the instant divided by the period", so a code is live for exactly one period (Totp.cs:13-17). The server holds the same secret, recomputes the code for the current step and its neighbors, and compares. Comparison is fixed time: every candidate step is computed and compared with CryptographicOperations.FixedTimeEquals, without stopping at a match, so the reply time does not say which step matched (Totp.cs:18-22). [Rubric §32, Dependency & Supply-Chain] applies as for Base32: the algorithm is about a hundred lines of BCL calls rather than a package.
  • Walkthrough:
    • Compute(key, utcInstant, periodSeconds, digits) (Totp.cs:32-33) computes the code for the step containing an instant.
    • Verify(key, code, utcInstant, periodSeconds, digits, windowSteps, out matchedStep) (:47-75) null-checks its inputs (:56-57), takes the current step (:59) and the presented code's bytes (:60), then walks every candidate step, computing the expected code and comparing in fixed time; the && !matched guard records the first match without leaving the loop early (:64-72). matchedStep is zero when nothing matched.
    • TimeStep (:77-82) rejects a non-positive period and divides whole Unix seconds by it.
    • Candidates (:84-97) yields the current step, then each earlier step out to the window but never below step zero (currentStep >= offset, :88), then each later step.
    • ComputeForStep (:99-124) bounds digits to 1..9 (:101-102), writes the step as a big-endian 64-bit counter into a stack buffer (:104-105), HMAC-SHA1s it (:107-110, with a scoped CA5350 suppression whose justification is that authenticator apps speak HMAC-SHA1 and HMAC does not rely on SHA-1 collision resistance), applies the RFC 4226 section 5.3 dynamic truncation (the low nibble of the last byte picks four bytes, read big endian with the top bit cleared, :112-115), and reduces modulo 10^digits, left-padding with zeros (:117-123).
  • Why it's built this way: two-factor authentication is opt-in (ADR-116); the algorithm is internal to Infrastructure, so Application, Domain and Shared take no dependency for it and TotpTwoFactorService is its only production caller.
  • Where it's used: TotpTwoFactorService.VerifyCode (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/TwoFactor/TotpTwoFactorService.cs:88-95); checked against the RFC test vectors by MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Auth/TwoFactor/TotpRfcVectorTests.cs.
  • Caveats / not-in-source: replay inside the window is not this type's concern; it only reports the matched step, and TwoFactorAuthenticator refuses a step it already accepted.

ViewAsReadOnlyEndpointAttribute

MMCA.Common.Shared · MMCA.Common.Shared.Auth · MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/ViewAsReadOnlyEndpointAttribute.cs:18 · Level 0 · class (sealed attribute)

  • What it is: a marker for a read-only gRPC service, or a single method of one, that may be called under a view-as token. gRPC is always POST, so without this mark ViewAsGuardMiddleware refuses every view-as read that fans out over gRPC (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/ViewAsReadOnlyEndpointAttribute.cs:3-10,18).
  • Depends on: BCL Attribute; AttributeUsage(Class | Method, AllowMultiple = false, Inherited = true) (ViewAsReadOnlyEndpointAttribute.cs:17).
  • Concept introduced, an exemption the host asserts and nothing verifies. [Rubric §11, Security] assesses whether a read-only mode is enforced by construction. The guard treats a POST to a marked endpoint as safe for the HTTP METHOD rule only: any other method is still refused, ViewAs:Enabled and the grant-liveness check still apply, and the command decorator still refuses every command (ViewAsReadOnlyEndpointAttribute.cs:6-9). The remarks are candid that the mark "is an assertion the host makes, which nothing can verify", so a host applies it deliberately and only to code that performs no write; there is no exemption by content type and none for gRPC in general (:11-16). See ADR-137.
  • Walkthrough: an empty sealed class deriving from Attribute (:18).
  • Why it's built this way: it lives in Shared "so a gRPC service project can apply it without taking a reference on the API package" (ViewAsReadOnlyEndpointAttribute.cs:14-15).
  • Where it's used: read from the routed endpoint's metadata by ViewAsGuardMiddleware (MMCA.Common/Source/Presentation/MMCA.Common.API/Middleware/ViewAsGuardMiddleware.cs:119); ADC's services tests check the posture of its gRPC endpoints against it (MMCA.ADC/Tests/Services/MMCA.ADC.Services.Tests/Live/GrpcViewAsPostureTests.cs).

ClaimsPrincipalExtensions

MMCA.Common.Shared · MMCA.Common.Shared.Auth · MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/ClaimsPrincipalExtensions.cs:18 · Level 1 · class (static)

  • What it is: the one place the framework reads identity claims off a ClaimsPrincipal: the raw user-id value, the parsed user id, the caller's roles, an explicit permission claim, the refresh-session id, whether a second authentication factor was presented, whether the request comes from a view-as token, which roles were withheld pending a second factor, and the sign-in instant (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/ClaimsPrincipalExtensions.cs:6-18).

  • Depends on: AuthClaimTypes for the claim names it reads (ClaimsPrincipalExtensions.cs:27 Subject, :131 Permission, :145 SessionId, :162,181 MultiFactor, :171 ViewAsActor, :198,208 MultiFactorWithheldRole, :224 AuthTime); the solution-wide UserIdentifierType alias; BCL System.Security.Claims and System.Globalization (ClaimsPrincipalExtensions.cs:1-2).

  • Concept introduced, one reader for a claim that arrives under two names. [Rubric §11, Security] assesses whether identity resolution is correct and uniform, and [Rubric §15, Best Practices & Code Quality] assesses whether a fragile detail is centralized or copy-pasted. The trap is ASP.NET Core's inbound claim mapping. Tokens carry the user identifier in the standard sub claim only, but that single value reaches readers under two different claim types depending on which pipeline produced the principal (ClaimsPrincipalExtensions.cs:8-16):

    • the JWT bearer handler maps inbound sub onto ClaimTypes.NameIdentifier, the long http://schemas.xmlsoap.org/... URI;
    • a handler that materializes an identity straight from a token's claims leaves the raw sub in place. SessionCookieAuthenticationHandler is exactly that case: it builds new ClaimsIdentity(jwt.Claims, ...) from the decoded token (MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/SessionCookieAuthenticationHandler.cs:61-62).

    A reader that hard-codes either name works under one pipeline and silently returns "anonymous" under the other, and "silently anonymous" in an authorization path is the worst failure shape available. Routing every framework reader through FindUserIdValue makes both shapes resolve identically, and means a consumer that changes its claim mapping does not lose the current user (ClaimsPrincipalExtensions.cs:13-15). FindAuthTime applies the same two-shape rule to auth_time. Note the deliberate use of C#'s classic this-parameter extension methods here rather than the extension(T) blocks the codebase uses for DI registration: these are plain static helpers on a BCL type.

  • Walkthrough: thirteen extension methods, twelve on ClaimsPrincipal? and one on Claim?, all null-tolerant by construction (a null principal or claim yields null, empty, or false rather than throwing).

    • FindUserIdValue(this ClaimsPrincipal?) (ClaimsPrincipalExtensions.cs:26-28) is the primitive: principal?.FindFirst(AuthClaimTypes.Subject)?.Value ?? principal?.FindFirst(ClaimTypes.NameIdentifier)?.Value. Raw sub wins, the mapped NameIdentifier is the fallback, and a principal carrying neither yields null.
    • GetUserId(this ClaimsPrincipal?) (ClaimsPrincipalExtensions.cs:40-44) parses that value into the module's UserIdentifierType and returns null when the claim is absent or unparsable. It parses through IParsable<TSelf>.TryParse in CultureInfo.InvariantCulture, which the remarks justify twice over (:34-38): it matches the writer (claims are formatted invariantly) and it stays correct if the solution-wide identifier alias changes shape, so the helper does not have to be rewritten when an app moves from int to Guid.
    • GetRoleValues(this ClaimsPrincipal?) (ClaimsPrincipalExtensions.cs:60-65) returns every role value the principal carries under any of three claim types: the standard ClaimTypes.Role URI, or the raw role/roles claim an identity provider emits with inbound-claim mapping off. The remarks mark it SECURITY: it is the framework's one definition of "the caller's roles", because the narrower BCL ClaimsPrincipal.IsInRole(string) sees only the identity's own role claim type and can therefore disagree with the authorization handler about who is privileged. The rule is scoped to access decisions (ClaimsPrincipalExtensions.cs:56-57): every role read that gates access goes through here, while the UI NavMenu's BCL IsInRole calls only decide which nav links are shown, not what the caller may do. The filter itself is IsRoleClaim() (ClaimsPrincipalExtensions.cs:64).
    • IsRoleClaim(this Claim?, bool includeIdentityRoleClaimType = false) (ClaimsPrincipalExtensions.cs:85-101) is the role-claim predicate behind GetRoleValues: a null claim is not a role claim, and a claim of type ClaimTypes.Role, role or roles (compared ordinally) is one. With includeIdentityRoleClaimType set it also matches the claim type the claim's own identity names as its ClaimsIdentity.RoleClaimType, which is what ClaimsPrincipal.IsInRole(string) reads. The remarks mark it SECURITY as the one role-claim predicate, so no reader that classifies claims as roles can drift from what the authorization handler treats as a role (ClaimsPrincipalExtensions.cs:72-76); the parameter exists for a reader that removes role claims, so a role the BCL check would still see cannot stay behind (:78-83).
    • HasRole(this ClaimsPrincipal?, string) (ClaimsPrincipalExtensions.cs:109-111) is GetRoleValues().Contains(role, StringComparer.OrdinalIgnoreCase), guarded against a blank role.
    • HasPermissionClaim(this ClaimsPrincipal?, string) (ClaimsPrincipalExtensions.cs:128-131) checks for an AuthClaimTypes.Permission claim matching the given permission, independently of role. The remarks mark it SECURITY too: both authorization gates, the HTTP policy handler and the CQRS pipeline gate, read it, so a grant the minting host stored and emitted as a claim is honored identically at both boundaries; in a multi-service deployment the claim is the only way such a grant reaches a service that does not own the grant table. It is additive, never a denial: a principal without the claim still passes on a role the registry grants.
    • FindSessionId(this ClaimsPrincipal?) (ClaimsPrincipalExtensions.cs:143-147) reads the sid claim and Guid.TryParses it. The remarks make the degradation explicit (:137-141): null is an ordinary answer, not an error, because tokens issued before sid shipped carry no such claim, and every reader treats its absence as "the caller's own session is unknown". Nothing authenticates on this value.
    • HasMultiFactor(this ClaimsPrincipal?) (ClaimsPrincipalExtensions.cs:161-162) is principal?.FindFirst(AuthClaimTypes.MultiFactor) is not null. The remarks mark it SECURITY: presence is the whole test, and absence denies rather than falling back to a role check, because only the sign-in flow stamps the claim, and only after a code verified.
    • IsViewAs(this ClaimsPrincipal?) (ClaimsPrincipalExtensions.cs:170-171) is the same presence test on ViewAsActor: true means the principal comes from a view-as token and the request is read-only.
    • FindMultiFactorMethod(this ClaimsPrincipal?) (ClaimsPrincipalExtensions.cs:180-181) returns the value of the MultiFactor claim, or null when the principal carries none, for audit and UI copy such as "signed in with a recovery code".
    • GetMultiFactorWithheldRoles(this ClaimsPrincipal?) (ClaimsPrincipalExtensions.cs:195-198) returns the values of every MultiFactorWithheldRole marker in recorded order, or an empty list. The remarks are precise that a withheld role is not held: GetRoleValues and HasRole do not see it, and this member exists so a caller can say "set up two-factor authentication to use this role" instead of treating the account as one without the role (:188-192).
    • HasMultiFactorWithheldRole(this ClaimsPrincipal?) (ClaimsPrincipalExtensions.cs:207-208) is the presence test for at least one such marker.
    • FindAuthTime(this ClaimsPrincipal?) (ClaimsPrincipalExtensions.cs:222-230) reads the raw auth_time first and falls back to ClaimTypes.AuthenticationInstant, the type the JWT bearer handler's inbound claim map renames it to (:215-219), then parses whole Unix seconds into a DateTimeOffset. It returns null for a token minted before the claim shipped and for a view-as token.
  • Why it's built this way: TokenService records the other half of the story in a comment (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/TokenService.cs:145-148): a duplicate custom user-id claim used to ride alongside sub, which meant two values that could disagree and two claim names every reader had to know. Collapsing the writer to one claim (TokenService.cs:151) is only safe because one reader absorbs the mapping difference, which is this type. The sid half comes from ADR-097, the view-as test from ADR-137, and the sign-in instant from ADR-139.

  • Where it's used: broadly, and always instead of a hand-rolled claim lookup. CurrentUserService resolves the ambient user id through GetUserId() (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Context/CurrentUserService.cs:20); ClaimBasedUserIdProvider uses FindUserIdValue() to key SignalR connections (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Context/ClaimBasedUserIdProvider.cs:15); the IdempotencyFilter uses it to scope an idempotency key to a caller (MMCA.Common/Source/Presentation/MMCA.Common.API/Idempotency/IdempotencyFilter.cs:600); CurrentUserTargetingContextAccessor uses it for feature-flag targeting (MMCA.Common/Source/Presentation/MMCA.Common.API/FeatureManagement/CurrentUserTargetingContextAccessor.cs:116); the opt-in "UserPolicy" rate-limit partition keys on httpContext.User?.Identity?.Name directly rather than on GetUserId() (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/WebApplicationBuilderExtensions.RateLimiting.cs:191-197); AuthControllerBase uses FindSessionId() to tell the session list which row is the caller's own (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/AuthControllerBase.cs:296); AuthenticationServiceBase<TUser> uses GetUserId() on the principal recovered from an expired access token during rotation and FindAuthTime() to carry the sign-in instant forward (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/AuthenticationServiceBase.cs:413,443); PasskeyStepUp judges recent sign-in with FindAuthTime() (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Passkeys/PasskeyStepUp.cs:27); and TestPrincipal writes sub precisely so test principals resolve the same way real ones do (MMCA.Common/Source/Hosting/MMCA.Common.Testing.UI/Infrastructure/TestPrincipal.cs:19,27). HasPermissionClaim backs both PermissionAuthorizationHandler (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/PermissionAuthorizationHandler.cs:31) and the CQRS AuthorizationGate (MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Decorators/AuthorizationGate.cs:47); HasMultiFactor backs the multi-factor role check in MultiFactorRoleAuthorizationHandler (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/MultiFactor/MultiFactorRoleAuthorizationHandler.cs:75) and MultiFactorRoleWithholding (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/MultiFactor/MultiFactorRoleWithholding.cs:96), which also strips withheld roles through IsRoleClaim(includeIdentityRoleClaimType: true) (MultiFactorRoleWithholding.cs:72); IsViewAs backs ViewAsGuardMiddleware (MMCA.Common/Source/Presentation/MMCA.Common.API/Middleware/ViewAsGuardMiddleware.cs:58) and the view-as command decorator (MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Decorators/ViewAsCommandDecorator.cs:28); the withheld-role readers back MultiFactorRoleAuthorizationHandler (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/MultiFactor/MultiFactorRoleAuthorizationHandler.cs:67-69).

  • Caveats / not-in-source: MMCA.Store's Sales UI module defines its own unrelated ClaimsPrincipalExtensions in a different namespace (MMCA.Store/Source/Modules/Sales/MMCA.Store.Sales.UI/Extensions/ClaimsPrincipalExtensions.cs:9); do not confuse the two when reading a using list. Also note GetUserId returns a nullable value type, so is { } userId pattern-matching (as the framework's controllers use, for example MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/TwoFactor/TwoFactorControllerBase.cs:100) is the idiomatic call shape, not a ! dereference.

TotpTwoFactorService

MMCA.Common.Infrastructure · MMCA.Common.Infrastructure.Auth.TwoFactor · MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/TwoFactor/TotpTwoFactorService.cs:34 · Level 2 · class

  • What it is: the RFC 6238 TOTP implementation of ITwoFactorService: secret generation, provisioning-URI construction, code verification, and recovery-code generation/hashing/matching (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/TwoFactor/TotpTwoFactorService.cs:9-12,34-165).
  • Depends on: ITwoFactorService (the contract it implements); TwoFactorSettings injected as IOptions<TwoFactorSettings>; RecoveryCodeSet as its return shape; the internal Totp (RFC 6238 over HMAC-SHA1) and Base32 (RFC 4648) in the same folder, no third-party package; System.Security.Cryptography (RandomNumberGenerator, SHA256, CryptographicOperations.FixedTimeEquals); the BCL TimeProvider as the clock a code's time step is judged against (:33-34).
  • Concept introduced, constant-time comparison for a secret the caller does not control the timing of. [Rubric §11, Security] assesses whether the codebase avoids timing side channels around secret comparison. TryMatchRecoveryCode never exits its scan early on a match: the loop "runs to the end so the answer takes the same time whichever code in the list was presented" (TotpTwoFactorService.cs:146-147), and each comparison itself goes through CryptographicOperations.FixedTimeEquals rather than == or SequenceEqual (:148). A byte-for-byte comparison that stops at the first differing byte leaks how many leading bytes an attacker guessed correctly across repeated attempts; a fixed-time comparison over a full linear scan removes that channel entirely. The type remarks add why the recovery hash is a plain SHA-256 rather than a key derivation: the codes are high-entropy random values, not user-chosen secrets, so stretching buys nothing an attacker cannot skip and would cost a derivation per stored code on every sign-in (:14-20).
  • Walkthrough: internal sealed class with a primary constructor taking IOptions<TwoFactorSettings> settings and TimeProvider timeProvider (:34), caching .Value once (:36).
    • GenerateSecret() returns Base32.Encode of RandomNumberGenerator.GetBytes(_settings.SecretByteLength) (:39-40).
    • BuildProvisioningUri rejects a blank secret or account name, URL-escapes the issuer and account name, and formats the standard otpauth:// URI a QR code encodes: the algorithm is fixed at SHA1, while digit count and period are read from settings (:43-54). The remarks explain why it is composed in one visible place: the issuer:account label and the redundant issuer parameter, which older authenticator apps read, are part of what a user's app has to accept (:26-30).
    • VerifyCode comes in two overloads. The two-argument form is a one-line forward to the three-argument form, discarding the step (:57). The three-argument form reports the matched TOTP time step through out long matchedStep, initialized to 0 so every early false leaves it defined (:60-62). It returns false for a blank secret or code (:63-66), then decodes the stored secret with Base32.Decode, catching ArgumentException and returning false rather than throwing when the value is not valid Base32: "a stored secret that is not Base32 can never mint a code, so it verifies nothing. That is a data fault, not a caller fault" (:68-79). A secret that decodes to no key (padding alone, or fewer than eight bits) verifies false for the same reason (:81-86). It then calls Totp.Verify with the injected clock's current UTC time (timeProvider.GetUtcNow().UtcDateTime), the configured period and digit count, and a window of _settings.VerificationWindowSteps steps on each side of now, every candidate compared in fixed time, writing the step the code matched into matchedStep (:88-95), so the time step follows whichever TimeProvider the container holds. The window tolerates clock drift between the server and the user's authenticator app; the reported step is what lets TwoFactorAuthenticator refuse a replay of the same code inside that window. The secret it receives is plaintext: unprotecting the stored value is the caller's job (DataProtectionTwoFactorSecretProtector).
    • GenerateRecoveryCodes produces _settings.RecoveryCodeCount codes, each a Base32-encoded random byte string of _settings.RecoveryCodeByteLength bytes with the = padding trimmed, alongside their SHA-256 hashes computed by HashRecoveryCode (:99-115). Base32 rather than Base64: "the alphabet has no case ambiguity and no characters a user has to guess at while copying a code off paper" (:106-107). Only the hashes and the caller-facing codes are returned as a RecoveryCodeSet (:114); nothing persists the plaintext codes here.
    • HashRecoveryCode normalizes the code (keeps letters and digits, upper-cases) then SHA-256-hashes it to an upper-case hex string (:118-123).
    • TryMatchRecoveryCode normalizes and hashes the presented code once, skips null stored entries, then fixed-time-compares it against every stored hash, returning the matched hash (not the code) through an out parameter (:126-155).
    • NormalizeCode is the shared helper both verification paths route through: it strips whitespace and separators a user types or a password manager inserts and upper-cases what remains, "so a code is matched the way it was generated" (:157-164).
  • Why it's built this way: two-factor authentication is opt-in (ADR-116), registered by AddTwoFactorAuthentication(config). The one-time-password algorithm and the Base32 codec are internal Infrastructure types rather than a package, so Application, Domain and Shared take no dependency for them, and this type, rather than anything in Application, is what computes and verifies codes.
  • Where it's used: registered in DI (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Auth.cs:58, a TryAddSingleton) as the ITwoFactorService implementation behind AddTwoFactorAuthentication(config) (DependencyInjection.Auth.cs:48), which also registers TimeProvider.System with TryAddSingleton so a host that supplies its own clock keeps it (DependencyInjection.Auth.cs:57), and consumed by TwoFactorAuthenticator for both TOTP and recovery-code verification.
  • Caveats / not-in-source: internal sealed, so it is reached only through the ITwoFactorService abstraction; a consumer cannot construct or type-check against this class directly.

RoleValue

MMCA.Common.Shared · MMCA.Common.Shared.Auth · MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/RoleValue.cs:26 · Level 3 · class (abstract)

  • What it is: the abstract base for a role value object. It stores one canonical string, gives it case-insensitive value equality and hashing, and offers a shared validation helper against a per-app set of known role names (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/RoleValue.cs:6-26).

  • Depends on: Result and Error from MMCA.Common.Shared.Abstractions (RoleValue.cs:2), plus System.Collections.Frozen from the BCL (RoleValue.cs:1). Its doc comments point at RoleNames for the canonical strings (RoleValue.cs:9) and at ICurrentUserService.IsInRole for the comparison semantics it matches (RoleValue.cs:17). Conceptually a value object (see ValueObject) but deliberately not derived from that base, for a reason the next bullet unpacks.

  • Concept introduced, a value object as an abstract class with type-guarded equality. [Rubric §4, Domain-Driven Design] assesses whether identity-less concepts are modeled as value objects rather than bare primitives, and [Rubric §1, SOLID] applies to how an open hierarchy is left safe to extend. A role has no database identity: two "Organizer" values are the same role, so the type is defined by its value, which is exactly the value-object shape. Two design decisions make this base unusual, and both are written into the source:

    1. No IEquatable<T> on the base (RoleValue.cs:18-24). The remarks cite Sonar S4035: an unsealed type implementing IEquatable<T> breaks the equality contract, because a subclass instance compared through the base-typed interface can report an equality the derived type would reject. Instead equality is the plain object.Equals override, and it is type-guarded: GetType() == other.GetType() before the value comparison (RoleValue.cs:91-94), so a role of one concrete type is never equal to a same-valued role of another. A sealed derived type is then free to layer a strongly-typed IEquatable<TSelf> plus ==/!= on top, which is what ADC's UserRole does (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Domain/Users/UserRole.cs:18,78-84).
    2. It does not derive from ValueObject, and that is a fitness-rule consequence, not an oversight. ValueObjectsAreImmutableSealedInShared requires every concrete class whose base type starts with MMCA.Common.Shared.ValueObjects.ValueObject to be sealed, immutable, and to live in the Shared layer (MMCA.Common/Source/Hosting/MMCA.Common.Testing.Architecture/Rules/Domain/ArchitectureRules.Immutability.cs:56-72). A concrete role type lives in its app's Domain layer (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Domain/Users/UserRole.cs:6), so deriving from ValueObject would fail that rule in every app. Keeping the base in MMCA.Common.Shared with its own equality also keeps it dependency-free and therefore usable from Blazor WebAssembly and UI code as well as Domain (RoleValue.cs:12-17). The same trade-off is made by Enumeration<TEnumeration>, whose own remarks name RoleValue as the shipped precedent (MMCA.Common/Source/Core/MMCA.Common.Shared/ValueObjects/Enumeration.cs:34).

    [Rubric §11, Security] applies too, because role strings arrive as JWT claim values whose casing is not under this codebase's control. Every comparison here is OrdinalIgnoreCase, so an authorization check does not silently miss on "organizer" against "Organizer".

  • Walkthrough: a get-only Value (RoleValue.cs:29) assigned by the protected constructor (RoleValue.cs:33), so an instance is immutable and only a derived type can create one. The static Validate(role, knownRoles, source) (RoleValue.cs:43) null-guards the supplied set (RoleValue.cs:45), then returns Result.Success() when the role is known, otherwise a Result failure carrying an Error of kind Invariant, coded User.Role.Invalid, with the caller's method name as source and role as target (RoleValue.cs:47-53). The membership test is the private IsKnown (RoleValue.cs:64-66) and it is more careful than it first looks: the fast path is the supplied set's own Contains (correct and O(1) for the intended OrdinalIgnoreCase sets, with a role ?? string.Empty coalesce so a null role becomes a clean failure rather than a NullReferenceException), and a miss falls back to an explicit case-insensitive Any scan, so a set built with the default ordinal comparer still validates case-insensitively as the contract promises (RoleValue.cs:56-63). Role sets hold a handful of entries, so the fallback is negligible and only ever runs on a miss. The protected generic BuildLookup<TRole>(params TRole[] roles) (RoleValue.cs:76) freezes the supplied singletons into a case-insensitive FrozenDictionary keyed by Value (RoleValue.cs:81-84), so a derived type can back its FromString/IsValid members with interned instances instead of re-allocating on every parse. ToString returns the value (RoleValue.cs:88), and GetHashCode uses the ordinal-ignore-case hash (RoleValue.cs:97) so it stays consistent with Equals, which is the contract any dictionary or HashSet key depends on.

  • Why it's built this way: the abstract-class-plus-type-guard shape is how you share equality behavior across an open hierarchy of value objects without violating the equality contract, and the S4035 rationale is documented inline (RoleValue.cs:18-24) so a future reader does not "helpfully" add IEquatable<T> to the base. The comparer-agnostic IsKnown fallback exists because Validate accepts any IReadOnlySet<string>: the type cannot see how the caller built the set, so it enforces its own promise instead of trusting the caller's comparer. That behavior is pinned by test, including the default-comparer case (MMCA.Common/Tests/Core/MMCA.Common.Shared.Tests/Auth/RoleValueTests.cs:24), the OrdinalIgnoreCase case (RoleValueTests.cs:36), a null role (RoleValueTests.cs:65), and a null role set throwing (RoleValueTests.cs:73).

  • Where it's used: the two apps consume it differently, and the difference is instructive. ADC derives a full sealed value object, UserRole, which fixes three roles (Organizer, Attendee, ContentEditor), interns them through BuildLookup (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Domain/Users/UserRole.cs:21-34), exposes FromString returning a Result<UserRole> and IsValid over that frozen lookup (UserRole.cs:52-66), and adds a case-insensitive IsOrganizer for raw claim strings (UserRole.cs:76) plus the sealed-type IEquatable<UserRole> and ==/!= operators the base leaves to subclasses (UserRole.cs:78-90). Store's UserRole is a static class, not a subclass: it fixes Admin and Customer as string properties over an OrdinalIgnoreCase set and calls the shared RoleValue.Validate helper for its IsValid (MMCA.Store/Source/Modules/Identity/MMCA.Store.Identity.Domain/Users/UserRole.cs:14,26-30,37), so it inherits the rule set (case-insensitive membership, the User.Role.Invalid code) without inheriting the type. Both key their known-role sets off the RoleNames constants, and PermissionRegistryBuilder keeps its role keys on the same case-insensitive comparer to match (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Permissions/PermissionRegistryBuilder.cs:11).

DataProtectionTwoFactorSecretProtector

MMCA.Common.Infrastructure · MMCA.Common.Infrastructure.Auth.TwoFactor · MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/TwoFactor/DataProtectionTwoFactorSecretProtector.cs:15 · Level 4 · class (internal sealed)

  • What it is: the default ITwoFactorSecretProtector, which encrypts a TOTP secret at rest with the host's ASP.NET Core data-protection key ring under the purpose MMCA.Common.Auth.TwoFactor.Secret.v1 (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/TwoFactor/DataProtectionTwoFactorSecretProtector.cs:8-13,15).
  • Depends on: ITwoFactorSecretProtector (the contract); the framework's Result<T> and Error; Microsoft.AspNetCore.DataProtection (IDataProtectionProvider, IDataProtector); BCL CryptographicException.
  • Concept introduced, an unreadable secret is a result, not an exception. [Rubric §11, Security] assesses whether secrets are protected at rest; [Rubric §29, Resilience & Business Continuity] assesses whether a key-management fault degrades instead of crashing a hot path. A multi-replica host needs the shared key ring (ADR-069), or a replica cannot read a secret another one wrote, and the remarks require that this "surfaces as a failed unprotect, never as an exception" (DataProtectionTwoFactorSecretProtector.cs:10-12). Unprotect therefore returns Result<string> and maps both failure exceptions to one coded failure.
  • Walkthrough:
    • Purpose (:18), "MMCA.Common.Auth.TwoFactor.Secret.v1", documented as part of the stored format, "so it never changes" (:17); the protector is created from it once (:23).
    • SecretUnreadableCode (:21), "Authentication.TwoFactorSecretUnreadable".
    • Protect(string) (:26-30) throws on null or empty and returns the protected payload.
    • Unprotect(string) (:33-52) answers a blank input as unreadable (:35-38), returns Result.Success with the plaintext (:40-43), and catches CryptographicException (:44-47) and FormatException (:48-51) into the same failure.
    • Unreadable() (:54-58) builds Error.Unexpected(SecretUnreadableCode, "The two-factor secret cannot be unprotected with this host's key ring.", nameof(Unprotect)): the failure is classified as an unexpected, host-side condition (a key ring that cannot read the payload), not as a caller error.
  • Why it's built this way: the sign-in path treats an unreadable secret as "no time-based code can verify" and keeps the recovery codes usable, so the owner still has a way in (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/TwoFactor/TwoFactorAuthenticator.cs:77-78); that is only possible because this type answers with a Result rather than throwing.
  • Where it's used: registered with TryAddSingleton behind AddTwoFactorAuthentication(config) (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Auth.cs:62), so a host can register its own protector first; consumed by TwoFactorAuthenticator.
  • Caveats / not-in-source: Not determinable from source read for this section: which caller invokes Protect when an enrollment stores the secret; the type is referenced directly only by its DI registration and by tests.

TwoFactorAuthenticator

MMCA.Common.Infrastructure · MMCA.Common.Infrastructure.Auth.TwoFactor · MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/TwoFactor/TwoFactorAuthenticator.cs:43 · Level 5 · class

  • What it is: the ITwoFactorAuthenticator implementation that turns a raw code plus a user's stored two-factor state into one of four challenge outcomes (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/TwoFactor/TwoFactorAuthenticator.cs:43-208).
  • Depends on: ITwoFactorService (code verification and recovery-code matching); ITwoFactorStore (loading state and consuming a recovery code); ITwoFactorSecretProtector (unprotecting the stored secret before a code is verified against it); ICacheService (remembering the last accepted TOTP time step per account); TwoFactorSettings via IOptions<T> (period and window size); IDistributedLock (serializing both code paths per account); TwoFactorErrors; TwoFactorOutcome; the framework's Result<T>; the UserIdentifierType alias.
  • Concept introduced, a challenge is answered with an outcome enum, not a bare boolean. [Rubric §1, SOLID] and [Rubric §11, Security] both bear on the shape of ChallengeAsync's return: Result<TwoFactorOutcome> distinguishes "not enrolled" (a success carrying TwoFactorOutcome.NotEnrolled, not a failure) from a missing code, an invalid code, and the two ways a valid one can be accepted, VerifiedTotp versus VerifiedRecoveryCode. Collapsing those five states into one boolean would force the caller to re-derive which one happened from side effects, and a login path that cannot tell "not enrolled" from "denied" cannot decide whether to prompt for enrollment or reject the sign-in.
  • Walkthrough: internal sealed class taking ITwoFactorService, ITwoFactorStore, ITwoFactorSecretProtector, ICacheService, IOptions<TwoFactorSettings>, and IDistributedLock as primary constructor parameters (:43-49), with two static lock timings: StepLockTimeToLive of 10 seconds (:51) and StepLockWait of 5 seconds (:53). It implements ChallengeAsync(userId, code, cancellationToken) (:56-87) and VerifyEnrollmentCodeAsync (:90-105).
    • Loads the user's state from the store first (:61). If the state is missing or IsTwoFactorEnabled is false, the challenge succeeds trivially with NotEnrolled: "an account that never enrolled, and an account whose row vanished between the password check and here, are both 'nothing to challenge'" (:63-69).
    • An enrolled account with no presented code fails with TwoFactorErrors.TwoFactorRequired (:71-75).
    • The code is checked first against the stored TOTP secret, but only after secretProtector.Unprotect succeeds with a non-empty plaintext; the plaintext goes to the out long matchedStep overload of ITwoFactorService.VerifyCode, and a match is not accepted outright but handed to AcceptTimeStepOnceAsync with the step it matched (:79-84). "A stored secret this host cannot unprotect verifies no time-based code; the recovery codes stay usable, so the owner still has a way in" (:77-78).
    • Otherwise the challenge goes to RedeemRecoveryCodeOnceAsync (:86).
    • VerifyEnrollmentCodeAsync(userId, secret, code, cancellationToken) (:90-105) checks the first code of an enrollment against a candidate secret that is not yet stored. The candidate arrives protected: a blank secret, one that does not unprotect to a non-empty plaintext, or a code that fails VerifyCode against the plaintext returns false (:96-101); a match is passed through the same AcceptTimeStepOnceAsync and returns whether that step was accepted (:103-104), so the code that confirms enrollment cannot then be replayed as the first sign-in challenge.
    • The private RedeemRecoveryCodeOnceAsync (:117-151) takes the same per-account lock the time-based path takes, lock:{StepKey(userId)} with StepLockTimeToLive and StepLockWait, and answers a submission that cannot take it with TwoFactorErrors.TwoFactorInvalid (:122-128). Inside the lock it re-reads the state and fails as invalid when the account is gone, no longer enrolled, or the code matches no stored hash through ITwoFactorService.TryMatchRecoveryCode (:130-139). A match is then consumed, not just verified: store.ConsumeRecoveryCodeAsync persists the redemption, and if that persistence fails, the challenge is answered as a failure rather than a success: "letting the sign-in through would hand out a code that is still live" (:141-149). Only a persisted consumption returns VerifiedRecoveryCode. Re-reading inside the lock is what makes two concurrent redemptions of one code yield exactly one success: the second reads the state after the first spent it (:107-112).
    • The private static StepKey(userId) (:156-157) builds the per-account key twofactor:laststep:{userId} that both paths lock on (:153).
    • The private AcceptTimeStepOnceAsync makes a TOTP code single use (:167-188). It takes the distributed lock on lock:{key} (:176-178), because "the read, the compare and the write below are one critical section: without it, two submissions of one code that both read before either writes would both pass" (:174-175). A submission that cannot take the lock within the wait gets a null handle and fails with TwoFactorErrors.TwoFactorInvalid (:179-182), never a second success. Holding the handle in an await using block, it delegates to AcceptIfNewerAsync (:184-187).
    • The private AcceptIfNewerAsync(key, matchedStep, cancellationToken) (:190-207) reads the last accepted step with GetFromSharedStoreAsync, deliberately bypassing a local copy: "a step accepted on another replica must be seen here, or a replayed code would pass against a stale local copy inside its window" (:195-197). A matched step not newer than the stored one fails with TwoFactorErrors.TwoFactorInvalid (:198-201). Otherwise the step is written back with a lifetime of PeriodSeconds * (2 * VerificationWindowSteps + 2) seconds, long enough to outlast every step the verification window could still accept, and the challenge returns VerifiedTotp (:203-206).
  • Why it's built this way: this is the runtime half of the opt-in two-factor feature (ADR-116). The type remarks give the order: the time-based code is tried first because it is the ordinary path and costs one HMAC, and walking the recovery list only on failure keeps a six-digit code from being compared against the recovery hashes in the common case (TwoFactorAuthenticator.cs:15-19). Both kinds of code are made one-time inside the challenge rather than left to the caller, because a caller that forgot would leave a code live for a second sign-in (:20-26). A TOTP code would otherwise stay valid for its whole verification window, so a code seen over someone's shoulder could be replayed; remembering the last accepted step closes that window. Remembering alone is not enough under concurrency, so the read, compare and write of that step, and the match and spend of a recovery code, run under an IDistributedLock on the account's step key (ADR-108), and a submission that cannot take the lock is answered as invalid, the same shape PasswordResetTokenService uses (:27-35).
  • Where it's used: registered in DI (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Auth.cs:66, a TryAddScoped) as the ITwoFactorAuthenticator behind AddTwoFactorAuthentication(config); the resolved instance is passed to AuthenticationServiceBase<TUser>, which answers Authentication.TwoFactorRequired or mints the mfa claim depending on the outcome, mapping VerifiedTotp and VerifiedRecoveryCode to the claim's method value (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/AuthenticationServiceBase.cs:901-902).

PermissionRoleEditUnit

MMCA.Common.Infrastructure · MMCA.Common.Infrastructure.Auth.Administration · MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/Administration/PermissionRoleEditUnit.cs:22 · Level 10 · class

  • What it is: the unit that runs one edit of a role's stored grants exclusively and atomically: under a per-role distributed lock and inside one database transaction, so two administrators editing the same role cannot each diff against the rows before the other's writes, and a refusal or failure part-way through leaves no row written (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/Administration/PermissionRoleEditUnit.cs:8-14,22-72).
  • Depends on: IDistributedLock (exclusive across replicas when the host has Redis, per the summary at :9); IDbContextFactory and its ExecuteInTransactionAsync for the transactional unit; Error and Result<T> for the busy refusal; IRoleAdministrationService as the error source name.
  • Concept introduced, a read-diff-write edit made safe by a lock around a transaction. [Rubric §11, Security] assesses whether an authorization surface stays correct under concurrent use; [Rubric §8, Data Architecture] assesses whether multi-row writes are atomic. A role edit computes its grants and revokes from a read, so without exclusion two concurrent edits each diff against the pre-edit rows and one set of revokes is lost. The lock serializes edits of one role across requests and replicas, and the transaction inside it makes the read and every write one unit, so a failure result or a throw rolls back whatever was written (:33-42).
  • Walkthrough: internal sealed class with a primary constructor taking IDbContextFactory and IDistributedLock (:22).
    • RoleBusyCode (:25, "PermissionGrant.RoleBusy"): the code an edit answers when another edit of the same role holds the lock.
    • LockTimeToLive is 30 seconds (:28), "comfortably above an edit's read and handful of writes: the crash guard, not the expected hold" (:27). LockWait is 5 seconds (:31), how long a second administrator waits behind the first before being told to retry (:30).
    • RunAsync<TValue>(canonicalRole, requestedRole, edit, cancellationToken) (:43-67) null-checks the edit (:49), then calls TryAcquireAsync on the role's lock key with the TTL and wait (:51-53). A null handle answers Error.Conflict(RoleBusyCode, ...) targeted at the role as the caller named it (:54-61). Otherwise the handle is disposed by await using around dbContextFactory.ExecuteInTransactionAsync(edit, cancellationToken), whose result is returned as is (:63-66).
    • LockKey builds "lock:permission-grants:role:" plus the canonical role upper-cased, so two spellings of one role contend for one lock (:69-71).
  • Why it's built this way: the remarks state the one limit. Called from inside an already open transaction, the unit joins it, and the outer scope's commit is what makes the edit durable; the lock is released when the unit returns, so the outer scope's remaining work runs unguarded. The shipped controller calls the service directly, so that case does not arise on the shipped path (:15-18). Using the framework's lock primitive matches ADR-108.
  • Where it's used: registered with TryAddScoped beside the role administration service, "scoped with the context factory it runs each edit's transaction on" (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Auth.cs:204-205), and injected into StoredPermissionRoleAdministrationService, whose SetStoredPermissionsAsync runs every set through RunAsync (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/Administration/StoredPermissionRoleAdministrationService.cs:158-163). Exercised by MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Auth/Administration/StoredPermissionRoleAdministrationServiceTests.cs.
  • Caveats / not-in-source: internal sealed. Whether the lock is exclusive across replicas depends on the IDistributedLock implementation the host registers (Redis-backed or in-process); this type does not choose it.

StoredPermissionRoleAdministrationService

MMCA.Common.Infrastructure · MMCA.Common.Infrastructure.Auth.Administration · MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/Administration/StoredPermissionRoleAdministrationService.cs:62 · Level 11 · class

  • What it is: the IRoleAdministrationService implementation that lets an operator list roles, read or replace a role's stored permissions, and view the compiled permission catalog, layered over the code-compiled permission registry (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/Administration/StoredPermissionRoleAdministrationService.cs:62-385).
  • Depends on: IPermissionRegistry (the compiled grants); IPermissionCatalog (the closed list of declared permissions); IPermissionGrantStore (persisted grants); IPermissionGrantCache and IPermissionGrantCacheInvalidator; PermissionGrantSettings (KnownRoles) via IOptions<T>; PermissionRoleEditUnit (the per-role lock and transaction); AdministrationPermissions (ManageRoles); the framework's Result<T> and Error factories.
  • Concept introduced, a layered grant surface that refuses to let stored data override the permission that guards it. [Rubric §11, Security] assesses whether an authorization surface can be used to escalate its own access, and [Rubric §4, DDD]/[Rubric §1, SOLID] the separation between the compiled and stored halves of a permission set. A set refuses to grant AdministrationPermissions.ManageRoles from a stored row, and the error message states the two-sided reason: granting it from a data row would make access to role administration itself a matter of data, while deleting the row "would lock every operator out of the screen that could restore it" (StoredPermissionRoleAdministrationService.cs:254-263). That permission is only ever compiled in, through a host's own permission registry. A second guard bounds the operator: with a ceiling predicate supplied, every permission the set adds must be one the caller holds, or the set is refused with the users-admin ceiling's own code (:34-38, :279-289).
  • Walkthrough: constructed with the registry, catalog, store, cache, invalidator, settings and the edit unit as primary constructor parameters (:62-69).
    • ListRolesAsync groups all stored grants by role, case-insensitively (:77-82), unions the result with the compiled and configured role universes via the private RoleUniverse helper (:84), and returns one RolePermissionsResponse per role pairing its compiled permissions (CompiledPermissions) with its stored ones (:86-92).
    • GetCatalogAsync returns every known role alongside the full compiled catalog.Permissions deliberately, not whatever happens to be stored: "widening it with whatever happens to be stored would let one typo legitimize itself" (:105-107).
    • GetRoleAsync first resolves the caller's spelling through the private CanonicalRole helper (:120), reads stored and compiled permissions under that canonical name, and returns not found when the private IsKnownRole rule fails (:124-127), so "a role the host has never named ... does not exist as far as this surface is concerned" rather than being reported as an empty, plausible-looking role (rule documented at :313-317). The response echoes the canonical spelling (:129).
    • The private IsKnownRole helper is the single existence rule: a role exists when the registry compiles at least one permission for it, or when it belongs to the RoleUniverse (catalog roles, configured KnownRoles, or a role that already carries a stored grant) (:322-324).
    • SetStoredPermissionsAsync(role, permissions, callerHoldsPermission, changedBy, cancellationToken) (:133-173) takes an optional ceiling predicate (:136). It resolves one canonical spelling that every read, write, lock and invalidation uses, so a route value cased differently from the stored rows cannot write a second casing beside them, revoke nothing on a case-sensitive collation, or take a second lock beside the first (:147-150). It then hands the body to PermissionRoleEditUnit.RunAsync as a lambda that builds a SetRequest and calls ApplySetAsync (:156-165). A finally invalidates the role's permission cache only when the body reached its writes, after the unit has committed or rolled back, so the process never keeps serving a snapshot the database no longer matches; a refused or busy set wrote nothing and invalidates nothing (:152-155, :166-172).
    • The private ApplySetAsync is the body run under the lock inside one transaction (:175-183). It applies the same existence rule first, reading the role's current stored grants once (:190-197): "a set must not be the route by which a typo becomes a role", whether with an empty list (answering success for a role that does not exist) or a non-empty one (creating it). It trims and de-duplicates the desired set (:199-202), asks RefuseSet for a refusal (:204-208), then marks the writes as reached and diffs: grants what is newly desired, revokes what was dropped, returning the first store failure either way (:210-231). The writes share the unit's transaction, so a failure rolls the earlier ones back (:210). On success it returns the fresh RolePermissionsResponse keyed by the canonical role (:233-235).
    • The private RefuseSet checks the three refusals in order (:238-241): ManageRoles named (PermissionGrant.ManageRolesMustBeCompiled, checked before the catalog test so the message names the real reason, :254-263); any permission absent from catalog.Permissions, with the unknown names listed (PermissionGrant.UnknownPermission, :265-277); then, when a ceiling predicate is supplied, any added permission (the desired set minus the stored one) the caller does not hold, answered as Error.Forbidden with UserAdministration.PrivilegeCeiling and a message that names no permission (:279-289). The ceiling counts additions only because the request replaces the whole stored list, so a full-set check would stop an operator from keeping or removing a permission they do not hold (:34-38). The code is reused from the users-admin ceiling so a client handles one privilege refusal for both administration surfaces (:345-349).
    • The private RoleUniverse helper unions the compiled catalog's roles, the configured KnownRoles, and whatever roles the store's own rows name, case-insensitively and sorted (:299-306).
    • The private CompiledPermissions helper reads "through the SAME registry the authorization path uses" and subtracts what the cache already reports, so the two lists a role response carries stay disjoint (:360-371).
    • The private CanonicalRole helper trims the name and looks it up case-insensitively in the RoleUniverse (catalog spelling first, then configured KnownRoles); a role named only by stored rows keeps the caller's trimmed spelling and the store folds it to the stored one (:330-343).
  • Why it's built this way: ADR-116 documents AddStoredPermissionGrants(config) as the opt-in that layers a PermissionGrant table over the compiled registry; MMCA.Common/CLAUDE.md's Authorization section describes the same union-only layering through LayeredPermissionRegistry "without changing the decorators' contract", the principle this service's ManageRoles refusal exists to protect. The type remarks give the reason for the edit unit: the diff is computed from a read, so two concurrent edits of one role would each diff against the rows before the other's writes and one set of revokes would be lost; a set that cannot take the lock within its wait answers PermissionGrant.RoleBusy (409) (:47-52). A set stays a diff rather than a truncate-and-insert, so an unchanged submission writes nothing and the GrantedAt stamps of untouched rows survive (:41-44).
  • Where it's used: registered in DI (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Auth.cs:206, a TryAddScoped) behind AddStoredPermissionGrants(config) (DependencyInjection.Auth.cs:183) as the IRoleAdministrationService implementation; consumed through RolesAdminControllerBase, which is itself gated on AdministrationPermissions.ManageRoles (MMCA.Common/CLAUDE.md, "Identity completions" section).
  • Caveats / not-in-source: internal sealed, so it is reached only through the IRoleAdministrationService abstraction. Which predicate a caller passes as callerHoldsPermission is decided by the controller, not here: Not determinable from this type's source.

CreateMachineClientRequest

MMCA.Common.Shared · MMCA.Common.Shared.Auth.MachineClients · MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/MachineClients/CreateMachineClientRequest.cs:15 · Level 0 · record (sealed)

  • What it is: the body of the create-machine-client call: a Name, the Role the service-account user behind the client is created with, and an optional SecretExpiresOn (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/MachineClients/CreateMachineClientRequest.cs:3-15).
  • Depends on: nothing first-party; BCL DateTime.
  • Concept: a machine client is a program that authenticates with a client id and secret (the OAuth client credentials grant) and acts as a dedicated service-account user (ADR-140). [Rubric §11, Security] assesses least privilege: the request carries a role rather than a permission list, so the client's tokens carry exactly that role's permissions, and the doc comment records that a role granting users:view-as, users:manage, roles:manage or clients:manage is refused (CreateMachineClientRequest.cs:7-11).
  • Walkthrough: three positional members (CreateMachineClientRequest.cs:15): Name, documented as 1 to 100 characters (:6); Role (:7-11); SecretExpiresOn, a UTC instant, defaulting to null for no expiry (:12-14).
  • Why it's built this way: the refusal list in the comment is enforced server-side by MachineClientService's ForbiddenPermissions, which names the matching AdministrationPermissions constants (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/MachineClients/MachineClientService.cs:58-63), so a program can never be minted with the power to create more programs or impersonate staff.
  • Where it's used: the [FromBody] of MachineClientsControllerBase.CreateAsync (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/MachineClients/MachineClientsControllerBase.cs:78-79), passed on to IMachineClientService; sent from the UI by MachineClientAdmin through MachineClientAdminService (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Administration/MachineClientAdminService.cs).

MachineClientResponse

MMCA.Common.Shared · MMCA.Common.Shared.Auth.MachineClients · MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/MachineClients/MachineClientResponse.cs:15 · Level 0 · record (sealed)

  • What it is: one machine client as the administration surface lists it: its ClientId, Name, ServiceAccountUserId, CreatedOn, SecretExpiresOn, RevokedOn, LastUsedOn and HasSecondarySecret (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/MachineClients/MachineClientResponse.cs:3-23).
  • Depends on: the UserIdentifierType alias for ServiceAccountUserId (MachineClientResponse.cs:18, see the primer on identifier-type aliases); BCL Guid, DateTime.
  • Concept: the read model of a machine client (ADR-140). [Rubric §11, Security] assesses data minimization on admin surfaces: the secret hashes are deliberately absent, because nothing an operator does with a client needs them (MachineClientResponse.cs:3-6).
  • Walkthrough: eight positional members (MachineClientResponse.cs:15-23). ClientId is the value a program presents as client_id (:7); the three nullable instants mean "no expiry", "still active" and "never used" when null (:11-13); HasSecondarySecret says a rotated secret is waiting to be promoted (:14), which is the state an operator needs to see between a rotate and a promote.
  • Why it's built this way: a flat, hash-free projection lets the same record answer list, promote and revoke, and be nested inside MachineClientSecretResponse when a secret is issued.
  • Where it's used: built by MachineClientService's private ToResponse (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/MachineClients/MachineClientService.cs:268) and returned from it (MachineClientService.cs:237,265); listed by MachineClientsControllerBase.GetAllAsync (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/MachineClients/MachineClientsControllerBase.cs:52-56); rendered by MachineClientAdmin.

MachineTokenErrorResponse

MMCA.Common.Shared · MMCA.Common.Shared.Auth.MachineClients · MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/MachineClients/MachineTokenErrorResponse.cs:11 · Level 0 · record (sealed)

  • What it is: the error body of POST auth/token in the RFC 6749 section 5.2 shape, a single error member, plus the three error codes the endpoint can send (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/MachineClients/MachineTokenErrorResponse.cs:5-21).
  • Depends on: nothing first-party; System.Text.Json.Serialization.JsonPropertyNameAttribute (MachineTokenErrorResponse.cs:1).
  • Concept: speaking a standard's wire format. [Rubric §9, API & Contract Design] assesses whether contracts follow the conventions their clients expect: an OAuth client library parses {"error": "..."}, so the property is pinned to the snake-case name with [property: JsonPropertyName("error")] (MachineTokenErrorResponse.cs:11) rather than left to the host's camel-case policy. [Rubric §11, Security] applies too: no error_description is sent, so a refusal never says which half of the credential was wrong (MachineTokenErrorResponse.cs:8).
  • Walkthrough: the positional Error (:11) and three public const string codes: InvalidClient ("invalid_client", :14) for an unknown, revoked, expired, wrong-secret or refused-role client; UnsupportedGrantType ("unsupported_grant_type", :17) for any grant other than client_credentials; InvalidRequest ("invalid_request", :20) when no grant type is sent.
  • Why it's built this way: collapsing every authentication failure into invalid_client keeps the endpoint from acting as an oracle for which client ids exist (ADR-140).
  • Where it's used: MachineTokenControllerBase maps MachineClientErrors codes to 400 with UnsupportedGrantType or InvalidRequest, and every other failure to 401 with InvalidClient (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/MachineClients/MachineTokenControllerBase.cs:120-130).

MachineTokenResponse

MMCA.Common.Shared · MMCA.Common.Shared.Auth.MachineClients · MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/MachineClients/MachineTokenResponse.cs:13 · Level 0 · record (sealed)

  • What it is: the success body of POST auth/token for the client credentials grant, in the RFC 6749 section 5.1 shape: access_token, token_type, expires_in (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/MachineClients/MachineTokenResponse.cs:5-16).
  • Depends on: nothing first-party; JsonPropertyNameAttribute (MachineTokenResponse.cs:1).
  • Concept: the success sibling of MachineTokenErrorResponse, with the same standard-wire-name reasoning ([Rubric §9, API & Contract Design]). There is deliberately no refresh token: a program holds its secret and asks again (MachineTokenResponse.cs:6-8).
  • Walkthrough: three positional members, each pinned to its snake-case name (MachineTokenResponse.cs:14-16): AccessToken, the signed token; TokenType, always Bearer (:11); ExpiresIn, the lifetime in seconds as an int (:12).
  • Why it's built this way: omitting a refresh token removes a long-lived credential from the machine flow, since the client secret already lets the program mint a new access token (ADR-140).
  • Where it's used: built by MachineClientService with "Bearer" and the configured lifetime in whole seconds (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/MachineClients/MachineClientService.cs:125); returned by MachineTokenControllerBase (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/MachineClients/MachineTokenControllerBase.cs:50).

PasskeyOptionsResponse

MMCA.Common.Shared · MMCA.Common.Shared.Auth.Passkeys · MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Passkeys/PasskeyOptionsResponse.cs:20 · Level 0 · record (sealed)

  • What it is: the first leg of a passkey ceremony: a FlowId and the WebAuthn Options the browser hands to navigator.credentials.create (registration) or navigator.credentials.get (sign-in) (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Passkeys/PasskeyOptionsResponse.cs:5-20).
  • Depends on: nothing first-party; System.Text.Json.JsonElement (PasskeyOptionsResponse.cs:1).
  • Concept introduced, the two-leg WebAuthn ceremony. Passkeys (ADR-139) are public-key credentials held by the user's device. The server first issues a random challenge wrapped in options (this record), the browser has the authenticator sign it, and a second request (PasskeyRegisterRequest or PasskeySignInRequest) sends the result back naming the same flow. [Rubric §11, Security] assesses replay resistance: the challenge behind FlowId is kept for five minutes and burned on the first completion, so a replayed completion is refused even when its signature is valid (PasskeyOptionsResponse.cs:9-13).
  • Walkthrough: FlowId, the opaque handle of the stored challenge (:15); Options, a raw JsonElement in the PublicKeyCredentialCreationOptionsJSON or PublicKeyCredentialRequestOptionsJSON shape with binary members base64url-encoded (:16-19).
  • Why it's built this way: carrying the options as a JsonElement passes the WebAuthn library's JSON straight through to the browser without a parallel C# model of the spec's option tree.
  • Where it's used: built by PasskeyService for both ceremonies (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Passkeys/PasskeyService.cs:68,190); returned by PasskeysControllerBase BeginRegistrationAsync and BeginSignInAsync (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Passkeys/PasskeysControllerBase.cs:65-69,233-236); consumed in the UI by AuthUIService (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/AuthUIService.cs).

PasskeyRegisterRequest

MMCA.Common.Shared · MMCA.Common.Shared.Auth.Passkeys · MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Passkeys/PasskeyRegisterRequest.cs:18 · Level 0 · record (sealed)

  • What it is: the second leg of a passkey registration: the FlowId the options were issued under, the browser's attestation as Credential, and an optional Name (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Passkeys/PasskeyRegisterRequest.cs:5-18).
  • Depends on: nothing first-party; JsonElement (PasskeyRegisterRequest.cs:1).
  • Concept: the completion half of the ceremony taught on PasskeyOptionsResponse.
  • Walkthrough: FlowId (:9); Credential, the PublicKeyCredential from navigator.credentials.create in the RegistrationResponseJSON shape (:10-13); Name, a label such as "Work laptop", defaulting to null, where a blank name becomes a default label (:14-18).
  • Why it's built this way: the credential stays raw JSON for the same pass-through reason as the options; the name is optional so registration never blocks on a label.
  • Where it's used: the [FromBody] of the PasskeysControllerBase registration completion (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Passkeys/PasskeysControllerBase.cs:119), handled by PasskeyService; sent from PasskeysPanel.

PasskeyRenameRequest

MMCA.Common.Shared · MMCA.Common.Shared.Auth.Passkeys · MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Passkeys/PasskeyRenameRequest.cs:5 · Level 0 · record (sealed)

  • What it is: renames one of the caller's passkeys; a single Name, documented as 1 to 100 characters after trimming (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Passkeys/PasskeyRenameRequest.cs:3-5).
  • Depends on: nothing.
  • Concept: see PasskeyOptionsResponse for the passkey model (ADR-139).
  • Walkthrough: one positional member, Name (PasskeyRenameRequest.cs:5); the passkey is addressed by the route, using PasskeyResponse.Id.
  • Where it's used: the [FromBody] of the PasskeysControllerBase rename action (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Passkeys/PasskeysControllerBase.cs:178); sent by AuthUIService (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/AuthUIService.cs).

PasskeyResponse

MMCA.Common.Shared · MMCA.Common.Shared.Auth.Passkeys · MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Passkeys/PasskeyResponse.cs:15 · Level 0 · record (sealed)

  • What it is: one row of the caller's passkey list: Id, Name, CreatedOn, LastUsedOn (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Passkeys/PasskeyResponse.cs:3-15).
  • Depends on: nothing first-party; BCL Guid, DateTime.
  • Concept: a sanitized projection of PasskeyCredential. [Rubric §11, Security] assesses data minimization: the credential id, the public key and the sign count are absent on purpose, because nothing a client does with a passkey row needs them and the list stays useless to anyone reading it over the user's shoulder (PasskeyResponse.cs:6-9).
  • Walkthrough: four positional members (PasskeyResponse.cs:15): Id, the row identifier that rename and delete are addressed to (:11); Name (:12); CreatedOn (:13); LastUsedOn, null if the passkey never signed the user in (:14).
  • Where it's used: built by PasskeyService's private ToResponse (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Passkeys/PasskeyService.cs:220) and returned after register and rename (PasskeyService.cs:114,144); listed by PasskeysControllerBase.ListAsync (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Passkeys/PasskeysControllerBase.cs:146-149); rendered by PasskeysPanel.

PasskeySignInRequest

MMCA.Common.Shared · MMCA.Common.Shared.Auth.Passkeys · MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Passkeys/PasskeySignInRequest.cs:15 · Level 0 · record (sealed)

  • What it is: the second leg of a passkey sign-in: the FlowId the options were issued under and the browser's assertion as Credential (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Passkeys/PasskeySignInRequest.cs:5-15).
  • Depends on: nothing first-party; JsonElement (PasskeySignInRequest.cs:1).
  • Concept: the completion half of the ceremony taught on PasskeyOptionsResponse. The request is anonymous and carries no email or user id: a discoverable credential carries its own user handle, so the credential itself names the account (PasskeySignInRequest.cs:6-8).
  • Walkthrough: FlowId (:10); Credential, the PublicKeyCredential from navigator.credentials.get in the AuthenticationResponseJSON shape (:11-14).
  • Where it's used: the [FromBody] of the PasskeysControllerBase sign-in completion (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Passkeys/PasskeysControllerBase.cs:264), handled by PasskeyService; sent from PasskeySignInButton (MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Auth/PasskeySignInButton.razor.cs).

OidcDiscoveryResponse

MMCA.Common.Shared · MMCA.Common.Shared.Auth.ExternalProviders · MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/ExternalProviders/OidcDiscoveryResponse.cs:10 · Level 0 · record (sealed, positional)

  • What it is: the home-realm discovery answer from GET auth/oauth/discover?email=: the configured OIDC provider whose Domains list holds the address's domain. The sign-in page then starts the challenge at auth/oauth/{Provider} (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/ExternalProviders/OidcDiscoveryResponse.cs:3-7,10).
  • Depends on: nothing; two string members, Provider (the provider name, which is also its scheme name and route segment) and DisplayName (the name shown to the user, :8-9).
  • Concept introduced: none new; it belongs to the external-login flow of ADR-036. [Rubric §9, API & Contract Design] applies: the response carries only the two values the sign-in page needs to route the user, not the provider's configuration.
  • Walkthrough: a one-line positional record (OidcDiscoveryResponse.cs:10).
  • Where it's used: returned by DiscoverOidcProvider on OAuthControllerBase (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/OAuthControllerBase.cs:179-186) and read by OidcDiscoveryUIService for the login page.

OidcReservedProviderNames

MMCA.Common.Shared · MMCA.Common.Shared.Auth.ExternalProviders · MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/ExternalProviders/OidcReservedProviderNames.cs:12 · Level 0 · class (static)

  • What it is: the list of names a generic OIDC provider section (OAuth:Oidc:<Name>) may not take, compared ignoring case: the three built-in providers and the literal route segments of the external sign-in controller under auth/oauth/ (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/ExternalProviders/OidcReservedProviderNames.cs:5-12).
  • Depends on: nothing first-party; BCL System.Collections.Frozen.FrozenSet and StringComparer.OrdinalIgnoreCase (OidcReservedProviderNames.cs:1,15-17).
  • Concept: none new; it belongs to the external-login flow of ADR-036, where a configured OIDC provider's section name is also its scheme name and its auth/oauth/{provider} route segment (see OidcDiscoveryResponse). [Rubric §15, Best Practices & Code Quality] assesses whether one rule lives in one place: the API and the UI both read this single list, so the two halves cannot disagree about which names are usable (OidcReservedProviderNames.cs:9-10).
  • Walkthrough: All (:15-17), an IReadOnlySet<string> built once as a frozen set of six names with an ordinal ignore-case comparer: google, github, apple (the built-in providers, whose literal routes and schemes already exist) and complete, exchange, discover (controller route segments that would shadow a provider's challenge route, :6-9). IsReserved(name) (:22) is a membership test against All.
  • Why it's built this way: an OIDC provider named, say, discover would register a challenge route that collides with the literal GET auth/oauth/discover action (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/OAuthControllerBase.cs:176), and one named google would collide with the built-in scheme and route (OAuthControllerBase.cs:117). Refusing the name at configuration time turns that collision into a startup error rather than a sign-in button that routes to the wrong action. A frozen set suits a list that never changes after startup and is read on every check.
  • Where it's used: OidcProviderSettings throws InvalidOperationException at startup for a reserved section name (MMCA.Common/Source/Presentation/MMCA.Common.API/Authentication/OidcProviderSettings.cs:74-78); ConfigurationOAuthUISettings skips a reserved section when it builds the sign-in options (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/OAuth/ConfigurationOAuthUISettings.cs:51-53). OidcReservedProviderNamesTests pins the list to the controller by reflecting over every non-parameterized [Http*] template on OAuthControllerBase (the three built-in provider routes included) and asserting the set equals All, so adding a literal route without reserving it fails that test (MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/Controllers/Auth/OidcReservedProviderNamesTests.cs:18-29).

MachineClientSecretResponse

MMCA.Common.Shared · MMCA.Common.Shared.Auth.MachineClients · MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/MachineClients/MachineClientSecretResponse.cs:13 · Level 1 · record (sealed)

  • What it is: a machine client together with a secret just issued for it: the answer to a create (the primary secret) or a rotate (the secondary secret) (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/MachineClients/MachineClientSecretResponse.cs:3-13).
  • Depends on: MachineClientResponse.
  • Concept: show-once secrets. [Rubric §11, Security] assesses credential storage: only the secret's SHA-256 hash is stored, so this response is the only place the plaintext ever appears, and a client that loses it rotates (MachineClientSecretResponse.cs:6-9).
  • Walkthrough: two positional members (MachineClientSecretResponse.cs:13): Client, the hash-free client row, and ClientSecret, base64url-encoded (:12).
  • Why it's built this way: wrapping rather than extending MachineClientResponse keeps the plaintext out of every other response shape, so no list or detail endpoint can leak it by accident (ADR-140).
  • Where it's used: built by MachineClientService on create and rotate (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/MachineClients/MachineClientService.cs:182,218); returned by MachineClientsControllerBase CreateAsync and RotateAsync (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/MachineClients/MachineClientsControllerBase.cs:73-78,104-109); shown once by MachineClientAdmin.

AdministrationPermissions

MMCA.Common.Shared · MMCA.Common.Shared.Auth.Permissions · MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Permissions/AdministrationPermissions.cs:15 · Level 0 · class (static)

  • What it is: the seven permission-string constants the framework's own opt-in administration controller bases gate on: ManageUsers ("users:manage"), ManageRoles ("roles:manage"), ViewAsUsers ("users:view-as"), ManageFeatures ("features:manage"), ManageClients ("clients:manage"), ViewAuditTrail ("audit:view") and ManageWebhooks ("webhooks:manage") (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Permissions/AdministrationPermissions.cs:15-55).
  • Depends on: nothing first-party; it is a plain const string holder consumed by the permission-authorization pipeline. Its doc comment points at IPermissionRegistry and PermissionRegistryBuilder as the way these names are granted (AdministrationPermissions.cs:3-7).
  • Concept introduced, the framework shipping its own permission vocabulary for the administration surface it also ships. [Rubric §11, Security] assesses the authorization model for built-in capabilities. The administration controller bases are framework code, so they need permission names that exist before any consuming app declares its own; these constants are those names, defined once so the base controllers and every host that wires a role to them agree on the string. They follow the same area:capability naming as a host's own permissions, and the remarks record the failure direction: a host that mounts one of the bases but grants none of these permissions serves endpoints that deny everyone (AdministrationPermissions.cs:3-14).
  • Walkthrough: seven public const string fields, each documented with the operation it gates (AdministrationPermissions.cs:17-54): ManageUsers (:18) for listing, inspecting, locking, unlocking and re-roling accounts; ManageRoles (:21) for listing roles and editing their stored permission grants; ViewAsUsers (:27) for read-only view-as of another account for at most 15 minutes, where an account holding it can never itself be viewed, so staff cannot view each other; ManageFeatures (:33) for listing feature flags and setting or clearing their stored overrides; ManageClients (:40) for creating, rotating, promoting and revoking machine clients, documented as to be granted as sparingly as ManageUsers because creating a client creates a service-account user; ViewAuditTrail (:46) for reading recorded entity change history; and ManageWebhooks (:54) for the outbound webhook subscription lifecycle, documented as to be granted as sparingly as the data the subscribed events carry.
  • Why it's built this way: part of the opt-in identity completions (ADR-116), extended by each later opt-in surface: view-as (ADR-137), feature-flag overrides (ADR-031), machine clients (ADR-140), the audit trail (ADR-075) and outbound webhooks (ADR-142). Naming them in the framework is what lets each shared controller base carry its own [HasPermission] attribute, so a host adopting a built-in screen grants a role the constant rather than inventing its own string (AdministrationPermissions.cs:9-14).
  • Where it's used: the controller bases carry them as class or action attributes: RolesAdminControllerBase (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Administration/RolesAdminControllerBase.cs:68), UsersAdminControllerBase<TUserDto> (ManageUsers at MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Administration/UsersAdminControllerBase.cs:67, ViewAsUsers on its view-as action at UsersAdminControllerBase.cs:161), ViewAsGrantsAdminControllerBase (ViewAsGrantsAdminControllerBase.cs:39), FeatureFlagsControllerBase (FeatureFlagsControllerBase.cs:37), AuditHistoryControllerBase (AuditHistoryControllerBase.cs:47), MachineClientsControllerBase (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/MachineClients/MachineClientsControllerBase.cs:41) and WebhookSubscriptionsControllerBase (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Webhooks/WebhookSubscriptionsControllerBase.cs:39). MachineClientService refuses a client role that grants ViewAsUsers, ManageUsers, ManageRoles or ManageClients (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/MachineClients/MachineClientService.cs:58-63); ViewAsService checks ViewAsUsers on the subject's role (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/ViewAs/ViewAsService.cs:193); StoredPermissionRoleAdministrationService refuses to grant ManageRoles through a stored row, since it guards the role-administration surface itself (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/Administration/StoredPermissionRoleAdministrationService.cs:256-260), and RoleAdminEdit.razor.cs disables that permission in the edit UI for the same reason (MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Administration/RoleAdminEdit.razor.cs:260,272). In ADC, IdentityPermissions aliases ManageUsers, ManageRoles, ViewAsUsers and ManageClients (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Shared/Authorization/IdentityPermissions.cs:26,41,52,64), IdentityPermissionGrants grants ViewAuditTrail (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Shared/Authorization/IdentityPermissionGrants.cs:50), and IdentityUIModule uses ManageUsers and ManageClients as the RequiredPermission of its Support Access and Machine Clients nav entries (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.UI/IdentityUIModule.cs:39,44).

IPermissionCatalog

MMCA.Common.Shared · MMCA.Common.Shared.Auth.Permissions · MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Permissions/IPermissionCatalog.cs:24 · Level 0 · interface

  • What it is: the read-only enumeration half of the permission model: every role the compiled registry grants something to, and every permission it grants to anyone, both sorted ordinally (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Permissions/IPermissionCatalog.cs:24-31).
  • Depends on: nothing first-party; it is a companion abstraction to IPermissionRegistry.
  • Concept introduced, separating "does this role grant that permission" from "what roles and permissions exist at all". [Rubric §1, SOLID] applies to interface segregation: IPermissionRegistry answers a per-request authorization question, IPermissionCatalog answers an administration-screen enumeration question, and a consumer that only needs to render a permission-grant matrix does not have to depend on the authorization interface at all.
  • Walkthrough: two get-only properties, Roles and Permissions, both IReadOnlyList<string>.
  • Why it's built this way: PermissionRegistry already holds the closed set of roles and permissions compiled into the host, so the catalog is a second, narrower interface the same class implements explicitly, rather than a second source of truth that could drift.
  • Where it's used: implemented explicitly by PermissionRegistry; read by StoredPermissionRoleAdministrationService (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/Administration/StoredPermissionRoleAdministrationService.cs), PermissionCatalogResponse (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Responses/PermissionCatalogResponse.cs), and AuthorizationExtensions (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/AuthorizationExtensions.cs); registered alongside IPermissionRegistry in both MMCA.Common.Application and MMCA.Common.Infrastructure DependencyInjection.cs.

IPermissionRegistry

MMCA.Common.Shared · MMCA.Common.Shared.Auth.Permissions · MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Permissions/IPermissionRegistry.cs:14 · Level 0 · interface

  • What it is: the abstraction that maps roles to the fine-grained permissions they grant, and the single place that knows which roles confer which capabilities (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Permissions/IPermissionRegistry.cs:3-14).
  • Depends on: nothing first-party; its remarks reference RoleNames for the case-insensitivity rule.
  • Concept introduced, permission (capability) authorization over role checks. [Rubric §11, Security] assesses the authorization model, and [Rubric §1, SOLID] assesses dependency inversion: endpoints depend on an abstraction, not on a role name. Instead of scattering [Authorize(Roles = "Organizer")] across endpoints, code authorizes against a permission (a capability such as sessions:manage) and this registry translates a principal's roles into the permissions they hold. The payoff is decoupling: adding a role or reshaping who-can-do-what is a registry change, not an edit to every endpoint (IPermissionRegistry.cs:4-7). The remarks also fix the comparison rules (IPermissionRegistry.cs:9-13): role lookups are case-insensitive, permission values are compared ordinally, and implementations are expected to be immutable and thread-safe. Those three sentences are what let the implementation be a frozen, lock-free structure.
  • Walkthrough: two members. GetPermissions(string role) (IPermissionRegistry.cs:21) returns the permission set for a role, or an empty set for an unknown role, never a throw (IPermissionRegistry.cs:16-18). HasPermission(IEnumerable<string> roles, string permission) (IPermissionRegistry.cs:29) answers whether any of a principal's roles grants the permission: the hot path the authorization handler calls per request.
  • Why it's built this way: ADR-020 records the decision. An empty-set-on-miss contract keeps callers branchless, and pushing the who-grants-what knowledge behind one interface is the capability-security expression of the framework's habit of hiding decision logic behind an abstraction.
  • Where it's used: implemented by PermissionRegistry (built via PermissionRegistryBuilder); registered as a lazily-built singleton by AuthorizationExtensions (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/AuthorizationExtensions.cs:78) and injected into PermissionAuthorizationHandler (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/PermissionAuthorizationHandler.cs:14).

PermissionRegistry

MMCA.Common.Shared · MMCA.Common.Shared.Auth.Permissions · MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Permissions/PermissionRegistry.cs:16 · Level 1 · class (sealed)

  • What it is: the immutable, thread-safe implementation of IPermissionRegistry and, since the catalog interface shipped, of IPermissionCatalog too, backed by a frozen role-to-permissions map (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Permissions/PermissionRegistry.cs:16-20).
  • Depends on: IPermissionRegistry and IPermissionCatalog; System.Collections.Frozen (FrozenDictionary and FrozenSet, BCL, PermissionRegistry.cs:1).
  • Concept introduced, Frozen* collections for read-optimized immutable lookups. [Rubric §12, Performance & Scalability] assesses hot-path data-structure choices. A FrozenDictionary or FrozenSet pays a higher one-time construction cost in exchange for faster repeated reads and no mutation support, which is exactly the authorization access pattern: built once at startup, queried on every authorized request, never written again. Immutability is also what makes the structure lock-free under concurrency, satisfying the interface's thread-safety expectation without a lock. The registry pins the interface's two comparison rules into the data structure itself: the outer dictionary uses StringComparer.OrdinalIgnoreCase so role lookups are case-insensitive, while each permission set uses StringComparer.Ordinal so permission values must match exactly (PermissionRegistry.cs:34-37).
  • Walkthrough: a shared empty FrozenSet sentinel and the frozen map field, plus two IReadOnlyList<string> backing fields for the catalog, _roles and _permissions (PermissionRegistry.cs:19-23). The constructor (PermissionRegistry.cs:30) guards its argument, freezes the supplied map with the two comparers (PermissionRegistry.cs:34), then materializes _roles (the map's keys, ordinally sorted) and _permissions (every permission across every role, deduplicated and ordinally sorted) once, at construction (PermissionRegistry.cs:41-48); the comment explains why: the registry is immutable, so computing the sorted lists once avoids re-sorting the whole map on every request an administration screen makes. Roles and Permissions (PermissionRegistry.cs:55,58) implement IPermissionCatalog explicitly, with a comment explaining that the catalog's Permissions and the registry's GetPermissions(role) answer different questions, so a caller holding the concrete type should not have to tell them apart (also Sonar CA1721); the catalog is meant to be consumed through the IPermissionCatalog interface. GetPermissions (PermissionRegistry.cs:61-65) returns the matching set, or the shared sentinel on a null or unknown role, so it never allocates and never throws: the empty-set-on-miss contract from the interface, made literal. HasPermission (PermissionRegistry.cs:67) guards its inputs (PermissionRegistry.cs:70-71), then walks the principal's roles and returns on the first role whose set contains the permission (PermissionRegistry.cs:73-83), so the common case of a matching first role costs one dictionary probe and one set probe.
  • Why it's built this way: freezing at construction trades a one-time build cost for fast, allocation-free, lock-free concurrent reads, which suits a startup-built structure hit on every authorized request (ADR-020). Adding IPermissionCatalog to the same class rather than a second type means the administration screen's "what roles and permissions exist" question is answered from the exact data structure the authorization question is answered from, so the two cannot drift apart.
  • Where it's used: constructed by PermissionRegistryBuilder.Build and registered as the IPermissionRegistry singleton in AuthorizationExtensions (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/AuthorizationExtensions.cs:76-78); read by PermissionAuthorizationHandler (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/PermissionAuthorizationHandler.cs:15,43); its IPermissionCatalog side is read by StoredPermissionRoleAdministrationService and exposed through PermissionCatalogResponse.

PermissionRegistryBuilder

MMCA.Common.Shared · MMCA.Common.Shared.Auth.Permissions · MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Permissions/PermissionRegistryBuilder.cs:8 · Level 2 · class (sealed)

  • What it is: a mutable accumulator that collects role-to-permission grants and freezes them into an immutable PermissionRegistry (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Permissions/PermissionRegistryBuilder.cs:3-8).
  • Depends on: PermissionRegistry, its build target.
  • Concept introduced, the builder pattern for multi-module contribution. [Rubric §2, Design Patterns] assesses idiomatic pattern use and [Rubric §7, Microservices Readiness] assesses whether a module can declare only what it owns. The builder separates the accumulation phase (mutable, order-independent, contributed to by many modules during startup) from the finished phase (an immutable snapshot read by every request). The property that makes it work for a modular monolith is in the doc comment (PermissionRegistryBuilder.cs:5-6): multiple modules may grant permissions for the same role and the grants are unioned, so a module never needs to know what the others granted, and load order does not change the result.
  • Walkthrough: a case-insensitive backing Dictionary<string, HashSet<string>> (PermissionRegistryBuilder.cs:14-15), preceded by a comment (PermissionRegistryBuilder.cs:10-12) that explains the scoped IDE0028 suppression: a collection expression cannot carry the OrdinalIgnoreCase comparer that keeps role keys case-insensitive, and the concrete Dictionary type is kept for CA1859. A private _built flag (PermissionRegistryBuilder.cs:18) records whether the builder has been sealed. Grant(role, params permissions) (PermissionRegistryBuilder.cs:32) guards its inputs (:34-35), throws InvalidOperationException if Build() has already run (:37-41), filters blank permissions (:43), then either unions into the existing set or seeds a new ordinal HashSet (:45-52), and returns this for chaining (:54): additive and idempotent, so a duplicate grant from a second module is a no-op. Build() (PermissionRegistryBuilder.cs:62) first sets _built (:64), then projects the grants into an IReadOnlyDictionary<string, IReadOnlySet<string>> (keeping the case-insensitive comparer) and hands it to the PermissionRegistry constructor (PermissionRegistryBuilder.cs:65-70). Its doc comment states the contract: building seals the builder, and building again returns an equal registry (PermissionRegistryBuilder.cs:57-60).
  • Why it's built this way: mutable while assembling, immutable once built is the safe way to let independent modules compose one shared authorization table at startup without any shared mutable state at runtime. The seal exists because, per the Grant exception doc, the built registry shares the builder's sets, so a late grant would silently change a registry that promises to be immutable, and in a host it would mean a module contributed its grants after the registry was first resolved (PermissionRegistryBuilder.cs:27-31).
  • Where it's used: AuthorizationExtensions registers exactly one builder instance and a lazily-built singleton registry over it, so the registry is materialized on first resolve, after every module has contributed (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/AuthorizationExtensions.cs:191-214); modules reach it through AddPermissions(...), which is deliberately safe to call once per module (AuthorizationExtensions.cs:108-123). MMCA.ADC's Conference, Engagement, Identity and Notification modules each pass their Shared-project grant map to it (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.API/DependencyInjection.cs:43, MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.API/DependencyInjection.cs:60, MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/DependencyInjection.cs:44, MMCA.ADC/Source/Modules/Notification/MMCA.ADC.Notification.API/DependencyInjection.cs:45), and the token-minting Identity service applies all four maps to its own builder so the permission claims it mints cover every module (MMCA.ADC/Source/Services/MMCA.ADC.Identity.Service/Authorization/TokenPermissionGrants.cs:16-24,44-45).
  • Caveats / not-in-source: the seal is a runtime check, not a compile-time one. A Grant after the first IPermissionRegistry resolve (which runs Build()) throws, with a message telling the caller to declare every grant before the host is built (PermissionRegistryBuilder.cs:39-40); the API doc gives the same rule (AuthorizationExtensions.cs:111). A grant made after the host is built but before that first resolve is not detected.

ChangePasswordRequest

MMCA.Common.Shared · MMCA.Common.Shared.Auth.Requests · MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Requests/ChangePasswordRequest.cs:8 · Level 0 · record struct (readonly)

  • What it is: (string CurrentPassword, string NewPassword), the payload for an authenticated password change (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Requests/ChangePasswordRequest.cs:3-10).
  • Depends on: nothing first-party.
  • Concept: the same readonly record struct DTO shape introduced by AuthenticationResponse. [Rubric §11, Security]: requiring the current password re-proves the caller's identity before a credential change, so a stolen session alone cannot lock the owner out. The strength rules for NewPassword are deliberately not here; they live in the shared ChangePasswordRequestValidator in MMCA.Common.Application (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Validation/ChangePasswordRequestValidator.cs:15), which keeps the wire contract free of policy.
  • Walkthrough: two positional parameters (ChangePasswordRequest.cs:8-10); no body.
  • Where it's used: bound as the body of the shared PUT password endpoint on UserAccountAuthControllerBase<TChangePasswordCommand, TChangePreferencesCommand> (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/UserAccountAuthControllerBase.cs:87,93), reached only through the IUserScopedCommand<ChangePasswordRequest> constraint on the app's command (UserAccountAuthControllerBase.cs:48); carried by each app's ChangePasswordCommand (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/ChangePassword/ChangePasswordCommand.cs:12-13 and its Store twin); validated by the shared MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Validation/ChangePasswordRequestValidator.cs:15, which requires a non-empty CurrentPassword (:20-21) and includes the shared StrongPasswordRules<T> for NewPassword (:23).
  • Caveats / not-in-source: nothing in this type prevents the password strings from reaching a log. That is an operational convention (PII masking plus the "never log the body" habit), not a compile-time or runtime guarantee.

ChangePreferencesRequest

MMCA.Common.Shared · MMCA.Common.Shared.Auth.Requests · MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Requests/ChangePreferencesRequest.cs:10 · Level 0 · record (sealed)

  • What it is: (string? Culture, string? Theme), the payload for updating the signed-in user's stored UI preferences (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Requests/ChangePreferencesRequest.cs:3-10).
  • Depends on: nothing first-party. It is the write-side counterpart of UserPreferencesResponse.
  • Concept introduced, null-means-unchanged partial update. [Rubric §9, API & Contract Design] assesses how a contract expresses partial intent, and [Rubric §19, State Management] assesses where user state lives and who may overwrite it. A naive "PUT the whole preferences object" endpoint has a real bug hiding in it: the app-bar language switcher knows only the culture and the theme toggle knows only the theme, so whichever fires last would send null for the other field and silently erase the user's other choice. The doc comment states the rule that removes the bug (ChangePreferencesRequest.cs:3-7): a null field leaves that preference unchanged, so each control can persist its own field in isolation. The rule is honored in exactly one place, the shared handler's command.Request.Culture ?? user.PreferredCulture / command.Request.Theme ?? user.PreferredTheme coalesce (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/ChangePreferences/ChangePreferencesHandlerBase.cs:54-55), which is why the contract can afford to be this terse. The two preferences themselves come from ADR-027 (culture) and ADR-028 (theme).
  • Walkthrough: two nullable positional parameters on a sealed record (ChangePreferencesRequest.cs:10); no body. Unlike the auth siblings this is a reference type (record, not record struct), which matters at the boundary: the controller binds it with [FromBody], so a completely absent body deserializes to null rather than to a silently valid all-defaults struct.
  • Why it's built this way: the payload record was byte-identical in both applications' Identity modules and was hoisted here, while the command record stayed app-side as the handler base's TCommand type parameter (ChangePreferencesHandlerBase.cs:22,27). The handler base's remarks still give the reason as ADC marking its command ICacheInvalidating while Store does not (ChangePreferencesHandlerBase.cs:16-18), but that difference no longer exists in source: both apps' commands implement only IUserScopedCommand<ChangePreferencesRequest> (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/ChangePreferences/ChangePreferencesCommand.cs:11-12, MMCA.Store/Source/Modules/Identity/MMCA.Store.Identity.Application/Users/UseCases/ChangePreferences/ChangePreferencesCommand.cs:11-12). The split still follows the framework's hoisting rule: share the shape, leave the per-app record behind.
  • Where it's used: the body of the shared PUT preferences endpoint (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/UserAccountAuthControllerBase.cs:113,119), which hands it to the app's command through the abstract CreateChangePreferencesCommand factory (UserAccountAuthControllerBase.cs:78-80,127); the generic constraint that ties the two together is where TChangePreferencesCommand : IUserScopedCommand<ChangePreferencesRequest> (UserAccountAuthControllerBase.cs:49). It is consumed by ChangePreferencesHandlerBase<TUser, TCommand> and carried by each app's ChangePreferencesCommand (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/ChangePreferences/ChangePreferencesCommand.cs:11-12).
  • Caveats / not-in-source: this type validates nothing. Rejecting an unknown culture such as "xx" or an unknown theme such as "blue" is the domain's job, inside UpdatePreferences on the User aggregate behind IUserPreferences, which returns a Result the handler propagates. Note also that the Blazor UI does not send this exact type: ApiUserPreferenceWriter declares its own private UserPreferencesRequest(string? Culture, string? Theme) wire record (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Preferences/ApiUserPreferenceWriter.cs:29,100), so the two shapes agree by convention rather than by a shared reference.

ConfirmEmailRequest

MMCA.Common.Shared · MMCA.Common.Shared.Auth.Requests · MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Requests/EmailConfirmationRequests.cs:27 · Level 0 · record struct (readonly)

  • What it is: (string Email, string Token) plus two optional init-only passwords, the payload that redeems a single-use email-confirmation token (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Requests/EmailConfirmationRequests.cs:14-43).

  • Depends on: nothing first-party. It pairs with SendEmailConfirmationRequest, which triggers the mail this one redeems.

  • Concept: the readonly record struct request shape from LoginRequest. [Rubric §11, Security]: like ResetPasswordRequest, the address and token are carried in the URI fragment, so the confirm-email page reads them client-side and posts them here; neither value ever reaches a server log or a Referer header, per the shared base controller action's own doc comment (EmailConfirmationControllerBase, MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/EmailConfirmationControllerBase.cs:98-102). The second rule this type carries is that the link proves the mailbox, not the account: anyone can open an account under an address they do not read, so for an unconfirmed account that holds a password the token alone is refused with EmailConfirmation.PasswordRequired unless the caller is signed in as that account, and the client posts again with one of the two password properties (EmailConfirmationRequests.cs:17-23).

  • Walkthrough: two positional parameters (EmailConfirmationRequests.cs:27-29) and two init-only properties:

    • CurrentPassword proves the caller owns the account as well as the mailbox, and confirms without changing the password (EmailConfirmationRequests.cs:31-35);
    • NewPassword lets the mailbox owner claim the account: the password is replaced, every signed-in session is revoked and any second factor is removed before the address is confirmed; it is not combined with CurrentPassword (EmailConfirmationRequests.cs:37-42).

    Both are properties rather than positional parameters, following the LoginRequest.TwoFactorCode precedent, so the constructor, the deconstruction and the JSON shape of every existing caller are unchanged (EmailConfirmationRequests.cs:20-23).

  • Why it's built this way: the shared handler decides which proof the request carries. An account with no stored password credential is confirmed by the token alone; a caller signed in as the same account needs nothing more; otherwise a non-empty CurrentPassword is verified, then a non-empty NewPassword is accepted when the user type supports a password change, and anything else answers PasswordRequired (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/EmailConfirmation/ConfirmEmailHandlerBase.cs:200-228). The current-password check runs under the same lockout accounting a password sign-in uses, and a PasswordRequired answer changes nothing, so the token stays redeemable for the retry (ConfirmEmailHandlerBase.cs:27-42).

  • Where it's used: shape-validated by ConfirmEmailRequestValidator, which caps CurrentPassword at the sign-in length limit, refuses a request carrying both passwords, and runs a supplied NewPassword through the shared StrongPasswordRules<T> (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Validation/EmailConfirmationRequestValidators.cs:43-54); handled through ConfirmEmailCommand (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/ConfirmEmail/ConfirmEmailCommand.cs) by the shared ConfirmEmailHandlerBase; exposed by ADC's EmailConfirmationController's anonymous, rate-limited, idempotent POST confirm-email (inherited from EmailConfirmationControllerBase.cs:106-125), which answers 204 on success; posted by the Common UI's EmailConfirmationUIService, token alone first and then again with a password (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/EmailConfirmationUIService.cs:28,31).

  • Caveats / not-in-source: email confirmation is send-only in ADC today (Authentication:EmailConfirmation:RequireConfirmedEmail stays false, MMCA.ADC/Source/Services/MMCA.ADC.Identity.Service/appsettings.json:175), so redeeming this request updates the stored confirmation state but never gates sign-in; Store does not wire this endpoint.

EndSessionRequest

MMCA.Common.Shared · MMCA.Common.Shared.Auth.Requests · MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Requests/RefreshTokenRequest.cs:19 · Level 0 · record (sealed)

  • What it is: (string RefreshToken), the payload for POST auth/session/end, which ends the one live session a refresh token names with the token as the only proof (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Requests/RefreshTokenRequest.cs:13-19).
  • Depends on: nothing first-party. It sits beside RefreshTokenRequest in the same file only because the Requests folder is at its width cap, as the doc comment says (RefreshTokenRequest.cs:14-16).
  • Concept: the minimal request shape from LoginRequest, here a sealed record carrying only what the endpoint reads. [Rubric §11, Security]: the endpoint is anonymous and always answers 204 No Content, revoking a live matching session and changing nothing for an empty, unknown, expired or already-revoked token, so the answer reveals nothing about the token (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/AuthControllerBase.cs:190-196). ADR-022 records the browser session-cookie design this request completes.
  • Walkthrough: one positional string RefreshToken on a sealed record (RefreshTokenRequest.cs:19); no body.
  • Why it's built this way: the Blazor web head 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, so the sign-out needs an endpoint that takes the refresh token alone (AuthControllerBase.cs:183-189). It is not throttled, for the same reason refresh is not: every Server-circuit sign-out arrives from the UI host's one address, and a refresh token is high-entropy (AuthControllerBase.cs:194-195). It is [NonIdempotent] because replaying a cached 204 would report a session as ended when the store was never touched (AuthControllerBase.cs:202).
  • Where it's used: bound as the body of AuthControllerBase's EndSessionAsync, which hands the token to IAuthSessionIssuer.SignOutByRefreshTokenAsync (AuthControllerBase.cs:201-215); built by CookieSessionEnder, which reads the browser's refresh cookie at DELETE /auth/session-cookie and posts it server-to-server to auth/session/end within a 5-second timeout, best effort, so the sign-out goes ahead whatever the identity endpoint answers (MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/CookieSessionEnder.cs:33,39,45-72).

ForgotPasswordRequest

MMCA.Common.Shared · MMCA.Common.Shared.Auth.Requests · MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Requests/ForgotPasswordRequest.cs:8 · Level 0 · record struct (readonly)

  • What it is: a single-field request (string Email) that starts a password reset (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Requests/ForgotPasswordRequest.cs:3-9).
  • Depends on: nothing first-party. It pairs with ResetPasswordRequest, which completes the flow this one starts.
  • Concept introduced, the anti-enumeration contract. [Rubric §11, Security] assesses whether an endpoint leaks facts an attacker can harvest, and [Rubric §9, API & Contract Design] assesses whether a contract's shape matches the answer it is allowed to give. A password-reset entry point is the classic account-enumeration oracle: if "no such user" answers differently from "email sent", an attacker can test an address list against your user base for free. The doc comment on this one-field record records the countermeasure as part of the contract (ForgotPasswordRequest.cs:3-6): the response is always accepted, so the payload carries no signal about whether the address belongs to an account. The rule is not aspirational, it is implemented in three coordinated places:
    • the request validator checks only the shape of the address, and its doc comment says exactly why it stops there, because a 400 on an unknown address would be the oracle the always-accepted response exists to close (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Validation/ForgotPasswordRequestValidator.cs:6-9,13-16);
    • the handler's inline dispatch never looks the address up: it schedules the command as an internal command and answers Result.Success() (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/ForgotPassword/ForgotPasswordHandlerBase.cs:86-88,94,101); the scheduled execution then completes a malformed address, an address with no account and a throttled request with Result.Success(), logging the real reason instead of returning it (:110-111,120-121,127-128), while a failed send propagates so the queue row is retried (:131-136);
    • the endpoint answers 202 Accepted on every well-formed request (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/PasswordResetAuthControllerBase.cs:79,92).
  • Walkthrough: one positional string Email (ForgotPasswordRequest.cs:8-9); no body, no validation attributes, no normalization. Normalizing the address is the handler's job, through Email.Create(command.Request.Email) (ForgotPasswordHandlerBase.cs:107), which is what lets the DTO stay a raw wire shape while the Email value object owns the parsing rules.
  • Why it's built this way: ADR-091 records the cache-backed reset design this request opens. Keeping the payload to a single field means there is nothing else for an attacker to probe, and keeping the "always accepted" promise in the type's doc comment puts it where a reader meets it before the handler.
  • Where it's used: bound as the body of the anonymous, rate-limited POST forgot-password action on PasswordResetAuthControllerBase<TForgotPasswordCommand, TResetPasswordCommand> (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/PasswordResetAuthControllerBase.cs:75,83), which turns it into the app's command through an abstract factory (:61) constrained to ICommandWithRequest<out TRequest> (:46); shape-validated by ForgotPasswordRequestValidator; handled by ForgotPasswordHandlerBase<TUser, TCommand>; posted by AuthUIService's RequestPasswordResetAsync, deliberately as an anonymous request with no bearer header so a signed-in caller does not bind the reset to the current session (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/AuthUIService.cs:254,258-261).
  • Caveats / not-in-source: both applications now wire this vertical. ADC has a ForgotPasswordCommand (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/ForgotPassword/ForgotPasswordCommand.cs:19-21) and a derived controller (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/Controllers/PasswordResetController.cs:36); Store has the same pair (MMCA.Store/Source/Modules/Identity/MMCA.Store.Identity.Application/Users/UseCases/ForgotPassword/ForgotPasswordCommand.cs:11, MMCA.Store/Source/Modules/Identity/MMCA.Store.Identity.API/Controllers/PasswordResetController.cs:33).

LoginRequest

MMCA.Common.Shared · MMCA.Common.Shared.Auth.Requests · MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Requests/LoginRequest.cs:8 · Level 0 · record struct (readonly)

  • What it is: the email/password payload for authentication: (string Email, string Password) (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Requests/LoginRequest.cs:3-10).
  • Depends on: nothing first-party.
  • Concept: the readonly record struct DTO introduced by AuthenticationResponse. [Rubric §11, Security]: the doc comment (LoginRequest.cs:7) records the rule that the password travels over TLS and is never logged. That convention is enforced operationally, not by this type, but the intent is documented at the source where a reader will meet it.
  • Walkthrough: two positional parameters (LoginRequest.cs:8-10), plus an init-only TwoFactorCode property carrying the second-factor code when the account has two-factor authentication enabled, either the authenticator-app code or a single-use recovery code (LoginRequest.cs:8-15,20-24). The doc remark explains why it is a property rather than a third positional parameter: a positional parameter would widen the generated Deconstruct, a source break for any caller that destructures a login request, while a property leaves the constructor, the deconstruction, and the JSON shape of every existing caller untouched, and a client that never sends the field simply leaves it null (LoginRequest.cs:16-19). Omitting it on the first attempt is the normal flow: sign-in answers Authentication.TwoFactorRequired when the account needs a code and none arrived, and the client retries the same credentials with the code filled in (LoginRequest.cs:21-23).
  • Where it's used: shape-validated by LoginRequestValidator, which is deliberately minimal (non-empty plus address shape) so that no field-level 400 hints at which half of the credential was wrong (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Validation/LoginRequestValidator.cs:6-10,15-20); then handled by AuthenticationServiceBase<TUser>.LoginAsync (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/AuthenticationServiceBase.cs:156-157), which is reached through AuthControllerBase's POST login (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/AuthControllerBase.cs:75,82-83).

OAuthCodeExchangeRequest

MMCA.Common.Shared · MMCA.Common.Shared.Auth.Requests · MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Requests/OAuthCodeExchangeRequest.cs:11 · Level 0 · record struct (readonly)

  • What it is: a request (string Code) with an optional init-only CodeVerifier, which exchanges a short-lived, single-use OAuth completion code for the token pair (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Requests/OAuthCodeExchangeRequest.cs:3-20).
  • Depends on: nothing first-party.
  • Concept reinforced, security by construction. [Rubric §11, Security] and [Rubric §26, Front-End Security] both assess safe token handling, in particular whether credentials can leak into places that are logged or replayed. The doc comment (OAuthCodeExchangeRequest.cs:3-9) explains why the indirection exists: the server mints an opaque code after the external-provider callback succeeds and carries that in the redirect URL, so the access and refresh tokens never appear in the address bar, browser history, the Referer header, or server access logs. The mint side is right there in the controller, with the same reasoning as a comment (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/OAuthControllerBase.cs:255-264). ADR-036 records the decision, and ADR-043 extends the pattern to the native mobile callback, where a custom-scheme redirect can be captured by another app; the CodeVerifier proof key closes that gap.
  • Walkthrough: one positional string Code (OAuthCodeExchangeRequest.cs:11-12) and one init-only string? CodeVerifier, the RFC 7636 proof-key verifier whose S256 challenge the client sent when it started the sign-in. It is required, and checked, only for a flow started with a challenge (the native heads' custom-scheme flow), and null for a flow started without one (OAuthCodeExchangeRequest.cs:14-19).
  • Why it's built this way: the code is worthless once redeemed, which is the property that makes putting it in a URL acceptable. OAuthControllerBase.ExchangeAsync rejects a blank code (OAuthControllerBase.cs:322-325). A supplied verifier must be well formed (43 to 128 unreserved characters) and is hashed to its S256 challenge, which selects the cache key the token pair was stashed under, so a code from a bound flow redeems nothing without the matching verifier and a verifier sent for an unbound flow misses the same way (OAuthControllerBase.cs:93-94,327-338,380-391); a missing or wrong verifier leaves the code redeemable by its owner until it expires (OAuthControllerBase.cs:299-303). The read and the burn then run under a distributed lock, so two replicas cannot both hand out the pair (OAuthControllerBase.cs:340-354): the pair is read from ICacheService's shared store and the code removed so a replayed code cannot mint a second token pair (OAuthControllerBase.cs:363-370). An unknown, burned, expired, contended or wrong-verifier code all return the same HTTP 400 with a deliberately non-specific message (OAuthControllerBase.cs:397-403). The action is also marked [NonIdempotent] with the reason inline: replaying a stored response would defeat the burn and let a leaked code mint the same tokens again (OAuthControllerBase.cs:314).
  • Where it's used: the body of the anonymous, auth-ip-throttled OAuth exchange endpoint (OAuthControllerBase.cs:313-320), posted by AuthUIService with the verifier set when it has one (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/AuthUIService.cs:102) after the provider redirect lands on the UI's /auth/oauth-complete page or the mobile return URL (OAuthControllerBase.cs:284-286,289-291).

RedeemSignInLinkRequest

MMCA.Common.Shared · MMCA.Common.Shared.Auth.Requests · MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Requests/SignInLinkRequests.cs:23 · Level 0 · record struct (readonly)

  • What it is: (string Email, string Token, bool AcceptedTerms = false), the payload that redeems a single-use sign-in link for a token pair (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Requests/SignInLinkRequests.cs:13-26).
  • Depends on: nothing first-party. It pairs with SendSignInLinkRequest, which causes the link this one redeems to be mailed.
  • Concept: the readonly record struct request shape from LoginRequest, and the fragment-carried redemption pattern from ConfirmEmailRequest. [Rubric §11, Security]: the link carries the address and the token in the URI fragment, so the page reads them client-side and posts them here, and neither reaches a server log or a Referer header, per the base controller action's own doc comment (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/SignInLinks/SignInLinkControllerBase.cs:100-104). The address travels with the token for the same reason ResetPasswordRequest carries it: the server checks the token was issued for that address rather than trusting it alone.
  • Walkthrough: three positional parameters (SignInLinkRequests.cs:23-26); no body. AcceptedTerms defaults to false and is read only when redeeming the link creates the account (an invitation to an address with no account yet), so the new account carries the same Terms of Service acceptance a registration would (SignInLinkRequests.cs:18-22).
  • Why it's built this way: account creation is opt-in per app. The shared handler's ProvisionUser(Email, SignInLinkProfile, RedeemSignInLinkRequest) refuses by default, and an override that records Terms acceptance reads AcceptedTerms there (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/SignInLinks/RedeemSignInLinkHandlerBase.cs:130-145); ADC overrides it (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/RedeemSignInLink/RedeemSignInLinkHandler.cs:66).
  • Where it's used: shape-validated by RedeemSignInLinkRequestValidator, which checks only a non-empty, well-formed address and a non-empty token, so an unknown or expired token is the handler's single generic rejection rather than a 400 that would confirm the token was at least well formed (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Validation/SignInLinkRequestValidators.cs:20-35); bound as the body of the anonymous, rate-limited POST sign-in-link/redeem action on SignInLinkControllerBase<TSendCommand, TRedeemCommand>, which is [NonIdempotent] because the token is single-use and a replayed response would hand back tokens minted for an earlier call (SignInLinkControllerBase.cs:108-127); the controller wraps it with the caller's IP and user-agent through the abstract CreateRedeemCommand (SignInLinkControllerBase.cs:71,121) into a command constrained to IRedeemSignInLinkCommand (SignInLinkControllerBase.cs:39), handled by RedeemSignInLinkHandlerBase<TUser, TCommand>. ADC's derived controller builds its command at MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/Controllers/SignInLinkController.cs:40; posted by AuthUIService (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/AuthUIService.cs:292).

RefreshTokenRequest

MMCA.Common.Shared · MMCA.Common.Shared.Auth.Requests · MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Requests/RefreshTokenRequest.cs:9 · Level 0 · record struct (readonly)

  • What it is: (string AccessToken, string RefreshToken); it sends the expired access token alongside the refresh token so the server can read its claims without forcing a full re-authentication (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Requests/RefreshTokenRequest.cs:3-11).
  • Depends on: nothing first-party.
  • Concept: the readonly record struct DTO shape from AuthenticationResponse. [Rubric §11, Security]: this is the request half of ADR-050's rotation scheme. Carrying the expired token lets the server reconstruct the principal cheaply, while the opaque refresh token is what actually gates the rotation, so possession of an expired access token alone buys nothing.
  • Walkthrough: two positional parameters (RefreshTokenRequest.cs:9-11); no body. Both are required to be non-empty, and the validator's doc comment says why each is needed: the access token for claim extraction, the refresh token for rotation verification (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Validation/RefreshTokenRequestValidator.cs:6-9,14-18).
  • Where it's used: shape-validated by RefreshTokenRequestValidator, handled by AuthenticationServiceBase<TUser>.RefreshTokenAsync (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/AuthenticationServiceBase.cs:396-397), which rejects an unreadable token or a principal with no usable user id with an Auth.InvalidToken failure before it ever looks at the refresh token (AuthenticationServiceBase.cs:410-414,420-424); exposed by AuthControllerBase's POST refresh (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/AuthControllerBase.cs:164,170-171).

ResetPasswordRequest

MMCA.Common.Shared · MMCA.Common.Shared.Auth.Requests · MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Requests/ResetPasswordRequest.cs:9 · Level 0 · record struct (readonly)

  • What it is: (string Email, string Token, string NewPassword), the payload that completes a password reset by redeeming the single-use token that ForgotPasswordRequest caused to be mailed (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Requests/ResetPasswordRequest.cs:3-12).
  • Depends on: nothing first-party; the readonly record struct shape from AuthenticationResponse.
  • Concept, the three-field redemption payload and the single collapsed failure. [Rubric §11, Security]: the address is carried alongside the token so the server can verify that the token was issued for that address rather than trusting the token in isolation, which is what the handler's ValidateAndConsumeAsync(request.Email, request.Token, ...) call checks (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/ResetPassword/ResetPasswordHandlerBase.cs:77-79). The anti-enumeration discipline that governs the forgot half continues here in a different form: an unknown, expired, mismatched or attempt-capped token and a vanished account all collapse to one Auth.InvalidResetToken 401 with the same message, so the response distinguishes none of them (ResetPasswordHandlerBase.cs:18-23,80-84,89-93,126-130). One ordering decision is worth internalizing: the token is consumed before the save, and the comment says why (ResetPasswordHandlerBase.cs:74-76), because leaving it live until the write succeeds would open a replay window in which the same token is redeemed twice; a token burned by a later invariant failure costs the user one more reset request, which is the cheaper failure.
  • Walkthrough: three positional parameters (ResetPasswordRequest.cs:9-12); no body. The doc comment repeats the never-logged rule for NewPassword (ResetPasswordRequest.cs:8), the same convention LoginRequest states.
  • Why it's built this way: the new password goes through the same StrongPasswordRules<T> that registration and change-password use, so a reset cannot become a way around the complexity policy (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Validation/ResetPasswordRequestValidator.cs:7-11,16-23). Reusing one rule set rather than restating it per endpoint is the reason the policy cannot drift. ADR-091 covers the token side.
  • Where it's used: bound as the body of the anonymous, rate-limited POST reset-password action on PasswordResetAuthControllerBase<TForgotPasswordCommand, TResetPasswordCommand>, which answers 204 on success (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/PasswordResetAuthControllerBase.cs:99,103,108,117); shape-validated by ResetPasswordRequestValidator; handled by ResetPasswordHandlerBase<TUser, TCommand>, which hashes the new password, lets the aggregate apply its own invariants, saves, and then clears the account's failed-attempt count so a user who reset because of a lockout is not still locked out (ResetPasswordHandlerBase.cs:110-111,117,119-120); posted by AuthUIService's ResetPasswordAsync (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/AuthUIService.cs:296,305-306). ADC carries it in a ResetPasswordCommand, a plain ICommandWithRequest<ResetPasswordRequest> (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/ResetPassword/ResetPasswordCommand.cs:10-11); Store carries its own (MMCA.Store/Source/Modules/Identity/MMCA.Store.Identity.Application/Users/UseCases/ResetPassword/ResetPasswordCommand.cs:12).

SendEmailConfirmationRequest

MMCA.Common.Shared · MMCA.Common.Shared.Auth.Requests · MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Requests/EmailConfirmationRequests.cs:12 · Level 0 · record struct (readonly)

  • What it is: a single-field request (string Email) that asks for a fresh confirmation link to be emailed to an address (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Requests/EmailConfirmationRequests.cs:3-12).
  • Depends on: nothing first-party. It is the anti-enumeration sibling of ForgotPasswordRequest: the doc comment says this endpoint is anonymous by necessity (an unconfirmed account may not be able to sign in at all) and answered identically whether or not the address holds an account, for the same reason the forgot-password endpoint is (EmailConfirmationRequests.cs:6-9).
  • Concept: see ForgotPasswordRequest for the anti-enumeration contract this reuses; not re-taught here.
  • Walkthrough: one positional string Email (EmailConfirmationRequests.cs:12); no body.
  • Where it's used: shape-validated by SendEmailConfirmationRequestValidator; bound as the body of the anonymous, rate-limited, idempotent POST send-email-confirmation action, which returns 202 Accepted on every well-formed request (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/EmailConfirmationControllerBase.cs:78-96, which ADC inherits through MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/Controllers/EmailConfirmationController.cs:29-34); carried by SendEmailConfirmationCommand (EmailConfirmationController.cs:37), handled by the shared SendEmailConfirmationHandlerBase. ADC's own AuthController.RegisterAsync schedules the send as part of registration rather than calling this endpoint directly.

SendSignInLinkRequest

MMCA.Common.Shared · MMCA.Common.Shared.Auth.Requests · MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Requests/SignInLinkRequests.cs:11 · Level 0 · record struct (readonly)

  • What it is: a single-field request (string Email) that asks for a single-use sign-in link to be emailed to an address (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Requests/SignInLinkRequests.cs:3-11).
  • Depends on: nothing first-party. It pairs with RedeemSignInLinkRequest, which redeems the link this one causes to be mailed.
  • Concept: see ForgotPasswordRequest for the anti-enumeration contract this reuses; not re-taught here. The doc remark states it in this type's own terms: anonymous, and answered identically whether or not the address holds an account (SignInLinkRequests.cs:6-9).
  • Walkthrough: one positional string Email (SignInLinkRequests.cs:11); no body. Normalizing the address is the handler's job, through Email.Create(command.Request.Email) (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/SignInLinks/SendSignInLinkHandlerBase.cs:110).
  • Where it's used: shape-validated by SendSignInLinkRequestValidator, which checks only the address shape because a 400 on an unknown address would be the enumeration oracle (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Validation/SignInLinkRequestValidators.cs:6-17); bound as the body of the anonymous, rate-limited, idempotent POST sign-in-link action on SignInLinkControllerBase<TSendCommand, TRedeemCommand>, which answers 202 Accepted on every well-formed request (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/SignInLinks/SignInLinkControllerBase.cs:80-97); turned into the app's command through the abstract CreateSendCommand factory (:61) constrained to ICommandWithRequest<out TRequest> (:38); handled by SendSignInLinkHandlerBase<TUser, TCommand>. ADC carries it in SendSignInLinkCommand (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/SendSignInLink/SendSignInLinkCommand.cs:20-21) and builds it in its derived controller (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/Controllers/SignInLinkController.cs:37); posted by AuthUIService (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/AuthUIService.cs:271,277).

SetRolePermissionsRequest

MMCA.Common.Shared · MMCA.Common.Shared.Auth.Requests · MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Requests/AdministrationRequests.cs:25 · Level 0 · record (sealed)

  • What it is: (IReadOnlyList<string> Permissions), the payload that replaces the complete set of stored permission grants for one role (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Requests/AdministrationRequests.cs:16-25).
  • Depends on: nothing first-party.
  • Concept introduced, replace rather than add/remove. [Rubric §9, API & Contract Design]: the doc remark explains the shape choice, a replace rather than an add/remove pair makes the request idempotent (re-submitting the same list is a no-op), and these are the stored grants only: permissions compiled into the host's IPermissionRegistry are not editable and are not returned here, so an operator can never remove a capability the code depends on by editing data (AdministrationRequests.cs:19-22).
  • Walkthrough: one positional IReadOnlyList<string> Permissions on a sealed record (AdministrationRequests.cs:25); no body.
  • Where it's used: bound as the body of RolesAdminControllerBase's SetPermissions action (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Administration/RolesAdminControllerBase.cs:154); shape-validated by SetRolePermissionsRequestValidator, which requires a non-null list and validates each entry (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Validation/AdministrationRequestValidators.cs:30,37,39); consumed by IRoleAdministrationService and posted by the Common UI's RoleAdminService (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Administration/RoleAdminService.cs).

SetUserRolesRequest

MMCA.Common.Shared · MMCA.Common.Shared.Auth.Requests · MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Requests/AdministrationRequests.cs:14 · Level 0 · record (sealed)

  • What it is: (IReadOnlyList<string> Roles), the payload that replaces the complete set of roles an account holds (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Requests/AdministrationRequests.cs:5-14).
  • Depends on: nothing first-party.
  • Concept: the same replace-not-patch shape as SetRolePermissionsRequest; see that section for the idempotency rationale. The doc remark restates it in this type's own terms: the administration UI edits a list, and a replace makes re-submitting the same list a no-op, where an add/remove pair would need the caller to know what the account already held (AdministrationRequests.cs:8-11).
  • Walkthrough: one positional IReadOnlyList<string> Roles on a sealed record (AdministrationRequests.cs:14); no body.
  • Where it's used: bound as the body of UsersAdminControllerBase<TUserDto>'s SetRoles action (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Administration/UsersAdminControllerBase.cs:299); shape-validated by SetUserRolesRequestValidator, which requires a non-null list and validates each entry (AdministrationRequestValidators.cs:11,18,20); consumed by IUserAdministrationService<TUserDto> and posted by the Common UI's UserAdminService (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Administration/UserAdminService.cs).

StartViewAsRequest

MMCA.Common.Shared · MMCA.Common.Shared.Auth.Requests · MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Requests/AdministrationRequests.cs:34 · Level 0 · record (sealed)

  • What it is: (string? Reason), the payload that starts a read-only view-as session on another account (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Requests/AdministrationRequests.cs:27-34).
  • Depends on: nothing first-party.
  • Concept introduced, the reason as the audit record. [Rubric §11, Security]: support access to another user's account is only defensible if every access says why. The doc comment makes the free-text reason (10 to 500 characters) part of the contract and says where it goes: onto the grant row, which is the audit record of the access (AdministrationRequests.cs:30-33). ADR-137 records the read-only view-as design.
  • Walkthrough: one nullable positional string? Reason on a sealed record (AdministrationRequests.cs:34); no body and no validation attributes. The length rule is not enforced here: ViewAsService checks the reason (and that the staff user is not viewing themselves) through ViewAsGrant.Create before any lookup (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/ViewAs/ViewAsService.cs:75-76), so the rule lives once in ViewAsGrant.
  • Where it's used: bound as the body of UsersAdminControllerBase<TUserDto>'s POST {userId}/view-as action, gated by AdministrationPermissions.ViewAsUsers and marked [NonIdempotent] because each call issues a new grant row (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Administration/UsersAdminControllerBase.cs:160-170); the action answers 404 when view-as is disabled or the host does not hold the grant store, and passes request?.Reason to IViewAsService.StartAsync (UsersAdminControllerBase.cs:178-189).

TwoFactorCodeRequest

MMCA.Common.Shared · MMCA.Common.Shared.Auth.Requests · MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Requests/TwoFactorCodeRequest.cs:16 · Level 0 · record struct (readonly)

  • What it is: a single-field request (string Code), the live-code proof shared by every two-factor action that has to be proved with a code: confirming enrollment, disabling the second factor, and regenerating the recovery codes (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Requests/TwoFactorCodeRequest.cs:3-16).
  • Depends on: nothing first-party.
  • Concept introduced, one payload for three actions. [Rubric §9, API & Contract Design] and [Rubric §11, Security]: the doc remark explains why one shape serves three actions rather than three identical ones, the code is the whole request body in each case and the account is taken from the authenticated caller, never from the request; disable and regenerate demand a code for the same reason enrollment does, so whoever holds a stolen access token still cannot strip the account's second factor with it (TwoFactorCodeRequest.cs:7-11). Each of the three handler bases enforces the shared shape through the same generic constraint, where TCommand : IUserScopedCommand<TwoFactorCodeRequest> (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/TwoFactor/ConfirmTwoFactorEnrollmentHandlerBase.cs:45, MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/TwoFactor/DisableTwoFactorHandlerBase.cs:41, MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/TwoFactor/RegenerateRecoveryCodesHandlerBase.cs:42).
  • Walkthrough: one positional string Code (TwoFactorCodeRequest.cs:16); no body.
  • Where it's used: shape-validated by TwoFactorCodeRequestValidator (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Validation/TwoFactorCodeRequestValidator.cs:16,23); handled by the three IUserScopedCommand<TwoFactorCodeRequest> handler bases above, each layered over ITwoFactorService and ITwoFactorAuthenticator.

ViewAsGrantListRequest

MMCA.Common.Shared · MMCA.Common.Shared.Auth.Requests · MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Requests/AdministrationRequests.cs:40 · Level 1 · record (sealed)

  • What it is: one page of the support access log with its filters; every filter is optional, they combine with AND, and the rows come newest first (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Requests/AdministrationRequests.cs:36-68).
  • Depends on: ViewAsGrantStatus for the status filter.
  • Concept introduced, one filter definition shared by every store. [Rubric §9, API & Contract Design]: the filters are defined once in this record and applied once, in ViewAsGrantLogQuery.Filter, over either an EF set or an in-memory sequence, so the EF store and the in-memory test store cannot disagree on what a filter means (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/ViewAs/ViewAsGrantLogQuery.cs:10-31). ADR-137 is the feature this log audits.
  • Walkthrough: a sealed record with init-only properties, not positional parameters (AdministrationRequests.cs:40-68), which suits [FromQuery] binding of many optional values. DefaultPageSize = 20 and MaxPageSize = 100 (:43,46). Staff and Viewed are case-insensitive "contains" text against the staff and viewed email (:49,52), matched against the stored display snapshots after folding the needle with ViewAsGrant.NormalizeDisplay (ViewAsGrantLogQuery.cs:34-47). From is inclusive and To exclusive on the granted-at instant, both UTC (AdministrationRequests.cs:55,58; ViewAsGrantLogQuery.cs:49-59). Status filters on the status derived at the time of the read, not a stored column (AdministrationRequests.cs:61; ViewAsGrantLogQuery.cs:19-20,31). PageNumber defaults to 1 and values below 1 read page 1; PageSize defaults to DefaultPageSize and is clamped into 1 to MaxPageSize (:64,67).
  • Why it's built this way: clamping rather than rejecting keeps an oversized page request harmless, and the controller reports the page actually served by clamping the same way the store does (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Administration/ViewAsGrantsAdminControllerBase.cs:93-97; MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Auth/EFViewAsGrantStore.cs:132).
  • Where it's used: bound [FromQuery] by ViewAsGrantsAdminControllerBase's GET list action, which answers 404 on a host without the grant store and returns a PagedCollectionResult<T> of ViewAsGrantSummaryResponse (ViewAsGrantsAdminControllerBase.cs:53-99); consumed by IViewAsGrantStore.ListAsync (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/ViewAs/IViewAsGrantStore.cs:56-63) and its EFViewAsGrantStore implementation (EFViewAsGrantStore.cs:121); sent by the Common UI's ViewAsGrantsService behind the SupportAccessLog page.

RegisterRequest

MMCA.Common.Shared · MMCA.Common.Shared.Auth.Requests · MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Requests/RegisterRequest.cs:20 · Level 4 · record struct (readonly)

  • What it is: the registration payload for a new account: email, password, first and last name, an optional postal address, and a terms-acceptance flag (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Requests/RegisterRequest.cs:5-19).
  • Depends on: Address from MMCA.Common.Shared.ValueObjects (RegisterRequest.cs:1), which is the only reason this otherwise Level 0-shaped DTO sits at Level 4.
  • Concept: the readonly record struct request shape introduced by LoginRequest; see that section for the value semantics. [Rubric §9, API & Contract Design] assesses whether the wire contract is explicit and evolvable. The optional Address? Address = null parameter (RegisterRequest.cs:25) is the notable detail here: positional record structs support default parameter values, so a caller with no address simply omits it rather than needing a second overload or a null literal at the call site. That default is what lets one shared contract serve two apps with different profile shapes (see Where it's used).
  • Walkthrough: six positional parameters and no body (RegisterRequest.cs:20-26): four strings, the nullable Address, and bool AcceptedTerms = false (RegisterRequest.cs:26). AcceptedTerms is deliberately a plain flag rather than a version string: the register page is anonymous and cannot read the current terms version, so the server stamps the version it has configured (RegisterRequest.cs:13-19). RegisterAsync refuses the request with LegalAcceptanceErrors.TermsNotAccepted only when the host configured a CurrentTermsVersion and the flag is false; with no terms version configured the flag is ignored (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/AuthenticationServiceBase.cs:308-314), and an overriding CreateUser stamps CurrentTermsVersion on the new user (AuthenticationServiceBase.cs:136-145). The strings arrive raw, with no validation attributes and no normalization. Shape checking is the validator's job and semantic conversion is the domain factory's, which is the codebase's standing division of labor: the framework's RegisterRequestValidator composes reusable rule sets over the four strings and applies AddressValidator only When the address is non-null (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Validation/RegisterRequestValidator.cs:31-38), while AuthenticationServiceBase<TUser> hands the whole request to an abstract CreateUser(RegisterRequest request, byte[] passwordHash, byte[] passwordSalt) that each app implements against its own User aggregate (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/AuthenticationServiceBase.cs:764). Note that Password is a plain string on the contract and never travels past the hashing call: RegisterAsync turns it into a hash and salt pair, and that pair, not the password, is what reaches CreateUser and the aggregate (AuthenticationServiceBase.cs:330-331). [Rubric §11, Security].
  • Where it's used: AuthenticationServiceBase<TUser>.RegisterAsync (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/AuthenticationServiceBase.cs:296-300), the register endpoint on AuthControllerBase, which binds it [FromBody] on an anonymous, rate-limited, idempotent POST (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/AuthControllerBase.cs:100-110), and each app's register form. The two apps' CreateUser overrides show why the address is optional: Store passes request.Address straight into User.Create (MMCA.Store/Source/Modules/Identity/MMCA.Store.Identity.Application/Users/AuthenticationService.cs:52-60), while ADC ignores it entirely and creates the user from email, names, hash, salt, and the default UserRole.Attendee (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/AuthenticationService.cs:201-208).

AuthenticationResponse

MMCA.Common.Shared · MMCA.Common.Shared.Auth.Responses · MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Responses/AuthenticationResponse.cs:10 · Level 0 · record struct (readonly)

  • What it is: the success payload of authentication, carrying AccessToken, RefreshToken, and AccessTokenExpiry, shared by the Identity API and the UI clients (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Responses/AuthenticationResponse.cs:3-13).
  • Depends on: nothing first-party; System.DateTime (BCL).
  • Concept introduced, the readonly record struct DTO. [Rubric §15, Best Practices & Code Quality] assesses consistent conventions and immutability, and [Rubric §9, API & Contract Design] assesses well-shaped request/response contracts. A positional record struct is a value type with a compiler-generated constructor, deconstruction, value equality, and ToString; readonly makes every field immutable. For small, short-lived request/response carriers this avoids a heap allocation while staying immutable, and it is this codebase's default shape for auth DTOs, reused by every sibling below. The explicit AccessTokenExpiry (AuthenticationResponse.cs:13) lets clients refresh proactively instead of waiting for a 401, which is the client-side half of ADR-051.
  • Walkthrough: three positional parameters and no body (AuthenticationResponse.cs:10-13).
  • Why it's built this way: value semantics keep the type cheap, but they have one consequence worth internalizing before you reuse the shape. A struct has no null, so a cache miss returns default(AuthenticationResponse) rather than null, and OAuthControllerBase therefore detects a missing exchange entry by testing string.IsNullOrEmpty(response.AccessToken), with the reason written down at the call site (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/OAuthControllerBase.cs:359-364).
  • Where it's used: produced by AuthenticationServiceBase<TUser> from the shared IssueTokensAsync helper that login and registration both funnel through (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/AuthenticationServiceBase.cs:252,361,828,848) and directly at the end of a rotation (AuthenticationServiceBase.cs:455); declared as the 200/201 response type on the three AuthControllerBase token endpoints (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/AuthControllerBase.cs:79,104,167); consumed by AuthUIService, DirectApiTokenRefresher, and CookieSessionRefresher.

PermissionCatalogResponse

MMCA.Common.Shared · MMCA.Common.Shared.Auth.Responses · MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Responses/PermissionCatalogResponse.cs:22 · Level 0 · record (sealed)

  • What it is: the full permission catalog for the admin role editor: every registered role name and every registered permission name, unpaired (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Responses/PermissionCatalogResponse.cs:22-24).
  • Depends on: nothing first-party at compile time.
  • Concept: a reference-data response, distinct from RolePermissionsResponse which pairs one role with its grants. This one is the lookup lists a role editor needs to populate a picker before a role has been chosen.
  • Walkthrough: two positional parameters on a sealed record, Roles and Permissions, both IReadOnlyList<string> (PermissionCatalogResponse.cs:22-24); no body.
  • Why it's built this way: ADR-116 is the role/permission administration surface this response is part of.
  • Where it's used: built by StoredPermissionRoleAdministrationService.GetCatalogAsync from the registered roles and the compiled PermissionRegistry's Permissions (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/Administration/StoredPermissionRoleAdministrationService.cs:98-107); declared as the 200 response of GET .../catalog on RolesAdminControllerBase (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Administration/RolesAdminControllerBase.cs:107-110); fetched client-side by RoleAdminService for the role admin pages.

RegistrationPendingResponse

MMCA.Common.Shared · MMCA.Common.Shared.Auth.Responses · MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Responses/AuthenticationResponse.cs:21 · Level 0 · record (sealed)

  • What it is: the 202 Accepted body of auth/register when the account was created but no session was opened, because the host requires a confirmed address before sign-in (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Responses/AuthenticationResponse.cs:15-21).
  • Depends on: nothing first-party at compile time. Its in-process counterpart is RegistrationOutcome, which is what tells the endpoint to answer with this type instead of an AuthenticationResponse.
  • Concept: a distinct wire shape for a distinct outcome. A registration that opened no session has no tokens to return, so rather than a 201 with empty token fields the endpoint answers 202 with only the address the user typed, and the client tells the user to open the confirmation link, then sign in (AuthenticationResponse.cs:16-18). [Rubric §9, API & Contract Design] assesses whether status codes and bodies say what happened; here the status code and the body type change together.
  • Walkthrough: one positional parameter, Email, documented as the address "as typed (trimmed)" (AuthenticationResponse.cs:20-21); no body.
  • Why it's built this way: the body carries no token and no user id, only the address the caller already sent, so a pending registration discloses nothing new. The endpoint also marks the response Cache-Control: no-store (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/AuthControllerBase.cs:142-149).
  • Where it's used: built only by the register endpoint on AuthControllerBase, from the trimmed request email, when the service result satisfies IsConfirmationPending() (AuthControllerBase.cs:142,149); ADC's Identity AuthController inherits that endpoint.

RolePermissionsResponse

MMCA.Common.Shared · MMCA.Common.Shared.Auth.Responses · MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Responses/RolePermissionsResponse.cs:19 · Level 0 · record (sealed)

  • What it is: one role's permission picture: its name, the permissions its registered policies compile to, and the permissions actually stored as an override, side by side (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Responses/RolePermissionsResponse.cs:19-22).
  • Depends on: nothing first-party at compile time; it is the response shape StoredPermissionRoleAdministrationService builds from PermissionRegistry and its permission-grant store.
  • Concept: RegisteredPermissions versus StoredPermissions is the diff a role editor renders: the compiled default from code-registered policies against whatever an administrator has overridden in the database. Carrying both, rather than one merged list, is what lets the UI show which permissions are the framework default and which were changed.
  • Walkthrough: three positional parameters on a sealed record, Role, RegisteredPermissions, StoredPermissions (RolePermissionsResponse.cs:19-22); no body.
  • Why it's built this way: no ADR is specific to this response shape; it follows the same DTO convention (sealed record, positional, immutable) as every response in this group.
  • Where it's used: built three times by StoredPermissionRoleAdministrationService, once per role for the list view (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/Administration/StoredPermissionRoleAdministrationService.cs:88-90), once for a single-role read (:116), and once after a permissions update (:190); declared as the 200 response of the list, get, and set-permissions endpoints on RolesAdminControllerBase (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Administration/RolesAdminControllerBase.cs:85-152); consumed by RoleAdminService and rendered on ADC's role list and role edit pages.

SignInEndReasons

MMCA.Common.Shared · MMCA.Common.Shared.Auth.Responses · MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Responses/SignInEndReasons.cs:9 · Level 0 · class (static)

  • What it is: the closed set of string values SignInSummaryResponse.EndReason carries, one constant per way a sign-in can end (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Responses/SignInEndReasons.cs:3-9).
  • Depends on: nothing first-party at compile time; its doc comments refer to SignInHistoryEntryKind.
  • Concept: string constants rather than an enum, so the history reports exactly what the session store recorded: each revocation reason matches the refresh session's own reason constant of the same value, and Expired and ViewAsEnded are the two values no session revocation writes (SignInEndReasons.cs:4-7).
  • Walkthrough: six const string members, each equal to its own name.
    • SignedOut: this device, everywhere, or a password change (:11-12).
    • ReuseDetected: a replayed refresh token revoked the account's live sessions, BR-206 (:14-15).
    • SessionCapExceeded: a newer sign-in evicted this one under the per-user session cap (:17-18).
    • AccountDeleted: the account was deleted and erased (:20-21).
    • Expired: the sign-in reached its refresh-token expiry unrevoked (:23-24).
    • ViewAsEnded: the staff user ended a view-as grant before it expired (:26-27).
  • Why it's built this way: ADR-097 is the per-device session model whose revocations these values name, and ADR-137 adds the view-as row and its ViewAsEnded value.
  • Where it's used: written by SignInHistory, which stamps ViewAsEnded or Expired on a view-as row and Expired on an unrevoked sign-in past its expiry (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Sessions/SignInHistory.cs:86,90,175); read by the Common UI SignInHistoryTable component, which maps each value to a localized status string (MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Auth/SignInHistoryTable.razor.cs:79-87).
  • Caveats / not-in-source: EndReason is typed string?, so nothing in the contract stops a value outside this set; the UI component's doc comment states it handles a reason it does not know (SignInHistoryTable.razor.cs:18).

SignInHistoryEntryKind

MMCA.Common.Shared · MMCA.Common.Shared.Auth.Responses · MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Responses/SignInHistoryEntryKind.cs:10 · Level 0 · enum

  • What it is: what a SignInSummaryResponse row records: a sign-in by the account holder, or a support view of the account (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Responses/SignInHistoryEntryKind.cs:5-20).
  • Depends on: System.Text.Json's JsonStringEnumConverter<T> (BCL).
  • Concept: an enum serialized by name. The [JsonConverter(typeof(JsonStringEnumConverter<SignInHistoryEntryKind>))] attribute (SignInHistoryEntryKind.cs:9) puts the member name on the wire, so a client built against an older list of kinds reads a newer one as an unknown string rather than a bare number (:6-7). [Rubric §9, API & Contract Design] assesses contract evolution; this is the additive, forward-readable choice.
  • Walkthrough: SignIn = 0, one rotation chain of refresh sessions (:12-13); ViewAs = 1, a staff user viewed the account read-only through a view-as grant, shown to the holder as "Viewed by support", spanning the grant rather than a device sign-in (:15-19).
  • Why it's built this way: ADR-137 puts support access into the account holder's own history; ADR-097 owns the sign-in rows it sits beside.
  • Where it's used: the Kind parameter of SignInSummaryResponse, defaulting to SignIn (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Responses/SignInSummaryResponse.cs:49); set to ViewAs by SignInHistory when it summarizes a grant (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Sessions/SignInHistory.cs:102); read by the Common UI SignInHistoryTable to describe the row's device (MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Auth/SignInHistoryTable.razor.cs:72).

TwoFactorRecoveryCodesResponse

MMCA.Common.Shared · MMCA.Common.Shared.Auth.Responses · MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Responses/TwoFactorResponses.cs:41 · Level 0 · record (sealed)

  • What it is: the one-time list of recovery codes handed back after two-factor enrollment is confirmed or after codes are regenerated (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Responses/TwoFactorResponses.cs:41).
  • Depends on: nothing first-party at compile time.
  • Concept: shown to the user exactly once, at the moment it is minted; nothing in the type marks that, the "show once" rule is procedural, not enforced by the shape.
  • Walkthrough: a single positional parameter, RecoveryCodes (IReadOnlyList<string>), no body (TwoFactorResponses.cs:41).
  • Why it's built this way: follows the same DTO convention as its siblings in this file.
  • Where it's used: produced by ConfirmTwoFactorEnrollmentHandlerBase.HandleAsync after a successful enrollment (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/TwoFactor/ConfirmTwoFactorEnrollmentHandlerBase.cs:105) and by RegenerateRecoveryCodesHandlerBase.HandleAsync after a code regeneration (.../TwoFactor/RegenerateRecoveryCodesHandlerBase.cs:76), both wrapping the codes returned from the two-factor store.
  • Caveats / not-in-source: nothing in the response marks the codes as single-display; the UI, not this type, is responsible for not persisting or re-showing them.

TwoFactorSetupResponse

MMCA.Common.Shared · MMCA.Common.Shared.Auth.Responses · MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Responses/TwoFactorResponses.cs:27 · Level 0 · record struct (readonly)

  • What it is: the payload of beginning two-factor enrollment: the TOTP shared key and the provisioning URI an authenticator app scans as a QR code (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Responses/TwoFactorResponses.cs:27-29).
  • Depends on: nothing first-party; follows the readonly record struct DTO shape AuthenticationResponse introduces.
  • Concept: the same value-type carrier convention as AuthenticationResponse; no new concept.
  • Walkthrough: two positional parameters, SharedKey and ProvisioningUri, no body (TwoFactorResponses.cs:27-29).
  • Why it's built this way: value semantics for a small, short-lived response, consistent with the rest of this file's auth DTOs.
  • Where it's used: produced by BeginTwoFactorEnrollmentHandlerBase.HandleAsync at the end of a successful enrollment start (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/TwoFactor/BeginTwoFactorEnrollmentHandlerBase.cs:98).

TwoFactorStatusResponse

MMCA.Common.Shared · MMCA.Common.Shared.Auth.Responses · MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Responses/TwoFactorResponses.cs:51 · Level 0 · record struct (readonly)

  • What it is: the caller's two-factor state, for an account page that decides between "set it up" and the enabled actions; it carries no secret and no code (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Responses/TwoFactorResponses.cs:43-51).
  • Depends on: nothing first-party; follows the readonly record struct DTO shape AuthenticationResponse introduces.
  • Concept: the same value-type carrier convention as AuthenticationResponse; no new concept.
  • Walkthrough: two positional parameters (TwoFactorResponses.cs:51): IsEnabled, whether the second factor is active and demanded at sign-in (:47), and RecoveryCodesRemaining, the count of unspent recovery codes, documented as 0 while two-factor authentication is off (:48-50).
  • Why it's built this way: a status read needs only a flag and a count, so the response exposes the count of recovery codes rather than anything derived from the stored hashes.
  • Where it's used: built by the GetStatusAsync endpoint on TwoFactorControllerBase, which reads ITwoFactorStore and reports the stored hash count only when the factor is enabled, otherwise 0 (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/TwoFactor/TwoFactorControllerBase.cs:94-115); fetched client-side by TwoFactorUIService.GetStatusAsync (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/TwoFactor/TwoFactorUIService.cs:32,41) and held as page state by the TwoFactorAccount page (MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/TwoFactor/TwoFactorAccount.razor.cs:45).

UserPreferencesResponse

MMCA.Common.Shared · MMCA.Common.Shared.Auth.Responses · MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Responses/UserPreferencesResponse.cs:9 · Level 0 · record (sealed)

  • What it is: (string? Culture, string? Theme), the read side of the stored UI preferences: what the server hands back when a returning user signs in (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Responses/UserPreferencesResponse.cs:3-9).
  • Depends on: nothing first-party. It is the exact mirror of ChangePreferencesRequest.
  • Concept: the null-means-absent convention. Where the request's null means "leave unchanged", the response's null means the user has never chosen that preference (UserPreferencesResponse.cs:4-5). [Rubric §9, API & Contract Design] assesses whether the same wire shape can carry two different meanings without confusing the reader: here it can, because the two directions are separate types with separate doc comments rather than one reused DTO. [Rubric §27, i18n] and [Rubric §20, Design System & Theming] both apply, since this is the cross-device carrier for the culture and theme choices of ADR-027 and ADR-028: the browser's own storage is per device, and this response is what makes the choice roam with the account.
  • Walkthrough: two nullable positional parameters on a sealed record (UserPreferencesResponse.cs:9); no body. Being a record (not a record struct) it also carries value equality, which the tests lean on directly, asserting whole-object equality rather than field-by-field (MMCA.ADC/Tests/Modules/Identity/MMCA.ADC.Identity.Application.Tests/Users/UseCases/GetPreferences/GetUserPreferencesHandlerTests.cs:44,58).
  • Why it's built this way: like its request twin, the response record was byte-identical in both applications' Identity modules and was hoisted into Shared, which is what let the read side become a shared base generic parameterized only on the User aggregate rather than on the query and the response too (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/GetPreferences/GetUserPreferencesHandlerBase.cs:19-20).
  • Where it's used: produced by GetUserPreferencesHandlerBase<TUser> from the aggregate's PreferredCulture/PreferredTheme (GetUserPreferencesHandlerBase.cs:42), against a GetUserPreferencesQuery; declared as the 200 response of the shared GET preferences endpoint on UserAccountAuthControllerBase<TChangePasswordCommand, TChangePreferencesCommand> (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/UserAccountAuthControllerBase.cs:139,141,143).
  • Caveats / not-in-source: the handler reads through GetReadRepository, not the write repository, and the remarks note this was a deliberate correction of a disagreement between the two app copies (ADC read, Store write), so Store gained a no-tracking read on adoption (GetUserPreferencesHandlerBase.cs:16,39). As with the request twin, the Blazor client does not deserialize into this type: ApiUserPreferenceReader reads auth/preferences into its own UI-side UserPreferences record and falls back to an empty one for anonymous users or any transport error (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Preferences/ApiUserPreferenceReader.cs:18,39-40,44-48).

ViewAsGrantResponse

MMCA.Common.Shared · MMCA.Common.Shared.Auth.Responses · MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Responses/ViewAsGrantResponse.cs:16 · Level 0 · record (sealed)

  • What it is: the answer to a granted view-as request: a short-lived, read-only access token for the viewed account, and nothing to renew it with (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Responses/ViewAsGrantResponse.cs:3-6).
  • Depends on: the UserIdentifierType alias (primer conventions); nothing else first-party at compile time. The grant row it points at is a ViewAsGrant.
  • Concept: a deliberately non-renewable credential. Unlike AuthenticationResponse there is no refresh token: a view-as token is never renewed, so the grant's expiry is the hard end of the view (ViewAsGrantResponse.cs:7-11). [Rubric §11, Security] assesses how privileged access is bounded; here the bound is in the shape itself, since nothing in the response can extend it.
  • Walkthrough: four positional parameters (ViewAsGrantResponse.cs:16-20, documented at :12-15): AccessToken, the signed token carrying the act_sub and vag claims; AccessTokenExpiry, when the token and its grant expire; GrantId, the grant row the token was minted for; TargetUserId, the account being viewed.
  • Why it's built this way: ADR-137 defines read-only view-as support access. On a host with the same-origin API proxy, the proxy moves the access token into its overlay cookie and hands the browser the claims-only copy, as it does for a sign-in (ViewAsGrantResponse.cs:8-10).
  • Where it's used: built by ViewAsService after it stores the grant and mints the short-lived token with the view-as actor and grant claims, passing the grant's own ExpiresAt as the expiry (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/ViewAs/ViewAsService.cs:101-117); declared as the 200 response of StartViewAsAsync on UsersAdminControllerBase (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Administration/UsersAdminControllerBase.cs:163,168).

ViewAsGrantStatus

MMCA.Common.Shared · MMCA.Common.Shared.Auth.Responses · MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Responses/ViewAsGrantStatus.cs:11 · Level 0 · enum

  • What it is: where a view-as grant stands, derived from its end and expiry instants rather than stored (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Responses/ViewAsGrantStatus.cs:5-11).
  • Depends on: System.Text.Json's JsonStringEnumConverter<T> (BCL).
  • Concept: the serialized-by-name enum introduced at SignInHistoryEntryKind (ViewAsGrantStatus.cs:10), applied to a computed status: there is no status column, so the value can never disagree with the instants it is derived from.
  • Walkthrough: Live = 0, neither ended nor expired (:13-14); Ended = 1, the staff user ended the view before it expired (:16-17); Expired = 2, the view ran out its lifetime without being ended (:19-20).
  • Why it's built this way: ADR-137 is the support-access model whose log these values label.
  • Where it's used: computed by ViewAsGrant.StatusAt(now), which returns Ended once an end instant is set, otherwise Live until expiry and Expired after (MMCA.Common/Source/Core/MMCA.Common.Domain/Auth/ViewAsGrant.cs:175-188); used as a log filter by ViewAsGrantLogQuery, which translates each value into the same predicate on EndedAt and ExpiresAt (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/ViewAs/ViewAsGrantLogQuery.cs:67-69); carried by ViewAsGrantSummaryResponse.Status; rendered as a colored chip on the Common UI SupportAccessLog page (MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Administration/SupportAccessLog.razor.cs:118-120).

RefreshSessionSummaryResponse

MMCA.Common.Shared · MMCA.Common.Shared.Auth.Responses · MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Responses/RefreshSessionSummaryResponse.cs:28 · Level 1 · record (sealed)

  • What it is: one row of a user's "signed-in devices" list, describing a live refresh session in the terms a person can recognize it by (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Responses/RefreshSessionSummaryResponse.cs:3-5).
  • Depends on: DeviceMetadata, the optional native-device description. It is the sanitized projection of the RefreshSession entity, and its IsCurrent flag is computed from the sid claim named by AuthClaimTypes.SessionId.
  • Concept introduced, the sanitized read model over a credential-bearing entity. [Rubric §11, Security] assesses what a response is allowed to expose, and [Rubric §9, API & Contract Design] assesses whether a contract carries exactly the fields its consumers need. The entity behind this row holds the material the refresh-token reuse check runs on: a TokenHash (MMCA.Common/Source/Core/MMCA.Common.Domain/Auth/RefreshSession.cs:88) and the rotation link ReplacedByTokenHash (RefreshSession.cs:103). Both are deliberately absent from this response, and the doc comment states the reasoning (RefreshSessionSummaryResponse.cs:6-11): shipping either would hand every caller a queryable index of another session's credentials-at-rest for no gain, since nothing a client does with a session needs anything but its id. The rule is enforced by a reflection assertion rather than by review habit: a test asserts the type's property names contain neither TokenHash nor ReplacedByTokenHash (MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Auth/RefreshSessionManagementTests.cs:203-205). This is the read-model half of the "never project a secret" discipline; the same instinct is what keeps password hashes out of every user DTO.
  • Walkthrough: seven positional parameters on a sealed record (RefreshSessionSummaryResponse.cs:28-35), documented one by one at :13-27.
    • SessionId (Guid) is the value a per-device sign-out is addressed to (:13), which is why it is the only identifying field the row needs.
    • CreatedAt and ExpiresAt (DateTime, both UTC) say when this device signed in and when the session stops being usable even if never revoked (:14-15).
    • IpAddress and UserAgent are nullable and explicitly labeled informational (:16-17): they are what a human recognizes a device by, and nothing authorizes on them.
    • IsCurrent (bool) marks the session the calling access token was minted for. The doc comment records the degradation rule (:18-22): it is always false for a caller whose token predates the sid claim, because nothing then identifies the caller's own device.
    • Device (DeviceMetadata?, defaulting to null) is the device metadata a native client reported for this session through PUT auth/sessions/current/device, and null for every browser session (:23-27). It is informational like UserAgent, which stays the fallback description. As the last parameter with a default, a positional construction may omit it.
  • Why it's built this way: ADR-097 introduces the per-device refresh session, and ADR-050 is the rotation scheme whose hashes this response must not leak. IsCurrent is computed server-side rather than guessed by the client, which is what keeps the UI from having to parse a token to know which row is its own: the issuer compares each session id against a currentSessionId argument (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Sessions/AuthSessionIssuer.cs:281), and the interface documents that passing null simply marks no row as current (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/IAuthenticationService.cs:93-98).
  • Where it's used: produced by AuthSessionIssuer.ListActiveAsync, which reads unrevoked sessions from IRefreshSessionStore, filters to those active at the current instant, orders newest-first, and projects each into this record, filling Device from the session (AuthSessionIssuer.cs:261-283); AuthenticationServiceBase<TUser>.GetSessionsAsync delegates to it (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/AuthenticationServiceBase.cs:505-512). UserSessionsAdministrationService.GetSessionsAsync builds the same projection for an administrator's view of another account, with IsCurrent: false on every row (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Administration/UserSessionsAdministrationService.cs:48-61), served by UsersAdminControllerBase (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Administration/UsersAdminControllerBase.cs:105). Returned to the account holder by the GET my-sessions endpoint on AuthControllerBase, which supplies the caller's own session via User.FindSessionId() (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/AuthControllerBase.cs:286-296); fetched client-side by AuthUIService.GetSessionsAsync (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/AuthUIService.cs:313,321) and rendered by the Sessions page, which refuses the revoke action on the caller's own row (IsCurrent) and describes each device from Device with UserAgent as the fallback (MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/Sessions.razor.cs:43,148-150,267).
  • Caveats / not-in-source: IpAddress and UserAgent are whatever the client sent at issue time and are stored verbatim, and Device is whatever the native client reported; nothing in this type or the projection validates, geolocates, or canonicalizes them, so a spoofed user-agent shows up as-is in the device list.

RegistrationOutcome

MMCA.Common.Shared · MMCA.Common.Shared.Auth.Responses · MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Responses/AuthenticationResponse.cs:28 · Level 1 · class (static)

  • What it is: the in-process signal for "registered, confirmation pending, no session": a successful registration result that carries no tokens (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Responses/AuthenticationResponse.cs:23-28).
  • Depends on: AuthenticationResponse, the value it names and tests.
  • Concept, a sentinel value instead of a new return type. IAuthenticationService.RegisterAsync keeps returning a result of AuthenticationResponse, and a token-less success means the confirmation is pending; that is what lets the register endpoint answer 202 instead of 201 without changing the service signature (AuthenticationResponse.cs:24-26). [Rubric §9, API & Contract Design] assesses stable contracts; the cost of this choice is that the meaning lives in a convention, so the convention is given a name and a single test method rather than left as scattered empty-string checks.
  • Walkthrough:
    • ConfirmationPending (AuthenticationResponse.cs:34-35): a static property holding an AuthenticationResponse with empty tokens and DateTime.MinValue expiry.
    • IsConfirmationPending(this AuthenticationResponse) (:44-45): an extension method returning string.IsNullOrEmpty(response.AccessToken), so it is true for ConfirmationPending and for any value without an access token, default included (:37-43). That second case matters because the struct has no null, the same consequence noted at AuthenticationResponse.
  • Why it's built this way: the gate that decides is the one that decides sign-in. The service returns ConfirmationPending exactly when the email-confirmed check that sign-in runs would refuse the new account, so a subclass override of that check moves registration and sign-in together (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/AuthenticationServiceBase.cs:382-388).
  • Where it's used: returned by AuthenticationServiceBase<TUser> (AuthenticationServiceBase.cs:387); tested by AuthControllerBase, which then answers 202 with a RegistrationPendingResponse (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/AuthControllerBase.cs:142-149); produced client-side by AuthUIService when the API answers 202, so UI code reads the same signal (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/AuthUIService.cs:442,462).

SignInSummaryResponse

MMCA.Common.Shared · MMCA.Common.Shared.Auth.Responses · MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Responses/SignInSummaryResponse.cs:40 · Level 1 · record (sealed)

  • What it is: one row of a sign-in history: a single sign-in (one rotation chain of refresh sessions) from the moment it opened to its last token refresh, and how it ended. A sign-in that rotated its refresh token a hundred times is still one row (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Responses/SignInSummaryResponse.cs:3-6).
  • Depends on: SignInHistoryEntryKind, DeviceMetadata, and the SignInEndReasons values its EndReason carries.
  • Concept: the sanitized read model introduced at RefreshSessionSummaryResponse, applied one level up: no token hash and no rotation link, only what a person recognizes a sign-in by (SignInSummaryResponse.cs:7-10). Where the session list shows what is live now, this shows history, so it adds an end instant and a reason.
  • Walkthrough: ten positional parameters (SignInSummaryResponse.cs:40-50, documented at :12-39).
    • SignInId: the id of the session that opened the sign-in (for a row written before sign-in grouping, the row's own id) (:12-15).
    • StartedAt and LastActiveAt: the earliest retained session and the last token refresh (:16-17).
    • IpAddress and UserAgent: recorded on the newest session, informational (:18-19).
    • EndedAt and EndReason: when and why it ended, both null while it is live (:20-26).
    • IsCurrent: the sign-in the calling token belongs to, always false in an administrator's view of another account (:27-30).
    • Kind (default SignIn): a sign-in or a view-as row, documented as the extension point for other account-access events (:31-35).
    • Device (default null): reported native device metadata from the newest session, null for every browser sign-in and every view-as entry (:36-39).
  • Why it's built this way: ADR-097 owns the per-device session model, and the Kind and the "Viewed by support" row come from ADR-137.
  • Where it's used: shaped by SignInHistory, which summarizes each RefreshSessionSignIn and each view-as grant (a view-as row has no IP or user agent and IsCurrent: false) (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Sessions/SignInHistory.cs:80-103,149-154), read through AuthSessionIssuer.ListSignInsAsync (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Sessions/AuthSessionIssuer.cs:292-296) and UserSessionsAdministrationService.GetSignInsAsync (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Administration/UserSessionsAdministrationService.cs:72); served by GET my-sign-ins on AuthControllerBase (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/AuthControllerBase.cs:369-379) and by UsersAdminControllerBase (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Administration/UsersAdminControllerBase.cs:129); fetched by AuthUIService (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/AuthUIService.cs:327,335) and rendered by the Common UI SignInHistoryTable component (MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Auth/SignInHistoryTable.razor.cs:30,71-87).
  • Caveats / not-in-source: EndReason is a string?, not an enum, so the set of values is fixed only by convention at SignInEndReasons.

ViewAsGrantSummaryResponse

MMCA.Common.Shared · MMCA.Common.Shared.Auth.Responses · MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Responses/ViewAsGrantSummaryResponse.cs:23 · Level 1 · record (sealed)

  • What it is: one row of the support access log: a view-as grant, who viewed whom, why, when, and how it ended. No token or claim travels here, only the audit record (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Responses/ViewAsGrantSummaryResponse.cs:3-6).
  • Depends on: ViewAsGrantStatus and the UserIdentifierType alias (primer conventions). It is the read projection of ViewAsGrant.
  • Concept: an audit read model. [Rubric §30, Compliance/Privacy/Data Governance] assesses whether privileged access to personal data is recorded and reviewable; this is the reviewable side of view-as, and it carries the staff user's stated reason in full. Unlike ViewAsGrantResponse it holds no credential.
  • Walkthrough: ten positional parameters (ViewAsGrantSummaryResponse.cs:23-33, documented at :7-22): Id (the token's vag claim); StaffUserId and TargetUserId; StaffDisplay and TargetDisplay, email snapshots taken when the grant was issued and null once that account was erased (or for a grant issued before the snapshot) (:9-17); Reason; GrantedAt, ExpiresAt and EndedAt; and Status, where the grant stands at the time of the read (:22).
  • Why it's built this way: ADR-137 defines the support access log. The display fields are documented as email snapshots taken at issue time, so a row still names both parties after either email changes.
  • Where it's used: built by ViewAsGrantsAdminControllerBase, which pages grants from the store and computes Status with StatusAt(now) against one read instant (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Administration/ViewAsGrantsAdminControllerBase.cs:75-90); fetched by the Common UI ViewAsGrantsService and rendered on the SupportAccessLog page.
  • Caveats / not-in-source: the claim that erasure nulls the display fields is taken from the parameter documentation (:9-17); the erasure code path itself was not read for this section.

IcsEvent

MMCA.Common.Shared · MMCA.Common.Shared.Calendars · MMCA.Common/Source/Core/MMCA.Common.Shared/Calendars/IcsEvent.cs:15 · Level 0 · record

  • What it is: one calendar entry handed to IcsCalendarBuilder: a stable Uid, a Summary, a UTC start and end, and two optional strings for description and location (MMCA.Common/Source/Core/MMCA.Common.Shared/Calendars/IcsEvent.cs:15-21).
  • Depends on: nothing first-party; System.DateTimeOffset (BCL).
  • Concept introduced, the UTC-only calendar contract. [Rubric §9, API & Contract Design] assesses whether a contract states its own invariants rather than leaving them to convention. The invariant here is written into the type's own doc comment: "Times are UTC by contract" (IcsEvent.cs:4). RFC 5545 lets a calendar carry local times paired with a VTIMEZONE block that restates the zone's DST rules inside the document; getting that block right (and keeping it right as tzdata moves) is a well-known source of bugs. By declaring the two timestamps DateTimeOffset and requiring them to already be UTC instants, this record pushes the wall-clock to UTC conversion onto the caller, which is where the zone knowledge actually lives, and lets the builder emit plain Z-suffixed timestamps with no VTIMEZONE machinery at all (IcsEvent.cs:5-7). The Uid carries a second contract: calendar clients de-duplicate re-imports by it, so it must be globally unique and stable across exports of the same thing (IcsEvent.cs:9).
  • Walkthrough: a positional sealed record with six parameters and no body. Uid, Summary, StartsAtUtc, EndsAtUtc are required by position; Description and Location default to null (IcsEvent.cs:16-21), which is how the builder decides to omit the corresponding lines entirely rather than emit an empty one. A record (reference type) rather than the readonly record struct that the auth DTOs in this group use: entries are built into a collection and enumerated once, so there is no per-call allocation to avoid.
  • Why it's built this way: the framework ships no calendar NuGet dependency, so the shape of an entry is the framework's to define. Keeping it to the six fields every calendar client honors is the same minimal-subset judgement the builder documents at MMCA.Common/Source/Core/MMCA.Common.Shared/Calendars/IcsCalendarBuilder.cs:7-10. No ADR governs calendar export; the decision lives in these two files' doc comments.
  • Where it's used: ADC's Conference module builds entries from sessions in CalendarExportMapper, which does the event-zone to UTC conversion the contract demands (its ToUtc helper at MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Application/Sessions/UseCases/ExportCalendar/CalendarExportMapper.cs:45) and composes the Uid as session-{id}@atldevcon (CalendarExportMapper.cs:29-42, the id at :38). The mapped entries reach ExportSessionCalendarHandler (.../ExportCalendar/ExportSessionCalendarHandler.cs:52-55) and ExportEventCalendarHandler (.../ExportCalendar/ExportEventCalendarHandler.cs:46-53).
  • Caveats / not-in-source: nothing in the type enforces that StartsAtUtc and EndsAtUtc really carry a zero offset, that the end follows the start, or that the Uid is unique. All three are contract-by-documentation; the only enforcement is the mapper that produces them.

ModuleNameConventions

MMCA.Common.Shared · MMCA.Common.Shared.Conventions · MMCA.Common/Source/Core/MMCA.Common.Shared/Conventions/ModuleNameConventions.cs:10 · Level 0 · class (static)

  • What it is: one function, GetModuleName(Type), that reads a CLR type's namespace and returns the module that owns it, following the workspace naming convention MMCA.{App}.{Module}.{Layer} (MMCA.Common/Source/Core/MMCA.Common.Shared/Conventions/ModuleNameConventions.cs:10-51). MMCA.Store.Sales.Domain.Orders gives "Sales"; MMCA.ADC.Conference.Application.Sessions gives "Conference"; a type outside that shape gives null.
  • Depends on: nothing first-party; System.Array.FindIndex/Array.Exists and string.Split (BCL).
  • Concept introduced, convention over configuration, with the convention hoisted to one function. [Rubric §15, Best Practices & Code Quality] assesses whether a rule two subsystems must agree on has one implementation. [Rubric §7, Microservices Readiness] assesses whether module ownership is a first-class, machine-readable fact rather than a naming habit. Two very different subsystems need to answer "which module does this type belong to": persistence, which turns the answer into a SQL schema name and a logical data-source name, and the CQRS logging decorators, which stamp it into every log scope. The class doc names the constraint that forced the hoist: Application "may not reference Infrastructure" (ModuleNameConventions.cs:6-8), so the derivation cannot live beside the persistence code that first needed it. [Rubric §3, Clean Architecture] in miniature: the rule moved down to MMCA.Common.Shared, the assembly every layer may see, rather than up into a layer that would have inverted the dependency. The alternative (each subsystem parsing namespaces its own way) is the drift the test file names explicitly: the two callers "must never disagree" (MMCA.Common/Tests/Core/MMCA.Common.Shared.Tests/Conventions/ModuleNameConventionsTests.cs:10-11).
  • Walkthrough:
    • NonDomainLayerSegments is a private static readonly string[] holding Application, Infrastructure, API, UI (ModuleNameConventions.cs:17). What is absent is the load-bearing part, and the comment says so: Shared is deliberately not in the list, so framework namespaces such as MMCA.Common.Shared.* cannot resolve to a phantom module (:13-16).
    • GetModuleName (:38) splits the namespace, defaulting to an empty array when the type has none (:40), so a compiler-generated or global-namespace type is handled without a null check at the call site.
    • Rule one, Domain at any position past the first segment (:41-46). This is the original persistence rule, and the remark records that it is kept byte-for-byte so schema and data-source names do not move (:26-28). domainIndex >= 1 is the guard: a namespace that starts with Domain has nothing preceding it to name.
    • Rule two, the other layer segments, only at the fourth segment or later (:48-50). The layerIndex >= 3 test is what makes MMCA.Common.Application.* return null rather than the phantom "Common": in that namespace Application sits at index 2, below the threshold, while in MMCA.ADC.Conference.Application it sits at index 3 and yields "Conference" (:29-31).
    • Every comparison is StringComparison.OrdinalIgnoreCase (:42,49), and the first matching segment wins (:22-23), so a module that happens to be named after a layer word resolves deterministically rather than by accident of ordering.
  • Why it's built this way: no ADR governs the derivation; the rationale is entirely in the class doc comment and in the test file's summary. The asymmetric threshold (any position for Domain, index 3 or later for the rest) is not elegance, it is compatibility: relaxing the Domain rule would rename live SQL schemas, and tightening the others is what keeps framework namespaces module-less.
  • Where it's used: two subsystems, exactly as the doc comment claims. LoggingQueryDecorator<TQuery, TResult> and LoggingCommandDecorator<TCommand, TResult> each resolve it into a private static readonly string ModuleName, falling back to "unknown" (MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Decorators/LoggingQueryDecorator.cs:100, .../LoggingCommandDecorator.cs:76) and push it into the log scope (LoggingQueryDecorator.cs:31,93, LoggingCommandDecorator.cs:26,69). Because the field is static on a closed generic, the namespace parse happens once per query or command type rather than per execution, which the doc comment calls out (LoggingQueryDecorator.cs:95-99). On the persistence side, the internal NamespaceConventions wrapper delegates straight to it (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/NamespaceConventions.cs:20-21), and that wrapper is what EntityTypeConfiguration<TEntity, TIdentifierType> uses for the SQL Server schema name (falling back to dbo, .../Configuration/EntityTypeConfiguration/EntityTypeConfiguration.cs:66) and the Cosmos container name (.../DataSources/Engines/CosmosDataSourceEngine.cs:95), and what EntityDataSourceRegistry uses to derive a logical database name when no [UseDatabase] attribute overrides it (.../DataSources/EntityDataSourceRegistry.cs:181).
  • Caveats / not-in-source: the parse keys on the type's own namespace and never on its type arguments, so List<SalesFakeAggregate> resolves to null rather than "Sales"; that is pinned by test rather than by anything visible in the method (ModuleNameConventionsTests.cs:46-48). The "framework namespaces resolve to no module" behavior has no direct test in this file either: the comment records that it is pinned indirectly, by the LoggingCommandDecorator tests asserting a scope of "unknown" for their own fake command (ModuleNameConventionsTests.cs:41-44).

ConcurrencyETag

MMCA.Common.Shared · MMCA.Common.Shared.Http · MMCA.Common/Source/Core/MMCA.Common.Shared/Http/ConcurrencyETag.cs:24 · Level 0 · class (static)

  • What it is: the translator between the framework's optimistic-concurrency token (the EF Core rowversion byte array carried by IConcurrencyAware) and the HTTP entity tag that represents that token on the wire. It owns three header constants plus a Format/TryParse pair (MMCA.Common/Source/Core/MMCA.Common.Shared/Http/ConcurrencyETag.cs:24-105).
  • Depends on: nothing first-party at runtime (the doc comment references IConcurrencyAware at ConcurrencyETag.cs:7). BCL only: Convert.ToBase64String, Convert.TryFromBase64Chars, ReadOnlySpan<char>, and [NotNullWhen] from System.Diagnostics.CodeAnalysis (ConcurrencyETag.cs:1).
  • Concept introduced, the HTTP conditional-request boundary for optimistic concurrency. Optimistic concurrency itself is introduced at IConcurrencyAware: a client echoes back the row version it last saw so a stale write is refused. This type is where that value becomes an HTTP citizen, and two decisions recorded in its own doc comment are the whole design. First, the tag is always weak (W/"...", ConcurrencyETag.cs:12-18): a strong entity tag promises byte-for-byte equality of the representation, and this one does not, because the same row version renders differently under a fields= projection and says nothing about serializer formatting. Weak is the honest strength for a token that answers "is this the same version of the resource", which is exactly what If-Match asks. Second, the payload is base64 of the raw token (ConcurrencyETag.cs:19-22), so the round trip is lossless and the value stays inside the quoted-string grammar RFC 9110 defines for an entity tag. [Rubric §9, API & Contract Design] assesses whether the framework speaks the standard protocol rather than inventing a private one: preconditions here travel in the headers HTTP already defines, so a generic client library can participate. [Rubric §8, Data Architecture] covers concurrency control as a deliberate persistence concern. This is also the same shared-wire-literal placement rule IdempotencyHeaders follows, and the doc comment says so: it lives in Shared "because both ends of the exchange need it: the API reads an If-Match value with it and the UI services write one with it" (ConcurrencyETag.cs:8-9).
  • Walkthrough:
    • Three constants name the protocol: IfMatchHeaderName = "If-Match" (ConcurrencyETag.cs:27), ETagHeaderName = "ETag" (:30), and Wildcard = "*" (:33), the If-Match value that matches any current version.
    • Format(byte[] rowVersion) (:40) null-guards (:42) and returns string.Concat("W/\"", Convert.ToBase64String(rowVersion), "\"") (:44), so a token renders as, for example, W/"AAAAAAAAB9E=".
    • TryParse(string? value, out byte[]? rowVersion) (:62) is deliberately forgiving on the way in and strict about what counts as success. It nulls the out parameter first (:64), returns false for a blank value (:66-69), then takes only the first entry of a comma-separated list (:71-77). The remark explains why (:57-61): a conditional write here is a single-version precondition, since there is one row version to compare against, so a list beyond its first entry has no meaning. It then trims (:79), strips a case-insensitive W/ prefix (:81-84), strips the surrounding quotes when both are present (:86-89), and fails on an empty remainder (:91-94).
    • Decoding is allocation-conscious: it sizes a buffer from the candidate length (:96), calls Convert.TryFromBase64Chars and rejects both a decode failure and a zero-length result (:97-100), then slices the buffer to the bytes actually written (:102).
    • The contract on false is spelled out in the doc (:52-56): a blank value, the wildcard, and anything that is not base64 all return false, and the caller decides which of those is an error in its context. That is what lets SupportsIfMatchAttribute treat a wildcard as "no precondition" while treating unparsable input as a 400.
  • Why it's built this way: ADR-035 is the governing record. It picks the header as the one transport because HTTP already defines ETag and If-Match for precisely this exchange (Website/docs-src/adr/035-optimistic-concurrency.md:23-24,147), and it states the Shared placement as a deliberate consequence: the type lives in MMCA.Common.Shared.Http "rather than in the API package precisely so both ends of the exchange can use it" (035-optimistic-concurrency.md:124-128). Keeping the wire format in one static class means the reader side and the writer side cannot disagree about weakness, base64, or list handling; pushing the error decision to the caller keeps the parser free of HTTP status opinions.
  • Where it's used: server side, ApiControllerBase.SetConcurrencyETag (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/ApiControllerBase.cs:136) writes Response.Headers[ConcurrencyETag.ETagHeaderName] = ConcurrencyETag.Format(rowVersion) (ApiControllerBase.cs:144), which EntityControllerBase<TEntity, TEntityDTO, TIdentifierType> calls after a successful by-id read (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/EntityControllerBase.cs:396), and the CRUD base does the same after a create (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/CrudEntityControllerBase.cs:113); SupportsIfMatchAttribute reads the request header (MMCA.Common/Source/Presentation/MMCA.Common.API/Concurrency/SupportsIfMatchAttribute.cs:155), compares against the wildcard (:110) and decodes with TryParse (:116). Client side, EntityServiceBase<TEntityDTO, TIdentifierType> formats the tag (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Api/EntityServiceBase.cs:217) and attaches it as If-Match by passing it to its base's dispatch (EntityServiceBase.cs:205), which adds the header (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Api/AuthenticatedServiceBase.cs:253), as do ADC's EventService (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.UI/Services/Events/EventService.cs:42,54), SessionQuestionUIService (MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.UI/Services/SessionLive/SessionQuestionUIService.cs:98) and LivePollUIService (MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.UI/Services/SessionLive/LivePollUIService.cs:137). Framework coverage is ConcurrencyETagTests (MMCA.Common/Tests/Core/MMCA.Common.Shared.Tests/Http/ConcurrencyETagTests.cs:16,21,33,47), and ADC's integration bases build their If-Match values through the same helper (MMCA.ADC/Tests/Integration/MMCA.ADC.Conference.IntegrationTests/Infrastructure/ConferenceIntegrationTestBase.cs:60,70,74).
  • Caveats / not-in-source: the ETag this type renders exists to be echoed back on the next write. Nothing here implements conditional GET: no code path compares an inbound If-None-Match against it, which ADR-035 records explicitly (Website/docs-src/adr/035-optimistic-concurrency.md:182-184).

IdempotencyHeaders

MMCA.Common.Shared · MMCA.Common.Shared.Http · MMCA.Common/Source/Core/MMCA.Common.Shared/Http/IdempotencyHeaders.cs:13 · Level 0 · class (static)

  • What it is: the two HTTP header names of the idempotency protocol, as const strings: Idempotency-Key (the request header a client sends) and X-Idempotent-Replay (the response header a server appends when it served a cached body) (MMCA.Common/Source/Core/MMCA.Common.Shared/Http/IdempotencyHeaders.cs:19,25).
  • Depends on: nothing.
  • Concept introduced, the shared wire-literal. [Rubric §15, Best Practices & Code Quality] assesses whether a fact that two components must agree on has exactly one home. [Rubric §9, API & Contract Design] assesses whether the protocol between client and server is expressed explicitly. Both ends of this protocol are first-party but live in packages that do not reference each other: the filter that reads the key ships in MMCA.Common.API, the service bases that write it ship in MMCA.Common.UI. The doc comment states the consequence plainly: "Hard-coding the string in both places is exactly the drift this constant exists to prevent" (IdempotencyHeaders.cs:8-12). Putting the literal in MMCA.Common.Shared, the one assembly both sides already depend on, is the standard placement rule for cross-layer constants in this framework, and it is the same rule ConcurrencyETag and the auth request DTOs follow.
  • Walkthrough: a static class with two const string fields and nothing else (IdempotencyHeaders.cs:13-26). const rather than static readonly so the values can appear in attribute arguments and constant patterns, matching AuthClaimTypes and RoleNames in this group.
  • Why it's built this way: ADR-017 defines the protocol: the client supplies the key, and a server that replays a cached response adds X-Idempotent-Replay: true so the caller can tell a replay from a fresh execution (Website/docs-src/adr/017-request-idempotency.md:31,46).
  • Where it's used: server side, IdempotencyFilter re-exports the request header name as a public property (MMCA.Common/Source/Presentation/MMCA.Common.API/Idempotency/IdempotencyFilter.cs:76), reads it in the one helper both filter stages share (IdempotencyFilter.cs:170), and appends the replay header when it serves a cached response (IdempotencyFilter.cs:433); NotificationsController reads the same request header directly (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Notifications/NotificationsController.cs:62). Client side, EntityServiceBase<TEntityDTO, TIdentifierType> attaches a generated key on retried writes: it mints one per create and update (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Api/EntityServiceBase.cs:180,204), and its base writes it under this header name on the client every retry attempt shares (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Api/AuthenticatedServiceBase.cs:242), as do ADC's SessionQuestionUIService (MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.UI/Services/SessionLive/SessionQuestionUIService.cs:72) and LivePollUIService (MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.UI/Services/SessionLive/LivePollUIService.cs:92,155).

QueryFilterKeys

MMCA.Common.Shared · MMCA.Common.Shared.Http · MMCA.Common/Source/Core/MMCA.Common.Shared/Http/QueryFilterKeys.cs:20 · Level 0 · class (static)

  • What it is: the shared grammar of a list-page filter key: a property name, optionally followed by ~ and a tag, so a second filter on the same property gets its own dictionary key (QueryFilterKeys.cs:20-55).
  • Depends on: nothing.
  • Concept introduced, the shared wire-literal again. [Rubric §9, API & Contract Design] asks whether the client-server protocol is explicit. The UI composes the key and the server parses it, in assemblies that do not reference each other, so the separator lives in MMCA.Common.Shared, the same placement rule as IdempotencyHeaders and ConcurrencyETag.
  • Walkthrough: AliasSeparator is the '~' char (QueryFilterKeys.cs:23) and SearchTag is the tag a list page's search box uses, "search" (:26). Alias(property, tag) (:34) rejects a null or blank argument and returns property~tag, for example Name~search. PropertyOf(key) (:48) is the inverse: it returns the part before the first ~, or the whole key when there is no separator.
  • Where it's used: the UI list base builds the search-box key with QueryFilterKeys.Alias(key, QueryFilterKeys.SearchTag) (MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Common/DataGridListPageBase.cs:1753), and QueryFilterService strips the tag with PropertyOf before validating the property (MMCA.Common/Source/Core/MMCA.Common.Application/Services/Filtering/QueryFilterService.cs:122,203). Framework coverage is QueryFilterAliasedKeyTests (MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Services/Query/QueryFilterAliasedKeyTests.cs).

IcsCalendarBuilder

MMCA.Common.Shared · MMCA.Common.Shared.Calendars · MMCA.Common/Source/Core/MMCA.Common.Shared/Calendars/IcsCalendarBuilder.cs:12 · Level 1 · class (static)

  • What it is: a dependency-free RFC 5545 writer. Given a product id, a collection of IcsEvent, and a timestamp, it returns a complete VCALENDAR document as a string (MMCA.Common/Source/Core/MMCA.Common.Shared/Calendars/IcsCalendarBuilder.cs:22-41).
  • Depends on: IcsEvent; System.Text.StringBuilder, System.Text.Encoding, and System.Globalization.CultureInfo (BCL). No NuGet package.
  • Concept introduced, the deterministic pure builder. [Rubric §14, Testability] assesses whether behavior can be asserted without a harness. This type takes dtStamp as a parameter rather than reading a clock, and the doc comment states the consequence: "Deterministic by design: the caller supplies dtStamp, so identical inputs produce identical output" (IcsCalendarBuilder.cs:9-10). That makes the whole document byte-assertable, which is exactly what the suite in MMCA.Common/Tests/Core/MMCA.Common.Shared.Tests/Calendars/IcsCalendarBuilderTests.cs does, including a determinism test that builds twice and compares (IcsCalendarBuilderTests.cs:138-143). [Rubric §32, Dependency & Supply-Chain] assesses what the framework takes on as a dependency. Emitting an ICS file is a few hundred lines of string handling; taking a calendar library for it would add a transitive surface to MMCA.Common.Shared, the assembly every other package depends on. The type instead states its scope as "the subset every calendar app imports reliably" (IcsCalendarBuilder.cs:7-9).
  • Walkthrough:
    • MaxLineOctets = 75 (IcsCalendarBuilder.cs:14) is RFC 5545's content-line limit, counted in octets rather than characters.
    • Build (:22) guards both inputs (ThrowIfNullOrWhiteSpace on the product id, ThrowIfNull on the events, :24-25), then writes the fixed calendar preamble VERSION:2.0, an escaped PRODID, CALSCALE:GREGORIAN, and METHOD:PUBLISH (:28-32), loops the entries in the order given (:34-37), and closes the document (:39). Note that an empty collection is legal: it produces a valid, entry-less calendar, which IcsCalendarBuilderTests.cs:151 pins.
    • AppendEvent (:43) writes the five mandatory VEVENT lines: UID, DTSTAMP, DTSTART, DTEND, SUMMARY (:46-50). DESCRIPTION and LOCATION are emitted only when the optional field is not null or whitespace (:52-60), so an all-blank location does not leave a stray empty property in the document.
    • FormatUtc (:65) is where the UTC-only contract shows up on the wire: it converts through UtcDateTime and formats yyyyMMdd'T'HHmmss'Z' under InvariantCulture (:66). The invariant culture is not optional decoration; a non-Gregorian or non-ASCII-digit current culture would otherwise corrupt the timestamp.
    • EscapeText (:69) implements RFC 5545 section 3.3.11 TEXT escaping. Order matters and is correct here: backslash is escaped first (:71), so the backslashes introduced by the later replacements are not double-escaped. Semicolon and comma follow (:72-73), then all three newline forms collapse to the literal escaped-n sequence (:74-76), CRLF before its parts so a Windows line break does not become two escapes.
    • AppendLine (:83) is the subtlest method: RFC 5545 folding. It walks the string counting UTF-8 octets per character, treating a surrogate pair as one unit (:89-90), and when the next character would push the line past 75 octets it emits CRLF plus a single space and resets the counter to 1 (:92-96). Two details are easy to get wrong and are handled: a fold never splits a multi-byte character (because the decision is made per character, before appending), and the continuation line's leading space counts against its own budget, which the inline comment states (:95). Every line, folded or not, ends in CRLF (:103).
  • Why it's built this way: no ADR covers calendar export; the rationale is entirely in the doc comments cited above. The minimal-subset choice is the same instinct as the IcsEvent UTC contract: avoid the parts of the specification whose correctness would need continuous maintenance.
  • Where it's used: ADC's Conference module only, from ExportSessionCalendarHandler for a single session (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Application/Sessions/UseCases/ExportCalendar/ExportSessionCalendarHandler.cs:52-55) and ExportEventCalendarHandler for a whole event (.../ExportCalendar/ExportEventCalendarHandler.cs:46-53), both passing CalendarExportMapper's ProductId constant -//MMCA//AtlDevCon//EN (.../ExportCalendar/CalendarExportMapper.cs:17).
  • Caveats / not-in-source: both ADC handlers now pass an injected TimeProvider's GetUtcNow() for dtStamp (ExportSessionCalendarHandler.cs:55, ExportEventCalendarHandler.cs:54), so the determinism the builder guarantees is exercised through the handlers as well as the builder's own tests.

CommitOutcomeUnknown

MMCA.Common.Shared · MMCA.Common.Shared.Http · MMCA.Common/Source/Core/MMCA.Common.Shared/Http/CommitOutcomeUnknown.cs:28 · Level 3 · class (static)

  • What it is: the wire contract for a write whose database commit failed with an unknown outcome, meaning the database may have made it durable and lost only the acknowledgement. It holds the error code, the response header name and value, the server's message, and three Is overloads that classify an Error, a Result or a raw HttpResponseMessage (MMCA.Common/Source/Core/MMCA.Common.Shared/Http/CommitOutcomeUnknown.cs:5-11,28-63).
  • Depends on: Error and Result from MMCA.Common.Shared.Abstractions (CommitOutcomeUnknown.cs:1); BCL System.Net.Http.HttpResponseMessage and LINQ Any.
  • Concept introduced, the never-resend signal. A commit that throws after it was sent is not a failure in the ordinary sense: the change may or may not exist. The remark states the one rule the type carries, in bold: "never resend such a write automatically" (CommitOutcomeUnknown.cs:14). The reason is a gap in the idempotency protocol that the same remark names: the idempotency filter stores a record only for a 2xx, so a resend under the same Idempotency-Key re-executes the handler, and against a commit that did land that duplicates the write (:15-17). Recovery is to read the resource back and decide, or to surface the error (:19). [Rubric §29, Resilience & Business Continuity] assesses whether retries are safe rather than merely present: this type is how every automatic retry layer in Common learns which 500 it must not retry. [Rubric §9, API & Contract Design] assesses whether the protocol is explicit at both ends, and the contract is deliberately double-encoded: a response header a synchronous retry predicate can read without consuming the body, and a code inside the Problem Details errors array that a parsed Result carries (:22-25). Its placement is the shared-wire-literal rule again, and the doc comment cites the precedent by name: the API writes it, the UI reads it, and neither references the other, "the same reason as IdempotencyHeaders" (:22-23; see IdempotencyHeaders).
  • Walkthrough:
    • Code = "Transaction.CommitOutcomeUnknown" (CommitOutcomeUnknown.cs:31) is the code the body's errors array carries.
    • HeaderName = "X-Commit-Outcome" (:34) and HeaderValue = "unknown" (:37) are the response header pair.
    • Message (:40-42) is the text the server reports with the code. It ends "Check the current state before trying again", and it deliberately never invites a plain retry.
    • Is(Error) (:47-48) is a null-safe ordinal comparison of the error's code with Code.
    • Is(Result) (:53-54) is true only for a failed result where any error satisfies Is(Error), so a success, or a failure carrying only other codes, is false.
    • Is(HttpResponseMessage) (:59-62) reads the header values without touching the content and matches HeaderValue case-insensitively (StringComparison.OrdinalIgnoreCase, :62), while the code comparison in Is(Error) stays case-sensitive (StringComparison.Ordinal, :48).
  • Why it's built this way: no ADR mentions the type; the rationale lives in its own remarks and in TransactionCommitAmbiguousException, whose doc comment explains that the exception exists to take a commit failure out of SQL Server's EnableRetryOnFailure path (a re-run against a possibly-durable commit duplicates every write, outbox rows included) and that the API answers it with this coded 500, which Common's own clients never retry (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/Factory/TransactionCommitAmbiguousException.cs:8-25). Keeping the classification in three Is overloads means the API, the HTTP retry policies and the offline queue cannot each spell the literal differently.
  • Where it's used: the chain starts in DbContextFactory, whose commit loop turns any commit failure into a TransactionCommitAmbiguousException naming what committed and what rolled back (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/Factory/DbContextFactory.cs:782). Server side, GlobalExceptionHandler routes that exception (MMCA.Common/Source/Presentation/MMCA.Common.API/Middleware/GlobalExceptionHandler.cs:112-115) to WriteCommitOutcomeUnknownAsync (GlobalExceptionHandler.cs:139), which sets a 500, writes the header (:144), uses Message as the detail (:150) and puts an Error.Unexpected carrying Code into the errors array (:152-154). Because that array is the lossless shape of ProblemDetailsResultReader, the client gets the code back intact, which CommitOutcomeUnknownHandlingTests pins by parsing the handler's output with ParseProblemDetails and asserting Is(error) and ErrorType.Unexpected (MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/Middleware/CommitOutcomeUnknownHandlingTests.cs:34-48). Three client layers honor the never-resend rule: AuthenticatedServiceBase's IsRetryableResponse returns false for a marked response whatever the request (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Api/AuthenticatedServiceBase.cs:273-275,285-288); the service-defaults HTTP resilience handler in the Aspire Extensions wraps the retry's ShouldHandle so a marked response is never retried, which matters for the PUT and DELETE it still retries (MMCA.Common/Source/Hosting/MMCA.Common.Aspire/Extensions.cs:76-83,89-97); and OfflineWriteQueue's Classify settles the entry as OfflineWriteOutcome.Rejected rather than keeping it for another attempt (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Offline/OfflineWriteQueue.cs:276,283-286, documented at :34-37). The type's own coverage is CommitOutcomeUnknownTests (MMCA.Common/Tests/Core/MMCA.Common.Shared.Tests/Http/CommitOutcomeUnknownTests.cs:15,21,25,37,46,55).
  • Caveats / not-in-source: the rule binds only clients that consult the type. A third-party caller that retries every 500, or that resends under the same Idempotency-Key, still re-executes the handler, because nothing on the server refuses that resend. The classification also cannot say whether the write landed: that answer needs the read-back the remark prescribes (CommitOutcomeUnknown.cs:19).

ProblemDetailsResultReader

MMCA.Common.Shared · MMCA.Common.Shared.Http · MMCA.Common/Source/Core/MMCA.Common.Shared/Http/ProblemDetailsResultReader.cs:59 · Level 3 · class (static)

  • What it is: the client-side inverse of the API's error edge. It reads an RFC 9457 Problem Details body (or a non-JSON body, or no body at all) and turns it back into the Error list and failed Result the server started from (MMCA.Common/Source/Core/MMCA.Common.Shared/Http/ProblemDetailsResultReader.cs:59-510).
  • Depends on: Error, Result and ErrorType from MMCA.Common.Shared.Abstractions (ProblemDetailsResultReader.cs:4); BCL only otherwise: System.Text.Json, System.Collections.Frozen, System.Net.Http.HttpResponseMessage, System.Globalization (:1-3).
  • Concept introduced, closing the Result round trip across an HTTP hop. The framework's error currency is a Result carrying typed Errors, and ADR-013 makes that the whole point: business failures are values, not exceptions. HTTP does not carry Results, so ApiControllerBase projects a failure into Problem Details on the way out. Without a reader, the client half of that trip is lossy in the worst way: a Blazor page would see "500" or an HttpRequestException where the server said "Session.AlreadyClosed, Conflict". This type is the missing half. [Rubric §9, API & Contract Design] assesses whether the contract is honored symmetrically at both ends; [Rubric §29, Resilience & Business Continuity] assesses whether a caller degrades usefully rather than crashing, which is why every unreadable-body path still yields exactly one usable Error. Its placement is the same rule IdempotencyHeaders and ConcurrencyETag follow, stated in the doc comment: the client half of the round trip is MMCA.Common.UI, "which references Shared only" (ProblemDetailsResultReader.cs:15-18), so the reader lives in Shared and uses nothing beyond the BCL. The doc comment also enumerates the four payload shapes it understands and, crucially, states its own fidelity limit in the same breath (:20-57): only the MMCA error array is lossless (and even there a type name the reader does not know, such as one a newer server added, falls back to the status-derived type, :50-52); the other three derive the ErrorType from the status code, which is "one-to-one for every status the API emits except 400 Bad Request" (:53-54), where both Validation and Invariant land and the reverse picks Validation (:54-56).
  • Walkthrough:
    • Three public const string codes name the synthesized failures: StatusErrorCodePrefix = "Http." (:66), EmptyResponseCode = "Http.EmptyResponse" (:72), and MalformedResponseCode = "Http.MalformedResponse" (:78). They are public precisely so tests and callers can branch on them without re-spelling the literal.
    • A block of private consts holds every JSON member name it looks for (:80-89), so the wire vocabulary is declared once.
    • StatusCodeToErrorType is a FrozenDictionary<int, ErrorType> (:97-109), documented as "the exact reverse of ErrorHttpMapping.ErrorTypeToStatusCode" (:92-93). It maps nine statuses one-to-one, including 503 to ErrorType.Unavailable (:101) and 429 to ErrorType.TooManyRequests (:107), the reverses of the forward map's Unavailable and TooManyRequests entries (MMCA.Common/Source/Presentation/MMCA.Common.API/Middleware/ErrorHttpMapping.cs:34,33). That forward map really does collapse two types onto 400 (Validation and Invariant, at ErrorHttpMapping.cs:25,26), which is exactly why the reverse is lossy there and picks Validation. The field's doc comment says so in the same terms: 400, "which the forward map uses for two error types, cannot be reversed exactly" and resolves to Validation (:93-95).
    • FromHttpStatusCode(int) (:133) is the public reverse mapping: a dictionary hit wins (:135-138), any other 4xx becomes Validation, anything else (every other 5xx included) becomes Unexpected (:140).
    • ParseProblemDetails(int, string?) (:158) is the pure core, and the doc says why it is separated from the HTTP surface: "no HTTP, no I/O, no allocation of an HttpResponseMessage, so it can be tested directly against captured payloads" (:144-146), which is [Rubric §14, Testability] made structural. Its flow: a blank body synthesizes one error (:160-163); a JsonException is caught and does the same, with the comment naming the real-world cases ("a bare challenge, an HTML error page, a proxy response", :166-174); a root that is not a JSON object likewise (:179-182). Otherwise it resolves the effective status (:184) and the fallback type (:185), then branches on the errors member: an array goes to ReadErrorArray (:191-193), an object to ReadValidationDictionary (:195-197). Parsed errors win only when the list is non-empty (:200-203); otherwise it falls through to a synthesized error carrying detail or title (:206).
    • ResolveStatus (:453) is a small but deliberate affordance: a caller that passes a non-positive status gets the status read out of the body's own status member instead (:460-464), which is what makes the parser usable against a captured payload with no response object around it.
    • ReadErrorArray (:353) maps each object element through ReadErrorObject and, notably, still salvages a degraded array of plain strings (:365-370). ReadErrorObject (:376) reads code, message, type, source and target, with a three-step fallback for the message (message, then code, then the generic default) so an Error is never constructed with an empty one (:382-387).
    • ReadValidationDictionary (:390) handles the standard ASP.NET Core shape. The key becomes Validation.{propertyName}, or bare Validation for an object-level rule with an empty key (:397-399), and the property name is carried separately as Target (:400). A value may be an array of messages or a single one, and both paths funnel through AddValidationError (:402-412), which silently ignores non-string and blank entries (:425-434).
    • ParseErrorType (:437) is the one place an inbound string becomes an enum, and it is defensive in the right way: Enum.TryParse with ignoreCase: true plus Enum.IsDefined (:439-440). Without the second check TryParse would happily accept an arbitrary numeric string and hand back an undefined enum value. Any miss (blank, unknown or undefined) returns the status-derived fallback type (:441-442), which is how a type name from a newer server degrades rather than fails.
    • ToFailureResult (:217) lifts the parsed errors into a failed Result.
    • TryGetSynthesizedStatus(Error, out int) (:231) answers whether an error is one the reader itself synthesized for a status because the response carried no message (a bodiless or unreadable error response). It is true only when the code is Http. followed by a number (StatusErrorCodePrefix, parsed with NumberStyles.None, :236-237) AND the message equals the reader's English default sentence for that status (:238, via the private DefaultMessage, :508-509), so a message the server phrased itself is never mistaken for a synthesized one. A UI uses it to localize the failure by status instead of showing the English default (doc :220-225). It throws ArgumentNullException on a null error (:233) and yields 0 for the status when it returns false (:235).
    • ReadAsync (:256) short-circuits on a 2xx to Result.Success() (:262-265) and otherwise parses the body. ReadAsync<T> (:291) is the value-returning overload: a non-success status parses errors (:303), a blank 2xx body is a failure coded EmptyResponseCode (:306-313), a body that deserializes to null is the same failure with a different message (:318-324), and a JsonException becomes MalformedResponseCode (:326-329). The "204 is a failure here" rule is stated in the doc with its escape hatch: use the non-generic overload for endpoints that legitimately answer without a body (:274-279).
    • Both ReadAsync overloads carry a SuppressMessage for analyzer RS0026 ("Do not add multiple public overloads with optional parameters", :255,290). The justification records them as grandfathered: released after the v1.152 public-API baseline while RS0026/RS0027 were off, so reshaping either signature now would be a breaking change. The two-overload shape is therefore frozen by the public API contract, not by preference.
    • ReadBodyAsync (:332) buffers the content as a string and swallows an HttpRequestException back to null (:345-350), with the comment explaining the judgement: a truncated body should still report the status-level failure rather than surface a transport exception "from a reader".
    • TryGetProperty (:478) does case-insensitive member lookup, trying the exact name first and only then enumerating (:487-493). The doc gives the reason (:472-477): the wire form is camelCase, but a hand-assembled or differently-configured payload can be PascalCase, and a reader that understood only one "would silently drop every error field".
  • Why it's built this way: ADR-094 is the governing record. It states that the client dispatch "returns a Result; it does not throw", hands the response to this reader in both service-base overloads, and records what the change replaced: the client used to pull domain wording out of the body and rethrow it as a DomainInvariantViolationException before falling back to EnsureSuccessStatusCode, and that helper "is deleted, not deprecated" (Website/docs-src/adr/094-client-entity-data-access.md:81-92).
  • Where it's used: it is the single funnel for every framework-shaped HTTP read on the client. EntityServiceBase<TEntityDTO, TIdentifierType> uses both overloads through the two SendRequestAsync dispatches of its base (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Api/AuthenticatedServiceBase.cs:186,214, documented at :150,168,194), ChildEntityServiceBase uses all three call shapes (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Api/ChildEntityServiceBase.cs:41,57,76), and the notification inbox service does the same (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Notifications/NotificationInboxService.cs:57,76,95,113). ADC's hand-written UI services call it directly rather than going through a base, for example UserService (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.UI/Services/UserService.cs:56,82,96,123,140), SpeakerDashboardService (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.UI/Services/Speakers/SpeakerDashboardService.cs:86), CategoryItemLookupService (.../Services/CategoryItemLookupService.cs:51) and SessionQuestionUIService (MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.UI/Services/SessionLive/SessionQuestionUIService.cs:34,53,79). The round trip is pinned end to end by ProblemDetailsRoundTripTests, which serializes a real failure through the API edge and reads it back with ParseProblemDetails (MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/Controllers/ProblemDetailsRoundTripTests.cs:48,72,87,126).
  • Caveats / not-in-source: ErrorHttpMapping is internal to MMCA.Common.API (MMCA.Common/Source/Presentation/MMCA.Common.API/Middleware/ErrorHttpMapping.cs:14) and this reader lives in MMCA.Common.Shared, so the two dictionaries cannot reference each other. Nothing in the type system keeps the reverse map aligned when a new ErrorType or status is added to the forward one; the alignment rests on the doc comment (ProblemDetailsResultReader.cs:92-96) and on the round-trip test. The [Rubric §15, Best Practices & Code Quality] reading is that this is a knowingly accepted duplication, priced against giving Shared a reference to the API package.

ImportConventions

MMCA.Common.Shared · MMCA.Common.Shared.Imports · MMCA.Common/Source/Core/MMCA.Common.Shared/Imports/ImportConventions.cs:25 · Level 0 · class (static)

  • What it is: the shared contract of a file-import endpoint, written down once: a single constant, DryRunFieldName = "dryRun" (ImportConventions.cs:28), plus a doc comment that states the status codes every import endpoint answers with (ImportConventions.cs:3-24).

  • Depends on: nothing at runtime; its documentation refers to ImportReportDTO and ImportRowErrorDTO.

  • Concept introduced, the file-import contract. An import endpoint accepts an upload (read by ReadCsvAsync, per the summary at :4-5) and answers in one of three shapes (:8-23):

    • Dry run: asked for through a form or query field named DryRunFieldName, default false. It writes nothing and answers 200 with a report whose DryRun is true.
    • Commit: a synchronous commit answers 200 with a report whose DryRun is false; a queued commit answers 202 with the application's own run DTO.
    • File-level failure: a malformed file, missing columns or a file over the size cap is a 400 Problem Details, never a report, because a report describes rows and an unreadable file has none. A row-level problem is an ImportRowErrorDTO inside ImportReportDTO.RowErrors.

    [Rubric §9, API & Contract Design] assesses whether endpoints share consistent, documented request and response conventions; this class embodies it by putting the field name in one constant that both server and client compile against, so the UI never hard-codes the string.

  • Why it's built this way: ADR-078 records this file-import contract as the import-side twin of the CSV export endpoint, with ADC as the only adopter.

  • Where it's used: ADC's ticket client sends the flag under this name (MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.UI/Services/Tickets/TicketService.cs:81). Framework coverage is ImportReportDTOTests (MMCA.Common/Tests/Core/MMCA.Common.Shared.Tests/Imports/ImportReportDTOTests.cs).

StronglyTypedIdValueParserDelegate<TValue>

MMCA.Common.Shared · MMCA.Common.Shared.Identifiers · MMCA.Common/Source/Core/MMCA.Common.Shared/Identifiers/StronglyTypedId.cs:161 · Level 0 · delegate

  • What it is: an internal TryParse-shaped delegate, bool (string? s, IFormatProvider? provider, out TValue value) (StronglyTypedId.cs:158-162), the signature StronglyTypedIdValueParser<TValue> binds a concrete parser method to.
  • Depends on: nothing beyond the closing generic constraint TValue : notnull.
  • Concept introduced: none on its own; it exists so StronglyTypedIdValueParser<TValue> can cache a bound method as a typed field instead of an untyped Delegate.
  • Where it's used: bound once per closed TValue by StronglyTypedIdValueParser<TValue>'s Build(), and invoked by StronglyTypedId.TryParse.

StronglyTypedIdValueParser<TValue>

MMCA.Common.Shared · MMCA.Common.Shared.Identifiers · MMCA.Common/Source/Core/MMCA.Common.Shared/Identifiers/StronglyTypedId.cs:173 · Level 1 · class (static)

  • What it is: the per-closed-TValue cache of a parser delegate, exposed as the single static field Instance (StronglyTypedId.cs:173-221).
  • Depends on: StronglyTypedIdValueParserDelegate<TValue>.
  • Concept introduced, the two supported primitive shapes. A wrapped primitive parses one of two ways: string takes a direct identity path, the route segment IS the value (ParseString, :203-207), and every other supported primitive implements IParsable<T> and is bound through reflection to ParseParsable<TParsable> (:209). string does implement IParsable<string> too, but parsing a string is the identity, so Build() takes the direct path ahead of the reflective binding (comment at :188-189). Build() (:186) returns null for a TValue that is neither, which is what lets StronglyTypedId.CanParseValues<TValue>() answer "unsupported" without throwing.
  • Walkthrough: Instance (:180) runs Build() once, at type-initialization time for the closed generic. Build() checks typeof(TValue) == typeof(string) first (:190-191), then tests IParsable<>.MakeGenericType(typeof(TValue)).IsAssignableFrom(typeof(TValue)) (:193-194) and returns null when neither holds. For the IParsable branch it reflects the private ParseParsable method off itself, closes it over TValue, and binds it with CreateDelegate (:196-200), a [SuppressMessage]d use of reflection the attribute justification explains: bound once per closed generic, never per request (:182-185).
  • Why it's built this way: ADR-115 is the governing record for the opt-in strongly typed identifier feature this class supports.
  • Where it's used: exclusively by StronglyTypedId.TryParse (StronglyTypedId.cs:67) and CanParseValues (StronglyTypedId.cs:87); nothing outside the defining file references it directly.

ImportRowErrorDTO

MMCA.Common.Shared · MMCA.Common.Shared.Imports · MMCA.Common/Source/Core/MMCA.Common.Shared/Imports/ImportRowErrorDTO.cs:9 · Level 2 · record (sealed)

  • What it is: one row-level problem of a file import: where it is (file line, and the column when one is to blame) and what it is (error code and message) (ImportRowErrorDTO.cs:5-9).
  • Depends on: Error from MMCA.Common.Shared.Abstractions (:1), the domain error it copies from.
  • Concept introduced: none new; it is the row-level leg of the contract ImportConventions documents, and it reuses the Result pattern's Error rather than inventing a second error vocabulary.
  • Walkthrough: LineNumber (:55, required) is the 1-based file line the record starts on, with the header as line 1, so a quoted line break in an earlier record still counts; the doc comment ties it to CsvRow.LineNumber (:51-54). Column (:58) names the offending column, or is null for a whole-row error. Code (:61) and Message (:64) are both required. The factory FromError(Error, int, string?) (:74) null-guards the error (:76) and copies its Code and Message into a new instance (:78-84), so a validator that already produced an Error turns it into a row error in one call.
  • Why it's built this way: ADR-078: a row problem travels inside the report, while a file problem is a 400 Problem Details.
  • Where it's used: carried by ImportReportDTO.RowErrors. Framework coverage is ImportReportDTOTests (MMCA.Common/Tests/Core/MMCA.Common.Shared.Tests/Imports/ImportReportDTOTests.cs).

IStronglyTypedId<TSelf, TValue>

MMCA.Common.Shared · MMCA.Common.Shared.Identifiers · MMCA.Common/Source/Core/MMCA.Common.Shared/Identifiers/IStronglyTypedId.cs:60 · Level 2 · interface

  • What it is: the opt-in contract a value-type identifier implements to become a "strongly typed id": a wrapper struct carrying one primitive TValue, parsable from route/query text the same way the primitive itself is. TSelf is the curiously-recurring self type, TValue the wrapped primitive (IStronglyTypedId.cs:60-63).
  • Depends on: IParsable<TSelf> from the BCL, the interface it extends (IStronglyTypedId.cs:60); its two default methods delegate to StronglyTypedId.Parse/TryParse.
  • Concept introduced, strongly typed identifiers as an opt-in alternative to the identifier-type-alias convention. Where a module's usual identifier is a global using OrderId = ... alias over the primitive (no compile-time distinction between an OrderId and any other Guid), a type implementing this interface is a real value type the compiler tells apart from Guid or int, at the cost of writing the wrapper. [Rubric §4, DDD] assesses whether identity is modeled as a first-class value rather than a primitive; [Rubric §9, API & Contract Design] covers whether route/query binding for the stronger type is as seamless as for the primitive it replaces, which is exactly what the two default interface methods buy: a wrapper writes only From, and route-model binding works through the inherited IParsable<TSelf>.Parse/TryParse.
  • Walkthrough: Value (:155) exposes the wrapped primitive. static abstract TSelf From(TValue value) (:162) is the one member an implementation must write, wrapping a primitive into the identifier. The two remaining members are default implementations of IParsable<TSelf>, so a wrapper never writes them: Parse (:172-173) and TryParse (:184-188) both delegate straight to StronglyTypedId's static Parse/TryParse overloads, closed over TSelf, TValue.
  • Why it's built this way: ADR-085 revisits the plain-alias identifier convention, and ADR-115 records the strongly-typed alternative as opt-in rather than a replacement: a module keeps its global using aliases by default and reaches for this interface only where the extra compile-time safety is worth the wrapper.
  • Where it's used: implemented by identifier structs registered with StronglyTypedIdRegistry; the constraint where TSelf : struct, IStronglyTypedId<TSelf, TValue> recurs across StronglyTypedId, StronglyTypedIdMappings<TSelf, TValue>, StronglyTypedIdTypeConverter<TSelf, TValue> and StronglyTypedIdConverter<TSelf, TValue>. Framework coverage: StronglyTypedIdFixtures (MMCA.Common/Tests/Architecture/MMCA.Common.Architecture.Tests/StronglyTypedIdFixtures/StronglyTypedIdFixtures.cs) and TestIdentifiers (MMCA.Common/Tests/Core/MMCA.Common.Shared.Tests/Identifiers/TestIdentifiers.cs) supply test implementations.

StronglyTypedId

MMCA.Common.Shared · MMCA.Common.Shared.Identifiers · MMCA.Common/Source/Core/MMCA.Common.Shared/Identifiers/StronglyTypedId.cs:19 · Level 2 · class (static)

  • What it is: the static toolkit behind IStronglyTypedId<TSelf, TValue>: parsing (Parse/TryParse), reflection-based type detection (GetValueType/IsStronglyTypedId/TryDescribe), and a capability check (CanParseValues) (StronglyTypedId.cs:19-149,210).
  • Depends on: StronglyTypedIdValueParser<TValue> for the actual parsing, IStronglyTypedId<TSelf, TValue> as the generic constraint on every method. BCL: ConcurrentDictionary<Type, Type?> as a process-lifetime cache (:217).
  • Concept introduced: none new; this is the mechanism IStronglyTypedId<TSelf, TValue> introduces, made concrete.
  • Walkthrough:
    • ValueTypeCache (:217) is a ConcurrentDictionary<Type, Type?> caching the wrapped primitive per identifier type, with a null entry for every type that is not one; the doc comment notes it is bounded by the number of CLR types the process loads, unlike a query-string keyed cache a caller could grow (:213-216).
    • Parse<TSelf, TValue>(string, IFormatProvider?) (:231) is the IParsable.Parse leg: it null-guards (:235), then throws FormatException when TryParse fails (:237-240), naming the offending text and target type in the message.
    • TryParse<TSelf, TValue>(string?, IFormatProvider?, out TSelf) (:254) fetches StronglyTypedIdValueParser<TValue>.Instance, invokes it with the invariant culture as the default provider (:259), and on success calls TSelf.From(value) (:261) to wrap the parsed primitive. A null Instance (an unsupported TValue) falls through to false (:265-266).
    • CanParseValues<TValue>() (:276) is a one-line capability check over the same Instance.
    • GetValueType(Type) (:288) and IsStronglyTypedId(Type) (:299) answer "does this type implement the contract for itself" via ResolveValueType (:326), which walks type.GetInterfaces() for a closed IStronglyTypedId<,> whose first generic argument equals the type being asked about (:328-336): the same self-referencing guard EnumerationJsonConverterFactory applies elsewhere in the framework, per the doc comment (:283-284).
    • TryDescribe(Type, out Type?, out Type?) (:309) unwraps Nullable<T> first (:316) so a caller inspecting an OrderId? property gets the same answer as one inspecting OrderId.
  • Why it's built this way: ADR-115 is the governing record; ADR-085 records why this sits alongside, not instead of, the plain-alias convention.
  • Where it's used: IStronglyTypedId.cs calls Parse/TryParse through the default interface methods; StronglyTypedIdJsonConverterFactory's CanConvert/CreateConverter call IsStronglyTypedId/GetValueType; StronglyTypedIdTypeConverter.ConvertFrom calls TryParse; StronglyTypedIdFilterStrategy and StronglyTypedIdRegistry call the type-detection surface. Framework coverage is StronglyTypedIdTests (MMCA.Common/Tests/Core/MMCA.Common.Shared.Tests/Identifiers/StronglyTypedIdTests.cs, 13 call sites).

ImportReportDTO

MMCA.Common.Shared · MMCA.Common.Shared.Imports · MMCA.Common/Source/Core/MMCA.Common.Shared/Imports/ImportReportDTO.cs:12 · Level 3 · record

  • What it is: the outcome of a file import, dry run or commit: the generic row counts and the row-level errors. It is an unsealed record class so an application adds its own counts on a derived record (ImportReportDTO.cs:3-6,12).
  • Depends on: ImportRowErrorDTO for RowErrors.
  • Concept introduced: none new; the report half of the contract ImportConventions documents.
  • Walkthrough: DryRun (:15) and TotalRows (:18, data rows with the header excluded) are required. Added (:21), Updated (:24), Unchanged (:27, rows that matched a record already holding the same values) and Rejected (:30) are optional counts; on a dry run Added and Updated count what would have happened. Every rejected row has at least one entry in RowErrors (:29). RowErrors (:33) defaults to [], in file order, so the remark at :8-10 holds: it serializes as an array, never null, and a client iterates it unconditionally.
  • Why it's built this way: ADR-078 records the import contract this report belongs to.
  • Where it's used: ADC's TicketRosterImportReport derives from it (MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.Application/Tickets/UseCases/ImportTicketRoster/TicketRosterImportReport.cs:13). Per ADR-078, the 200 dry-run body ADC puts on the wire is its own TicketRosterImportResultDTO mapped from that report, not an ImportReportDTO. Framework coverage is ImportReportDTOTests (MMCA.Common/Tests/Core/MMCA.Common.Shared.Tests/Imports/ImportReportDTOTests.cs).

StronglyTypedIdConverter<TSelf, TValue>

MMCA.Common.Shared · MMCA.Common.Shared.Identifiers · MMCA.Common/Source/Core/MMCA.Common.Shared/Identifiers/StronglyTypedIdJsonConverterFactory.cs:38 · Level 3 · class

  • What it is: a private nested JsonConverter<TSelf>, one per closed identifier type, created by StronglyTypedIdJsonConverterFactory (StronglyTypedIdJsonConverterFactory.cs:38-70).
  • Depends on: System.Text.Json.Serialization.JsonConverter<T> from the BCL; StronglyTypedId.TryParse for the dictionary-key path.
  • Concept introduced: none new; the JSON leg of the wrap/unwrap pattern StronglyTypedIdMappings<TSelf, TValue> applies for manual DTO mapping.
  • Walkthrough: Read (:364) deserializes the wrapped primitive and calls TSelf.From (:366-368), so default stands in for a null primitive rather than throwing. Write (:371) serializes value.Value directly. WriteAsPropertyName (:379) and ReadAsPropertyName (:387) handle the identifier-as-dictionary-key case: the wrapped primitive becomes the JSON member name via Convert.ToString (:382-383), and reading it back throws JsonException on failure rather than silently defaulting (:390-391), documented as making Dictionary<OrderId, T> serialize exactly like Dictionary<int, T>.
  • Why it's built this way: ADR-115.
  • Where it's used: instantiated by StronglyTypedIdJsonConverterFactory.CreateConverter via Activator.CreateInstance; nothing outside the defining file references it directly. Framework coverage is StronglyTypedIdSerializationTests (MMCA.Common/Tests/Core/MMCA.Common.Shared.Tests/Identifiers/StronglyTypedIdSerializationTests.cs).

StronglyTypedIdMappings<TSelf, TValue>

MMCA.Common.Shared · MMCA.Common.Shared.Identifiers · MMCA.Common/Source/Core/MMCA.Common.Shared/Identifiers/StronglyTypedIdMappings.cs:36 · Level 3 · class (static)

  • What it is: two small static conversion helpers between a wrapped identifier and its primitive, meant to be called from a manual DTO mapper (StronglyTypedIdMappings.cs:36-49).
  • Depends on: IStronglyTypedId<TSelf, TValue> as the generic constraint.
  • Concept introduced: none new; the manual-mapping convention (Mapperly / manual DTO mapping) applied to strongly typed identifiers, so a hand-written mapper does not repeat the wrap/unwrap logic per identifier type.
  • Walkthrough: ToValue(TSelf) unwraps the identifier to its primitive (StronglyTypedIdMappings.cs:43) and ToIdentifier(TValue) wraps a primitive through TSelf.From(value) (:48). There are no nullable overloads: a mapper that needs "not set" handles the null itself.
  • Where it's used: StronglyTypedIdMapperTests (MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Mapping/StronglyTypedIdMapperTests.cs) plus one further call site not covered by this pass.

StronglyTypedIdTypeConverter<TSelf, TValue>

MMCA.Common.Shared · MMCA.Common.Shared.Identifiers · MMCA.Common/Source/Core/MMCA.Common.Shared/Identifiers/StronglyTypedIdTypeConverter.cs:21 · Level 3 · class

  • What it is: a System.ComponentModel.TypeConverter for one closed identifier type, letting the BCL conversion pipeline (model binding, some UI frameworks) treat the identifier like its wrapped primitive (StronglyTypedIdTypeConverter.cs:21-69).
  • Depends on: StronglyTypedId.TryParse for the string-to-identifier path; System.ComponentModel.TypeConverter from the BCL.
  • Concept introduced: none new; the TypeConverter leg of the wrap/unwrap pattern StronglyTypedIdConverter<TSelf, TValue> applies for JSON.
  • Walkthrough: CanConvertFrom/CanConvertTo (:461, 467) accept string and TValue in addition to whatever the base converter accepts. ConvertFrom (:473) pattern-matches: null passes through, a TValue wraps via TSelf.From, a parsable string wraps via StronglyTypedId.TryParse, and an unparsable string throws FormatException naming the text and target type (:474-482). ConvertTo (:485) unwraps a TSelf to its TValue or to a culture-formatted string, and null-guards destinationType explicitly rather than delegating that check to the base class (:500-502).
  • Where it's used: registered per identifier type by StronglyTypedIdTypeConverters.Register. Framework coverage is StronglyTypedIdTypeConverterTests (MMCA.Common/Tests/Core/MMCA.Common.Shared.Tests/Identifiers/StronglyTypedIdTypeConverterTests.cs).

StronglyTypedIdJsonConverterFactory

MMCA.Common.Shared · MMCA.Common.Shared.Identifiers · MMCA.Common/Source/Core/MMCA.Common.Shared/Identifiers/StronglyTypedIdJsonConverterFactory.cs:22 · Level 4 · class

  • What it is: a JsonConverterFactory that detects any strongly typed identifier and hands System.Text.Json a closed StronglyTypedIdConverter<TSelf, TValue> for it, so no per-identifier-type converter registration is needed (StronglyTypedIdJsonConverterFactory.cs:22-71).
  • Depends on: StronglyTypedId.IsStronglyTypedId/GetValueType for detection; StronglyTypedIdConverter<TSelf, TValue>, instantiated reflectively.
  • Concept introduced: none new; the JSON registration point for the strongly-typed-id feature.
  • Walkthrough: CanConvert(Type) (:527) delegates straight to StronglyTypedId.IsStronglyTypedId. CreateConverter(Type, JsonSerializerOptions) (:530) resolves the wrapped TValue with GetValueType, returns null when it is not an identifier, and otherwise MakeGenericTypes the nested converter and instantiates it with Activator.CreateInstance (:532-538).
  • Why it's built this way: ADR-115.
  • Where it's used: registered in MMCA.Common.API's DependencyInjection (MMCA.Common/Source/Presentation/MMCA.Common.API/DependencyInjection.cs) and consulted by StronglyTypedIdSchemaTransformer (MMCA.Common/Source/Presentation/MMCA.Common.API/OpenApi/StronglyTypedIdSchemaTransformer.cs). Framework coverage is StronglyTypedIdSerializationTests (MMCA.Common/Tests/Core/MMCA.Common.Shared.Tests/Identifiers/StronglyTypedIdSerializationTests.cs).

StronglyTypedIdTypeConverters

MMCA.Common.Shared · MMCA.Common.Shared.Identifiers · MMCA.Common/Source/Core/MMCA.Common.Shared/Identifiers/StronglyTypedIdTypeConverter.cs:82 · Level 4 · class (static)

  • What it is: the registration surface for StronglyTypedIdTypeConverter<TSelf, TValue>: register one identifier type explicitly, or scan an assembly and register every identifier type it declares (StronglyTypedIdTypeConverter.cs:82-166).
  • Depends on: StronglyTypedId.GetValueType/IsStronglyTypedId for detection; StronglyTypedIdTypeConverter<TSelf, TValue>, attached via TypeDescriptor.AddAttributes.
  • Concept introduced: none new; the assembly-scan companion to the per-type converter.
  • Walkthrough: Register(Type) (:89) resolves the wrapped value type or throws ArgumentException naming the offending type (:93-96), builds the closed StronglyTypedIdTypeConverter<,> and attaches it with TypeDescriptor.AddAttributes(identifierType, new TypeConverterAttribute(converterType)) (:100). For a value-type identifier it then calls TypeDescriptor.Refresh on the closed Nullable<TId> (:108-111). The comment gives the failure this prevents (:102-107): MVC binds an optional TId? query-string parameter through Nullable<TId>'s converter, and TypeDescriptor caches that NullableConverter with whatever underlying converter it saw first. If anything resolved it before registration (another host in the process, a library scanning types), the cached converter still wraps the default struct converter, which cannot read a string, so MVC treats TId? as a complex type and the request answers 500. Refreshing drops the cache so the next lookup sees the converter just registered. RegisterAll(params Assembly[]) (:119) calls Register for every candidate GetIdentifierTypes yields and returns the count. GetIdentifierTypes(Assembly) (:143) tolerates a partially loadable assembly: it catches ReflectionTypeLoadException and falls back to the partial Types array (:149-156), the doc comment noting this matches the tolerance the architecture map's loadable-types helper applies elsewhere, then filters to non-generic value types satisfying IsStronglyTypedId (:158-164).
  • Why it's built this way: ADR-115.
  • Where it's used: called from MMCA.Common.Infrastructure's DependencyInjection (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs) and by StronglyTypedIdRegistry for its own assembly-scan constructor. Framework coverage is StronglyTypedIdTypeConverterTests (MMCA.Common/Tests/Core/MMCA.Common.Shared.Tests/Identifiers/StronglyTypedIdTypeConverterTests.cs) plus StronglyTypedIdApiTests (MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/Identifiers/StronglyTypedIdApiTests.cs).

StronglyTypedIdRegistry

MMCA.Common.Shared · MMCA.Common.Shared.Identifiers · MMCA.Common/Source/Core/MMCA.Common.Shared/Identifiers/StronglyTypedIdRegistry.cs:22 · Level 5 · class

  • What it is: an instance-level catalog of the strongly typed identifier types a host declares, built once by scanning assemblies or by an explicit list, and reused wherever a host needs to enumerate them (StronglyTypedIdRegistry.cs:22-75).
  • Depends on: StronglyTypedIdTypeConverters.GetIdentifierTypes for the scan constructor; StronglyTypedId.IsStronglyTypedId/GetValueType for validation and description.
  • Concept introduced: none new; this is the top of the strongly-typed-id stack, the object a host DI registration actually holds.
  • Walkthrough: the assembly-scan constructor (:692) deduplicates the input assemblies, flattens GetIdentifierTypes across them, deduplicates the result, and orders it by FullName (:696-703) for a stable enumeration order across runs. The explicit-list constructor (:712) validates every entry with IsStronglyTypedId and throws ArgumentException naming the first offender (:718-724) rather than silently accepting a non-identifier type. IdentifierTypes (:730) exposes the ordered result. Describe() (:737) pairs each identifier type with its wrapped primitive via GetValueType, using the null-forgiving ! because every entry already passed validation.
  • Why it's built this way: ADR-115.
  • Where it's used: constructed and consulted by MMCA.Common.Infrastructure's DependencyInjection (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs) and by StronglyTypedIdModelConfiguration (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Conventions/StronglyTypedIdModelConfiguration.cs) and ApplicationDbContext (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/ApplicationDbContext.cs) for EF value-converter wiring. Framework coverage is StronglyTypedIdTests (MMCA.Common/Tests/Core/MMCA.Common.Shared.Tests/Identifiers/StronglyTypedIdTests.cs).

AcceptLegalTermsRequest

MMCA.Common.Shared · MMCA.Common.Shared.Legal · MMCA.Common/Source/Core/MMCA.Common.Shared/Legal/AcceptLegalTermsRequest.cs:12 · Level 0 · record struct

  • What it is: the POST body for recording a terms acceptance, a one-field readonly record struct carrying the Version string the user is accepting (MMCA.Common/Source/Core/MMCA.Common.Shared/Legal/AcceptLegalTermsRequest.cs:12).
  • Depends on: nothing first-party; BCL string only.
  • Concept introduced, the client names the version it saw. The request does not say "accept whatever is current": it carries the version the user was shown, so the server can reject a stale acceptance (see LegalAcceptanceErrorCodes). [Rubric §30, Compliance / Privacy / Data Governance] assesses whether consent is bound to the exact text consented to.
  • Walkthrough: a positional record struct, so there is no behavior, only the Version parameter (AcceptLegalTermsRequest.cs:12). Being a value type with no validation attributes, the version check happens server-side against the configured current version.
  • Where it's used: bound with [FromBody] by LegalAcceptanceControllerBase (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Legal/LegalAcceptanceControllerBase.cs:100) and constructed by LegalAcceptanceUIService when the gate posts an acceptance (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Legal/LegalAcceptanceUIService.cs:53). Framework coverage is LegalAcceptanceControllerBaseTests (MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/Controllers/Legal/LegalAcceptanceControllerBaseTests.cs).

LegalAcceptanceDTO

MMCA.Common.Shared · MMCA.Common.Shared.Legal · MMCA.Common/Source/Core/MMCA.Common.Shared/Legal/LegalAcceptanceDTO.cs:18 · Level 0 · record

  • What it is: a user's terms-acceptance standing: CurrentVersion, AcceptedVersion, AcceptedOn and the derived IsCurrent flag (MMCA.Common/Source/Core/MMCA.Common.Shared/Legal/LegalAcceptanceDTO.cs:18-54).
  • Depends on: nothing first-party; BCL only.
  • Concept introduced, standing is computed once, in one place. [Rubric §30, Compliance / Privacy / Data Governance] assesses whether the "is this user up to date" decision is consistent across the API and the UI. All four properties are init-only and IsCurrent is never set by callers: the static factory Evaluate derives it, so no caller can disagree about what "current" means.
  • Walkthrough: Evaluate(currentVersion, acceptedVersion, acceptedOn) (LegalAcceptanceDTO.cs:42-53) trims the configured version and treats null or whitespace as "none configured" (:44). IsCurrent is true when no version is configured, or when the accepted version equals the current one by ordinal comparison (:51). With nothing configured every user is current, so a host that sets no terms version never gates anyone.
  • Where it's used: built by LegalAcceptancePolicy (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Legal/LegalAcceptancePolicy.cs:51), by the controller's empty-standing fallback (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Legal/LegalAcceptanceControllerBase.cs:68), and returned through ILegalAcceptanceService (ILegalAcceptanceService.cs:18). The UI TermsAcceptanceGate consumes it to decide whether to show the acceptance dialog. Unit coverage is LegalAcceptanceDTOTests (MMCA.Common/Tests/Core/MMCA.Common.Shared.Tests/Legal/LegalAcceptanceDTOTests.cs).

LegalAcceptanceErrorCodes

MMCA.Common.Shared · MMCA.Common.Shared.Legal · MMCA.Common/Source/Core/MMCA.Common.Shared/Legal/LegalAcceptanceErrorCodes.cs:7 · Level 0 · class (static)

  • What it is: the wire-visible error code constants for the legal-acceptance flow; currently one, VersionNotCurrent = "Legal.VersionNotCurrent" (MMCA.Common/Source/Core/MMCA.Common.Shared/Legal/LegalAcceptanceErrorCodes.cs:13).
  • Depends on: nothing; constants only.
  • Concept introduced, error codes live in Shared so the UI can match them. The server builds the Error in the Application layer and the Blazor client must recognise it without referencing Application, the same placement rule AuthErrorCodes follows. [Rubric §15, Best Practices & Code Quality] covers the single source of truth for a literal both ends compare.
  • Walkthrough: the doc comment states the meaning: an acceptance named a version other than the configured current one, including any acceptance while no version is configured, and a client should re-read the standing and show the current terms (LegalAcceptanceErrorCodes.cs:9-12).
  • Where it's used: aliased as VersionNotCurrentCode by LegalAcceptanceErrors (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Legal/LegalAcceptanceErrors.cs:17), and matched by TermsAcceptanceGate to trigger a standing refresh (MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Legal/TermsAcceptanceGate.razor.cs:207).

LegalAcceptanceRoutes

MMCA.Common.Shared · MMCA.Common.Shared.Legal · MMCA.Common/Source/Core/MMCA.Common.Shared/Legal/LegalAcceptanceRoutes.cs:7 · Level 0 · class (static)

  • What it is: the route literals for the legal-acceptance endpoint: Action = "me/legal-acceptance" and Path = "Users/" + Action (MMCA.Common/Source/Core/MMCA.Common.Shared/Legal/LegalAcceptanceRoutes.cs:7-17).
  • Depends on: nothing; constants only.
  • Concept introduced, one route literal for server and client. The API attribute and the UI HTTP call must agree on the URL, so both read the same constants from Shared, as MessageHeaders does for broker headers. [Rubric §15, Best Practices & Code Quality] covers the single-source-of-truth angle.
  • Walkthrough: Action is the template relative to a controller routed at Users (the data-export precedent): GET reads the caller's standing, POST records an acceptance (LegalAcceptanceRoutes.cs:9-13). Path is the full relative path the client calls (:16).
  • Where it's used: [HttpGet]/[HttpPost] on LegalAcceptanceControllerBase (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Legal/LegalAcceptanceControllerBase.cs:59,93) and the two HTTP calls in LegalAcceptanceUIService (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Legal/LegalAcceptanceUIService.cs:34,52).

UserDataExportSectionDTO

MMCA.Common.Shared · MMCA.Common.Shared.Privacy · MMCA.Common/Source/Core/MMCA.Common.Shared/Privacy/UserDataExportDTO.cs:61 · Level 0 · record

  • What it is: one section of a data-subject export package: a SectionName, an Available flag, an opaque Data payload, and an UnavailableReason (MMCA.Common/Source/Core/MMCA.Common.Shared/Privacy/UserDataExportDTO.cs:61-89). It is the envelope around whatever one contributor holds about the subject.
  • Depends on: nothing first-party; System.Runtime.Serialization.DataContractAttribute/DataMemberAttribute (BCL). It is the element type of UserDataExportDTO.Sections.
  • Concept introduced, "no data" is not the same fact as "not retrieved". [Rubric §29, Resilience & Business Continuity] assesses how a composite operation behaves when one contributor is down. [Rubric §30, Compliance / Privacy / Data Governance] assesses whether a data-subject right can be honored under partial failure. A naive export either fails whole when any peer is unreachable (denying the subject the data that is available) or silently omits the failed section (telling the subject, falsely, that nothing is held there). This envelope refuses both: a section that could not be produced is still present in the document, reporting Available = false, and the doc comment records the distinction the reader must draw: false "means the section is incomplete and the export can be retried later; it does not mean the subject has no data here" (UserDataExportDTO.cs:68-69). This is the shape ADR-096 calls best-effort, applied to a read.
  • Walkthrough: four init-only properties, ordered explicitly with [DataMember(Order = n)] (UserDataExportDTO.cs:64,71,79,87) so the serialized field order is a stated part of the contract rather than a reflection accident. SectionName and Available are required (UserDataExportDTO.cs:65,72), so a section envelope cannot be constructed without answering both questions. Data is typed object? for the same reason UserDataExportDTO.Subject is: the framework owns the envelope, the contributor owns the payload shape, and System.Text.Json serializes an object-typed property by its runtime type (UserDataExportDTO.cs:74-78). The fourth property carries the section's most security-sensitive rule: UnavailableReason is "a short, caller-safe explanation" that "never carries exception messages, stack traces, connection strings, or peer addresses: this string is handed to the data subject" (UserDataExportDTO.cs:82-86).
  • Why it's built this way: ADR-076 settled the three questions neither app had answered, the first of which was exactly what an export does when one contributing source is unavailable (Website/docs-src/adr/076-data-subject-export.md:52-53). Degrading one section preserves the legal deadline on the rest of the document, and the ADR names the trade-off it accepts in return: an export that looks successful can be incomplete, which is what the Available flag exists to disclose (076-data-subject-export.md:84-88).
  • Where it's used: produced by ExportUserDataHandlerBase<TUser, TQuery> on both paths of its per-section try/catch: from a successful UserDataExportSectionResult (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/ExportUserData/ExportUserDataHandlerBase.cs:205-211) and from the catch that degrades a throwing contributor (ExportUserDataHandlerBase.cs:213-226), where the reason is the fixed string on UserDataExportSectionDefaults rather than anything derived from the exception (:224) and the exception detail goes to the log instead (:218). The envelopes are collected into UserDataExportDTO.Sections at ExportUserDataHandlerBase.cs:123-126,135. The contributors themselves implement IUserDataExportSection (ExportUserDataHandlerBase.cs:63).
  • Caveats / not-in-source: nothing prevents an envelope from setting Available = true and a non-null UnavailableReason at the same time, or Available = false with a payload. The consistency is a convention the producing handler upholds, not a type invariant.

MessageHeaders

MMCA.Common.Shared · MMCA.Common.Shared.Messaging · MMCA.Common/Source/Core/MMCA.Common.Shared/Messaging/MessageHeaders.cs:22 · Level 0 · class (static)

  • What it is: five const string message-broker header names carried on every outbound message: the tenant the publishing scope was resolved to, the publishing user's identifier, that user's roles as a comma-separated list, that user's permission claims as a JSON array, and the correlation id of the interaction that produced the message (MessageHeaders.cs:25-41).
  • Depends on: nothing; BCL-free constants only.
  • Concept introduced, the cross-layer wire literal for a broker envelope. Same placement rule ConcurrencyETag and IdempotencyHeaders follow for an HTTP header, applied here to a message-broker header: the publisher and the consumer are separate assemblies that must agree on a literal, so it lives once in Shared. [Rubric §10, Messaging & Integration] assesses whether cross-service metadata (tenant, actor, correlation) travels explicitly on the envelope rather than being inferred on the consuming side; [Rubric §15, Best Practices & Code Quality] covers the single-source-of-truth angle.
  • Walkthrough: a static class with five const fields: TenantId = "MMCA-Tenant-Id" (:25), UserId = "MMCA-User-Id" (:28), UserRoles = "MMCA-User-Roles" (:31), UserPermissions = "MMCA-User-Permissions" (:38), and CorrelationId = "MMCA-Correlation-Id" (:41). Each doc comment states when the header is absent: TenantId for a tenant-less publish, UserId for work raised by the system rather than a user, UserRoles and UserPermissions when the actor holds none. UserPermissions is carried in full, never truncated, because a missing permission would deny the consumer what the publisher was allowed to do.
  • Why it's built this way: ADR-021 and ADR-073 are the governing records; the multi-tenancy model relies on the tenant header traveling with every message rather than being re-derived on the consuming side.
  • Where it's used: BrokerMessageBus sets these headers on publish (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/BrokerMessageBus.cs), and ConsumerOriginRestore reads them back to rehydrate the tenant/actor context for a handler (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Consumers/ConsumerOriginRestore.cs). Framework coverage is BrokerMessageBusTests (MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Messaging/BrokerMessageBusTests.cs) and IntegrationEventConsumerContextTests (MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Messaging/Consumers/IntegrationEventConsumerContextTests.cs).

PrivacyFeatures

MMCA.Common.Shared · MMCA.Common.Shared.Privacy · MMCA.Common/Source/Core/MMCA.Common.Shared/Privacy/PrivacyFeatures.cs:8 · Level 1 · class (static)

  • What it is: one const string naming the feature flag that gates the data-subject export surface, Privacy.DataExport (MMCA.Common/Source/Core/MMCA.Common.Shared/Privacy/PrivacyFeatures.cs:12).
  • Depends on: FeatureFlagAttribute and FeatureFlagLifetime (both MMCA.Common.Shared.FeatureFlags), which the const now carries.
  • Concept introduced, the feature flag as a shared, self-declaring constant. [Rubric §30, Compliance / Privacy / Data Governance] assesses how the codebase handles data-subject rights and how deliberately those surfaces are turned on. [Rubric §9, API & Contract Design] assesses whether concerns like feature gating are applied uniformly rather than ad hoc. A data-subject access endpoint returns a complete dossier of one person's personal data, so it is the last endpoint that should default to reachable. Naming the flag once, in the assembly every layer can see, lets the attribute that gates the controller and the host configuration that enables it refer to the same string. The flag's own evaluation is the Microsoft.FeatureManagement [FeatureGate] attribute, whose behavior is not this type's concern; see ADR-031. What the const also now declares is its own lifecycle: [FeatureFlag(FeatureFlagLifetime.Permanent, Owner = "MMCA.Common")] (PrivacyFeatures.cs:11) marks it as a flag that is never expected to be removed, which is the same governance annotation NotificationFeatures carries (MMCA.Common/Source/Core/MMCA.Common.Shared/Notifications/NotificationFeatures.cs:11).
  • Walkthrough: a static class containing a single [FeatureFlag(FeatureFlagLifetime.Permanent, Owner = "MMCA.Common")] public const string DataExport = "Privacy.DataExport"; (PrivacyFeatures.cs:8-13). The dotted name is a namespace convention for the flag key, not C# syntax: it is one opaque string as far as the feature manager is concerned. The attribute takes the lifetime as a positional argument and Owner as a named one; a Permanent flag must not name a RemoveBy date, unlike a Temporary one (MMCA.Common/Source/Core/MMCA.Common.Shared/FeatureFlags/FeatureFlagAttribute.cs:10-11).
  • Why it's built this way: ADR-076 makes the whole export capability opt-in and records the gate explicitly: a host that has not turned the feature on gets a 404 from the endpoint rather than an unauthorized-looking 403 (Website/docs-src/adr/076-data-subject-export.md:124). The [FeatureFlag] annotation is the later, codebase-wide discipline that makes every flag self-reporting: FeatureFlagLifecycleTestsBase fails the build on a flag that carries no declaration or on a Temporary one past its RemoveBy (MMCA.Common/CLAUDE.md, "FeatureGate" bullet), and FeatureFlagRegistry reports the same inventory at runtime.
  • Where it's used: the framework side is DataExportControllerBase<TQuery>, which carries [FeatureGate(PrivacyFeatures.DataExport)] on the class (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Privacy/DataExportControllerBase.cs:60) with the rationale in the same file's remarks (DataExportControllerBase.cs:54-55). Both apps subclass that base with a thin, route-only controller: UsersDataExportController (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/Controllers/UsersDataExportController.cs:26-35, MMCA.Store/Source/Modules/Identity/MMCA.Store.Identity.API/Controllers/UsersDataExportController.cs:28-38), and both Identity service hosts turn the flag on in configuration (MMCA.ADC/Source/Services/MMCA.ADC.Identity.Service/appsettings.json:21, MMCA.Store/Source/Services/MMCA.Store.Identity.Service/appsettings.json:18). ADC's config carries the operational warning beside it: the flag "must stay true: with the flag off the endpoint 404s and ADC has no other DSAR surface" (MMCA.ADC/.../appsettings.json:17-19). The [FeatureFlag] declaration is read by FeatureFlagLifecycleTests and FeatureFlagRegistryTests (MMCA.Common/Tests/Architecture/MMCA.Common.Architecture.Tests/Governance/FeatureFlagLifecycleTests.cs, MMCA.Common/Tests/Core/MMCA.Common.Shared.Tests/FeatureFlags/FeatureFlagRegistryTests.cs).
  • Caveats / not-in-source: those two appsettings.json files are the only places in the workspace that declare the flag. Both apps deploy the endpoint from their Identity service host, so the deployed path is covered, but any other host that mounted the controller would serve a 404 until it added its own FeatureManagement entry.

UserDataExportDTO

MMCA.Common.Shared · MMCA.Common.Shared.Privacy · MMCA.Common/Source/Core/MMCA.Common.Shared/Privacy/UserDataExportDTO.cs:15 · Level 1 · record

  • What it is: the whole data-subject export package: a format version, a generation timestamp, the subject's id, an app-owned snapshot of the account itself, and a list of UserDataExportSectionDTO envelopes (MMCA.Common/Source/Core/MMCA.Common.Shared/Privacy/UserDataExportDTO.cs:15-49).
  • Depends on: UserDataExportSectionDTO; the UserIdentifierType alias (ADR-085); System.Runtime.Serialization attributes (BCL).
  • Concept introduced, the versioned, PII-by-design document. [Rubric §30, Compliance / Privacy / Data Governance] assesses how personal data is classified and handled. Most DTOs in this codebase carry incidental personal data; this one is personal data end to end, and the type says so in bold in its own summary: "This document is PII by design. It exists to hand a data subject everything an app holds about them, so it must only ever be produced for the account owner (or a privileged role) and must never be logged, cached, or persisted by the pipeline that serves it" (UserDataExportDTO.cs:9-11). That single comment is what makes three otherwise-invisible decisions legible: the query is not IQueryCacheable, so the caching decorator never sees it (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/ExportUserData/ExportUserDataHandlerBase.cs:55-56); the degradation path logs the exception but hands the subject a generic reason (ExportUserDataHandlerBase.cs:213-225); and the controller serializes to bytes and returns a file rather than an ObjectResult (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Privacy/DataExportControllerBase.cs:103-113). [Rubric §9, API & Contract Design]: FormatVersion versions "the export document shape itself (not the app's data)" (UserDataExportDTO.cs:18-19), so a consumer parsing an old file can detect an envelope change rather than guess at it.
  • Walkthrough: five init-only properties under [DataContract] (:14), each with an explicit [DataMember(Order = n)] (UserDataExportDTO.cs:21,25,29,39,47) pinning field order into the contract.
    • FormatVersion, GeneratedOn, and UserId are required (:22,26,30), so the envelope cannot be constructed without them.
    • Subject is object? (:40), and the doc comment gives the full reasoning: the framework owns the envelope, each app owns which of its own fields are portable personal data, and an object-typed property serializes by its runtime type under System.Text.Json (:32-38). That last clause is the mechanism that makes the erasure of the static type harmless. null is legal and means the app publishes no subject fields.
    • Sections defaults to an empty collection expression, = [] (:48), so an export with no registered contributors is a well-formed document rather than a null-bearing one. Order is the section registration order, which the comment makes part of the contract (:42-46).
  • Why it's built this way: ADR-076 hoisted this shape out of two near-identical app implementations. It is the export half of the data-subject obligation whose erasure half was settled by ADR-005, which explicitly scoped export out and left it to consumers (Website/docs-src/adr/076-data-subject-export.md:21-23).
  • Where it's used: it is the result type of the export query all the way through the stack. ExportUserDataHandlerBase<TUser, TQuery> implements IQueryHandler<TQuery, Result<UserDataExportDTO>> (ExportUserDataHandlerBase.cs:66), stamps CurrentFormatVersion = "1.0" into it (ExportUserDataHandlerBase.cs:74,131), and takes GeneratedOn from an injected TimeProvider rather than a static clock (ExportUserDataHandlerBase.cs:132). DataExportControllerBase<TQuery> declares it as the 200 response type (DataExportControllerBase.cs:80) and derives the download file name from the package's own GeneratedOn so the file name and the document can never disagree (DataExportControllerBase.cs:111,131-141). Both apps subclass the handler (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/ExportUserData/ExportUserDataHandler.cs:37, MMCA.Store/Source/Modules/Identity/MMCA.Store.Identity.Application/Users/UseCases/ExportUserData/ExportUserDataHandler.cs:39) and expose it through their own UsersDataExportController (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/Controllers/UsersDataExportController.cs:27, MMCA.Store/Source/Modules/Identity/MMCA.Store.Identity.API/Controllers/UsersDataExportController.cs:29).

ForgotPasswordRequestValidator

MMCA.Common.Application · MMCA.Common.Application.Auth.Validation · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Validation/ForgotPasswordRequestValidator.cs:11 · Level 1 · class

  • What it is: the FluentValidation validator for ForgotPasswordRequest. It checks one field, Email, for non-empty and address shape (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Validation/ForgotPasswordRequestValidator.cs:13-16).
  • Depends on: ForgotPasswordRequest; FluentValidation's AbstractValidator<T> (NuGet).
  • Concept introduced, validation that deliberately stops short. [Rubric §11, Security] assesses whether the system leaks facts an attacker can use, and account enumeration is the classic leak: if "forgot password" answers differently for a registered and an unregistered address, the endpoint becomes a membership oracle. The forgot-password endpoint answers 202 Accepted unconditionally (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/PasswordResetAuthControllerBase.cs:79,92), and this validator is the place that could quietly undo it: a rule that checked whether the address belongs to an account would turn a miss into a 400, which is the same oracle by a different status code. The class doc comment names that trap and refuses it: a 400 there "would be the enumeration oracle the always-accepted response exists to close" (ForgotPasswordRequestValidator.cs:7-9), and the controller's own remarks agree that only a malformed payload may reach 400 (PasswordResetAuthControllerBase.cs:28-30). [Rubric §24, Forms / Validation / UX Safety]: shape validation still runs, so a genuinely malformed address gets a useful client-side message without costing an email send.
  • Walkthrough: an expression-bodied constructor with a single chained rule, RuleFor(x => x.Email).NotEmpty().EmailAddress(), each stage carrying an explicit WithMessage (ForgotPasswordRequestValidator.cs:13-16). The messages are literal English strings rather than resource lookups, which is how every validator in this assembly is written.
  • Why it's built this way: the reset flow itself is ADR-091; the uniform-response posture it depends on is only as strong as its weakest responder, and a validator runs before the handler does.
  • Where it's used: registered by assembly scan. services.AddValidatorsFromAssemblyContaining<ClassReference>() (MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.cs:70) picks up every validator in MMCA.Common.Application, with the comment explaining why it must happen here rather than in the per-module scan (DependencyInjection.cs:67-69). The resolved IValidator<ForgotPasswordRequest> is then consumed indirectly: an app's forgot-password command implements ICommandWithRequest<ForgotPasswordRequest> (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/ForgotPassword/ForgotPasswordHandlerBase.cs:71), and CommandRequestValidator<TCommand, TRequest> bridges the command's Request property to this validator (MMCA.Common/Source/Core/MMCA.Common.Application/Validation/CommandRequestValidator.cs:37-39), auto-registered for every such command at MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.ModuleScanning.cs:84-100.

JwtAlgorithms

MMCA.Common.Infrastructure, MMCA.Common.API, MMCA.Common.Testing (linked source) · MMCA.Common.Auth · MMCA.Common/Source/Build/Auth/JwtAlgorithms.cs:16 · Level 1 · class (static, internal)

  • What it is: the one list of JWT signature algorithms the framework signs with and accepts, plus the clock skew every bearer validator allows. One internal source file, compiled into each project that issues or validates a token through a <Compile Include ... Link="Auth\JwtAlgorithms.cs" /> item (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/MMCA.Common.Infrastructure.csproj:21, MMCA.Common/Source/Presentation/MMCA.Common.API/MMCA.Common.API.csproj:49, MMCA.Common/Source/Hosting/MMCA.Common.Testing/MMCA.Common.Testing.csproj:51), so no site carries its own copy (MMCA.Common/Source/Build/Auth/JwtAlgorithms.cs:6-10).
  • Depends on: JwtSigningAlgorithm (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/JwtSigningAlgorithm.cs:23); Microsoft.IdentityModel.Tokens.SecurityAlgorithms for the JOSE names.
  • Concept introduced, algorithm-family pinning. [Rubric §11, Security] assesses whether authentication resists known attack classes; the classic JWT one is algorithm confusion, where a token signed with HMAC using the published public key as the secret is accepted by a validator that tries every algorithm. The remarks state the defence: an asymmetric validator accepts exactly Asymmetric, an HMAC validator exactly Symmetric, and no validator ever accepts both (JwtAlgorithms.cs:11-14). [Rubric §15, Best Practices & Code Quality] assesses duplication and consistency; a linked internal source gives three assemblies one definition without making it public API, so the issuer, the JWKS publisher, both bearer validators and the test token generator cannot disagree about the list.
  • Walkthrough:
    • ClockSkew (JwtAlgorithms.cs:22): TimeSpan.FromSeconds(30), the tolerance past expiry and before not-before that every validator the framework configures uses.
    • Asymmetric (JwtAlgorithms.cs:25-30): RS256, PS256 and ES384. Symmetric (JwtAlgorithms.cs:33): HS256 only.
    • IsAsymmetric (JwtAlgorithms.cs:38): every value except HS256. UsesEcKey (JwtAlgorithms.cs:43): ES384 only, the one algorithm whose key is elliptic-curve rather than RSA.
    • ToSecurityAlgorithm (JwtAlgorithms.cs:49-56): maps the configured enum to its JOSE alg value and throws ArgumentOutOfRangeException for an undefined value.
    • AcceptedFor (JwtAlgorithms.cs:61-62): the accepted list for a configured algorithm, Asymmetric or Symmetric by IsAsymmetric.
  • Why it's built this way: crypto agility (ADR-149). Each key the JWKS publishes carries its own alg, and the JWKS validator accepts the whole asymmetric list, so a key rotation that also changes the algorithm keeps validating (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/WebApplicationBuilderExtensions.Authentication.cs:104-110). ADR-149 records the 30-second skew as a breaking change for consumers.
  • Where it's used: the forwarded (JWKS) bearer validator (WebApplicationBuilderExtensions.Authentication.cs:110-111) and the in-process BuildValidationParameters (WebApplicationBuilderExtensions.Authentication.cs:227-229,247-248,261-262); the issuer TokenService, which picks its validation list and signing alg here (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/TokenService.cs:93,95,279,297); RsaJwksProvider, which stamps alg on each published key (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/RsaJwksProvider.cs:38,88); JwksSettings, which refuses an HS256 additional key (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/JwksSettings.cs:137,142); the startup key strength validators (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/Auth/JwtKeyStrengthValidator.cs:35,41, MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/Auth/JwksKeyStrengthValidator.cs:36,47,75); JwtKeyMaterial (MMCA.Common/Source/Build/Auth/JwtKeyMaterial.cs:77,113); and the Testing package's JwtTokenGenerator (MMCA.Common/Source/Hosting/MMCA.Common.Testing/Support/JwtTokenGenerator.cs:148,209).
  • Caveats / not-in-source: because the type is internal and linked, each of the three assemblies compiles its own MMCA.Common.Auth.JwtAlgorithms; they agree because they are one file, not because they share a type identity.

RedeemSignInLinkRequestValidator

MMCA.Common.Application · MMCA.Common.Application.Auth.Validation · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Validation/SignInLinkRequestValidators.cs:24 · Level 1 · class

  • What it is: the validator for redeeming a sign-in link (RedeemSignInLinkRequest): Email must be non-empty and a valid address, Token must be non-empty (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Validation/SignInLinkRequestValidators.cs:29-34).
  • Depends on: RedeemSignInLinkRequest; FluentValidation's AbstractValidator<T>.
  • Concept: the shape-only posture ForgotPasswordRequestValidator introduced, applied to a token. [Rubric §11, Security]: the doc comment states why the token gets no format check: "an unknown or expired token is the handler's single generic rejection, not a 400 that would tell a caller their token was at least well formed" (SignInLinkRequestValidators.cs:19-23). Whether the token is live is decided by SignInLinkTokenService, which answers every miss with the same SignInLinkErrors failure.
  • Walkthrough: a block-bodied constructor with two independent RuleFor chains (SignInLinkRequestValidators.cs:29-34), each stage carrying an explicit WithMessage, sharing the file with SendSignInLinkRequestValidator.
  • Why it's built this way: sign-in links sit with the other opt-in identity completions (ADR-116); a validator that stops at shape keeps the handler as the only place a link's validity is decided.
  • Where it's used: registered by the assembly scan (MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.cs:70) and reached through CommandRequestValidator<TCommand, TRequest> for a command carrying this request.
  • Caveats / not-in-source: no first-party or test reference to this type appears outside its defining file; the assembly scan is the only wiring visible in source.

RefreshTokenRequestValidator

MMCA.Common.Application · MMCA.Common.Application.Auth.Validation · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Validation/RefreshTokenRequestValidator.cs:10 · Level 1 · class

  • What it is: the validator for RefreshTokenRequest. Both fields are required and nothing more is checked (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Validation/RefreshTokenRequestValidator.cs:14-18).
  • Depends on: RefreshTokenRequest; FluentValidation's AbstractValidator<T>.
  • Concept: the shape is the one ForgotPasswordRequestValidator introduced. What this validator teaches is why both fields are mandatory, which the doc comment states: the expired access token is needed "for claim extraction" and the refresh token "for rotation verification" (RefreshTokenRequestValidator.cs:7-8). [Rubric §11, Security]: rotation verifies the presented refresh token against the one stored for the identity carried by the access token, so a request missing either half cannot be evaluated at all. Deliberately absent: any JWT well-formedness or signature check. Parsing a token is the token service's job, and doing it here would duplicate the trust boundary in a layer that has no key material.
  • Walkthrough: two single-stage RuleFor(...).NotEmpty() chains with explicit messages (RefreshTokenRequestValidator.cs:14-18).
  • Why it's built this way: keeping the validator to presence checks leaves exactly one place where a token's authenticity is decided, which is what makes the refresh endpoint's failure responses uniform.
  • Where it's used: picked up by the same assembly scan (MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.cs:70, named in the comment at :67-68) and injected as IValidator<RefreshTokenRequest> into AuthenticationValidators (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/AuthenticationValidators.cs:36,72).

SendEmailConfirmationRequestValidator

MMCA.Common.Application · MMCA.Common.Application.Auth.Validation · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Validation/EmailConfirmationRequestValidators.cs:13 · Level 1 · class

  • What it is: the validator for requesting a confirmation email: Email must be non-empty and a valid address, nothing else (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Validation/EmailConfirmationRequestValidators.cs:16-18).
  • Depends on: SendEmailConfirmationRequest; FluentValidation's AbstractValidator<T>.
  • Concept: the same shape-only posture as ForgotPasswordRequestValidator: the field is checked for well-formedness, not for whether it belongs to an account. [Rubric §11, Security] applies for the same reason a resend-confirmation endpoint is a candidate for the same account-enumeration trap a forgot-password endpoint is.
  • Walkthrough: an expression-bodied constructor with a single RuleFor(x => x.Email).NotEmpty().EmailAddress() chain (EmailConfirmationRequestValidators.cs:16-18), sharing the file with ConfirmEmailRequestValidator.
  • Why it's built this way: email confirmation is one of the identity completions ADR-116 added, all opt-in through AddEmailConfirmation(config).
  • Where it's used: registered by the assembly scan (MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.cs:70). MMCA.ADC/Tests/Architecture/MMCA.ADC.Architecture.Tests/Cqrs/CommandValidatorCoverageTests.cs is the only reference to this type outside its defining assembly, asserting the command that carries this request has a validator registered.

SendSignInLinkRequestValidator

MMCA.Common.Application · MMCA.Common.Application.Auth.Validation · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Validation/SignInLinkRequestValidators.cs:11 · Level 1 · class

  • What it is: the validator for requesting a sign-in link (SendSignInLinkRequest): Email must be non-empty and a valid address, nothing else (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Validation/SignInLinkRequestValidators.cs:14-17).
  • Depends on: SendSignInLinkRequest; FluentValidation's AbstractValidator<T>.
  • Concept: the enumeration-safe posture ForgotPasswordRequestValidator introduced, word for word. [Rubric §11, Security]: the doc comment says whether the address belongs to an account "is deliberately not a validation concern, because a 400 there would be the enumeration oracle the always-accepted response exists to close" (SignInLinkRequestValidators.cs:6-10).
  • Walkthrough: an expression-bodied constructor with a single RuleFor(x => x.Email).NotEmpty().EmailAddress() chain (SignInLinkRequestValidators.cs:14-17), sharing the file with RedeemSignInLinkRequestValidator.
  • Why it's built this way: the per-address cap on how often a link can be emailed is not a validation rule either; it lives in SignInLinkTokenService's issue path, where it can count requests across the distributed cache.
  • Where it's used: registered by the assembly scan (MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.cs:70) and reached through CommandRequestValidator<TCommand, TRequest>.
  • Caveats / not-in-source: no first-party or test reference to this type appears outside its defining file.

TwoFactorCodeRequestValidator

MMCA.Common.Application · MMCA.Common.Application.Auth.Validation · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Validation/TwoFactorCodeRequestValidator.cs:16 · Level 1 · class

  • What it is: the validator for a submitted two-factor code: Code must be non-empty and no longer than MaxCodeLength (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Validation/TwoFactorCodeRequestValidator.cs:22-24).
  • Depends on: TwoFactorCodeRequest; FluentValidation's AbstractValidator<T>.
  • Concept: presence and a length ceiling only, the shape-only posture ForgotPasswordRequestValidator introduced, applied here to bound input size rather than to avoid an enumeration oracle. [Rubric §11, Security]: whether a TOTP code or a recovery code was presented is not decided here; both shapes are short strings, so the validator can only reject the obviously wrong length, and the doc comment names 64 as the ceiling (TwoFactorCodeRequestValidator.cs:17).
  • Walkthrough: public const int MaxCodeLength = 64; (:17) followed by an expression-bodied constructor chaining NotEmpty().MaximumLength(MaxCodeLength) on Code (:22-24). The constant is public so a caller (or a test) can reference the same ceiling rather than re-guessing it.
  • Why it's built this way: two-factor authentication is one of the opt-in identity completions (ADR-116); the actual decision between a TOTP match and a recovery-code match happens downstream in TwoFactorAuthenticator, not in this validator.
  • Where it's used: registered by the assembly scan (MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.cs:70).
  • Caveats / not-in-source: no first-party or test reference to this type appears outside its defining file; the assembly scan is the only wiring visible in source.

ChangePasswordRequestValidator

MMCA.Common.Application · MMCA.Common.Application.Auth.Validation · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Validation/ChangePasswordRequestValidator.cs:15 · Level 2 · class (sealed)

  • What it is: the framework's FluentValidation rule set for a password change: the current password must be present, and the new password must clear the shared strong-password policy (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Validation/ChangePasswordRequestValidator.cs:18-24).
  • Depends on: ChangePasswordRequest; StrongPasswordRules<T> (MMCA.Common/Source/Core/MMCA.Common.Application/Validation/CommonValidationRules.cs:248); FluentValidation's AbstractValidator<T> and its Include composition.
  • Concept: the Include composition ResetPasswordRequestValidator introduces, applied to the third password-writing path. [Rubric §11, Security]: the doc comment states the intent, the new password goes through "the same StrongPasswordRules{T} registration and password reset use, so a change cannot be a way around the complexity policy" (ChangePasswordRequestValidator.cs:7-10). [Rubric §24, Forms / Validation / UX Safety]: every rule answers under its own code, so a host localizes each message by code rather than by English text (ChangePasswordRequestValidator.cs:10-12).
  • Walkthrough: one block-bodied constructor (ChangePasswordRequestValidator.cs:18-24).
    • RuleFor(x => x.CurrentPassword).NotEmpty() with the message "Current password is required." and the error code ChangePassword.CurrentPassword.Required (ChangePasswordRequestValidator.cs:20-21).
    • Include(new StrongPasswordRules<ChangePasswordRequest>(x => x.NewPassword, codePrefix: "ChangePassword.NewPassword")) (ChangePasswordRequestValidator.cs:23). With a codePrefix each policy rule answers under {codePrefix}.{Rule} (for example ChangePassword.NewPassword.MinLength), the shape the shared WithRuleCode helper produces (MMCA.Common/Source/Core/MMCA.Common.Application/Validation/CommonValidationRules.cs:36-37).
  • Why it's built this way: the current password is checked only for presence, never for strength. Its correctness is a credential comparison against the stored hash, made by ChangePasswordHandlerBase<TUser, TCommand>, and an old account may legitimately hold a password that predates today's policy; applying the strength rules to it would lock that user out of the very screen that fixes the problem. The same reasoning keeps complexity off LoginRequestValidator.
  • Where it's used: registered by AddApplication() (the class remarks say so, ChangePasswordRequestValidator.cs:14) through the framework assembly scan services.AddValidatorsFromAssemblyContaining<ClassReference>() (MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.cs:70). It reaches the pipeline through CommandRequestValidator<TCommand, TRequest> for a command that implements ICommandWithRequest<ChangePasswordRequest>. The framework handler's own constraint is only IUserScopedCommand<ChangePasswordRequest> (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/ChangePassword/ChangePasswordHandlerBase.cs:63), which deliberately does not opt a command into that bridge (MMCA.Common/Source/Core/MMCA.Common.Application/Users/IUserScopedCommand.cs:7-11), so the app's command declares both: ADC's ChangePasswordCommand does (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/ChangePassword/ChangePasswordCommand.cs:13). Covered by MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Auth/Validation/ChangePasswordRequestValidatorTests.cs, and its registration by MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/DependencyInjectionTests.cs.

JwtKeyMaterial

MMCA.Common.Infrastructure, MMCA.Common.API (linked source) · MMCA.Common.Auth · MMCA.Common/Source/Build/Auth/JwtKeyMaterial.cs:13 · Level 2 · class (static, internal)

  • What it is: the PEM key loader for JWT signing and validation keys, by algorithm (RS256 and PS256 read an RSA key, ES384 an ECDSA key on P-384), plus the measure of a key against the strength floor (MMCA.Common/Source/Build/Auth/JwtKeyMaterial.cs:8-12). Linked into the issuer's and the validator's projects (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/MMCA.Common.Infrastructure.csproj:22, MMCA.Common/Source/Presentation/MMCA.Common.API/MMCA.Common.API.csproj:50), but not into Testing.
  • Depends on: JwtAlgorithms (JwtKeyMaterial.cs:77,113), JwtSigningAlgorithm; BCL RSA, ECDsa and CryptographicException; Microsoft.IdentityModel.Tokens RsaSecurityKey, ECDsaSecurityKey and AsymmetricSecurityKey.
  • Concept: the algorithm-family split JwtAlgorithms introduces, applied to key material. [Rubric §11, Security]: a key is checked for shape as well as readability, so an ES384 deployment cannot run on a weaker curve and an RSA deployment cannot run below the configured modulus floor. [Rubric §34, Architecture Governance & Documentation] assesses whether rules are enforced rather than remembered; this type is one of the few named in the cryptography allow-list the architecture suite enforces (MMCA.Common/Tests/Architecture/MMCA.Common.Architecture.Tests/Governance/Cryptography/CryptographyUsageTests.cs:16-18), so new key-loading code elsewhere fails a test instead of drifting.
  • Walkthrough:
    • P384Oid and P384FriendlyNames (JwtKeyMaterial.cs:16,18): the curve is matched by OID 1.3.132.0.34 or by any of four friendly names, because platforms report a named curve by OID value, friendly name, or both (JwtKeyMaterial.cs:15).
    • ImportRsa (JwtKeyMaterial.cs:23-36): creates an RSA, imports the PEM and returns it; on any failure it disposes the instance and rethrows. The caller owns the result.
    • ImportP384 (JwtKeyMaterial.cs:45-64): the same shape for ECDsa, plus a CryptographicException naming the actual curve when the key is not on P-384.
    • CreatePublicKey (JwtKeyMaterial.cs:74-96): imports with the right loader, then exports includePrivateParameters: false into a fresh key, so a private PEM supplied by mistake still yields only the public half; stamps KeyId when one is given.
    • StrengthShortfall (JwtKeyMaterial.cs:109-132): returns a description of the shortfall (an RSA modulus below minimumRsaKeySizeBits, or an EC key off P-384) or null. It also returns null when the PEM cannot be read (ArgumentException or CryptographicException), because reading the key is the loader's check, not this one (JwtKeyMaterial.cs:105-107).
    • IsP384 and CurveName (JwtKeyMaterial.cs:134-146): IsP384 requires a named curve matched by OID (ordinal) or friendly name (ordinal ignore-case); CurveName falls back to "unnamed".
  • Why it's built this way: one loader keeps the issuer, the JWKS publisher and the in-process validator reading a key the same way, and the floor makes key strength a startup failure rather than a review item (ADR-149, which records that a non-Development host with a key below 3072 bits fails to start until it rotates or sets the override).
  • Where it's used: the issuer TokenService loads its signing and validation keys through ImportP384/ImportRsa (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/TokenService.cs:326-327); the in-process validator builds its key with CreatePublicKey (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/WebApplicationBuilderExtensions.Authentication.cs:245), as does JwksSettings for each additional rotation key (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/JwksSettings.cs:291); and the startup options validator measures every configured PEM with StrengthShortfall against the floor set by Jwt:MinimumRsaKeySizeBits (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/Auth/JwtKeyStrengthValidator.cs:27,76).
  • Caveats / not-in-source: an unreadable PEM produces no shortfall here by design; the failure surfaces where the key is actually loaded.

ResetPasswordRequestValidator

MMCA.Common.Application · MMCA.Common.Application.Auth.Validation · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Validation/ResetPasswordRequestValidator.cs:12 · Level 1 · class

  • What it is: the validator for ResetPasswordRequest: address shape on Email, presence on Token, and the shared strong-password policy on NewPassword (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Validation/ResetPasswordRequestValidator.cs:16-23).
  • Depends on: ResetPasswordRequest; StrongPasswordRules<T>; FluentValidation's AbstractValidator<T> and its Include composition.
  • Concept introduced, composing a rule set with Include. [Rubric §11, Security] assesses whether a policy holds on every path that can change the guarded value, and [Rubric §1, SOLID] the single-responsibility split that makes that possible. A password-complexity policy is only a policy if every write path enforces it; if registration demands an uppercase letter and reset does not, reset is a documented downgrade route. FluentValidation's Include merges another validator's rules for the same model type into this one, so the policy can live in exactly one class and be pulled into each writer. The doc comment states the intent: the new password goes through "the same StrongPasswordRules<T> the registration and change-password requests use, so a reset cannot be a way around the complexity policy" (ResetPasswordRequestValidator.cs:8-10). StrongPasswordRules<T> is generic over the containing model and takes a selector expression, which is what lets one rule set attach to a differently-shaped request each time (MMCA.Common/Source/Core/MMCA.Common.Application/Validation/CommonValidationRules.cs:248-262): it enforces non-empty, 8 to 128 characters, and one each of uppercase, lowercase, digit, and non-alphanumeric.
  • Walkthrough: three statements in a block-bodied constructor (ResetPasswordRequestValidator.cs:14-24). Email gets NotEmpty().EmailAddress() (:16-18), matching the forgot-password half so the two steps agree on what an address is. Token gets NotEmpty() with a reset-specific message (:20-21); no format check, because the token's validity is a lookup, not a shape. Then Include(new StrongPasswordRules<ResetPasswordRequest>(x => x.NewPassword)) (:23) grafts the seven policy rules onto the NewPassword field (CommonValidationRules.cs:254-260).
  • Why it's built this way: the reset flow is ADR-091, and the hashing the accepted password ends up under is ADR-102 (which supersedes ADR-032). Neither is this validator's concern, which is the point: it only decides whether the candidate is policy-compliant.
  • Where it's used: registered by the assembly scan (MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.cs:70) and reached through CommandRequestValidator<TCommand, TRequest> for any command implementing ICommandWithRequest<ResetPasswordRequest>, the constraint ResetPasswordHandlerBase<TUser, TCommand> declares (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/ResetPassword/ResetPasswordHandlerBase.cs:51). The request arrives at PasswordResetAuthControllerBase<TForgotPasswordCommand, TResetPasswordCommand> (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/PasswordResetAuthControllerBase.cs:108), which is why a policy failure surfaces as the documented 400 (PasswordResetAuthControllerBase.cs:104) while a bad token collapses to 401 (PasswordResetAuthControllerBase.cs:97,105).

SetRolePermissionsRequestValidator

MMCA.Common.Application · MMCA.Common.Application.Auth.Validation · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Validation/AdministrationRequestValidators.cs:30 · Level 4 · class

  • What it is: the validator for replacing a role's stored permission grants: Permissions must be non-null, and each entry must be non-empty and within PermissionGrant.PermissionMaxLength (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Validation/AdministrationRequestValidators.cs:34-40).
  • Depends on: SetRolePermissionsRequest; PermissionGrant (for PermissionMaxLength); FluentValidation's AbstractValidator<T>.
  • Concept: shape validation for a role-administration write, the same posture the request validators earlier in this group establish, but the field it guards is a collection rather than a scalar. [Rubric §11, Security]: an empty Permissions list is deliberately legal, and the doc comment on the rule states why: it "is how an operator undoes every grant. It never removes what the host compiled in" (AdministrationRequestValidators.cs:37-38). What this validator refuses is null, a malformed request, not an empty intent; and it bounds each entry's length so a caller cannot smuggle an oversized string into a permission name.
  • Walkthrough: a block-bodied constructor with RuleFor(x => x.Permissions).NotNull() (:39) followed by RuleForEach(x => x.Permissions).NotEmpty().MaximumLength(PermissionGrant.PermissionMaxLength) (:41-44), each stage carrying an explicit WithMessage. It shares its file with SetUserRolesRequestValidator, the sibling that guards role assignment rather than permission grants.
  • Why it's built this way: what a stored permission grant is layered over, and why the compiled AdministrationPermissions.ManageRoles permission can never itself become a stored grant, is StoredPermissionRoleAdministrationService's concern, not this validator's; this type only decides whether the shape of a replacement list is acceptable.
  • Where it's used: registered by the assembly scan (MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.cs:70).
  • Caveats / not-in-source: no first-party or test reference to this type appears outside its defining file.

SetUserRolesRequestValidator

MMCA.Common.Application · MMCA.Common.Application.Auth.Validation · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Validation/AdministrationRequestValidators.cs:11 · Level 4 · class

  • What it is: the validator for replacing a user's role list: Roles must be non-null, and each entry must be non-empty and within PermissionGrant.RoleMaxLength (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Validation/AdministrationRequestValidators.cs:15-21).
  • Depends on: SetUserRolesRequest; PermissionGrant (for RoleMaxLength); FluentValidation's AbstractValidator<T>.
  • Concept: the mirror of SetRolePermissionsRequestValidator one level up in the same file: an empty list is a legitimate intent (stripping every role from an account) while null is a malformed body. The doc comment draws the same line: "What is rejected is a null list, which is a malformed body rather than an intent" (AdministrationRequestValidators.cs:18-19).
  • Walkthrough: RuleFor(x => x.Roles).NotNull() (:20) followed by RuleForEach(x => x.Roles).NotEmpty().MaximumLength(PermissionGrant.RoleMaxLength) (:22-25), each with an explicit WithMessage.
  • Why it's built this way: the same administration surface SetRolePermissionsRequestValidator guards; both validators keep the shape check separate from the business rule (which roles/permissions actually exist), which is decided downstream by the role-administration service.
  • Where it's used: registered by the assembly scan (MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.cs:70).
  • Caveats / not-in-source: no first-party or test reference to this type appears outside its defining file.

RegisterRequestValidator

MMCA.Common.Application · MMCA.Common.Application.Auth.Validation · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Validation/RegisterRequestValidator.cs:20 · Level 6 · class (sealed)

  • What it is: the framework's rule set for a registration request: a well-formed email of at most EmailMaxLength (100) characters, the strong-password policy, required first and last names of at most NameMaxLength (100) characters, and an optional address validated only when present (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Validation/RegisterRequestValidator.cs:23,26,29-39).
  • Depends on: RegisterRequest; EmailRules<T>, StrongPasswordRules<T>, RequiredStringRules<T> (MMCA.Common/Source/Core/MMCA.Common.Application/Validation/CommonValidationRules.cs:77,112,248), AddressValidator (MMCA.Common/Source/Core/MMCA.Common.Application/Validation/AddressValidationRules.cs:13); FluentValidation.
  • Concept: composition by Include, the technique ResetPasswordRequestValidator introduces, taken to its limit: four of the five statements are Include calls, so the shared rule sets carry the logic and this class only chooses which property each applies to. [Rubric §15, Best Practices & Code Quality]: the length ceilings are public constants on the validator (RegisterRequestValidator.cs:23,26) rather than literals inside the rules, so a caller or a test references the same number. [Rubric §24, Forms / Validation / UX Safety]: every rule answers under its own Register.{Field}.{Rule} code (Register.Email.Invalid, Register.Password.Uppercase, Register.FirstName.MaxLength), so a host localizes each message by code (RegisterRequestValidator.cs:11-13).
  • Walkthrough: one block-bodied constructor (RegisterRequestValidator.cs:29-39).
    • EmailRules<RegisterRequest>(x => x.Email, "Email", EmailMaxLength, codePrefix: "Register.Email") (RegisterRequestValidator.cs:31): presence, format and length.
    • StrongPasswordRules<RegisterRequest>(x => x.Password, codePrefix: "Register.Password") (RegisterRequestValidator.cs:32), the same policy ChangePasswordRequestValidator applies to a new password.
    • Two RequiredStringRules<RegisterRequest> for the names, each bounded by NameMaxLength (RegisterRequestValidator.cs:33-34).
    • The conditional address rule, RuleFor(x => x.Address).SetValidator(new AddressValidator()!).When(x => x.Address is not null) (RegisterRequestValidator.cs:36-38). When is what makes the address genuinely optional: omitting it is valid, supplying a malformed one is not.
  • Why it's built this way: registration is anonymous and internet-facing, the most hostile input surface in the identity flow, so it takes the framework-owned rule sets and a tightening of the shared password policy applies here without a code change ([Rubric §11, Security]). The remarks also record what is deliberately absent: AcceptedTerms is not validated here, because whether it is required depends on the host's configured terms version, which the authentication service checks (RegisterRequestValidator.cs:16-18).
  • Where it's used: registered by AddApplication() through the framework assembly scan (MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.cs:70), resolved as IValidator<RegisterRequest> into AuthenticationValidators (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/AuthenticationValidators.cs:35,69), and run at the top of the registration workflow in AuthenticationServiceBase<TUser> (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/AuthenticationServiceBase.cs:302). Covered by MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Auth/Validation/RegisterRequestValidatorTests.cs, with registration asserted in MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/DependencyInjectionTests.cs.

LoginRequestValidator

MMCA.Common.Application · MMCA.Common.Application.Auth.Validation · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Validation/LoginRequestValidator.cs:21 · Level 7 · class

  • What it is: the validator for LoginRequest: Email must be non-empty, at most EmailMaxLength characters and a valid address; Password must be non-empty and at most PasswordMaxLength (1024) characters; the optional TwoFactorCode is only bounded in length (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Validation/LoginRequestValidator.cs:24,30,34-44).
  • Depends on: LoginRequest; RegisterRequestValidator for the email bound and TwoFactorCodeRequestValidator for the code bound; PasswordComplexity as the reference the password bound sits above; FluentValidation's AbstractValidator<T>.
  • Concept: the same "validation that deliberately stops short" posture introduced by ForgotPasswordRequestValidator. [Rubric §11, Security]: the doc comment is explicit that the minimalism is a security property, not laziness. Credential verification "happens in the authentication service to avoid leaking information about which field was wrong" (LoginRequestValidator.cs:8-12). The length bounds are a cost guard, not a policy: they keep an oversized body from reaching the password hasher, whose cost grows with the input, and the user lookup, and they are deliberately no tighter than what an account can hold (LoginRequestValidator.cs:14-20). EmailMaxLength is the registration bound itself (LoginRequestValidator.cs:24, aliasing RegisterRequestValidator.EmailMaxLength, 100, at MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Validation/RegisterRequestValidator.cs:23), and 1024 sits well above PasswordComplexity.MaximumLength (128, MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/PasswordComplexity.cs:24), so no settable password is refused here. Notice what is absent: no StrongPasswordRules<T> include, the one password-policy rule set (MMCA.Common/Source/Core/MMCA.Common.Application/Validation/CommonValidationRules.cs:248). Applying the complexity policy at login would tell an attacker that a candidate password could not possibly be the stored one, and would lock out any account whose password predates the current policy. Complexity belongs on the writing paths only, which is why ResetPasswordRequestValidator includes it and this one does not.
  • Walkthrough: two public constants, EmailMaxLength (LoginRequestValidator.cs:24) and PasswordMaxLength = 1024 (LoginRequestValidator.cs:30), then a block-bodied constructor with three independent RuleFor chains (LoginRequestValidator.cs:32-45), each stage given an explicit WithMessage. Email runs NotEmpty, MaximumLength, EmailAddress (:34-37); Password runs NotEmpty, MaximumLength (:39-41); TwoFactorCode runs only MaximumLength against TwoFactorCodeRequestValidator.MaxCodeLength (64, MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Validation/TwoFactorCodeRequestValidator.cs:19) with the generic message "The two-factor code is not valid." (:43-44). The two length messages are built with string.Create(CultureInfo.InvariantCulture, ...). Because the chains are independent, failures on different fields are all reported.
  • Why it's built this way: uniform failure responses for authentication are the same discipline as the forgot-password 202, applied to a different endpoint. The complementary defence against guessing at scale is the per-IP rate-limit policy the login action carries, [EnableRateLimiting(WebApplicationBuilderExtensions.RateLimitPolicyAuthIp)] (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/AuthControllerBase.cs:78, with the posture stated in the class remarks at :27-30), which is ADR-029.
  • Where it's used: registered by the assembly scan at MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.cs:70 (which names this class in its comment, DependencyInjection.cs:67), then injected as IValidator<LoginRequest> into AuthenticationValidators, the parameter object that bundles the three auth validators (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/AuthenticationValidators.cs:34,66), which is in turn what AuthenticationServiceBase<TUser> consumes. PasswordMaxLength is also the cap ConfirmEmailRequestValidator applies to a supplied current password (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Validation/EmailConfirmationRequestValidators.cs:43-46). Covered by MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Auth/Validation/LoginRequestValidatorTests.cs.
  • Caveats / not-in-source: AuthenticationValidators also requires an IValidator<RegisterRequest> (AuthenticationValidators.cs:35,69), which the framework's own RegisterRequestValidator supplies (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Validation/RegisterRequestValidator.cs:20), picked up by the same assembly scan; neither ADC nor Store source declares an app-level RegisterRequestValidator, so the bundle resolves from the framework scan alone.

ConfirmEmailRequestValidator

MMCA.Common.Application · MMCA.Common.Application.Auth.Validation · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Validation/EmailConfirmationRequestValidators.cs:31 · Level 8 · class

  • What it is: the validator for redeeming an email-confirmation link: Email must be non-empty and a valid address, Token must be non-empty (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Validation/EmailConfirmationRequestValidators.cs:36-41), and the two optional password proofs the request can carry are checked for shape: a supplied CurrentPassword is length-capped, a supplied NewPassword must meet the strong-password policy, and the two are never accepted together (EmailConfirmationRequestValidators.cs:43-54).
  • Depends on: ConfirmEmailRequest; LoginRequestValidator for PasswordMaxLength; StrongPasswordRules<T> (MMCA.Common/Source/Core/MMCA.Common.Application/Validation/CommonValidationRules.cs:248); FluentValidation's AbstractValidator<T>.
  • Concept: the same "validation that deliberately stops short" posture ForgotPasswordRequestValidator introduces: shape only, no lookup of whether the token is live or already consumed. [Rubric §11, Security]: token validity is a database read guarded by hashing and expiry (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Interfaces/IEmailConfirmationTokenService.cs usage in the consuming handler), not a shape a validator can decide, so putting that check here would either duplicate the lookup or race it. The password rules follow the read/write split LoginRequestValidator draws: a current password is a sign-in proof and gets only the sign-in length cap, while a new password is a writing path and gets the same StrongPasswordRules a reset does (EmailConfirmationRequestValidators.cs:22-30). The request's own remarks explain when they appear: for an unconfirmed account that holds a password, the token alone is refused with EmailConfirmation.PasswordRequired unless the caller is signed in as that account, and the client posts again with one of the two (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Requests/EmailConfirmationRequests.cs:17-23).
  • Walkthrough: a block-bodied constructor (EmailConfirmationRequestValidators.cs:34-55), each rule carrying an explicit WithMessage, sharing the file with SendEmailConfirmationRequestValidator.
    • Email and Token (:36-41): two independent RuleFor chains.
    • CurrentPassword (:43-46): MaximumLength(LoginRequestValidator.PasswordMaxLength), only When it is not null.
    • NewPassword must be Empty() whenever CurrentPassword is non-empty (:48-50), with the message "Enter either your current password or a new password, not both."
    • A When block (:52-54) that Includes StrongPasswordRules<ConfirmEmailRequest> on NewPassword only when a new password is supplied and no current password is, so the policy never runs on an empty field or alongside the mutual-exclusion failure.
  • Why it's built this way: email confirmation is one of the opt-in identity completions (ADR-116): a host calls AddEmailConfirmation(config) to register the feature, and sign-in gating only kicks in when RequireConfirmedEmail is configured and the User implements IEmailConfirmableUser (MMCA.Common/CLAUDE.md, "Identity completions" section).
  • Where it's used: registered by the assembly scan (MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.cs:70) and reached through CommandRequestValidator<TCommand, TRequest> for any command implementing ICommandWithRequest<ConfirmEmailRequest>, the constraint ConfirmEmailHandlerBase<TUser, TCommand> declares (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/EmailConfirmation/ConfirmEmailHandlerBase.cs:70). Covered by MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Auth/Validation/ConfirmEmailRequestValidatorTests.cs, the only reference to this type outside its defining file.

PasswordCredential

MMCA.Common.Domain · MMCA.Common.Domain.Auth.Credentials · MMCA.Common/Source/Core/MMCA.Common.Domain/Auth/Credentials/PasswordCredential.cs:8 · Level 1 · class

  • What it is: an internal static helper with one predicate, IsStored(IAuthUser), which answers whether an account carries stored password material: a non-empty PasswordHash AND a non-empty PasswordSalt (MMCA.Common/Source/Core/MMCA.Common.Domain/Auth/Credentials/PasswordCredential.cs:13-14).
  • Depends on: IAuthUser (its PasswordHash and PasswordSalt members).
  • Concept: one definition of a security-relevant fact, shared by every path that asks it. [Rubric §11, Security]: "does this account have a password" is decided in two places (password sign-in and sign-in-link redemption), and if the two ever disagreed, one path could treat as passwordless an account the other still lets in by password. The class doc comment names the shape it recognises: an account with no password (an external-login account, ADR-036) has an empty hash and an empty salt, and password sign-in never accepts it (PasswordCredential.cs:3-7).
  • Walkthrough: a single expression-bodied method, user.PasswordHash.Length > 0 && user.PasswordSalt.Length > 0 (PasswordCredential.cs:13-14). Both halves must be present, so a half-written credential counts as no credential.
  • Why it's built this way: the type is internal to MMCA.Common.Domain, and the Domain project opens its internals to MMCA.Common.Application (and to the Domain tests) through InternalsVisibleTo (MMCA.Common/Source/Core/MMCA.Common.Domain/MMCA.Common.Domain.csproj:13-14), so the two Application callers share it without it becoming public API a consumer could depend on.
  • Where it's used: AuthenticationServiceBase<TUser> wraps it as HasStoredCredential (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/AuthenticationServiceBase.cs:937), which CanSignInWithPassword combines with the service-account check (AuthenticationServiceBase.cs:943-944). RedeemSignInLinkHandlerBase asks it before confirming an existing unconfirmed account, and only an account that holds a password goes on to the IPasswordClearableUser branch (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/SignInLinks/RedeemSignInLinkHandlerBase.cs:302,308).

Releaser

MMCA.Common.Shared · MMCA.Common.Shared.Concurrency · MMCA.Common/Source/Core/MMCA.Common.Shared/Concurrency/KeyedSemaphoreStripe.cs:78 · Level 0 · record struct (readonly, nested)

  • What it is: the handle KeyedSemaphoreStripe.AcquireAsync returns. Disposing it releases the stripe that was taken (MMCA.Common/Source/Core/MMCA.Common.Shared/Concurrency/KeyedSemaphoreStripe.cs:78-86).
  • Depends on: nested inside KeyedSemaphoreStripe; implements System.IDisposable; wraps a System.Threading.SemaphoreSlim (BCL).
  • Concept introduced, the disposable-scope handle over a manual acquire/release pair. [Rubric §15, Best Practices & Code Quality] assesses whether resource lifetimes are expressed so the compiler enforces them. A raw SemaphoreSlim requires WaitAsync and Release to be paired by hand, and the pairing has to survive an exception in between; forgetting the finally deadlocks every later caller on that semaphore permanently. Returning a handle turns the pairing into a using statement, which the compiler expands to a try/finally for you. The caller's whole contract becomes one line, and the doc comment says so: "Await the call inside a using statement so the release happens even when the guarded work throws" (KeyedSemaphoreStripe.cs:53-55). [Rubric §12, Performance & Scalability]: making it a readonly record struct means the handle costs one machine word on the stack rather than a heap allocation on the hot path of every cache read.
  • Walkthrough: one private field, SemaphoreSlim? _stripe (KeyedSemaphoreStripe.cs:80), set by an internal constructor so only the enclosing stripe set can hand out a live handle (KeyedSemaphoreStripe.cs:82). Dispose is _stripe?.Release() (KeyedSemaphoreStripe.cs:85). The null-conditional is load-bearing rather than defensive noise: a struct always has a parameterless default form that no constructor ever ran for, so default(Releaser).Dispose() is reachable C# and must be a no-op instead of a NullReferenceException. The doc comment states that guarantee (KeyedSemaphoreStripe.cs:84).
  • Why it's built this way: synchronous IDisposable rather than IAsyncDisposable because SemaphoreSlim.Release does not block. Contrast the distributed path, where InProcessDistributedLock returns an IAsyncDisposable? (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Concurrency/InProcessDistributedLock.cs:42), because releasing a lock held in a remote store is I/O.
  • Where it's used: every caller of AcquireAsync, always inside a using: MemoryCacheService at MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Caching/MemoryCacheService.cs:181 (its GetOrCreateAsync implementation), CookieSessionRefresher at MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/CookieSessionRefresher.cs:167, and IdempotencyFilter at MMCA.Common/Source/Presentation/MMCA.Common.API/Idempotency/IdempotencyFilter.cs:225. ICacheService declares GetOrCreateAsync with no default body (MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/ICacheService.cs:130), so each store brings its own stampede protection. CachingQueryDecorator<TQuery, TResult> is the one caller that names the type explicitly: its TryAcquirePopulateLockAsync returns KeyedSemaphoreStripe.Releaser? (MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Decorators/CachingQueryDecorator.cs:179, acquiring at :182 or, under a budget, :189), so the nullable handle can carry "no lock was taken" as a value rather than as a separate flag.

IUserAdminDTO

MMCA.Common.Shared · MMCA.Common.Shared.Auth.Administration · MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Administration/IUserAdminDTO.cs:25 · Level 1 · interface

  • What it is: the shape the built-in user-administration list page renders a row from: account id, email, role, and a locked flag (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Administration/IUserAdminDTO.cs:25-38).
  • Depends on: IBaseDTO<TIdentifierType> closed over the solution-wide UserIdentifierType alias (IUserAdminDTO.cs:25), so the account identifier is the DTO's own Id.
  • Concept introduced, an app-supplied DTO shape behind a framework-defined contract. [Rubric §1, SOLID] assesses dependency inversion for a UI component shipped by the framework but rendering app-owned data. UserAdminList.razor.cs cannot know each app's concrete user-list DTO, so it depends on this interface instead; each app's own list DTO implements it. IsLocked is deliberately one boolean over two different underlying representations: the doc comment states ADC reads it off LockedOn is not null while Store reads it off !IsActive (IUserAdminDTO.cs:33-37), so the list page renders identically regardless of which lockout model the app uses.
  • Walkthrough: three get-only properties of its own: Email (:28, the row's primary label), Role (:31, the account's single role), and IsLocked (:37, whether the account is shut out of sign-in). The account identifier is inherited as Id from IBaseDTO<UserIdentifierType>; it is the key for the detail route and every administration call, and it lets the app's generic paged entity endpoint serve the same DTO.
  • Why it's built this way: the built-in administration UI is framework code shared by every consumer, so it can only render through an abstraction each app's own user-list projection implements.
  • Where it's used: consumed by UserAdminList.razor.cs (MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Administration/UserAdminList.razor.cs) and registered by MMCA.Common.UI's DependencyInjection.cs; implemented by ADC's UserListDTO (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Shared/Users/UserListDTO.cs).

PasskeySettingsValidator

MMCA.Common.Passkeys · MMCA.Common.Passkeys · MMCA.Common/Source/Core/MMCA.Common.Passkeys/PasskeySettingsValidator.cs:12 · Level 1 · class

  • What it is: the startup validator for the Passkeys configuration section. It checks the relying-party settings a WebAuthn ceremony needs, but only when passkeys are switched on (MMCA.Common/Source/Core/MMCA.Common.Passkeys/PasskeySettingsValidator.cs:12-62).
  • Depends on: PasskeySettings (the bound options); IValidateOptions<T> and ValidateOptionsResult from Microsoft.Extensions.Options; System.Uri (BCL).
  • Concept introduced: a disabled feature validates nothing. [Rubric §33, Developer Experience] assesses how quickly a misconfiguration surfaces and how clearly it is explained. Validate returns success immediately when Enabled is false (:28-31), so a host that registers the package but leaves passkeys off never has to supply a relying party. When it is on, every problem is collected into one list (:33) and reported together (:60), and each message names the configuration key and gives an example value, for instance "the registrable domain, for example example.com" (:36). This is the fail-fast configuration contract of ADR-070 applied to one settings type.
  • Walkthrough:
    • IsAbsoluteOrigin (:17-22), internal static: an origin passes when Uri.TryCreate parses it as absolute, the scheme is https or http, the path is exactly /, and there is no query and no fragment. Its doc comment states the test: whether "the browser could report it as a ceremony origin" (:14-16).
    • Validate (:25-61) throws on a null options object (:27), short-circuits when disabled (:28-31), then requires RelyingPartyId (:34-37) and RelyingPartyName (:39-42), requires at least one entry in Origins (:44-47) and adds one failure per entry that IsAbsoluteOrigin rejects, quoting the offending value (:48-53), and requires DataSourceName (:55-58).
  • Why it's built this way: the origin rule matches what the ceremony does with the value: the Fido2 verifier is configured with each origin cut back to scheme and authority (MMCA.Common/Source/Core/MMCA.Common.Passkeys/Fido2PasskeyCeremony.cs:139-141), so a configured path, query or fragment would be silently dropped there. Refusing it at startup turns that into a named error instead.
  • Where it's used: registered by PasskeysServiceCollectionExtensions with TryAddEnumerable next to ValidateOnStart() (MMCA.Common/Source/Core/MMCA.Common.Passkeys/PasskeysServiceCollectionExtensions.cs:41-44).
  • Caveats / not-in-source: internal sealed, reached only through the options pipeline.

SignInLinkEntry

MMCA.Common.Infrastructure · MMCA.Common.Infrastructure.Auth.SignInLinks · MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/SignInLinks/SignInLinkTokenService.cs:212 · Level 1 · record

  • What it is: the internal sealed positional record a sign-in-link token is cached as: TokenHashBase64, Purpose, optional FirstName and LastName, FailedAttempts, and ExpiresAtUnixSeconds (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/SignInLinks/SignInLinkTokenService.cs:212-218).
  • Depends on: SignInLinkPurpose.
  • Concept: a cache record shaped for its serializer. The doc comment states the rule: every member is a JSON primitive (or an enum) "because the cache round-trips values through System.Text.Json" (SignInLinkTokenService.cs:202-205). [Rubric §11, Security]: the record stores the Base64 of the token's SHA-256, "never the token itself" (SignInLinkTokenService.cs:206), so a cache dump yields nothing redeemable.
  • Walkthrough: FirstName and LastName carry the provisioning name an invitation brings and are null for a plain sign-in link (SignInLinkTokenService.cs:208-209). ExpiresAtUnixSeconds exists so a rewrite after a wrong guess can keep the original lifetime (SignInLinkTokenService.cs:211); the service rewrites with entry with { FailedAttempts = attempts } and the remaining TTL (SignInLinkTokenService.cs:194-198).
  • Why it's built this way: it mirrors the record the email-confirmation service caches (EmailConfirmationEntry), the design SignInLinkTokenService says it follows (SignInLinkTokenService.cs:12-15).
  • Where it's used: only inside SignInLinkTokenService, which creates it on issue (SignInLinkTokenService.cs:85-91), reads it from the shared store on redeem (SignInLinkTokenService.cs:113), and maps its name fields back to a SignInLinkProfile (SignInLinkTokenService.cs:173-176).

KeyedSemaphoreStripe

MMCA.Common.Shared · MMCA.Common.Shared.Concurrency · MMCA.Common/Source/Core/MMCA.Common.Shared/Concurrency/KeyedSemaphoreStripe.cs:22 · Level 2 · class

  • What it is: an in-process, per-key mutual-exclusion primitive. Callers ask to serialize on a string key; the key is hashed onto one of a fixed number of SemaphoreSlim stripes, and the caller gets back a Releaser to dispose (MMCA.Common/Source/Core/MMCA.Common.Shared/Concurrency/KeyedSemaphoreStripe.cs:22-87).

  • Depends on: its own nested Releaser; System.Threading.SemaphoreSlim (BCL).

  • Concept introduced, lock striping. [Rubric §12, Performance & Scalability] assesses how shared state is guarded under concurrency and what that guard costs. The naive way to lock per key is a ConcurrentDictionary<string, SemaphoreSlim>, and the class doc comment lays out why that shape is a trap, in the code rather than in tribal memory (KeyedSemaphoreStripe.cs:8-15):

    • If you remove the entry when the last holder releases, you open a race. Caller A looks the semaphore up, then B releases and removes it, then A waits on an object no longer in the table while C creates a fresh one and takes that. A and C now both run the guarded section, which is precisely what the lock existed to prevent.
    • If you never remove it, the table grows without bound, and the keys here are caller-supplied (an idempotency key, a parameterized cache key), so that is an attacker-influenced memory leak.

    Striping sidesteps both by never creating or destroying anything: the table is allocated once at the declared width and every key maps into it forever. The price is stated honestly in the same comment: two unrelated keys can collide on a stripe and briefly serialize against each other. That is harmless for the double-check-locking callers this exists for, because each one re-checks its own key's state after acquiring (KeyedSemaphoreStripe.cs:13-15).

  • Walkthrough:

    • DefaultWidth = 256 (:25), described as "ample concurrency without a meaningful memory cost" (:24); 256 SemaphoreSlim instances is a fixed, small, one-time allocation.
    • The parameterless constructor chains to the width-taking one (:30-33). The real constructor validates with ArgumentOutOfRangeException.ThrowIfLessThanOrEqual(width, 0) (:39), then eagerly fills the array with binary semaphores, new SemaphoreSlim(1, 1) (:42-46). Eager fill is what removes every later allocation and every later race: after the constructor there is no mutation of the table at all, which is why the type is safe to share without any lock of its own.
    • Width is a get-only property (:50), exposed so tests can reason about collisions; one test computes the exact stripe index a key lands on, precisely so it "cannot flake on the one-in-DefaultWidth collision" (MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/SessionCookies/CookieSessionRefresherTests.cs:740,771).
    • AcquireAsync (:60) resolves the stripe, awaits WaitAsync(cancellationToken) with ConfigureAwait(false) per ADR-049 (:63), and wraps the semaphore in a Releaser (:64). The parameter doc draws a line worth remembering: the token "Cancels the wait, not the work that follows it" (:58).
    • GetStripe (:67) does the hashing: (uint)string.GetHashCode(key, StringComparison.Ordinal) % (uint)Width (:73). Two deliberate choices, both commented (:71-72). StringComparison.Ordinal is passed explicitly rather than relying on the default, which keeps the mapping culture-independent. And the comment says the hash is reinterpreted as unsigned, by casting to uint, rather than passed to Math.Abs, because int.MinValue has no positive counterpart and Math.Abs would throw on it.
  • Why it's built this way: the class is a hoisted shared primitive rather than a private helper because five separate call sites needed the same guard. ADR-017 records its role in the idempotency filter explicitly: the striped semaphore is the fallback for a host that registers no IDistributedLock, and the ADR reproduces the same two-defects argument (Website/docs-src/adr/017-request-idempotency.md:59-65). The scaling limit is stated there too: a process-local lock only serializes duplicates that land on the same replica (017-request-idempotency.md:91-93), which is why IDistributedLock is preferred when present (MMCA.Common/Source/Presentation/MMCA.Common.API/Idempotency/IdempotencyFilter.cs:35-38).

  • Where it's used: four holders, all static or instance fields that live for the lifetime of their owner, matching the remark that instances are "intended to be held in a static field for the process lifetime" and that stripes are never disposed (KeyedSemaphoreStripe.cs:18-21): IdempotencyFilter (IdempotencyFilter.cs:93), CookieSessionRefresher (MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/CookieSessionRefresher.cs:94), MemoryCacheService (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Caching/MemoryCacheService.cs:58), and the QueryCacheKeyLocks holder behind CachingQueryDecorator<TQuery, TResult> (MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Decorators/CachingQueryDecorator.cs:263-266). InProcessDistributedLock cites the same reasoning in its own doc comment (InProcessDistributedLock.cs:20).

  • Caveats / not-in-source: .NET randomizes string hash codes per process, so the stripe a given key lands on differs between runs. That is invisible to correctness (any key consistently maps to one stripe within a process) but it means collision behavior cannot be reproduced across processes.

IPasswordClearableUser

MMCA.Common.Domain · MMCA.Common.Domain.Auth.Credentials · MMCA.Common/Source/Core/MMCA.Common.Domain/Auth/Credentials/IPasswordClearableUser.cs:24 · Level 3 · interface

  • What it is: an opt-in extension of IAuthUser with one member, Result ClearPassword(), which replaces the stored hash and salt with empty material so password sign-in is no longer a path the account has (MMCA.Common/Source/Core/MMCA.Common.Domain/Auth/Credentials/IPasswordClearableUser.cs:24-31).
  • Depends on: IAuthUser; Result from MMCA.Common.Shared.Abstractions.
  • Concept: a link proves the mailbox, not the password. [Rubric §11, Security]: the doc comment explains the threat. A sign-in link redeemed for an UNCONFIRMED account that already holds a password "proves the mailbox but not the password", so the workflow confirms the address and removes the password in the same save, and the owner later sets one through forgot password (IPasswordClearableUser.cs:5-11). Without that, whoever registered the address first (before it was proven) would keep a working password on an account the real mailbox owner has just claimed. The target shape is the one an external-login account already carries, which PasswordCredential reads as "no password" (IPasswordClearableUser.cs:13-17).
  • Walkthrough: the same opt-in capability pattern as IPasswordChangeableUser and IPasswordRehashableUser: the shared workflow type-tests the user and falls back to a safe refusal. The remarks state the fallback: an account type that holds password material but does not implement this interface "has its sign-in-link redemption refused while it is unconfirmed" (IPasswordClearableUser.cs:18-21).
  • Why it's built this way: keeping the mutation on the aggregate (a Result-returning method rather than a setter the workflow writes to) leaves the aggregate's invariants in the aggregate, and the interface lets an app opt in without Common knowing its User type.
  • Where it's used: RedeemSignInLinkHandlerBase.ConfirmExistingAccountAsync checks PasswordCredential first, refuses with the generic invalid-link error (and logs) when the user is not IPasswordClearableUser, revokes every session, then calls ClearPassword() before confirming and saving (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/SignInLinks/RedeemSignInLinkHandlerBase.cs:300-335). ADC's User implements it (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Domain/Users/User.cs:39) by emptying both arrays and raising no domain event (User.cs:605-619), covered by MMCA.ADC/Tests/Modules/Identity/MMCA.ADC.Identity.Domain.Tests/Users/UserClearPasswordTests.cs.

IRoleAdministrationService

MMCA.Common.Application · MMCA.Common.Application.Auth.Administration · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Administration/IRoleAdministrationService.cs:35 · Level 3 · interface

  • What it is: the application-layer contract for a role-permission administration screen: list every role with its compiled and stored permissions, read one role, read the closed catalog of roles and permissions an editor may pick from, and replace one role's stored permissions (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Administration/IRoleAdministrationService.cs:35-90).
  • Depends on: RolePermissionsResponse and PermissionCatalogResponse (both in MMCA.Common.Application.Auth.Administration), and Result and its generic form.
  • Concept introduced: an editor's writable set is a strict subset of its readable catalog, and of the caller's own permissions. [Rubric §11, Security] assesses whether an administrative surface can grant more than it should. The remarks on GetCatalogAsync (:57-61) state that the permission list it returns is the compiled catalog, so an editor built from that response can never submit anything SetStoredPermissionsAsync would refuse as unknown, and the parameter doc on SetStoredPermissionsAsync (:70-74) adds the one hard exclusion: no submitted list may include AdministrationPermissions.ManageRoles, so a role editor can never grant a role the permission to edit roles. The interface remarks name the two validation refusals, PermissionGrant.ManageRolesMustBeCompiled and PermissionGrant.UnknownPermission (:23-26), and a third, privilege guard: when the caller supplies a ceiling predicate, a set that ADDS a permission the caller does not hold is refused as forbidden with UserAdministration.PrivilegeCeiling. Only additions are checked, because the set replaces the whole stored list, so an operator may keep or remove a permission they do not hold but never grant one (:29-32).
  • Walkthrough: four methods.
    • ListRolesAsync(CancellationToken cancellationToken = default) (:43) returns one RolePermissionsResponse per known role, ordered by role name.
    • GetRoleAsync(string role, CancellationToken cancellationToken = default) (:51) reads one role's compiled and stored permissions, matched case-insensitively, or a not-found failure.
    • GetCatalogAsync(CancellationToken cancellationToken = default) (:64) returns the two closed sets, roles and permissions, an editor renders from, both sorted ordinally.
    • SetStoredPermissionsAsync(string role, IReadOnlyList<string> permissions, Func<string, bool>? callerHoldsPermission = null, string? changedBy = null, CancellationToken cancellationToken = default) (:84-89) replaces a role's stored permissions and invalidates the cached snapshot, recording an optional changedBy principal name on the rows it creates. callerHoldsPermission is the privilege ceiling: every permission the set adds to the role's stored list (the submitted set minus the stored one, computed under the role's edit lock) must pass it; null applies no ceiling, which is for a trusted caller with no principal such as a seeder or an operations script, and the HTTP surface always supplies it (:75-80).
  • Why it's built this way: separating the compiled catalog (GetCatalogAsync) from the writable operation (SetStoredPermissionsAsync), and stating the ManageRoles exclusion and the privilege ceiling as contract obligations rather than leaving them to each implementation, keeps every host's role editor equally safe against granting itself the permission that edits roles, or any permission its operator does not hold.
  • Where it's used: implemented by StoredPermissionRoleAdministrationService (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/Administration/StoredPermissionRoleAdministrationService.cs); consumed by RolesAdminControllerBase (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Administration/RolesAdminControllerBase.cs), which passes its CallerHoldsPermission() ceiling on every set (RolesAdminControllerBase.cs:160), and, through it, by each app's admin roles controller, for example MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/Controllers/AdminRolesController.cs; registered through MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs.

IUserAdministrationService<TUserDto>

MMCA.Common.Application · MMCA.Common.Application.Auth.Administration · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Administration/IUserAdministrationService.cs:25 · Level 3 · interface

  • What it is: the application-layer contract for an account administration screen: read one account, read the role it holds, lock or unlock it, and replace its roles (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Administration/IUserAdministrationService.cs:25-75).
  • Depends on: the UserIdentifierType alias, and Result and its generic form. Generic over TUserDto, the app's shape for one account. The list read is not part of this contract: the paged, filtered account list is served by the app's generic paged entity endpoint (see IUserAdminDTO).
  • Concept introduced: locking an account is a workflow, not a flag flip. [Rubric §11, Security] assesses whether an administrative action actually removes access rather than merely marking it removed. The remarks on SetLockedAsync (:48-57) state the obligation and where it is already met: derive UserAdministrationServiceBase<TUser, TUserDto> rather than implementing the interface by hand, because a lock must both refuse the account's already-issued access tokens (the soft-deleted user marker, written through ISoftDeletedUserMarkerWriter) and revoke its live refresh sessions (RefreshSessionRevocation's RevokeAllAsync over IRefreshSessionStore), or the lock only takes effect once the current access token expires; an unlock clears the marker. "The base does all three", and it answers a lock whose marker did not reach the shared store with an ErrorType.Unavailable failure (the lock itself is saved) so the administrator retries it.
  • Walkthrough: four methods.
    • GetAsync(UserIdentifierType userId, CancellationToken cancellationToken = default) (:33) reads one account, or a not-found failure.
    • GetRoleAsync(UserIdentifierType userId, CancellationToken cancellationToken = default) (:43) returns the account's current role name, or the same not-found failure. Its summary names the reader: UsersAdminControllerBase uses it "to refuse administering an account whose role grants a permission the caller does not hold" (:35-39), and the controller calls it at MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Administration/UsersAdminControllerBase.cs:414.
    • SetLockedAsync(UserIdentifierType userId, bool locked, CancellationToken cancellationToken = default) (:62) locks or unlocks an account.
    • SetRolesAsync(UserIdentifierType userId, IReadOnlyList<string> roles, CancellationToken cancellationToken = default) (:71-74) replaces the complete set of roles an account holds.
  • Why it's built this way: generic over TUserDto so each app's admin DTO can carry app-specific columns without the framework knowing about them, while the security-relevant lock behavior (marker plus session revocation) lives once in a framework base class that the contract's remarks point implementers at, rather than being left to whichever app implements the interface first.
  • Where it's used: consumed by UsersAdminControllerBase (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Administration/UsersAdminControllerBase.cs); implemented through UserAdministrationServiceBase<TUser, TUserDto> by each app's UserAdministrationService, for example MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/Administration/UserAdministrationService.cs:37-43, and registered through MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/DependencyInjection.cs.

IUserSessionsAdministrationService

MMCA.Common.Application · MMCA.Common.Application.Auth.Administration · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Administration/IUserSessionsAdministrationService.cs:13 · Level 3 · interface

  • What it is: the read-only contract an administrator uses to see who is signed in: one user's live sessions, that user's sign-in history, a roster's "signed in" filter predicate, and a per-user live-session count for a roster page (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Administration/IUserSessionsAdministrationService.cs:13-75).
  • Depends on: RefreshSessionSummaryResponse, SignInSummaryResponse, BaseEntity<TIdentifierType> (the filter's TUser constraint), System.Linq.Expressions.Expression, the UserIdentifierType alias, and Result and its generic form.
  • Concept introduced: "signed in" is a question about refresh sessions, answered by a narrow read contract. [Rubric §11, Security] assesses whether administrators can observe session state without being handed the means to mutate it. Revocation stays on the existing session paths (RefreshSessionRevocation); this interface only reads, and the history method's doc says so in as many words: "View only, like the session list" (:30). A live session means not revoked and not expired at the injected clock's now, so the three live-session answers agree on one definition.
  • Walkthrough: four methods.
    • GetSessionsAsync(UserIdentifierType userId, CancellationToken cancellationToken = default) (:23-25) returns the user's live sessions, newest first, each with IsCurrent false because an administrator is never on the viewed user's device. No sessions, or no such user, yields an empty list.
    • GetSignInsAsync(UserIdentifierType userId, CancellationToken cancellationToken = default) (:36-38) returns the user's sign-in history: one row per sign-in, ended ones included with how they ended, newest first, capped at the newest 50, each with IsCurrent false. A user with no retained sessions, or no such user, yields an empty list (:28-32).
    • GetSignedInFilterAsync<TUser>(bool signedIn, CancellationToken cancellationToken = default) where TUser : BaseEntity<UserIdentifierType> (:59-62) builds an Expression<Func<TUser, bool>> that holds for an account with at least one live session or, with signedIn false, for an account with none (:41-44). The remarks (:45-54) fix how it scales: when the user entity and the refresh sessions resolve to the same physical data source the predicate carries the session query itself and runs as one subquery in the database, however many users are signed in; when they do not (a database-per-service host can split them) it carries a materialized id list bounded at UserSessionsAdministrationService.MaxSignedInUsersAcrossDataSources, and above that bound it fails with UserSessionsAdministrationService.SignedInFilterTooLargeCode rather than answer from a cut list.
    • CountLiveSessionsAsync(IReadOnlyCollection<UserIdentifierType> userIds, CancellationToken cancellationToken = default) (:72-74) counts live sessions per requested user in one store query. A user with none is absent from the result rather than a zero entry, and an empty request answers empty without querying the store (:65-68).
  • Why it's built this way: the roster page needs a count for a whole page of users at once, so the batch method exists to avoid one store query per row, and the "absent, never zero" rule keeps the result a sparse map a caller can test with a plain lookup. Returning a composable predicate rather than an id list lets the roster's paged query apply the filter in the database, so the cost does not grow with the number of signed-in users; the bounded fallback refuses instead of silently filtering on a truncated list.
  • Where it's used: implemented by UserSessionsAdministrationService and registered in MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:210; consumed by UsersAdminControllerBase (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Administration/UsersAdminControllerBase.cs) and by ADC's UserListEntityQueryService, which calls GetSignedInFilterAsync<User> and CountLiveSessionsAsync over the page's ids (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UserListEntityQueryService.cs:164,190). See ADR-097.

IEmailIdentifiedUser

MMCA.Common.Domain · MMCA.Common.Domain.Auth.Credentials · MMCA.Common/Source/Core/MMCA.Common.Domain/Auth/Credentials/IEmailIdentifiedUser.cs:18 · Level 5 · interface

  • What it is: a one-member interface, Email Email { get; }, that exposes the address an account signs in with so the shared identity workflows can find the account behind an address themselves (MMCA.Common/Source/Core/MMCA.Common.Domain/Auth/Credentials/IEmailIdentifiedUser.cs:5-10,18-22).
  • Depends on: the Email value object from MMCA.Common.Shared.ValueObjects.Contact (IEmailIdentifiedUser.cs:1).
  • Concept: the same opt-in capability shape as IPasswordClearableUser and IEmailConfirmableUser, but required rather than optional: the workflows that look an account up by address constrain TUser to it. The doc comment lists them: password sign-in, forgot password, email confirmation and both sign-in-link workflows "look the account up through this one member, so an app maps the column once and writes no lookup of its own" (IEmailIdentifiedUser.cs:7-10). [Rubric §1, SOLID]: the framework depends on the narrowest abstraction it needs (one property), not on the app's User type.
  • Walkthrough: the remarks carry the one implementation rule. Implement the member with the aggregate's own mapped Email property as an implicit implementation, not an explicit one, because the lookup is an EF-translated predicate and EF binds it to the column by the property name; Email.Create stores the address trimmed and lower-cased, so the comparison is exact (IEmailIdentifiedUser.cs:12-17). The predicate itself is UserEmailLookup.HasEmail<TUser>, user => user.Email == email (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UserEmailLookup.cs:28-30), and the read is FindUntrackedByEmailAsync, untracked and still under the soft-delete filter (UserEmailLookup.cs:15-16,38-43).
  • Why it's built this way: one lookup, written once against this member, replaces a per-app query in each workflow; because the read keeps the soft-delete filter, an erased or deleted account is never found by its old address (UserEmailLookup.cs:15-16).
  • Where it's used: a TUser constraint on AuthenticationServiceBase<TUser> (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/AuthenticationServiceBase.cs:86), ForgotPasswordHandlerBase (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/ForgotPassword/ForgotPasswordHandlerBase.cs:70), SendEmailConfirmationHandlerBase (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/EmailConfirmation/SendEmailConfirmationHandlerBase.cs:71), SendSignInLinkHandlerBase (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/SignInLinks/SendSignInLinkHandlerBase.cs:69) and RedeemSignInLinkHandlerBase (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/SignInLinks/RedeemSignInLinkHandlerBase.cs:68). Covered by MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Users/Lookup/UserEmailLookupTests.cs and, for the SQL translation, MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/Conversions/UserEmailLookupTranslationTests.cs.
  • Caveats / not-in-source: ADC's User does not list this interface (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Domain/Users/User.cs:38-39), and both ADC and Store pin MMCA.Common.Domain at 1.326.0 (MMCA.ADC/Directory.Packages.props:146, MMCA.Store/Directory.Packages.props:29), so no consumer app implements it in source yet.

SignInLinkTokenService

MMCA.Common.Infrastructure · MMCA.Common.Infrastructure.Auth.SignInLinks · MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/SignInLinks/SignInLinkTokenService.cs:45 · Level 6 · class

  • What it is: the sealed implementation of ISignInLinkTokenService over ICacheService: it issues a one-time sign-in or invitation token for an address (IssueAsync) and redeems it (ValidateAndConsumeAsync), with no database table (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/SignInLinks/SignInLinkTokenService.cs:45-49,58,99).
  • Depends on: ICacheService (the token records); ICounterStore (the per-address request throttle); IOptions<SignInLinkSettings> (SignInLinkSettings); TimeProvider; SignInLinkEntry, SignInLinkPurpose, SignInLinkProfile, SignInLinkGrant, SignInLinkErrors, EmailIdentity.
  • Concept: a passwordless credential with the same four guards as the confirmation-token design it copies (EmailConfirmationTokenService, named at SignInLinkTokenService.cs:12-15). [Rubric §11, Security], from the class doc comment (SignInLinkTokenService.cs:16-25):
    • One active token per address and purpose: issuing overwrites the record for that purpose, so an older link dies when a newer one is requested, while a sign-in request leaves an outstanding invitation alone (the key carries the purpose, SignInLinkTokenService.cs:151-152).
    • Hashed at rest: only the token's SHA-256 is stored (SignInLinkTokenService.cs:86,156-157).
    • Attempt cap: a wrong token counts against every outstanding record of the address, and a record is dropped at MaxValidationAttempts (SignInLinkTokenService.cs:139-142,186-190).
    • Per-address request throttle: a counter with the request window's TTL caps how often one address can trigger an email (SignInLinkTokenService.cs:64-80).
  • Walkthrough:
    • IssueAsync increments signinlink:req:{address} through ICounterStore.IncrementAsync with a RequestWindowMinutes window and, once the count passes MaxRequestsPerEmail, returns Error.TooManyRequests("Authentication.SignInLinkThrottled", ...) with RetryAfter set to the request window: a 429 whose Retry-After is the whole window, because the counter exposes no remaining lifetime (SignInLinkTokenService.cs:64-80). The comment at :64 states the contract: an atomic fixed-window throttle whose window opens on the first request and is never extended, so concurrent requests cannot undercount. Otherwise it draws 32 random bytes (TokenByteLength, :51), Base64Url-encodes them as the token (:82), takes the purpose's lifetime from LifetimeFor (:83), and caches a SignInLinkEntry under that lifetime (:85-93).
    • ValidateAndConsumeAsync hashes the presented token once (:104), then walks both purposes, sign-in and invite (Purposes, :53). Each record is read with GetFromSharedStoreAsync, so a token consumed on another replica is a miss here rather than a stale local copy that would let it be redeemed twice (:111-113). An unreadable hash is removed outright (:119-124). The comparison is CryptographicOperations.FixedTimeEquals (:126); on a match the record is removed from the cache AND the address's request counter is reset through ICounterStore.ResetAsync, so the signed-in owner is not left throttled (:128-131), and the result is a SignInLinkGrant carrying the purpose and any invitation profile (:133). With no match, every outstanding record gets a failed attempt (:139-142) and the caller receives one generic SignInLinkErrors.InvalidLink (:144).
    • RecordFailedAttemptAsync removes the record once attempts reach the cap or its time is up, and otherwise rewrites it with the REMAINING lifetime, so a wrong guess cannot extend how long the token stays redeemable (:178-199).
    • Keys run the address through EmailIdentity.KeySegment, so User@x.com and user@x.com share one token and one counter (:147-154).
  • Why it's built this way: the cache substrate is ADR-077, and sign-in links are one of the opt-in identity completions (ADR-116). The keys carry their own signinlink: prefix so one workflow can never silently invalidate another's outstanding link (SignInLinkTokenService.cs:28-29). Redemption deliberately takes no IDistributedLock: two concurrent redemptions of one token would both open a session for the account the link already proved, which is what a double tap asks for (SignInLinkTokenService.cs:31-34). The defaults it reads live in SignInLinkSettings: a 15-minute sign-in link, a 20160-minute (14-day) invitation, 5 validation attempts, and 3 requests per 60-minute window (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/SignInLinks/SignInLinkSettings.cs:35,39,45,49,53).
  • Where it's used: registered scoped by AddSignInLinks(configuration), which binds Authentication:SignInLinks with ValidateDataAnnotations().ValidateOnStart() (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Auth.cs:115-124); its remarks note that registering issues nothing until the app wires the handler bases and a controller and sets Authentication:SignInLinks:Enabled (DependencyInjection.Auth.cs:111-114). Consumers resolve the interface, not this class. Tests construct it directly in MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Auth/SignInLinkTokenServiceTests.cs and in MMCA.ADC/Tests/Architecture/MMCA.ADC.Architecture.Tests/Privacy/InvitationLifetimeTests.cs:57,72.

Fido2PasskeyCeremony

MMCA.Common.Passkeys · MMCA.Common.Passkeys · MMCA.Common/Source/Core/MMCA.Common.Passkeys/Fido2PasskeyCeremony.cs:20 · Level 8 · class

  • What it is: the IPasskeyCeremony implementation that builds WebAuthn registration and sign-in options and verifies the browser's attestation and assertion responses, using the Fido2 .NET library's Fido2 verifier (MMCA.Common/Source/Core/MMCA.Common.Passkeys/Fido2PasskeyCeremony.cs:20-172).
  • Depends on: IPasskeyCeremony, PasskeySettings, PasskeyAttestation, PasskeyStoredKey, PasskeyErrors, Result and Error; externally the Fido2 library (Fido2, Fido2Configuration, Fido2VerificationException and its request/response types) and System.Text.Json.
  • Concept introduced: the WebAuthn library stays behind one internal class. [Rubric §32, Dependency & Supply-Chain] assesses how far a third-party dependency reaches into the codebase. Every Fido2 type is used here and nowhere in the contract: the ceremony takes and returns JSON strings, JsonElement, byte arrays and the framework's own records, so the application layer's PasskeyService never sees the library, and the extension method's remarks note that a host that never references this package "carries no WebAuthn library" (MMCA.Common/Source/Core/MMCA.Common.Passkeys/PasskeysServiceCollectionExtensions.cs:23-26). [Rubric §11, Security] assesses how verification failures are handled: every library refusal is caught as Fido2VerificationException and returned as a validation Result carrying the library's error code (:78-81, :127-130), and malformed input never reaches the library (:55-59, :105-109). The class summary adds the user-verification rule: both ceremonies REQUIRE user verification, because a passkey sign-in satisfies the second factor itself (mfa=passkey), so the authenticator's own PIN or biometric check is demanded; the library enforces the UV flag only when the stored options say required, and under preferred it accepts a presence-only assertion (:11-15). See ADR-139.
  • Walkthrough:
    • Verifier (:23) is built on first use through the field ??= backing-field form; the comment says why: "a host with passkeys disabled never reads the relying-party settings" (:22). Create (:133-143) maps RelyingPartyId, RelyingPartyName and the origins, each cut back with GetLeftPart(UriPartial.Authority) into a case-insensitive set (:139-141), and passes metadataService: null (:143).
    • CreateRegistrationOptions (:26-44) requests a new credential for the given user handle, names and excluded credential ids, so "the browser refuses to create a second passkey on an authenticator that already holds one for this account" (:34-36). It requires a resident (discoverable) key, requires user verification (UserVerificationRequirement.Required), and asks for no attestation (:37-42).
    • VerifyRegistrationAsync (:47-82) deserializes the attestation (null on a non-object or bad JSON, :148-159), refuses it as "malformed attestation" (:55-59), then calls MakeNewCredentialAsync with the original options JSON and the caller's credential-id uniqueness callback (:63-70). Success becomes a PasskeyAttestation of id, public key, sign count and transport names (:72-76).
    • CreateSignInOptions (:85-90) asks for an assertion with an empty AllowedCredentials list, so the authenticator offers whichever discoverable passkeys it holds for the relying party, and with UserVerificationRequirement.Required (:89).
    • ReadCredentialId (:93-94) pulls the raw credential id from an assertion, or null, so the caller can look up the stored key before verifying.
    • VerifyAssertionAsync (:97-131) calls MakeAssertionAsync with the stored public key and signature counter, and an ownership callback that requires the assertion's user handle to equal the stored credential's UserHandle byte for byte (:120-121). It returns the new signature counter (:125).
    • TransportName (:162-171) maps each AuthenticatorTransport to the WebAuthn spelling the browser reports (usb, nfc, ble, smart-card, hybrid, internal), falling back to ToString().
  • Why it's built this way: discoverable credentials with an empty allow list give a usernameless sign-in, and AttestationConveyancePreference.None with no metadata service means the server does not try to verify the authenticator's make and model ("no authenticator model information is collected", :12). Requiring user verification on both ceremonies is what lets a passkey sign-in count as the second factor (:13-15). Not determinable from source: the rationale for skipping attestation is not stated in this file.
  • Where it's used: registered as a singleton IPasskeyCeremony by PasskeysServiceCollectionExtensions, whose comment notes the verifier "holds only the bound relying-party settings" (MMCA.Common/Source/Core/MMCA.Common.Passkeys/PasskeysServiceCollectionExtensions.cs:46-47); consumed by PasskeyService. The required-verification options are covered by MMCA.Common/Tests/Core/MMCA.Common.Passkeys.Tests/Fido2PasskeyCeremonyUserVerificationTests.cs.
  • Caveats / not-in-source: internal sealed, reached only through IPasskeyCeremony.

UserAdministrationServiceBase<TUser, TUserDto>

MMCA.Common.Application · MMCA.Common.Application.Auth.Administration · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Administration/UserAdministrationServiceBase.cs:62 · Level 8 · class

  • What it is: the abstract base that implements IUserAdministrationService<TUserDto> once for every app: load, save, revoke and log live here, while the app supplies the handful of aggregate-specific steps (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Administration/UserAdministrationServiceBase.cs:62-329).
  • Depends on: IUnitOfWork, IRefreshSessionStore, TimeProvider, ISoftDeletedUserMarkerWriter and ILogger (primary constructor, :62-67); TUser constrained to AuditableAggregateRootEntity<TIdentifierType> over UserIdentifierType (:68); RefreshSessionRevocation; Result and Error.
  • Concept introduced: the security steps are fixed, the domain steps are abstract. [Rubric §2, Design Patterns] assesses whether a pattern is applied where it earns its keep; this is a template method. The public methods own the order of operations, and the app overrides only MapToDto, IsLocked, ApplyLockState, GetRole, ApplyRole and CreateExactlyOneRoleError (abstract, :220-273) plus, optionally, ValidateRequestedRole (virtual, defaulting to success, :261). [Rubric §11, Security] assesses whether an administrative change actually takes access away. On a lock the base writes the soft-deleted user marker first and then revokes every refresh session, and the comment explains the order: the marker "is what refuses the access tokens already issued, and the session revocation below only stops new ones being minted" (:138-151). A failed marker write is surfaced, not swallowed: the class remarks state that the writer confirms the marker in the shared store and retries once, and when it still fails the lock logs a warning, revokes the sessions anyway and answers LockMarkerNotWrittenCode (503), because the account's access tokens keep working until they expire and the administrator must know to retry (:27-33). A role change does not revoke sessions: it is saved only, because "the refresh path re-reads the account and mints from the stored role, so the next refresh carries the new one without a fresh sign-in" (:209-210), and a change that must take effect at once is a lock (:43-49). See ADR-047.
  • Walkthrough:
    • LockMarkerNotWrittenCode (:74) is the public constant "UserAdministration.LockMarkerNotWritten", the code of the 503 a lock answers when its marker did not reach the shared store.
    • GetAsync (:77-89) and GetRoleAsync (:93-105) read through GetReadRepository and return MapToDto(user) or GetRole(user), or a not-found error built by NotFound, which stamps the calling method as source and typeof(TUser).Name as target (:275-276).
    • SetLockedAsync (:114-159) loads through the tracking GetRepository (:119-126), records wasLocked = IsLocked(user) (:128), calls ApplyLockState with the clock's UTC now and returns its failure before anything is saved (:130-134), then saves (:136). A lock writes the marker and revokes sessions (:138-144); when the marker write reported failure it logs the change and returns the LockMarkerNotWritten() failure, built with Error.Unavailable and the source SetLockedAsync (:146-150, :278-288). An unlock clears the marker only when the account was actually locked (:152-155). Otherwise it logs the change and returns success (:157-158).
    • SetRolesAsync (:169-215) refuses anything but exactly one role with the app's CreateExactlyOneRoleError (:174-177), runs ValidateRequestedRole before the account is loaded (:179-183), loads it, applies the role, and compares GetRole before and after ordinally. An unchanged role returns success with nothing saved (:202-207), so "re-submitting the same value does not sign the account out" (:40). A change is saved, the live refresh sessions are left alone, and the old and new roles are logged (:209-213).
    • WriteMarkerAsync (:290-303) returns true once MarkDeletedAsync completes and, on any exception except cancellation, logs a warning and returns false, leaving the saved lock in place for the caller to surface (:299). ClearMarkerAsync (:305-316) still swallows any exception except cancellation and logs a warning, since "the unlock is saved: a cache fault must not report it as failed" (:313). The warnings state the consequence: already-issued tokens keep working until they expire, or the unlocked account's tokens are refused until the marker expires (:324-328).
    • Four [LoggerMessage] source-generated log methods (:318-328), which is why the class is partial.
  • Why it's built this way: the remarks on CreateExactlyOneRoleError explain why the app owns the whole error, code included: the API's error localizer (ADR-027) keys text by code, so a framework-emitted code "would take the framework's translation and replace the app's message" (:268-272). The marker failure is a 503 rather than a success because the clear is the safe direction and the write is not: a failed clear only keeps an unlocked account refused for a while, while a failed write leaves a locked account's tokens working (:32-33, :278-283). The interface's own remarks direct implementers here rather than to a hand-written implementation (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Administration/IUserAdministrationService.cs:48-57).
  • Where it's used: derived by ADC's UserAdministrationService (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/Administration/UserAdministrationService.cs:37-43, closed over User and UserAdminDTO); reached through UsersAdminControllerBase; tested by UserAdministrationServiceBaseTests (MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Auth/Administration/UserAdministrationServiceBaseTests.cs).
  • Caveats / not-in-source: a failed marker write does not undo the saved lock, so until the administrator retries the lock the account's current access tokens stay valid until expiry; the 503 and the log warning are what record it. The marker clear on an unlock remains best effort (:27-33).

UserSessionsAdministrationService

MMCA.Common.Application · MMCA.Common.Application.Auth.Administration · MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Administration/UserSessionsAdministrationService.cs:19 · Level 8 · class

  • What it is: the IUserSessionsAdministrationService implementation, a thin read over the refresh-session store, plus the sign-in history read and the roster's signed-in filter (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Administration/UserSessionsAdministrationService.cs:19-139).
  • Depends on: IUserSessionsAdministrationService, IRefreshSessionStore, RefreshSessionSummaryResponse, SignInSummaryResponse, SignInHistory, the optional IViewAsGrantStore, TimeProvider, the UserIdentifierType alias, and Result and Error.
  • Concept introduced: liveness is decided against an injected clock, not the store's idea of now. [Rubric §11, Security] assesses whether session state is evaluated consistently. Every method reads timeProvider.GetUtcNow().UtcDateTime (:45, :79, :93, :134) and applies it, so tests can pin the clock and all answers share one definition of live.
  • Walkthrough: public sealed class with a primary constructor taking IRefreshSessionStore, TimeProvider, and an optional ViewAs.IViewAsGrantStore? defaulting to null (:19-22).
    • Two public constants bound the cross-source fallback: MaxSignedInUsersAcrossDataSources = 2000, kept under SQL Server's 2100-parameter ceiling so the id list still translates should EF expand it into one parameter per id (:24-30), and SignedInFilterTooLargeCode = "UserSessions.SignedInFilterTooLarge" (:33).
    • GetSessionsAsync (:41-65) loads the user's un-revoked rows with GetUnrevokedByUserAsync, keeps those where UserId matches and IsActiveAt(now) holds (the store returns expired-but-unrevoked rows on purpose, so expiry is filtered in memory), orders by CreatedAt then Id descending, and projects each to a RefreshSessionSummaryResponse with IsCurrent: false and the row's ToDeviceMetadata() (:60-61). No user lookup is made, so an unknown user is an empty list rather than a 404, revealing nothing the GET Admin/Users/{userId} endpoint does not (:35-40).
    • GetSignInsAsync (:72-85) delegates to SignInHistory.ReadAsync with the store, the user, the clock's now, currentSessionId: null and the view-as grant store (:76-82): "the same store-aggregated read the account holder's own history uses", with no current sign-in because an administrator is never on the viewed user's device (:68-71). Passing the grant store is what lets the history show each time support viewed the account (ADR-137).
    • GetSignedInFilterAsync<TUser> (:88-119) first asks the store for QueryUserIdsWithLiveSessions(typeof(TUser), now) (:95), an unexecuted query that composes into a query over the user entity and is null whenever the user entity does not resolve to the same physical data source as the sessions, or the store cannot compose (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/IRefreshSessionStore.cs:101-114). With a query it returns user => composed.Contains(user.Id) or its negation (:96-101). Otherwise it reads GetUserIdsWithLiveSessionsAsync(now, MaxSignedInUsersAcrossDataSources + 1), one more than the bound so a cut list is detectable (:103-106), fails with Error.Validation(SignedInFilterTooLargeCode, ...) when the count exceeds the bound (:107-113), and otherwise returns the same predicate shape over a materialized List<UserIdentifierType> (:115-118).
    • CountLiveSessionsAsync (:122-138) rejects a null argument, answers an empty dictionary for an empty request without touching the store (:128-132), and otherwise calls CountLiveSessionsByUserAsync(userIds, now) (:135).
  • Why it's built this way: it reuses the same store reads as the account holder's own devices and history pages rather than adding a parallel query path, and keeps the empty-request short circuit here so every caller gets it. The filter prefers the composed subquery so a single-database host pays nothing per signed-in user, and the bounded id list keeps a database-per-service host correct: it refuses with a validation failure rather than filter on a truncated list.
  • Where it's used: registered with TryAddScoped at MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:210; exercised by UserSessionsAdministrationServiceTests and UserSessionsAdministrationServiceSignedInTests under MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Auth/Administration/, and by ViewAsSignInHistoryTests (MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Auth/ViewAs/ViewAsSignInHistoryTests.cs). See ADR-097.

PasskeysServiceCollectionExtensions

MMCA.Common.Passkeys · MMCA.Common.Passkeys · MMCA.Common/Source/Core/MMCA.Common.Passkeys/PasskeysServiceCollectionExtensions.cs:10 · Level 9 · class

  • What it is: the one public entry point of the MMCA.Common.Passkeys package, an AddPasskeys(configuration) extension member on IServiceCollection that registers passkey sign-in (MMCA.Common/Source/Core/MMCA.Common.Passkeys/PasskeysServiceCollectionExtensions.cs:10-58).
  • Depends on: PasskeySettings, PasskeySettingsValidator, IPasskeyCeremony and Fido2PasskeyCeremony, PasskeyChallenges, IPasskeyService and PasskeyService; IConfiguration, TimeProvider, and the TryAdd* helpers of Microsoft.Extensions.DependencyInjection.
  • Concept introduced: registering a feature is not enabling it. [Rubric §33, Developer Experience] assesses whether an opt-in is safe to wire before it is configured. The remarks say calling this "alone turns nothing on": with Passkeys:Enabled false every passkey endpoint answers 404 and no context maps the PasskeyCredentials table, and a host that never calls it, or never references the package, behaves the same way, "needs no migration and carries no WebAuthn library" (:22-26). The extension-member shape is the DI surface convention of ADR-106; the feature is ADR-139.
  • Walkthrough: AddPasskeys (:37-56) throws on a null configuration (:39), then:
    • binds PasskeySettings to its SectionName with ValidateOnStart() and adds PasskeySettingsValidator through TryAddEnumerable (:41-44), so a bad section fails the host at startup (ADR-070);
    • registers Fido2PasskeyCeremony as a singleton IPasskeyCeremony, because "the verifier holds only the bound relying-party settings" (:46-47);
    • registers PasskeyChallenges and IPasskeyService as scoped, because the service reads the request's passkey store and signs in through the app's scoped authentication service (:49-52);
    • adds TimeProvider.System with TryAddSingleton, so a host's own clock registration wins (:53).
  • Why it's built this way: the remarks list what turning passkeys on still needs from the host: a controller deriving from PasskeysControllerBase routed at auth/passkeys, the PasskeyCredentials migration on the Identity database (DesignTimeDbContextOptions.EnablePasskeys), and an app AuthenticationService deriving from AuthenticationServiceBase. The passkey store comes from AddInfrastructure, and the challenges need the shared cache and the distributed lock AddCaching registers (:28-35; ADR-108). Every registration uses a TryAdd* form, so a host can replace any piece before calling it.
  • Where it's used: no call site exists outside the defining file in the scanned source; a host opts in by calling services.AddPasskeys(configuration).

MachineClientSettingsValidator

MMCA.Common.Infrastructure · MMCA.Common.Infrastructure.Auth.MachineClients · MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/MachineClients/MachineClientSettingsValidator.cs:15 · Level 4 · class

  • What it is: the startup validator for the MachineClients configuration section: it bounds the machine access-token lifetime, requires a data source name, and, when machine clients are enabled, checks that the app registered the service-account provisioner they depend on (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/MachineClients/MachineClientSettingsValidator.cs:15-45).
  • Depends on: MachineClientSettings (the bound options and its MinAccessTokenMinutes/MaxAccessTokenMinutes bounds); IServiceAccountProvisioner; IServiceProvider and IServiceProviderIsService (Microsoft.Extensions.DependencyInjection); IValidateOptions<T>.
  • Concept introduced: a validator that checks the container, not just the values. [Rubric §33, Developer Experience] assesses how early and how clearly a misconfiguration is reported. Beyond the value checks, this validator takes the root IServiceProvider in its primary constructor (:15) and, when Enabled is true, asks IServiceProviderIsService whether IServiceAccountProvisioner is registered (:35-37). A missing registration becomes a startup failure whose message spells out the fix, services.AddScoped<IServiceAccountProvisioner, ...>() (:39-40), instead of a resolution error on the first token request. [Rubric §11, Security] assesses whether credentials stay revocable: the lifetime bound's own message gives the reason for the ceiling, "a longer token would outlive the revocation marker" (:27). Both follow ADR-070; machine clients themselves are ADR-140.
  • Walkthrough: one method, Validate (:18-44), collecting failures into one list (:22).
    • AccessTokenMinutes outside MinAccessTokenMinutes to MaxAccessTokenMinutes fails, with the message built through string.Create(CultureInfo.InvariantCulture, ...) (:23-28).
    • A blank DataSourceName fails (:30-33). Neither this check nor the lifetime check depends on Enabled.
    • The provisioner check runs only when Enabled is true and the container exposes IServiceProviderIsService; if the container does not, the check is skipped rather than failed (:35-41).
    • All failures are returned together through ValidateOptionsResult.Fail (:43).
  • Why it's built this way: the provisioner is the one dependency an app must supply itself (the message describes it as the app's implementation over its User aggregate, :40), so it is the most likely thing to be forgotten when a host flips MachineClients:Enabled.
  • Where it's used: registered with TryAddEnumerable as an IValidateOptions<MachineClientSettings> singleton (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.MachineClients.cs:46).
  • Caveats / not-in-source: internal sealed, reached only through the options pipeline.

ClaimBasedUserIdProvider

MMCA.Common.Infrastructure · MMCA.Common.Infrastructure.Context · MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Context/ClaimBasedUserIdProvider.cs:11 · Level 8 · class

  • What it is: a two-line SignalR IUserIdProvider that tells the hub infrastructure which user a connection belongs to, by reading the identity claim off the connection's principal (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Context/ClaimBasedUserIdProvider.cs:6-10).
  • Depends on: Microsoft.AspNetCore.SignalR (IUserIdProvider, HubConnectionContext) and ClaimsPrincipalExtensions for FindUserIdValue (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Context/ClaimBasedUserIdProvider.cs:1-2).
  • Concept: [Rubric §11, Security] assesses that identity is derived from the validated token and never from client-supplied input, and [Rubric §9, API & Contract Design] assesses whether that derivation is centralized once. SignalR keys its user-targeted sends on whatever string an IUserIdProvider returns; the built-in provider reads ClaimTypes.NameIdentifier. This framework mints the user id only into sub (see TokenService, MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/TokenService.cs:151), and whether that survives as sub or arrives mapped to NameIdentifier depends on which handler authenticated the connection. Routing through the shared extension is what makes both shapes resolve identically, so a consumer that changes its inbound claim mapping does not silently start delivering zero notifications.
  • Walkthrough: the entire type is GetUserId(HubConnectionContext connection) (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Context/ClaimBasedUserIdProvider.cs:14-15), an expression body returning connection?.User.FindUserIdValue(). Two null paths are handled without a branch: a null connection short-circuits to null, and FindUserIdValue is an extension on a nullable ClaimsPrincipal that returns null when neither claim is present (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/ClaimsPrincipalExtensions.cs:26-28). An unauthenticated connection therefore has no user id, and SignalR treats it as belonging to no user rather than failing connection setup.
  • Why it's built this way: the value returned here is compared as a string against the string a sender passes to Clients.User(...), so both sides must format the identifier the same way. The raw claim value is used verbatim on this side, and the sender formats with CultureInfo.InvariantCulture (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Notifications/Push/SignalRPushNotificationSender.cs:19), matching the invariant formatting the token writer used (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/TokenService.cs:151). Keeping the whole provider to one delegating line is what makes that three-way agreement checkable at a glance.
  • Where it's used: registered as services.TryAddSingleton<IUserIdProvider, ClaimBasedUserIdProvider>() (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Notifications.cs:99), in the same block that swaps the null notification implementations for the SignalR-backed ones (:64-66). SignalR's connection manager calls it on every connection, and it is what makes SignalRPushNotificationSender reach the right sockets on NotificationHub (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Notifications/Push/SignalRPushNotificationSender.cs:17-21 for the single-user send and :25-34 for the batched multi-user send).

CurrentUserService

MMCA.Common.Infrastructure · MMCA.Common.Infrastructure.Context · MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Context/CurrentUserService.cs:17 · Level 9 · class

  • What it is: the per-request implementation of ICurrentUserService. It answers "who is calling" by reading claims off the current HTTP request's principal: the raw ClaimsPrincipal, the typed user id, the role, and any other parsable claim by name (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Context/CurrentUserService.cs:10-16).
  • Depends on: ICurrentUserService (the Application port) and ClaimsPrincipalExtensions for the identity read (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Context/CurrentUserService.cs:4-5); externals are Microsoft.AspNetCore.Http.IHttpContextAccessor, System.Security.Claims and System.Globalization. The claims it reads are the ones TokenService writes.
  • Concept introduced: a scoped identity snapshot, computed lazily and parsed invariantly. [Rubric §3, Clean Architecture] applies first: application code needs the caller's identity but must not reference HttpContext, so the port lives in Application and this HTTP-aware implementation lives in Infrastructure, which is the only place IHttpContextAccessor appears. [Rubric §12, Performance & Scalability] explains the Lazy<T> fields (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Context/CurrentUserService.cs:19, :21): because the service is registered scoped (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:398), the claim walk happens at most once per request no matter how many handlers, filters and save operations ask. [Rubric §27, i18n] covers the trap most codebases miss: claim values are machine-written under CultureInfo.InvariantCulture, so they must be read invariantly too, or a request running under a culture with different separators misreads decimal, double and DateTime claims. Both parse paths say so explicitly (:40, with the comment at :38-39, and the identifier parse inside ClaimsPrincipalExtensions.GetUserId at MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/ClaimsPrincipalExtensions.cs:43).
  • Walkthrough
    • The primary constructor takes IHttpContextAccessor httpContextAccessor (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Context/CurrentUserService.cs:17) and is captured directly by the lazy initializers, so there is no field boilerplate.
    • _userId (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Context/CurrentUserService.cs:19-20) defers to ClaimsPrincipalExtensions.GetUserId, which reads sub first and falls back to the mapped ClaimTypes.NameIdentifier (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/ClaimsPrincipalExtensions.cs:26-28) before parsing into UserIdentifierType. That indirection is the reason a JWT-bearer request and a session-cookie request resolve to the same user.
    • _role (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Context/CurrentUserService.cs:22-23) caches the first ClaimTypes.Role claim.
    • User (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Context/CurrentUserService.cs:26) returns the principal, substituting a fresh empty ClaimsPrincipal when there is no HTTP context. That fallback is what makes the service safe to resolve from a background job or hosted service: callers get an anonymous principal instead of a NullReferenceException.
    • UserId and Role (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Context/CurrentUserService.cs:29, :31) are one-line projections of the two lazies, both nullable, both null when unauthenticated.
    • GetClaimValue<T>(string claimType) (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Context/CurrentUserService.cs:35-42) is constrained to T : struct, IParsable<T> and calls the static abstract T.TryParse, so any parsable value type (int, Guid, DateTime) can be lifted out of a named claim without Common knowing what the claim means. It returns null for an absent or unparsable claim, and unlike UserId/Role it is a fresh lookup on every call.
  • Why it's built this way: scoped lifetime plus Lazy<T> yields a stable per-request identity snapshot at minimal cost, while the empty-principal fallback keeps the same abstraction usable outside a request. Reading identity through the shared extension rather than a hand-rolled FindFirst("sub") is the load-bearing part: it is what stops a consumer's claim-mapping choice from silently emptying the current user (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/ClaimsPrincipalExtensions.cs:9-16).
  • Where it's used: registered as services.TryAddScoped<ICurrentUserService, CurrentUserService>() (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:398). The highest-traffic consumer is DbContextFactory, which takes it as a constructor dependency (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/Factory/DbContextFactory.cs:53, :57) and passes UserId into every save so audit fields are stamped with the acting user (:248, :291, :330, :352, :414); EFRepository<TEntity, TIdentifierType> accepts it as an optional dependency (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Repositories/EFRepository.cs:30). Application handlers in both apps inject the port for ownership checks and caller-scoped queries.
  • Caveats / not-in-source: this class implements four members. Roles and IsInRole are default interface members on the port (MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Auth/ICurrentUserService.cs:46, :88), not overridden here, so multi-role behavior is defined on the interface rather than in this file. Outside an HTTP request HttpContext is null and UserId is therefore null, which means a save performed by a background worker stamps no acting user; nothing in this file substitutes a system identity.

⬅ Persistence & EF Core • Index • Caching ➡