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 throughCryptographicOperations.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).
Sign-in links and invitations
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.AttributeandAttributeUsageAttribute(BCL). It is read (never constructed) byOwnerOrAdminFilter. - 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.Methodallows both controller-wide and per-action application;AllowMultiple = falsebecause a second copy would mean nothing;Inherited = trueso a controller base class can carry it. It holds no data: presence in the endpoint metadata is the entire signal, which is exactly whatOwnerOrAdminFilter.HasAllowMissingOwnerlooks 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
OwnerOrAdminFilterthrough endpoint metadata. In MMCA.Store it marks four actions onMMCA.Store/Source/Modules/Sales/MMCA.Store.Sales.API/Controllers/ShoppingCartsController.cs:92,107,136,172and six onMMCA.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 totrue; 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 mutableIList<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
ExemptPathPrefixesdoc comment), so a coarse prefix like/_frameworkcovers 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_DeclareAnAuthorizationDecisionas 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 byFallbackAuthorizationHandlerinsideAuthorizationExtensions.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
IAuthorizationRequirementattached 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). UnlikePermissionRequirement, 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
FallbackAuthorizationHandlerreacts 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
AuthorizationPolicyset as ASP.NET Core'sAuthorizationOptions.FallbackPolicybyAuthorizationExtensions.AddAuthorizationPolicieswhenFallbackAuthorizationOptions.Enabledis true, and evaluated byFallbackAuthorizationHandler.
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
OwnerOrAdminFilterneeds: 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.DataAnnotationsfor[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_idandid), 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 throughservices.Configure<OwnerOrAdminFilterOptions>(o => o.BypassRole = MyRoleNames.Admin), and a host that never applies the filter configures nothing. - Walkthrough: three mutable auto-properties.
OwnerClaimTypestill defaults to"customer_id"(MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/OwnerOrAdminFilterOptions.cs:16).BypassRolenow carries[Required]and defaults tostring.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).OwnerParameterNamestill 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;(notinit) is the shape the ASP.NET Core options binder expects, so the values can arrive fromappsettingsor aConfigurecallback; requiringBypassRolerather 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>intoOwnerOrAdminFilter(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 atClaimTypes.NameIdentifier, theOrganizerbypass role, and auserIdparameter (MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.API/DependencyInjection.cs:44,52-54); the comment above those assignments explains whyNameIdentifierand not the rawsubclaim 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;PermissionPolicyProviderthen 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; andNameFor(string permission)(MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/PermissionPolicy.cs:17), an expression-bodiedPrefix + permissionthat builds the policy name.HasPermissionAttributecallsNameForto build the[Authorize]policy string, andPermissionPolicyProviderstripsPrefixback 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) andPermissionPolicyProvider(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
IAuthorizationRequirementcarrying 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 matchingAuthorizationHandler<T>decides whether it is satisfied. This type is the passive half;PermissionAuthorizationHandleris the active half, as the doc comment states (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/PermissionRequirement.cs:5-9). - Walkthrough: a
sealedclass implementingIAuthorizationRequirement(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 withArgumentException.ThrowIfNullOrWhiteSpace(permission)(MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/PermissionRequirement.cs:16) and stores the value into the get-onlyPermissionproperty (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
Permissionimmutable 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 byPermissionAuthorizationHandler.
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 asIOptions<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 noIHttpContextAccessor). - 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 ofcontext.User.Identity?.IsAuthenticated == true,IsExemptPath(context.Resource),IsUnmatchedRequest(context.Resource)orIsApiVersioningRejection(context.Resource)holds (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/Fallback/FallbackAuthorizationHandler.cs:49-52); otherwise it returns without callingcontext.Succeed, leaving the requirement unmet.IsUnmatchedRequest(MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/Fallback/FallbackAuthorizationHandler.cs:79-96) returnsfalsefor 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 theIWebHostEnvironment.WebRootFileProviderand 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 becauseUseStaticFileswould 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 theAsp.Versioning.Routingnamespace, constant atMMCA.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 atMMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/Fallback/FallbackAuthorizationHandler.cs:60-66).IsExemptPathhas 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: anHttpContextis used as is, a SignalRHubInvocationContextyields the connection's ownHttpContextthroughinvocation.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 compilerNullableContextAttributeis enough), so the fallback policy also runs per invocation; Blazor's circuit hub hits this onConnectCircuit, 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#elsebody keeps the plainHttpContextpattern match and returnsfalsefor anything else (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/Fallback/FallbackAuthorizationHandler.cs:118-126). Both bodies end inIsExemptRequestPath(MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/Fallback/FallbackAuthorizationHandler.cs:129-132), which checks the path against the non-empty entries ofoptions.Value.ExemptPathPrefixeswithStartsWithSegments(prefix, StringComparison.OrdinalIgnoreCase). The comment aboveIsUnmatchedRequest(MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/Fallback/FallbackAuthorizationHandler.cs:76-78) explains why noIHttpContextAccessoris needed: under endpoint routing the authorization resource IS theHttpContext, 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
AuthorizationHandlerContextinstead of injectingIHttpContextAccessorkeeps the handler stateless and singleton-safe; never callingcontext.Fail()follows the same ASP.NET Core convention asPermissionAuthorizationHandler, 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
IAuthorizationHandlersingleton and wired as ASP.NET Core'sAuthorizationOptions.FallbackPolicyhandler byAuthorizationExtensions.AddAuthorizationPolicieswheneverFallbackAuthorizationOptions.Enabledis 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 withPermissionPolicy.NameFor(permission): setting the inheritedPolicyto"perm:<permission>"is what routes the check throughPermissionPolicyProvider. It also stores the barepermissionon the get-onlyPermissionproperty (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 inheritedPolicystring 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
PermissionPolicyProviderand satisfied byPermissionAuthorizationHandleragainst the grants each module declares throughAuthorizationExtensions.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 aPermissionRequirement, 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 atMMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/PermissionAuthorizationHandler.cs:14), and the sharedClaimsPrincipalextension methodsHasPermissionClaim/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 byGetRoleValues()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 staticmethodHolds(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 istrueonly 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 whenHolds(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 standardClaimTypes.RoleURI plus the raw"role"/"roles"claims) lives once, on the sharedClaimsPrincipalExtensions.GetRoleValues()used by both this handler andICurrentUserService.Roles, so the two call sites cannot restate the predicate and drift. - Why it's built this way: never calling
context.Fail()(onlycontext.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 staticHoldslets 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
IAuthorizationHandlersingleton byAuthorizationExtensions.AddAuthorizationPolicies(MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/AuthorizationExtensions.cs:75-76); invoked by the authorization middleware for every policy that carries aPermissionRequirement.Holdsis called directly byMultiFactorRoleAuthorizationHandler(MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/MultiFactor/MultiFactorRoleAuthorizationHandler.cs:56), byPublicEndpointOutputCachePolicyfor its bypass permissions (MMCA.Common/Source/Presentation/MMCA.Common.API/Caching/PublicEndpointOutputCachePolicy.cs:257), and byUsersAdminControllerBasewhen 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
IAuthorizationPolicyProviderthat lazily builds anAuthorizationPolicyfor any policy name starting with thePermissionPolicyprefix, attaching aPermissionRequirementfor 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 aDefaultAuthorizationPolicyProviderbuilt from the ambientAuthorizationOptionsand keeps it in_fallbackPolicyProvider(MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/PermissionPolicyProvider.cs:15).GetDefaultPolicyAsyncandGetFallbackPolicyAsync(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 withPermissionPolicy.Prefixit 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 expressionpolicyName[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 freshPermissionRequirement(permission)(MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/PermissionPolicyProvider.cs:41-44). Note theRequireAuthenticatedUser()atMMCA.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
DefaultAuthorizationPolicyProviderrather than reimplementing it means all pre-registered policies survive; only theperm:namespace is intercepted. That is what letsHasPermissionAttributework for any permission string without a registration step. - Where it's used: installed (via
Replace) as the singleIAuthorizationPolicyProviderbyAuthorizationExtensions.AddAuthorizationPolicies(MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/AuthorizationExtensions.cs:77-78). - Caveats / not-in-source: a policy object is built on every
GetPolicyAsynccall for aperm: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(theTokenUseclaim type and theTokenUseMachinevalue),Error(Error.Forbidden),ErrorHttpMapping(the standarderrorsextension) and, when registered,IErrorLocalizer;Microsoft.AspNetCore.Mvc.Filters.IAuthorizationFilterandMicrosoft.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 asHasPermissionAttribute(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 constantErrorCode = "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 claimAuthClaimTypes.TokenUsewith the valueAuthClaimTypes.TokenUseMachine(MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/RefuseMachineClientsAttribute.cs:44-47); for a machine token it setscontext.Result, which short-circuits the action (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/RefuseMachineClientsAttribute.cs:49). The privateRefusal(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 registeredProblemDetailsFactorywhen there is one, otherwise a plainProblemDetails, 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 theerrorsextension fromErrorHttpMapping.BuildErrorsExtensionover oneError.Forbidden(ErrorCode, detail, nameof(RefuseMachineClientsAttribute)), localized when anIErrorLocalizeris registered (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/RefuseMachineClientsAttribute.cs:72-74), and returns anObjectResultwith status 403 (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/RefuseMachineClientsAttribute.cs:76). - Why it's built this way: an
IAuthorizationFilterruns 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 testMachineClientParticipationTestsrequires 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 inAuthorizationExtensions)
- What it is: the private helper
AuthorizationExtensionsuses to replace the registeredIAuthorizationMiddlewareResultHandlerwith aMultiFactorRefusalResultHandlerwrapped around it. - Depends on:
MultiFactorRefusalResultHandlerand theServiceDescriptorit replaces (primary constructor parameteroriginal,MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/AuthorizationExtensions.cs:222);ActivatorUtilities,ILogger<T>andNullLogger<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: itsImplementationInstance, else the result of itsImplementationFactory, elseActivatorUtilities.CreateInstanceover itsImplementationType(MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/AuthorizationExtensions.cs:226-228). It resolves anILogger<MultiFactorRefusalResultHandler>, falling back toNullLogger<MultiFactorRefusalResultHandler>.Instance(MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/AuthorizationExtensions.cs:230-231), and returnsnew MultiFactorRefusalResultHandler(inner, logger)(MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/AuthorizationExtensions.cs:233). - Why it's built this way:
WrapResultHandlerregisters the bound methodwrapper.Createas the replacement factory, soImplementationFactory.Targetis the wrapper instance; checkingTarget is ResultHandlerWrapper(MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/AuthorizationExtensions.cs:179) is how a secondAddAuthorizationPoliciescall 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,MultiFactorRefusalResultHandlerand its own nestedResultHandlerWrapper;Microsoft.Extensions.DependencyInjectionplus itsExtensionsnamespace forTryAddEnumerable. - 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). Theextension(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 addsAddAuthorizationPoliciesandAddPermissionsdirectly ontoIServiceCollection. 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 fromFallbackAuthorizationOptions.DefaultExemptPathPrefixes, the opt-out isAddAuthorizationPolicies(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 byAuthorizeRouteView, 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 toAddAuthorizationPolicies(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): callsservices.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:TryAddEnumerableaddsPermissionAuthorizationHandleras a singletonIAuthorizationHandler(MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/AuthorizationExtensions.cs:75-76),ReplaceinstallsPermissionPolicyProvideras the transientIAuthorizationPolicyProvider(MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/AuthorizationExtensions.cs:77-78), andEnsurePermissionRegistry(services)guarantees a registry exists (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/AuthorizationExtensions.cs:79). Next it callsAddMultiFactorRoleRequirement(services)(MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/AuthorizationExtensions.cs:81-84), the role-level second factor driven byAuthorization:MultiFactor:RequiredForRoles, which the comment there notes is inert while that list is empty. It then bindsFallbackAuthorizationOptions, appliesconfigureFallbackwhen supplied, registersFallbackAuthorizationHandleras a singletonIAuthorizationHandler, and configuresAuthorizationOptions.FallbackPolicythrough the options pipeline (Configure<IOptions<FallbackAuthorizationOptions>>) rather than inline, so theEnabledflag is read after everyAddAuthorizationPolicies/Configurecall the host makes (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/AuthorizationExtensions.cs:86-103): aFallbackAuthorizationRequirement-carrying policy whenEnabledis 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 viaEnsurePermissionRegistry, and invokesconfigure(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 inPermissionRegistryBuilder.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) notesAddAuthorizationPoliciesruns more than once in a Blazor web host. Only when no non-keyedIAuthorizationHandlerdescriptor already namesMultiFactorRoleAuthorizationHandler(MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/AuthorizationExtensions.cs:131-135) does it add that handler as a singleton and bindMultiFactorAuthorizationSettingsfromMultiFactorAuthorizationSettings.SectionName, readingIConfigurationwithGetServiceso 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 thenTryAddEnumerablesMultiFactorBearerWithholdingas anIPostConfigureOptions<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 callsWrapResultHandler(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-keyedIAuthorizationMiddlewareResultHandlerdescriptor (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) notesservices.AddAuthorization()has alreadyTryAdded the framework default, so there is always one. A descriptor whose factory target is already aResultHandlerWrapperis 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 iswrapper.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 throughMultiFactorRefusalResultHandlerwith a coded body.EnsurePermissionRegistry(IServiceCollection)(MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/AuthorizationExtensions.cs:194): the idempotent core. If aPermissionRegistryBuilderis 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 builtPermissionRegistryas a singleton factory (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/AuthorizationExtensions.cs:202-204). BothIPermissionRegistryandIPermissionCatalogare then registered as singleton factories that resolve that same concretePermissionRegistry(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 callingbuilder.Build()a second time to satisfy the second contract would build two. Because the registry is built on first resolve, every module'sAddPermissionscall has already contributed by the time any request evaluates a permission, which is the point the comment atMMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/AuthorizationExtensions.cs:191-193makes.
- Why it's built this way:
TryAddEnumerablelets the permission handler (and, separately, the fallback handler) coexist with any other authorization handlers a host registers;Replaceguarantees exactly one policy provider (the permission-aware one); and the lazybuilder.Build()factory is what makes module registration order irrelevant, since all grants are collected before the firstBuild(). ResolvingIPermissionRegistryandIPermissionCatalogfrom the same singleton factory output (rather than each callingbuilder.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 atWebApplicationBuilderExtensions.Authentication.cs:118) andAddCommonAuthentication(WebApplicationBuilderExtensions.Authentication.cs:142, the call atWebApplicationBuilderExtensions.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
IPermissionRegistryregistered at all. That case is covered elsewhere in this group byUnconfiguredPermissionRegistry, 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
nullwhen 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 atMMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/OwnershipHelper.cs:1), plusResultandErrorfor the two gate methods. The specification it hands back is typically aSpecification<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). WhereOwnerOrAdminFilterblocks 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 tocurrentUserService.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.Roleis 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).bypassRolehas no default argument: every caller supplies its own, normally sourced fromOwnerOrAdminFilterOptions.BypassRole, so the framework itself declares no role names (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/OwnershipHelper.cs:14-17).OwnerOrAdminFilterreuses 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 returnsnullfor 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 viacurrentUserService.GetClaimValue<TId>(claimType)and, when present, calls the suppliedspecFactory(id.Value)to build the scoping specification (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/OwnershipHelper.cs:57-58). LikeIsAdmin,bypassRoleis a required parameter with no default (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/OwnershipHelper.cs:45). Thewhere 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 fixesTIdtointand the claim to"customer_id", but still takesbypassRoleas 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 throughGetOwnershipSpecification. It returnsResult.Success()when the caller passesIsAdminor carries a parsable owner claim, and otherwise aForbiddenfailure (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 sameForbiddenfailure and the lookup never runs (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/OwnershipHelper.cs:157-160); otherwise the privateCheckOwnershipAsync(MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/OwnershipHelper.cs:165) awaits the caller-suppliedisOwnedBy(ownerId, cancellationToken)predicate (typically anExistsAsyncquery) and answersError.NotFoundwith 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
nullfor 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 takesbypassRoleas a required parameter and checks it through the sameIsAdmin, so the scope and both gates agree on who is privileged, and, likeOwnerOrAdminFilterOptions.BypassRole, the framework names no default role anywhere in the ownership axis.ValidateOwnershipAsyncanswers 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
ShoppingCartsControllerwrapsGetOwnershipSpecificationandRequireResolvableOwnerin private helpers (MMCA.Store/Source/Modules/Sales/MMCA.Store.Sales.API/Controllers/ShoppingCartsController.cs:65-67,79-84), andOrdersControllerdoes the same (MMCA.Store/Source/Modules/Sales/MMCA.Store.Sales.API/Controllers/OrdersController.cs:66-68,80-85), also routing its mutating endpoints throughValidateOwnershipAsync(MMCA.Store/Source/Modules/Sales/MMCA.Store.Sales.API/Controllers/OrdersController.cs:353-357). In MMCA.ADC,EventQuestionAnswersControllerandSessionQuestionAnswersControllerscope by user id withGetOwnershipSpecificationand gate withRequireResolvableOwner(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).IsAdminalso decides the export overrideAllowUnscopedExporton all four controllers (for exampleMMCA.Store/Source/Modules/Sales/MMCA.Store.Sales.API/Controllers/OrdersController.cs:249) and is the bypass check insideOwnerOrAdminFilter(MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/OwnerOrAdminFilter.cs:43). - Caveats / not-in-source: two gaps are worth knowing.
TSpecis an open generic with only aclassconstraint (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. AndGetOwnershipSpecificationalso returnsnullfor 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;RequireResolvableOwnerdoes, 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 theIsAdmincheck),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 toOwnershipHelper'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 atMMCA.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 currentsettings = options.Value(MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/OwnerOrAdminFilter.cs:38-41), then walks four decisions in order:- Bypass role: if
OwnershipHelper.IsAdmin(currentUserService, settings.BypassRole)it callsnext()and returns (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/OwnerOrAdminFilter.cs:43-47). - 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 toForbidResultwhen the claim is absent (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/OwnerOrAdminFilter.cs:51-55). - Unresolvable owner parameter: if
TryGetOwnerParametercannot produce an int, the request is denied unless the endpoint carriesAllowMissingOwnerAttribute, in which case it falls through tonext()(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. - 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 reachesawait 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) readscontext.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 atOwnerOrAdminFilter.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 settingvalue = 0and returningfalse(MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/OwnerOrAdminFilter.cs:109-110). Both parses passNumberStyles.IntegerandCultureInfo.InvariantCultureexplicitly (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'sCurrentCulturemust not decide which strings are ids.- Bypass role: if
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 toIdempotencyFilteratDependencyInjection.cs:87; scoped because this filter takes the scopedICurrentUserService, per the comment atDependencyInjection.cs:84-86) and applied as[ServiceFilter(typeof(OwnerOrAdminFilter))], per the remarks atMMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/OwnerOrAdminFilter.cs:25-30. MMCA.Store applies it at controller level onShoppingCartsController(MMCA.Store/Source/Modules/Sales/MMCA.Store.Sales.API/Controllers/ShoppingCartsController.cs:49) andCustomersController(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 carryAllowMissingOwnerAttribute. MMCA.ADC instead applies it per action, on twoBookmarksControllerendpoints (MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.API/Controllers/BookmarksController.cs:91,147), against the Engagement vocabulary configured atMMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.API/DependencyInjection.cs:44-55.Caveats / not-in-source: the owner id is parsed as
intonly (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/OwnerOrAdminFilter.cs:97,104), and the claim is read asGetClaimValue<int>(OwnerOrAdminFilter.cs:49), so a host whose owner id is aGuidor 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 exampleAdmin), and a session without themfaclaim 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) andMultiFactorRefusalResultHandler(the coded403body). - Walkthrough:
SectionNameis the constant"Authorization:MultiFactor"(MultiFactorAuthorizationSettings.cs:31);RequiredForRolesis a get-onlyIList<string>initialized to an empty collection (MultiFactorAuthorizationSettings.cs:34), so binding appends into it. The remarks give the JSON shape and the environment-variable formAuthorization__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 inAuthorizationExtensionsthroughAddOptions<MultiFactorAuthorizationSettings>().Configure<IServiceProvider>(...)withGetService<IConfiguration>(), deliberately with noValidateDataAnnotationsorValidateOnStart, 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 intoMultiFactorRoleAuthorizationHandler(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 atMultiFactorAuthorizationSettings.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); externalsSystem.Security.ClaimsandMicrosoft.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-emptyRequiredForRoles(MultiFactorRoleWithholding.cs:40-44), then delegates with the resolvedIPermissionRegistry, 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 predicateclaim.IsRoleClaim(includeIdentityRoleClaimType: true): the three spellingsClaimTypes.Role,"role","roles"plus whatever type the claim's own identity names as itsRoleClaimType, which is whatClaimsPrincipal.IsInRolereads, 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
MultiFactorWithheldRolemarker per distinct withheld role and oneMultiFactorWithheldPermissionmarker per distinct withheld permission to the primaryClaimsIdentity(MultiFactorRoleWithholding.cs:85-89). IsSubjectToTheRulerequires an authenticated principal that is not a machine client (token_use= machine) and carries no second factor (MultiFactorRoleWithholding.cs:93-96).RemoveClaimscopies 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
MultiFactorRoleAuthorizationHandlertell "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
MultiFactorBearerWithholdingon every JWT bearerOnTokenValidated(MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/MultiFactor/MultiFactorBearerWithholding.cs:35), and exercised directly byMultiFactorRoleRequirementTestsandMultiFactorTestPrincipalsunderMMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/Authorization/MultiFactor/. - Caveats / not-in-source: markers are added only when
principal.Identityis aClaimsIdentity(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 chainsMultiFactorRoleWithholdingonto theOnTokenValidatedevent of every JWT bearer scheme, after whatever handler is already there (MultiFactorBearerWithholding.cs:6-11). - Depends on:
MultiFactorRoleWithholding; externalsMicrosoft.AspNetCore.Authentication.JwtBearerandMicrosoft.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 inAddJwtBearer, such as the hub access-token events (MultiFactorBearerWithholding.cs:13-14). - Walkthrough:
PostConfigure(MultiFactorBearerWithholding.cs:22) guards the options, createsEventsif absent (MultiFactorBearerWithholding.cs:26), captures the existingOnTokenValidateddelegate (MultiFactorBearerWithholding.cs:27), and installs a new one that awaits the previous delegate first (MultiFactorBearerWithholding.cs:28-33) and then callsMultiFactorRoleWithholding.Apply(context.Principal, context.HttpContext.RequestServices)(MultiFactorBearerWithholding.cs:35). - Why it's built this way: changing the identity inside
OnTokenValidatedhappens 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 withTryAddEnumerable, which keys on the implementation type, so repeatedAddAuthorizationPoliciescalls 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 ofMultiFactorRoleAuthorizationHandler(MultiFactorRoleAuthorizationHandler.cs:16). - Caveats / not-in-source: a non-bearer scheme (a cookie session) is not touched (
MultiFactorBearerWithholding.cs:16-17);MultiFactorRoleAuthorizationHandleris 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 reasonAuthErrorCodes.MultiFactorRequiredwhen 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; externalMicrosoft.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 whenRequiredForRolesis empty (MultiFactorRoleAuthorizationHandler.cs:45-48) or the user is not authenticated (MultiFactorRoleAuthorizationHandler.cs:50-54).- It asks
PermissionAuthorizationHandler.Holdswhether 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 anAuthorizationFailureReasonwhose handler isthisand whose message isAuthErrorCodes.MultiFactorRequired(MultiFactorRoleAuthorizationHandler.cs:59). WasWithheldrequires 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).HoldsThroughAnUnwithheldListedRolerequires no second factor, not a machine client, and any non-blank listed role held (MultiFactorRoleAuthorizationHandler.cs:74-77).
- The primary constructor takes the registry and the bound settings (
- Why it's built this way: a caller whose withheld role would not have granted the permission keeps the plain
403and 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
IAuthorizationHandlerbyAuthorizationExtensions, with an explicit already-registered check (MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/AuthorizationExtensions.cs:131-138).MultiFactorRefusalResultHandlerrecognizes its failure reasons by handler type (MultiFactorRefusalResultHandler.cs:46). Covered byMultiFactorRoleRequirementTestsandMultiFactorPermissionBackstopTestsunderMMCA.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
IAuthorizationMiddlewareResultHandlerthat turns a refusal raised byMultiFactorRoleAuthorizationHandlerinto a coded403Problem Details body (Authorization.MultiFactorRequiredin theerrorsextension) 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; externalsMicrosoft.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 sameerrorsextension shape the rest of the API uses. - Walkthrough:
- Constants: the
application/problem+jsoncontent 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 isForbidden, at least one failure reason came fromMultiFactorRoleAuthorizationHandler, and the request is not gRPC (MultiFactorRefusalResultHandler.cs:45-51). Otherwise it takes the firstPermissionRequirement's permission name (MultiFactorRefusalResultHandler.cs:53), logs it (MultiFactorRefusalResultHandler.cs:54) and writes the refusal (MultiFactorRefusalResultHandler.cs:56).IsGrpcchecks for anapplication/grpccontent-type prefix (MultiFactorRefusalResultHandler.cs:59-60).WriteRefusalAsyncbuildsError.Forbidden(AuthErrorCodes.MultiFactorRequired, Message, "HasPermission")(MultiFactorRefusalResultHandler.cs:66), aProblemDetailswith the RFC 9110 section 15.5.4 type, status403and a detail localized throughIErrorLocalizerwhen one is registered (MultiFactorRefusalResultHandler.cs:68-74), and theerrorsextension fromErrorHttpMapping.BuildErrorsExtension(MultiFactorRefusalResultHandler.cs:75). It sets status403andCache-Control: no-store(MultiFactorRefusalResultHandler.cs:78-79), prefersIProblemDetailsService.TryWriteAsync(MultiFactorRefusalResultHandler.cs:81-89) and falls back toWriteAsJsonAsyncwith the problem content type (MultiFactorRefusalResultHandler.cs:91-92).MultiFactorRefusedis a source-generated[LoggerMessage]at Information that logs the permission name only, no user id and no address (MultiFactorRefusalResultHandler.cs:95-97).
- Constants: the
- 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:
AuthorizationExtensionsreplaces the last registered non-keyedIAuthorizationMiddlewareResultHandlerwith 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 byMultiFactorRefusalEndpointTestsunderMMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/Authorization/MultiFactor/. - Caveats / not-in-source: when no
IAuthorizationMiddlewareResultHandleris registered, the wrap is skipped (AuthorizationExtensions.cs:173-176); the code comment statesAddAuthorization()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
CookieSessionRefresherthat captures the browser's user-agent and remote IP from the triggering request, so the refresher's server-to-serverauth/refreshcall can pass them on. - Depends on:
HttpContextandHttpRequestMessage(ASP.NET Core / BCL) only. It isprivate 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 trustsX-Forwarded-ForthroughCommonForwardedHeaders. - Walkthrough:
From(HttpContext)(:291-297) reads theUser-Agentheader, storingnullwhen it is blank, andConnection.RemoteIpAddressas a string (possiblynull).ApplyTo(HttpRequestMessage)(:299-312) copies each non-null value onto the outgoing request:User-AgentandX-Forwarded-For, both throughTryAddWithoutValidation(: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 structgives value equality and no per-refresh heap allocation for two strings' worth of state. - Where it's used: created by the refresher's
GetOrRefreshAsyncpath (MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/CookieSessionRefresher.cs:143), passed throughRefreshAsync(:152) andCallRefreshAsync(:171), and applied to theauth/refreshrequest 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 sealedCookieSessionEnder(:28), sits in the same file. - Depends on: ASP.NET Core
HttpContext. The implementation takesIHttpClientFactoryandILogger<CookieSessionEnder>(:28-30), readsSessionCookieEndpoints.RefreshTokenCookieName(:45), reusesCookieSessionRefresher.RefreshClientName(:55) and posts anEndSessionRequest(: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 anonymousauth/session/endbefore the cookies go. The comment above theDELETEroute (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. InCookieSessionEnder,EndSessionPath = "auth/session/end"(:33) is relative to the gateway root, andTimeoutdefaults 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 ownCancellationTokenSource(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 theEndSessionRequestas JSON (:57-61) and logs a non-success status throughLogEndRefused(:62-65, a Warning at:75-76). Any exception is caught under a scopedCA1031suppression and logged throughLogEndFailed(: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). TheDELETE /auth/session-cookieroute ofSessionCookieEndpointsresolves it optionally (MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/SessionCookieEndpoints.cs:56-59), so a host withoutAddServerAuthSessionCookiekeeps the cookie-only delete. Pinned byMMCA.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 answering204, no refresh cookie calling nothing (:74), a cross-site delete refused with403and 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 isSessionCookieStore, a thin adapter over the internalSessionCookieJarthat appliesSessionCookieSettings. - 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 onlyMMCA.Common.APIitself 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 inMMCA.Common.UI.Web, which receives tokens from the identity endpoint and must persist them with exactly the options (HttpOnly,Secureoutside Development, the configuredSameSite, 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 oncontext.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 intoSameOriginApiProxyEndpoint(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 ofSessionHandoffEndpoints(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, andJwtSecurityTokenHandler(System.IdentityModel.Tokens.Jwt). Switched on bySessionCookieSettings.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:16records.Create(string? accessToken)(:25) returnsnullfor a blank value or anythingJwtSecurityTokenHandler.CanReadTokenrefuses (:27-30), then splits on.and, for a three-segment compact JWT, returns{UnsecuredHeader}.{payload}.(:32-33); any other shape is alsonull. 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
expthe API issued (ADR-131). - Where it's used: the
/auth/session/tokenroute ofSessionCookieEndpoints, 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 byMMCA.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), andnullfor 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
:37checks 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
SameSitemode 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) andTimeSpan(BCL) only. Read throughIOptions<SessionCookieSettings>bySessionCookieEndpoints,SessionCookieStore,CookieSessionRefresherandSessionCookieJar.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
SameSitefrom this one object instead of each choosing a value. What the browser is handed is not a setting here:POST /auth/session/tokenalways answers with a claims-onlySessionClaimsToken, never the credential. - Walkthrough:
SameSite(MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/SessionCookieSettings.cs:19) defaults toSameSiteMode.Lax; the doc comment (:13-18) explains the same-origin API proxy raises it toStrictbecause the cookie then authenticates data calls, not only server-side rendering.Lifetime(:28, aTimeSpan?, doc:21-27) is theMax-Ageof both cookies:null(the default) derives it fromJwt:RefreshTokenExpirationDayswhen 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 bindJwtand runs a non-default refresh lifetime sets it here. The resolution itself lives inSessionCookieJar.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) throwsArgumentOutOfRangeExceptionfor 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-201says so), so a host that never opts in keepsLaxcookies; the proxy tightensSameSitein one place (ADR-131).RefreshTimeoutexists 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).CookieSessionRefresherbuilds its refresh call'sCancellationTokenSourcefromRefreshTimeoutand the injectedTimeProvider(MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/CookieSessionRefresher.cs:209, comment:205-208), so a timeout lands in itsOperationCanceledExceptionpath as unavailable. The proxy's registration inSameOriginApiProxyServiceExtensionsconfigures it (MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/SameOriginProxy/SameOriginApiProxyServiceExtensions.cs:69-70), copyingSameSitefromSameOriginApiProxySettings.SessionCookieSameSite(defaultStrict,MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/SameOriginProxy/SameOriginApiProxySettings.cs:116). The configuredSameSitereaching the logout delete is pinned byMMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/SessionCookies/ClaimsOnlySessionCookieEndpointsTests.cs:65.RefreshTimeoutis pinned byMMCA.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) andUnavailable = 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:
Refreshedmeans a usable access token is available (still-valid cookie, or a rotated pair written back,:6-9);Rejectedmeans no refresh cookie or the identity endpoint refused it with 400, 401 or 403, so clearing the cookies is correct (:12-15);Unavailablecovers 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(itsClassifyFailure,CookieSessionRefresher.cs:130-133) and branched on by the proxy'sFailRefreshAsync(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
SessionCookieEndpointsfrom aSessionTokenResult. - 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 internalSessionTokenResult, 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/tokenhandler (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
ICookieSessionRefresherand projected onto the wire-facingSessionTokenResponse. - Concept: the value-type twin of
SessionTokenResponse. Same two members, but this one stays server-side and is used asSessionTokenResult?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; areadonly record structis 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:13naming its provenance ("acquired from the session cookies"). - Where it's used: the return type of
ICookieSessionRefresher.GetOrRefreshAsync(:36); constructed byCookieSessionRefresherat:71(cookie still valid) and:92(after a rotation); unwrapped bySessionCookieEndpointsatSessionCookieEndpoints.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) andJwtSecurityTokenHandler(System.IdentityModel.Tokens.Jwt). TheSameSiteits callers pass is the session cookies' own, fromSessionCookieSettings. - 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,CookieTokenReaderduring 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 fromSessionCookieEndpoints.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) returnsfalsefor a blank value (:82-85), for a value that throwsCryptographicExceptionorFormatExceptionwhile being unprotected (:88-95), for anythingJwtSecurityTokenHandler.CanReadTokenrefuses (:98-101), and for a token whoseValidTois at or beforenow(:106-109); a malformed token that throwsArgumentExceptionorFormatExceptionwhile being read is alsofalse(: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 asexpiresAt - now.UtcDateTime(:137), writes nothing when that is not positive (:138-141), and otherwise appends the protected token with that lifetime asMaxAge(: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 anulllifetime. The privateCreateProtector(: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 privateBuildOptions(:163-177) emitsHttpOnly = true,Secure = !development || context.Request.IsHttps, the caller'sSameSiteandPath = "/"(:171-174); it resolvesIWebHostEnvironmentthrough a nullableRequestServicesbecause that property is null on a bareDefaultHttpContext(comment:165). - Why it's built this way: the comment at
:160-161namesSessionCookieJaras the rule it copies:Secureoutside Development whatever the request scheme, and in Development whenever the request itself is HTTPS. The conditionalSecureis bracketed by the same scoped#pragma warning disable S2092with an inline justification (:162,:178). Takingnowas a parameter in bothTryReadandWrite, rather than reading the system clock inside, lets a caller measure liveness and lifetime against an injectedTimeProvider. Reading the expiry from the token on every check (rather than trusting the cookie's ownMax-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/tokenroute ofSessionCookieEndpoints(MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/SessionCookieEndpoints.cs:93), both passing the injected clock'sGetUtcNow(); that type'sDELETE /auth/session-cookieroute also expires a present overlay at sign-out (:62-65). On the proxy side,SameOriginApiProxyEndpointchecks presence and liveness (MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/SameOriginProxy/SameOriginApiProxyEndpoint.cs:412-413,:449),SameOriginProxyTransformerlists 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, passingTimeProvider.System.GetUtcNow()asnow(:212), andSessionHandoffEndpointsprefers it (MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/SameOriginProxy/SessionHandoffEndpoints.cs:40) and deletes a present one (:79-81). The protection is pinned byMMCA.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 byMMCA.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'sDELETE /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 passTimeProvider.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
CookieSessionRefresherstores after a successful rotation: the rotatedAuthenticationResponsepaired with theBrowserOriginthat triggered it. - Depends on:
AuthenticationResponseandBrowserOrigin. Nestedprivate sealed recordinsideCookieSessionRefresher, 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-180states 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 byCallRefreshAsyncwithcache.Set(cacheKey, new RotationGraceEntry(auth, origin), RotationGrace)(:232), keyed by the OLD refresh token's hash (comment:230-231) and living forRotationGrace = TimeSpan.FromSeconds(10)(:92).TryGetGraceEntry(:181-191) reads it and answers only whenentry.Origin == origin(:183), relying on record-struct value equality ofBrowserOrigin.RefreshAsyncchecks 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 theIMemoryCacheinjected at:82and registered byAddServerAuthSessionCookie(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.ValidateOrRefreshAsyncand.RefreshAsync: aSessionRefreshStatus, the token when the status isRefreshed, and the upstream'sRetry-Afterhint when it isUnavailable(doc comment,MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/SessionRefreshOutcome.cs:26-31). - Depends on:
SessionRefreshStatusandSessionTokenResult;TimeSpanfrom the BCL. - Concept: a closed result type built only through named factories, so a caller cannot assemble an
inconsistent combination (a
Rejectedoutcome carrying a token, say). It is the richer sibling of the nullableSessionTokenResult?thatGetOrRefreshAsyncstill 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 atSessionRefreshStatus. - Walkthrough: the constructor is private (
:36-41).Status(:44),Session(:47, set only forRefreshed) andRetryAfter(:53, set only forUnavailablewhen the identity endpoint sent one) are get-only. The factories areRefreshed(SessionTokenResult session)(:58-59),Rejected()(:63), which returns one cachedRejectedOutcomeinstance (:34) since it carries no data, andUnavailable(TimeSpan? retryAfter = null)(:68-69). - Where it's used: built throughout
CookieSessionRefresherand consumed by the proxy'sFailRefreshAsync(MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/SameOriginProxy/SameOriginApiProxyEndpoint.cs:298-310):Rejectedends the session, whileUnavailablekeeps the cookies and answers503with aRetry-Aftertaken fromoutcome.RetryAfteror 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
SessionRefreshOutcomethat 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,SessionRefreshOutcomeandSessionRefreshStatus. Its only implementation isCookieSessionRefresher. - 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'sauth/refreshendpoint 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 onHttpContext.Itemsso the current request's SSR authentication can read it before theSet-Cookietakes 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",nullmeans "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:Rejectedwhen there is no refresh cookie or the identity endpoint refused it,Unavailablefor any other outcome (5xx, 429, 408, a misrouted 404, a 409Auth.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 likeGetOrRefreshAsync, 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/tokenendpoint 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:
GetOrRefreshAsyncbyCookieSessionRefreshMiddleware(which runs before authentication on navigations), by the/auth/session/tokenhandler (MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/SessionCookieEndpoints.cs:98) and bySessionHandoffEndpoints(MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/SameOriginProxy/SessionHandoffEndpoints.cs:45);ValidateOrRefreshAsyncandRefreshAsyncbySameOriginApiProxyEndpoint(MMCA.Common/Source/Presentation/MMCA.Common.UI.Web/SameOriginProxy/SameOriginApiProxyEndpoint.cs:105,:321,:358). Registered as a singleton atMMCA.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
UseAuthenticationon 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:
RequestDelegateandICookieSessionRefresher, both primary-constructor parameters (MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/CookieSessionRefreshMiddleware.cs:13). Registered throughCookieSessionRefreshMiddlewareExtensions. - 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 onHttpContext.Itemsis what authentication then reads. - Walkthrough:
InvokeAsync(:16-26) null-checks the context (:18), asksShouldAttempt(:20), and on a match awaitsrefresher.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 toGETrequests whoseAcceptheader containstext/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(withUseAuthentication()on the very next statement at:205), which both Blazor Server hosts call throughUseMmcaBlazorWebPipeline(MMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI.Web/Program.cs:120andMMCA.Store/Source/Hosts/UI/MMCA.Store.UI.Web/Program.cs:92). Its gating rules are pinned one test per branch inMMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/SessionCookies/CookieSessionRefreshMiddlewareTests.cs: an HTML navigation refreshes (:19), a browser-style multi-valueAcceptlist still matches (:31), a non-HTMLAccept(:45), a missingAccept(:60) and aPOST(:74) all skip, and anullrefresh result still callsnext(: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) andPOST /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(viaIOptions<T>),SessionClaimsToken,SessionTokenResponse,ViewAsOverlayCookie,IDataProtectionProvider,TimeProvider, and ASP.NET Core routing plusResults. The cookies are written bySessionCookieStoreandCookieSessionRefresherand read back byCookieTokenReader. - Concept introduced, the cookie names are the shared contract.
AccessTokenCookieName = "mmca_auth_access"andRefreshTokenCookieName = "mmca_auth_refresh"(:23-24) arepublic 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 (ExcludeFromDescriptionat:69and: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 callapp.MapSessionCookieEndpoints(). InsideMapSessionCookieEndpoints(:36-114): the asyncDELETE /auth/session-cookie(:49-71) refuses a cross-site request with403(:51-54). It then resolves anICookieSessionEnderfromRequestServicesand, when one is registered, awaits its best-effortEndAsync(:56-59), callsSessionCookieJar.Deletewith the configuredSameSite(:61), expires a present view-as overlay with the sameSameSite(:62-65) and returns204(:67); it is excluded from description,AllowAnonymous()andDisableAntiforgery()(: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 withoutAddServerAuthSessionCookiekeeps the cookie-only delete. The/auth/session/tokenPOST(:78-111) takesICookieSessionRefresher,IDataProtectionProviderand a[FromServices] TimeProvider(:79-83) and first rejects an obvious cross-site request with403(:85-88). Next, a live view-as overlay (ViewAsOverlayCookie.TryRead, judged attimeProvider.GetUtcNow(),:93) is answered directly with a claims-only copy of its token and its expiry (:95); the comment at:90-92explains 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 awaitsrefresher.GetOrRefreshAsync(:98); anullresult becomes a401JSON body{ error = "no_session" }(:101). Otherwise the answer is aSessionTokenResponsecarryingSessionClaimsToken.Create(...) ?? string.Emptyand the access token's expiry (:105-107, comment:104: the browser gets an unsigned copy of the claims, never the credential). That route isAllowAnonymous()(:110) because it authenticates via the cookies themselves. The privateIsCrossSite(:120-122) inspects theSec-Fetch-Siterequest header and treats a missing header as allowed, which the comment at:117-119attributes to older browsers. - Why it's built this way: CSRF is defended in depth rather than by antiforgery tokens. The comments
at
:73-77and:117-119spell it out: the cookies' configuredSameSite(which already blocks cross-site cookie attachment on a POST or DELETE; the comments nameLaxas the default andStricton the same-origin proxy, both set throughSessionCookieSettings), and theSec-Fetch-Sitecheck together stop a cross-site page from driving these endpoints, which is what makes disabling antiforgery safe here (ADR-022). [Rubric §11, Security]. The explicitAllowAnonymous()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 byMMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/SessionCookies/SessionCookieEndpointsTests.cs, whoseCreateHostAsync(:225) builds a real pipeline around the mapper; the cases that matter most are the cross-site403on theDELETEthat clears nothing (:23) and on the token route (:90), theDELETEexpiring a view-as overlay too (:72), the no-session401(: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 byMMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/SessionCookies/SessionCookieEndOnDeleteTests.cs(:26,:49,:62,:87).MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/SessionCookies/ClaimsOnlySessionCookieEndpointsTests.cspins an unsigned claims copy instead of the credential (:26), thatPOST /auth/session-cookieis not mapped at all, so script cannot seed the cookies (:46), and the delete using the configuredSameSite(: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,IWebHostEnvironmentandSameSiteMode(ASP.NET Core),IDataProtectionProvider/IDataProtector(ASP.NET Core DataProtection), plus the cookie-name constants andAccessTokenCookieProtectionPurposeonSessionCookieEndpoints. TheSameSitevalue its callers pass comes fromSessionCookieSettings. - 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 isHttpOnly = true(:113),Secureset by!environment.IsDevelopment() || context.Request.IsHttps(:114),SameSiteset to the caller's mode (:115), andPath = "/"(:116). TheSecurerule 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) whereRequest.IsHttpsis only true once the forwarded-headers step has appliedX-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, sohttp://localhostdev 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 conditionalSecureis the one thing an analyzer objects to, and the suppression carries its justification inline (:110and:119bracket 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 theJwtsection (comment:26-27).CreateAccessTokenProtector(IDataProtectionProvider)(:33-37) returns the protector underAccessTokenCookieProtectionPurpose; callers create it once and hold it.Appendhas two overloads: the five-argument form (:39-40) forwards withSameSiteMode.Lax, and the six-argument form (:42-47) builds options once with the givenSameSiteand the resolved lifetime, writes the access cookie asaccessTokenProtector.Protect(accessToken)(:45) and the refresh cookie as issued (:46), both with that lifetime asMaxAge.ReadAccessToken(HttpRequest, IDataProtector)(:57-73, doc:49-56) returnsnullfor a missing or blank cookie (:60-63) and for a value that throwsCryptographicExceptionorFormatExceptionon 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.Lifetimewhen the host set it (:85-88), elseJwtSettings.RefreshTokenExpirationDayswhen theJwtsection is bound and positive (:90-92), elseDefaultLifetime. It reads both throughcontext.RequestServiceswithGetService, null-tolerant because the property is null on a bareDefaultHttpContext(comment:82).DeletemirrorsAppend: the three-argument form (:95-96) forwards withLax, and the four-argument form (:98-103) rebuilds the options from the sameHttpContextwithTimeSpan.Zero, which:117turns into anullMaxAge, and callsCookies.Deletefor both names. - Why it's built this way: a delete must send back the same
Path,SameSiteandSecureattributes as the original write or the browser will not match the cookie and will not clear it. SharingBuildOptionsbetweenAppendandDelete(both pass the request, so an HTTPS Development delete carries the sameSecureflag as its write), and having every caller pass the same configuredSameSite, guarantees that (ADR-022). TheLax-defaulting overloads keep the long-standing call shape for callers with no settings in hand. - Where it's used:
SessionCookieEndpoints(clear atSessionCookieEndpoints.cs:61),CookieSessionRefresher(protector atCookieSessionRefresher.cs:95, reads at:104and:117, rewrite after rotation at:150),SessionCookieStore(protector atISessionCookieStore.cs:36, write at:39, clear at:42), the write and clear paths all passingSessionCookieSettings.SameSite, andCookieTokenReader(protector atCookieTokenReader.cs:30, read at:53). ItsBuildOptionsis also named in the culture cookie's conditionalSecuresuppression (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/WebApplicationExtensions.cs:109), as the rule that cookie follows:Securealways 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 byMMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/SessionCookies/SessionCookieJarTests.cs, including the HTTPS Development cases forAppendandDelete(: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 addsCookieSessionRefreshMiddlewareto the request pipeline. - Depends on:
IApplicationBuilder(ASP.NET Core) andCookieSessionRefreshMiddleware. - Concept: the standard
UseXxx()middleware-registration idiom, written with the codebase'sextension(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 onUseMiddleware<T>. - Walkthrough:
UseCookieSessionRefresh()(:43-47) null-guards the builder (:45) and returnsapp.UseMiddleware<CookieSessionRefreshMiddleware>()(:46). The XML comment (:39-42) states the load-bearing rule in bold: register it immediately beforeUseAuthentication()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 atMMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/SessionCookies/CookieSessionRefreshMiddlewareTests.cs:115and: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 toSessionCookieJarwith the configuredSameSiteand the access-token DataProtection protector. - Depends on:
IWebHostEnvironment,IOptions<SessionCookieSettings>andIDataProtectionProvider(primary constructor,MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/ISessionCookieStore.cs:31-34),SessionCookieSettingsandSessionCookieJar. - 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 singleBuildOptions, and the protector comes from the jar'sCreateAccessTokenProtector(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
_accessTokenProtectoronce from the injected provider (:36).Write(:38-39) callsSessionCookieJar.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) callsSessionCookieJar.Delete(context, environment, settings.Value.SameSite). Readingsettings.Valueon each call means writes and deletes always agree onSameSite. - Why it's built this way:
internal sealed, so consumers outsideMMCA.Common.APIdepend on the interface and the jar stays hidden; the one-line summary at:30names it "theISessionCookieStoreoverSessionCookieJar". 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
ISessionCookieStorebyAddServerAuthSessionCookie(MMCA.Common/Source/Presentation/MMCA.Common.API/DependencyInjection.cs:209), right afterservices.AddDataProtection()(:203, with the multi-replica key-ring note at:199-202); seeISessionCookieStorefor 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 thereforelocalStorageare unreachable. - Depends on:
IHttpContextAccessor,IDataProtectionProviderandTimeProvider(primary constructor,MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/CookieTokenReader.cs:17-20, params documented at:11-16),SessionCookieJarfor the protector and the unprotecting read, the cookie-name constants onSessionCookieEndpoints, plusViewAsOverlayCookiefor the overlay check. Consumed bySessionCookieAuthenticationHandlerand byServerTokenStorageService. - 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 agreedHttpContext.Itemskey under whichCookieSessionRefresherparks a just-rotated access token, as the comment at:22-26explains.ReadAccessTokenchecks 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; theSet-Cookiefrom the rotation only affects the next request. - Walkthrough: two private fields keep the provider (
:29) and the access-cookie protector built once bySessionCookieJar.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) returnsnullwhen there is noHttpContext(:41-44), then returns the overlay token whenViewAsOverlayCookie.TryReadfinds one that unprotects and has not expired as oftimeProvider.GetUtcNow()(:46-49), then prefers a non-emptystringunderFreshAccessTokenItemKey(:51-55), and otherwise falls back toSessionCookieJar.ReadAccessToken(:57), which answersnullfor a cookie that does not unprotect. Thefresh is string freshTokenpattern 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 byAddServerAuthSessionCookie(MMCA.Common/Source/Presentation/MMCA.Common.API/DependencyInjection.cs:188), which also registers the systemTimeProviderwithTryAdd(:214) for a host that has no other clock registration. Covered byMMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/SessionCookies/CookieTokenReaderTests.cs, including a cookie that is not server-protected reading asnull(: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
AuthenticationHandlerthat reads the JWT out of the session cookie, parses its claims, and populatesHttpContext.Userduring 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) plusCookieTokenReader(MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/SessionCookieAuthenticationHandler.cs:25-30), andSystem.IdentityModel.Tokens.Jwt. Registered bySessionCookieAuthenticationExtensions. - 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 apublic constso registration never repeats a literal.HandleAuthenticateAsync(:35-69) reads the token throughCookieTokenReader(:37) and returnsAuthenticateResult.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 whenjwt.ValidTois in the past according to the base handler's injectableTimeProvider(:55-58, with the rationale at:53-54). On success it builds aClaimsIdentityfrom the JWT claims withClaimTypes.NameIdentifierandClaimTypes.Roleas the name and role claim types (:60), wraps it in aClaimsPrincipaland anAuthenticationTicketstamped with the scheme name (:61-63), and returnsSuccess. Malformed-token exceptions are narrowed toArgumentExceptionandFormatExceptionand returned asFail(:65-68).HandleChallengeAsync(:72-77) redirects to/login?returnUrl=...with the original path and query URL-escaped (:74-75), andHandleForbiddenAsync(:80-84) sets a bare403. - 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
TimeProviderrather thanDateTime.UtcNowkeeps 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
SessionCookiescheme on both Blazor Server hosts,MMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI.Web/Program.cs:105-106andMMCA.Store/Source/Hosts/UI/MMCA.Store.UI.Web/Program.cs:111-112. Covered directly byMMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/SessionCookies/SessionCookieAuthenticationHandlerTests.cs, including the fresh-token-from-Items path (:95, which stashes the token underCookieTokenReader.FreshAccessTokenItemKeyat:102and asserts it wins over an expired cookie) and the proof that expiry is judged by the handler'sTimeProviderrather 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'sauth/refreshendpoint 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>andIDataProtectionProvider(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);SessionCookieSettingsfor the cookieSameSiteand theRefreshTimeoutbound on the outbound call;SessionRefreshOutcomeandSessionRefreshStatus;CookieTokenReaderfor the Items key;SessionCookieEndpointsfor the cookie names; and theAuthenticationResponse/RefreshTokenRequestcontracts fromMMCA.Common.Shared.Auth. It reads token expiry withSystem.IdentityModel.Tokens.Jwtand namesPolly.ExecutionRejectedExceptionin 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 stripedKeyedSemaphoreStripekeyed 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-secondRotationGrace(: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 privateRotationGraceEntry(:319) that also records theBrowserOriginthat rotated it, andTryGetGraceEntry(: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 awaitsValidateOrRefreshAsyncand returns its.Session, so every failure becomesnull.ValidateOrRefreshAsync(:100-111) reads the access cookie throughSessionCookieJar.ReadAccessTokenwith the protector (:104), which returnsnullfor a missing cookie or one that does not unprotect (MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/SessionCookieJar.cs:57-73), and, ifTryReadValidExpirypasses, returns aRefreshedoutcome around it untouched (:105-108, wrapped inTask.FromResult); otherwise it returns the task fromRefreshFromCookiesAsync(:110) directly. Both are non-asyncmethods that return aTaskwithout awaiting it, so they add no state machine of their own. The publicRefreshAsync(:113-119) reads the cookie the same way (:117), skips the validity check and returnsRefreshFromCookiesAsync(:118), which is the forced rotation the interface promises.RefreshFromCookiesAsync(:135-156) returnsRejectedwhen there is no refresh cookie (:137-141), captures the browser's identity withBrowserOrigin.From(context)(:143), calls the privateRefreshAsync(:144) and passes its failure through (:145-148), writes the rotated pair withSessionCookieJar.Append, the protector and the configuredSameSite(:150), stashes the fresh (unprotected) access token oncontext.Items[CookieTokenReader.FreshAccessTokenItemKey](:154, with the reason at:152-153), and returns aRefreshedoutcome around the newSessionTokenResult(:155). The privateRefreshAsync(: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 ownCancellationTokenSourcefromcookieSettings.Value.RefreshTimeoutand the injectedTimeProvider(:209), builds anHttpRequestMessagePOST to the relativeauth/refreshURI carrying aRefreshTokenRequestas 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-208gives 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 throughClassifyFailure(:220-225):Rejected, orUnavailablecarrying the parsedRetry-After. The body is read under the same bounded token (:227), and an empty access token isUnavailable(:228-231). Success caches aRotationGraceEntrypairing theAuthenticationResponsewith the origin, under the hashed old refresh token, forRotationGrace(:235).ClassifyFailure(:130-133) isinternal static: 400, 401 and 403 are the identity endpoint refusing the token, soRejected; anything else (5xx, 429, 408, a 404 from a misrouted gateway, and a 409) says nothing about the token, soUnavailable(doc:121-129). The 409 case isAuth.RefreshSuperseded: another request (a second tab, or the same browser served by another replica) rotated this token a moment ago, insideRefreshSessions: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 injectedTimeProvider(:261-265), and clamps a negative result to zero.TryReadValidExpiry(:270-299) rejects a blank token, refuses anythingJwtSecurityTokenHandlercannot read (:279-282), treats the token as expired whenjwt.ValidTo <= timeProvider.GetUtcNow().UtcDateTime + ClockSkew(:287, withClockSkewa 30-second margin at:91), and swallows onlyArgumentException/FormatException(:295-298); it is an instance method because it reads the injected clock.CacheKey(:307-308) buildsmmca: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-306explains the hash (no credential sits in a cache key, since diagnostics and cache dumps list keys) and that it isinternalrather thanprivateso 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 injectedTimeProvideris 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 privateBrowserOriginrecord struct (:321-345) is captured from the triggering request before the lock is taken (:143, doc:313-318, which sits aboveRotationGraceEntryat:319):Fromreads theUser-Agentheader, treating blank asnull, and the connection's remote IP (:323-329).ApplyTo(:331-344) addsUser-AgentandX-Forwarded-Forto the outbound request withTryAddWithoutValidation(: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 trustsX-Forwarded-ForthroughCommonForwardedHeaders. Capturing it beforeRefreshAsyncmatters because the work that follows runs under the lock and cache, where the triggeringHttpContextis 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.
CallRefreshAsyncwraps the POST in atrywhose filter narrows toHttpRequestException,OperationCanceledException,JsonException,NotSupportedExceptionandPolly.ExecutionRejectedException(:241-242); the comment at:238-240explains the last one: the resilience pipeline's own refusals (a timed-out attempt, an open circuit, a rate-limited call) throw it, for exampleTimeoutRejectedExceptionwith the gateway down, which is neither transport exception. A call that outlivesRefreshTimeout(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 anOperationCanceledException; 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-generatedLogRefreshCallFailed(:244, declared with[LoggerMessage]at:310-311, which is why the class ispartialat:80) and returnsUnavailable(:245). The comment at:198-204gives the reasoning: this code runs during SSR, so an escaping exception would turn a signed-in user's navigation into a500instead of an anonymous render; it isUnavailable, notRejected, 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 reachescache.Setat:235), so the next navigation retries, and a missingBaseAddressraisesInvalidOperationExceptionand 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
RejectedfromUnavailableis what lets the same-origin proxy clear cookies only for a session that is really over and answer a transient identity-endpoint fault with503plusRetry-After(ADR-131). - Where it's used: resolved as
ICookieSessionRefresherbyCookieSessionRefreshMiddleware, by the/auth/session/tokenendpoint, and by the same-origin proxy (SameOriginApiProxyEndpoint,SessionHandoffEndpoints). Its namedHttpClient,RefreshClientName = "SessionCookieRefreshClient"(:89), is configured with the API base address inAddServerAuthSessionCookie(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 registersTimeProvider.SystemwithTryAdd(: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 ofCookieSessionEnder. The validate, rotate, grace-cache and failure paths are covered byMMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/SessionCookies/CookieSessionRefresherTests.cs, including refusal asRejected(:419,:434), undecidable statuses asUnavailablewith no cookies written (:446), the rotation-race 409 asUnavailablethat keeps the cookies (:476,:490), resilience-pipeline rejections (:522), a hung identity call abandoned at the refresh timeout asUnavailable(:537), the timeout's 10-second default and its non-positive guard (:571,:563), bothRetry-Afterforms (: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 sealedimplementation ofICookieSessionEnder. When a browser deletes its session cookies at sign-out, it posts the refresh cookie server-to-server to the identity endpoint's anonymousauth/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:
IHttpClientFactoryandILogger<CookieSessionEnder>(primary constructor,MMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/CookieSessionEnder.cs:28-30); the named client ofCookieSessionRefresher(RefreshClientName,:55);SessionCookieEndpointsfor the refresh-cookie name (:45); and theEndSessionRequestcontract fromMMCA.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 aninternalinit-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 ownCancellationTokenSourcefromTimeout(:52) rather than taking the request's token, so the browser leaving mid-request does not cancel the revoke (comment:51). Inside thetryit creates the named client (:55), POSTs anEndSessionRequestas JSON (:57-61), and logs a non-success status throughLogEndRefused(:62-65). Any exception is caught (:68, withCA1031suppressed and the reason stated at:67) and logged throughLogEndFailed(:71). Both log methods are source-generated[LoggerMessage]warnings (:75-76,:78-79), which is why the class ispartial. Unlike the refresher, the timeout source is built without aTimeProvider. - Why it's built this way: posting from the server keeps the refresh token off browser JS, the
same reason the refresher calls
auth/refreshserver-to-server (ADR-022). The identity side,EndSessionAsynconAuthControllerBase(MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/AuthControllerBase.cs:201-215), is anonymous and always answers204, revoking a live matching session throughIAuthSessionIssuer(: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
ICookieSessionEnderbyAddServerAuthSessionCookie(MMCA.Common/Source/Presentation/MMCA.Common.API/DependencyInjection.cs:198, comment:196-197), and resolved optionally by theDELETE /auth/session-cookieendpoint before it deletes the cookies (SessionCookieEndpoints.cs:56-59), so a host without that registration keeps the cookie-only delete. Covered byMMCA.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 with204(:49,:62), no call without a refresh cookie (:74), a cross-site delete refused with403and 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 singleAddSessionCookieAuthentication()that wires the scheme into anAuthenticationBuilder. - Depends on:
AuthenticationBuilder(ASP.NET Core) andSessionCookieAuthenticationHandler. - Concept: the same
extension(T)DI-registration idiom introduced by the other extension helpers in this group. The method is declared inside anextension(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 explicitnullarguments are named, so the call site says what it is skipping. The doc comment (:94-97) directs callers to use it afterAddAuthentication(SessionCookieAuthenticationHandler.SchemeName). - Where it's used:
MMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI.Web/Program.cs:106andMMCA.Store/Source/Hosts/UI/MMCA.Store.UI.Web/Program.cs:112, chained onto the host'sAddAuthentication(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.DataAnnotationsfor the range attributes andSystem.Diagnostics.CodeAnalysisfor 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 withValidateDataAnnotations().ValidateOnStart()(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:179-182), so a typo such asTokenLifetimeMinutes: 0fails 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 tostring.Emptyand 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 scopedCA1056suppression (:21-24) explaining why it is astringand not aSystem.Uri: it is bound fromPasswordReset__ResetUrl, concatenated with a URL fragment, and the empty default is not a validUri. 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), andRequestWindowMinutes(:44,[Range(1, 1440)], default 60). All five members areinit-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 plusValidateOnStartmake 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 protectedSettingsproperty (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
RefreshSessionstable, 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 onEnabledstates the distinction precisely (:20-23): the flag "gates the model, not the workflow". The workflow always issues, rotates and revokes sessions;Enableddecides which host maps the table, runs its migrations, and sweeps it. In a modular host the service that owns identity sets it totrueand every other service leaves itfalse, which is what keeps one table in one database instead of one per service. TheScheduler:Enabledprecedent 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 tofalse. 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 equalsDataSourceName(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Auth/RefreshSessionModelBuilderExtensions.cs:146-148, a contributor ApplicationDbContext keeps only when itsAppliesTopasses,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.0keeps every row forever (:67-69).CleanupIntervalHours(:80,[Range(1, 168)], default 6) is how often the sweep runs, ignored whenRetentionDaysis0, 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 answered409 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 asRotatedqualifies: a row already flagged as reuse fails that request alone, without revoking the family a second time, however recent (:92-94), and0treats every rotated token that comes back as reuse.LostResponseRecoveryMinutes(:123,[Range(0, 1440)], default0, 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 asRotatedinside 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. DefaultingEnabledtofalseis the safe direction for a multi-service host: a service that never opts in never grows a table it does not own. DefaultingLostResponseRecoveryMinutesto0keeps 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 asIOptions<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:624and the cap at:707), into EFRefreshSessionStore (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Auth/EFRefreshSessionStore.cs:38, which routes byDataSourceNameat: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 (withEnabled = trueandDataSourceNameset to the context's physical source) to the refresh-session model contributor whenEnableRefreshSessionsis set, sodotnet efcan 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'sAuthenticationServicehas 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),CrossServiceCacheKeysfor the unqualified key prefix, theUserIdentifierTypealias, andSystem.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
DefaultClockSkewof 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 throughMarkerDurationFor. 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 thanMarkerDuration(:56-57).KeyFor(UserIdentifierType userId)(:76-77) builds{CrossServiceCacheKeys.Prefix}user:deleted:{userId}throughstring.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 throughMarkerDurationFor. It null-guards the cache (:106), then writestrueunderKeyFor(userId)(:111) and reads it back throughICacheService.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 throwsInvalidOperationException(: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 throughICacheService.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 throughGetFromSharedStoreAsync.
- A private
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 withMarkerDurationFor(tokens.AccessTokenLifetime, ...)or falls back toMarkerDurationwhen no ITokenService is registered (:177-180). Written through SoftDeletedUserMarkerWriter, the default ISoftDeletedUserMarkerWriter, which writes throughMarkDeletedForAsyncforMarkerDurationFor(tokenService.AccessTokenLifetime)and clears throughClearMarkerAsync(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), andMicrosoft.Extensions.Loggingfor 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, namingAddAuthorizationPolicies()/AddPermissions(...)and the required ordering beforeAddApplicationDecorators()). 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 anIPermissionRegistryconstructor 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, andprivate int _warned(:223) is the one-time-warning latch.IReadOnlyList<string> Roles => [](:229) andIReadOnlyList<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 returnsNone.HasPermission(IEnumerable<string> roles, string permission)(:242-249) argument-guards both parameters (:244-245) before warning and returningfalse, so a caller bug still surfaces as anArgumentExceptionrather than being swallowed by the stub.WarnOnce()(:256-262) usesInterlocked.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, onlyGetPermissions/HasPermissiondo.LogNoPermissionsConfigured(:264-267) is a[LoggerMessage]source-generatedWarning, which is why the class ispartial.
- Why it's built this way: it is registered with
TryAddSingletonfrom insideAddApplicationDecorators()(MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.cs:154), and the surrounding comment (:119-123) states both halves of the rule:TryAddso a host that already declared its grants (viaAddAuthorizationPolicies()orAddPermissions(...), both of which run before this call) keeps its own registry and never constructs this type, and here rather than inAddApplication()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 oneTryAddSingletoncall 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
GetCatalogAsyncon 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-8names both a distributed and an in-memory cache as valid backers). Returning Result fromCheckLockoutAsync(:18) andCheckRegistrationRateLimitAsync(: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) andIncrementRegistrationCountAsync(:49) throttle account creation per client IP. Both accept a nullableipAddressand skip the check when it is null, so a host that cannot resolve the caller IP degrades to no limit rather than blocking everyone;CheckRegistrationRateLimitAsyncreturnsResult.Success()in that case (doc comment,:36-37).
All five take a
CancellationTokenwith adefaultargument, per convention.- Email-scoped (failed-login lockout):
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),IncrementFailedAttemptsAsyncon both the unknown-email and wrong-password branches (:211,:221),ResetFailedAttemptsAsyncon success (:281),CheckRegistrationRateLimitAsync(:329) andIncrementRegistrationCountAsync(:392). The concrete, cache-backed LoginProtectionService (tuned by LoginProtectionSettings, bound atMMCA.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 theUserIdentifierTypealias. 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 twoResult-returning methods, and the cache substrate is entirely the implementation's business (ADR-091).The second teaching point is in the return shapes.
ValidateAndConsumeAsyncis 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. TheuserIdparameter 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
emailon 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. ReturningResult<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) soUser@x.comanduser@x.comcannot 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 atMMCA.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.Authmeter instance of the Application assembly, carrying one counter,mmca.auth.signin, tagged by a low-cardinalityoutcome. 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.MetricsforMeterandCounter<long>(BCL,AuthenticationServiceBase.cs:2), Error and TwoFactorErrors (itsTwoFactorRequiredCode) 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 ininvalid_credentialsorlocked_outis 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") andRejected("rejected": the app gate or the issuance refused the account). - The
Meterbuilt fromMeterName(:1130),internalrather 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 theSignInscounter (:1133-1136), created asmmca.auth.signinwith unit{attempt}, one count perLoginAsynccall. ForSecondFactorFailure(IEnumerable<Error> errors)(:1145-1146) maps a failed challenge tosecond_factor_requiredwhen any error carriesTwoFactorErrors.TwoFactorRequiredCode(no code supplied) and tosecond_factor_failedfor 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 singleoutcometag.
- 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
internalbeside the workflow means the outcome vocabulary changes in the same file as the branches that emit it. Counting a validation failure asinvalid_credentialsrather than adding an eighth value keeps the tag set small and matches what the caller is told. Sharing the oneMeterinstance 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 recordsSuccessonce the tokens are issued (AuthenticationServiceBase.cs:288) and routes every failure through the privateSignInFailedhelper (:978-986), which callsRecord(:983) and then writes the matching Warning through AuthenticationServiceLog. The second-factor branch picks its tag throughForSecondFactorFailure(:248). ItsMeteralso 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 sameMMCA.Common.Authmeter as AuthSignInMetrics'smmca.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.MetricsforCounter<long>(BCL,AuthenticationServiceBase.cs:2) and theAuthSignInMetrics.Meterinstance 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: theMMCA.Common.Authmeter name also carriesmmca.auth.lockout(recorded by the Infrastructure login protection) andmmca.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), aCounter<long>namedmmca.auth.refresh_reusewith unit{event}, created onAuthSignInMetrics.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
Meterinstance rather than a newMeter(MeterName)keeps one instance of the name per assembly. Keeping itinternalkeeps 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,
PasswordRehashRejectedandSignInFailed, and theEmailLogHashhelper 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.LoggingforILogger,LogLeveland the[LoggerMessage]generator (AuthenticationServiceBase.cs:6),System.Security.CryptographyandSystem.Textfor the SHA-256 digest (:4-5), the Email value object for normalizing the address, and the solution-wideUserIdentifierTypealias 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 apartialmethod on apartialtype. Putting it on the public abstract base would force that base to bepartialand make the generated method generic overTUser; 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 isinternal, 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 atLogLevel.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 atWarningwith "Password sign-in failed ({Outcome}) for address hash {EmailHash}", whereOutcomeis one of the AuthSignInMetrics tag values.EmailLogHash(string? email)(:1074-1089) normalizes a blank address to the empty string (:1077-1080), otherwise takesEmail.Create(email)'s normalized value and falls back toTrim().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
RehashPasswordreturned 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:
PasswordRehashRejectedis called once, from the privateRehashPasswordIfNeededAsyncof AuthenticationServiceBase<TUser> whenIPasswordRehashableUser.RehashPasswordfails (AuthenticationServiceBase.cs:1025-1032).SignInFailedandEmailLogHashare called together from the base's privateSignInFailedhelper (:982), which every failing branch ofLoginAsyncreturns through. Both use the base's overridableLoggerproperty as the sink, which defaults toNullLogger.Instance(:153), so the lines are emitted only by an app subclass that overridesLoggerwith 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 inMMCA.Common.Shared.Auth),ILoggerFactoryandILoggerfromMicrosoft.Extensions.Logging(:2) for the service's logger,IOptions<LegalAcceptanceOptions>andLegalAcceptancePolicyfromMMCA.Common.Application.Auth.Legalfor 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'sAuthenticationServicebelow the application-service constructor-arity ceiling (a god-class analyzer guardrail) without giving up per-request validation. Because the request DTOs already live inMMCA.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 (theloggerFactoryparameter 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 threeIValidator<T>instances, a requiredILoggerFactory loggerFactory, and an optionalIOptions<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,legalAcceptancewithout a default, plus a requiredITwoFactorAuthenticator twoFactor, chains to the primary and setsTwoFactor. Its doc comment (:42-55) gives the selection rule: the container picks it only when anITwoFactorAuthenticatoris registered (byAddTwoFactorAuthentication(configuration)), so a host that has not adopted two-factor resolves the primary constructor and is unchanged. The class-levelRS0027suppression (: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) andRefresh(:72) surface the validators by name.Logger(:78) is created once from the factory underLoggerCategoryby the privateCreateLogger(: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) returnsLegalAcceptancePolicy.ResolveCurrentVersion(legalAcceptance?.Value): the Terms of Service version registration requires, ornullwhen acceptance is not configured.TwoFactor(:91) is the sign-in challenge, ornullwhen the host registered none. Its doc comment (:86-90) fixes precedence:AuthenticationServiceBaseuses it only when its owntwoFactorconstructor argument is null, so an explicit argument wins. Beyond the resolver call and the logger creation the type has no logic.
- The primary constructor (
- Why it's built this way: a
sealedgrouping 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, whileIValidator<RegisterRequest>is satisfied by the app's ownRegisterRequestValidator, 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), whoseLoginAsync,RegisterAsync, andRefreshTokenAsynccallvalidators.Login(:162),validators.Register(:302), andvalidators.Refresh(:402) respectively before doing any work, which re-exposesCurrentTermsVersionas a protected property (:145) thatRegisterAsynctests (:311), whoseSignInFailedhelper and password rehash log throughvalidators.Logger(:984,:1015,:1028), and whoseChallengeSecondFactorAsyncresolvestwoFactor ?? 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:36andMMCA.Store/Source/Modules/Identity/MMCA.Store.Identity.Application/DependencyInjection.cs:42, bothTryAddScoped<AuthenticationValidators>().AddTwoFactorAuthenticationregisters 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-inAddLegalAcceptance(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
UserIdentifierTypealias.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) andSignInWithPasskeyAsync(:209-215) reject throughSignInLinkErrors.NotSupportedandPasskeyErrors.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; andHasSignInMethodBesidesPasskeysAsync(:229-232) answersfalse, 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:AuthenticationServiceBasedeclares 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 returnsResult<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,RegisterAsyncandRefreshTokenAsyncall take optionalipAddressanduserAgent(: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, ...)returnsResult<AuthenticationResponse>(:23-27).RegisterAsync(RegisterRequest, string? ipAddress = null, string? userAgent = null, ...)(:39-43); theipAddressdoes 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 carryingRegistrationOutcome.ConfirmationPendingand 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.currentSessionIdis the caller token'ssidclaim and is used only to setRefreshSessionSummaryResponse.IsCurrent; passingnullmarks 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).currentSessionIdsetsSignInSummaryResponse.IsCurrentthe 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 returnNotFoundand are indistinguishable, so a caller cannot probe for another user's sessions; and revoking an already-revoked session changes nothing and also returnsNotFoundwith the codeAuth.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.emailVerifiedis whether the provider asserted the address as verified (itsemail_verifiedclaim as the framework's provider registrations map it,falsewhen 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 istrue; 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 carriesmfa=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
remarksrather 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), byRedeemSignInLinkHandlerBasefor 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.SignInIdis the chain's sharedRefreshSession.SignInId, or, for a row written before that column existed, the row's ownId(:10-13), so older data still lists.Headis read-only: a store may return it untracked, so a mutation on it is never persisted (:15-18). - Walkthrough: a positional
sealed recordwith three members (:19):Guid SignInId,DateTime StartedAt(the UTC issue instant of the earliest retained session,:14) andRefreshSession 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
GetRecentSignInsAsyncbound 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'sListSignInsAsyncthat AuthenticationServiceBase<TUser>'sGetSignInsAsynccalls. 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 theUserIdentifierTypealias. 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 throughRefreshSession.Revokeon instances this store returned, so an implementation that tracks its entities persists a revocation with no update method at all, andTryRotateAsyncis 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 exceptFindByIdUntrackedAsync, 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 withRefreshSession.HashTokenand 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 newestmaxSignInssign-ins as RefreshSessionSignIn entries, newest first byStartedAt, aggregated in the store: one entry perRefreshSession.SignInIdwith its earliest issue instant and only its newest row (:64-68). A row with noSignInId(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 bymaxSignIns, never by the user's total row count.GetUserIdsWithLiveSessionsAsync(DateTime now, int limit, ...)(:96-99) returns each user holding at least one live session atnowexactly once, at mostlimitof them, where live means not revoked andExpiresAtstrictly afternow(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 unexecutedIQueryable<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 answersnullwhenever 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 atMMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Auth/EFRefreshSessionStore.cs:222,:243and: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. Anullanswer 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 asRefreshSession.ReasonRotated, linked to the successor), then stages and persists the successor. Theboolreturn 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. Returningfalsetells the caller it lost the claim. The caller then re-reads the row throughFindByIdUntrackedAsyncto 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 conditionalExecuteUpdateAsyncthe 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 aDbContextwith, so a login and its session insert commit together. Consumed by AuthSessionIssuer, not byAuthenticationServiceBase(injected atMMCA.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 BCLTimeProvider.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), andrefreshSessions 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 stampsnowfrom the suppliedtimeProviderorTimeProvider.System(:42), callssession.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 throughIRefreshSessionStore.GetAllByUserAsync, revokes the un-revoked ones asRefreshSession.ReasonAccountDeleted, and callsAnonymize()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 byDeleteUserHandlerBase(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 (
RevokeAllAsyncis public so an app-sideIUserAdministrationServicecan 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
SetLockedAsyncobligation (see that type); alsoChangePasswordHandlerBase(MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/ChangePassword/ChangePasswordHandlerBase.cs) andResetPasswordHandlerBase(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
Useraggregate. It realises IAuthenticationService and leaves the genuinely app-specific decisions to a small set ofabstractandvirtualhooks 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?andIOptions<EmailConfirmationSettings>?(:84-85, both defaultnullso a subclass that adopts neither passes nothing), the IAuthUser credential contract, IEmailIdentifiedUser and AuditableAggregateRootEntity<TIdentifierType> as theTUserconstraint (:86), UserEmailLookup for the sign-in lookup by address (class doc,:35-37) and, where a host adopts the matching feature, IEmailConfirmableUser (matched inCheckEmailConfirmed), 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'sTokenServiceproperty), TwoFactorOutcome, TwoFactorErrors and AuthClaimTypes (themfaclaim values), SignInLinkErrors and PasskeyErrors, RegistrationOutcome, Email (normalizing the login and register address), ClaimsPrincipalExtensions (principal.GetUserId(),principal.FindMultiFactorMethod()andprincipal.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 thesidandmfaclaims 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; whentwoFactoris null the challenge falls back toAuthenticationValidators.TwoFactor, and an explicit argument wins (parameter doc,:66-72). A private constantPasswordRehashOperation = "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 byRefreshTokenAsyncso 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-exposeUnitOfWork(:112),TokenService(:124), which returnssessionIssuer.TokenService, the issuer's stamping instance, so minting through it is what putssidon the token (remarks,:116-122), and aRepositoryresolved lazily asunitOfWork.GetRepository<TUser, UserIdentifierType>()(:127-128). A protectedCurrentTermsVersion(:145) forwardsvalidators.CurrentTermsVersion, so adopting Terms of Service acceptance adds no constructor dependency here or in the app's subclass; when it is non-null,RegisterAsynchas already refused a request whoseAcceptedTermsis false beforeCreateUserruns, so aCreateUseroverride 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 tovalidators.Logger, the bundle's logger under theAuthenticationValidators.LoggerCategorycategory, 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 theMMCA.Common.Authmeter by outcome, and every outcome butsuccesswrites one Warning throughAuthenticationValidators.Loggercarrying the outcome and a truncated hash of the normalized address (remarks,:147-155). Each failing branch returns through the privateSignInFailed(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 asinvalid_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'sIEmailIdentifiedUser.Email, to verify credentials without change-tracker overhead. The gate isCanSignInWithPassword(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, throughPasswordCredential.IsStored); an external-OAuth account (ADR-036) carries none. All three refusals answer the identical generic 401 after the identicalBurnPasswordVerificationCost(request.Password)call (:198) andIncrementFailedAttemptsAsync(:199), so none of them can be told apart, by status or by timing, from an unknown address (comment,:192-195).passwordHasher.VerifyPasswordruns next (:207) and fails the same way on a wrong password. Only after the password check does the app gate (ValidateLoginCandidateAsync,:221, outcomerejected) 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, outcomeemail_not_confirmed, hook at:834-844), off unless the host both suppliedEmailConfirmationSettings.RequireConfirmedEmailand the app'sUserimplements IEmailConfirmableUser, andChallengeSecondFactorCountingFailuresAsync(untracked.Id, request, cancellationToken)(:243-244, private helper at:878-891, outcome chosen byAuthSignInMetrics.ForSecondFactorFailure). That helper runs the overridableChallengeSecondFactorAsynchook (:860-866) and counts aTwoFactorErrors.TwoFactorInvalidCodefailure against the account throughIncrementFailedAttemptsAsyncexactly 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'sCreateAccessTokenhook mints from, and the second lookup turns a race that deleted the account between the two steps into a clean 404, counted asinvalid_credentialsbecause it reads as an unknown address (:258-266). ThenResetFailedAttemptsAsync(:269), and_multiFactorMethod = MultiFactorMethodFor(secondFactor.Value)(:272, private helper at:899-908, mapping a verified TOTP or recovery code to themfaclaim value and any unrecognized outcome tonull) arms the field in atry/finallyaround the privateIssueTokensCoreAsync(: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 asrejected(:283-286), a success is recorded (:288), and thenRehashPasswordIfNeededAsync(issued, user, request.Password)(:290) runs beforereturn issued(:292).RegisterAsync(:296-393): validate (:302), refuse unaccepted terms when a version is configured (:311-314, returningLegalAcceptanceErrors.TermsNotAccepted), IP rate-limit (ADR-029 and BR-213,:317-321), reject a duplicate email through theEmailExistsAsynchook (:323-328), hash the password (:330), build the user through theCreateUserhook and unwrap it withTryGetValue(:331-335), seed the account's language from the request culture (SeedRegistrationCulture,:337-341, private helpers at:773-781and:790-800),AddAsyncand save (:343-348), run theOnUserRegisteredAsyncpost-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 aUserthat 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: ifCheckEmailConfirmed(tokenUser)fails, the result is a success carryingRegistrationOutcome.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 onEmail(ADC unfiltered, Store filtered onIsDeleted). Without the catch, that race surfaces as a generic 500 instead of the 409 a serialized pair would have produced. The catch cannot nameDbUpdateException, 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 sharedEmailAlreadyExistsFailure()helper; anything else rethrows untouched and still reaches the exception middleware. The re-check passesCancellationToken.Noneon 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 viaTokenService.GetPrincipalFromExpiredToken(:410, the issuer's instance; signature still checked, only lifetime skipped), read the identifier withprincipal.GetUserId()(:420, rides the standardsubclaim, also accepts theNameIdentifierform the bearer handler maps it to, and parses throughIParsableso the identifier alias can change shape without editing this file), load the tracked user (:427, a missing user answered byCreateRefreshUserMissingError,:430), run the refresh app gate (:434), and hand the presented refresh token tosessionIssuer.RotateAsync(:455-461) together with a mint callback overCreateAccessTokenForSession. 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'ssid. Two claims ride the rotation, both read off the presented access token, whose signature was already validated, and both armed in onetry/finallyaround 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 noauth_timerotates into one with none (comment,:447-449, ADR-139).RevokeTokenAsync(:471-485): load the user (aNotFoundwhen absent), then delegate tosessionIssuer.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, throughsessionIssuer.SignOutEverywhereAsync(:498).GetSessionsAsync(:505-513) andGetSignInsAsync(:517-525): no user lookup, so each is one call to the issuer,sessionIssuer.ListActiveAsync(:510) for live devices andsessionIssuer.ListSignInsAsync(:522) for the sign-in history, wrapped in a success (remarks,:504,:516).RevokeSessionByIdAsync(:533-537): an expression-bodied delegation tosessionIssuer.RevokeSessionAsync. Ownership is checked by the issuer's store query, so another account's id and a nonexistent id produce the sameNotFound(remarks,:528-532); an already-revoked session writes nothing and returnsNotFoundwithAuth.SessionAlreadyRevoked, matching the interface contract (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/IAuthenticationService.cs:126-128).ExternalLoginAsync(:544-551): declaredabstracthere, with the interface'sbool emailVerifiedparameter. The remarks (:540-543) and the class doc (:47-49) give the reason: OAuth linking is coupled to the app'sUserfactory, 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 thanNotEnrolledis refused withSignInLinkErrors.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 throughIssueTokensCoreAsync(:594).SignInWithPasskeyAsync(:613-642): the passkey path. A missing account or a service account answersPasskeyErrors.AssertionFailed(:620-625), the app gate runs (:627), and with no second-factor challenge_multiFactorMethodis armed toAuthClaimTypes.MultiFactorMethodPasskeyaround the issuance (:633-641): a passkey is possession of the authenticator plus its own user verification, so it satisfies the second factor itself, andRefreshTokenAsynccarriesmfa=passkeyacross rotations likeotp(remarks,:606-610).HasSignInMethodBesidesPasskeysAsync(:650-662): a vanished account answersfalse(:655-658); otherwise a non-empty stored password hash counts, and so does the virtualHasExternalLoginAsync(:660-661, hook at:673-674, defaultfalse).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 withTwoFactorErrors.TwoFactorRequiredand opening no session (:710-722; doc:688-696). It ends in the privateIssueTokensCoreAsync(: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 genericAuth.InvalidCredentials401 (:743-747), which makes it the backstop behind every path-specific refusal (doc:680-687), and otherwise delegates tosessionIssuer.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 underLoginAsync.MultiFactorMethodFor(:899-908) maps an unrecognized outcome tonull, so an enum that grew cannot silently mint anmfaclaim.HasStoredCredential(:937) delegates toPasswordCredential.IsStored, andCanSignInWithPassword(:943-944) adds the existence and service-account checks.BurnPasswordVerificationCost(:960-968) skips a blank password and otherwise calls the hasher's ownpasswordHasher.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 throughvalidators.Logger(:984).RehashPasswordIfNeededAsync(:1006-1037) is the work-factor upgrade. It returns at once unless the issuance succeeded and the app'sUseropts in by implementing IPasswordRehashableUser (:1008-1011). Otherwise it runs insideBestEffort.ExecuteAsync(PasswordRehashOperation, validators.Logger, ..., CancellationToken.None)(:1013-1036): whenpasswordHasher.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 torehashable.RehashPassword(hash, salt)(:1023-1024), logs AuthenticationServiceLog.PasswordRehashRejectedthroughvalidators.Loggerwith 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.Noneis 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 concreteUserso EF translates the predicate against the app's own mapped columns, and explicitly leaves the app to decide whether soft-deleted accounts count (ignoreQueryFilters: trueblocks re-registration of an erased address);CreateUser(:764) runs the app's domain factory;CreateAccessToken(:803) mints the app's claim set (for examplespeaker_idversuscustomer_id); andExternalLoginAsync(:544) is the OAuth path above. The sign-in lookup by address is not a hook: the framework owns it overIEmailIdentifiedUser.Email(class doc,:35-37). Eightvirtualmethods can be overridden:CreateAccessTokenForSession(:823-824) callssessionIssuer.MintForSession(sessionId, _multiFactorMethod, _authenticatedAt, () => CreateAccessToken(user)), so the issuer arms its stamping token service for the duration of the app hook andsid(plusmfawhen this request verified a second factor, andauth_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 toCreateAccessToken'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 throughtwoFactor ?? validators.TwoFactor(:864) and, with neither, answersTwoFactorOutcome.NotEnrolledwith 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) andValidateRefreshCandidateAsync(: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; andCreateRefreshUserMissingError(: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'sPasswordHashandPasswordSalt(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 bindsTUser = User, adds the Attendee default role (BR-45) and thespeaker_idclaim (BR-209, claims builder documented at:558), takes the injected AuthenticationValidators and IAuthSessionIssuer (:56-57) and passes them through to the base, re-listsIAuthenticationService(:69) so it can re-implementRegisterAsyncwithnew(:83), overrides the abstractExternalLoginAsync(:290), and overridesHasExternalLoginAsync(:182). ADC'sUseropts into the sign-in rehash by implementingIPasswordRehashableUser(MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Domain/Users/User.cs:38). MMCA.Store supplies its own subclass with acustomer_idclaim. Consumed by the Identity API controllers via the IAuthenticationService port.Caveats / not-in-source:
ExternalLoginAsynchas 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 theMMCA.Common.Application.Auth.AuthenticationServicecategory (AuthenticationValidators.LoggerCategory) in every app, so log-level configuration for that category is what silences or surfaces them; themmca.auth.signincounter records every attempt regardless, and a thrown rehash failure is also counted on theMMCA.Common.BestEffortmeter.
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:EmailConfirmationconfiguration 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]) andSystem.Diagnostics.CodeAnalysis([SuppressMessage]) validate the bound values. - Concept introduced: the config-bound settings-class shape (a
SectionNameconstant plusinit-only, range-validated properties with sane defaults) is the same one the siblingPasswordResetSettingsuses 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) andRequestWindowMinutes(line 59) throttle re-issuance per address.RequireConfirmedEmail(line 70) defaults tofalse. - Why it's built this way: the
RequireConfirmedEmaildefault 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
AuthenticationServiceBaseandEmailConfirmationTokenService(MMCA.Common/Source/Core/MMCA.Common.Application/Auth/AuthenticationServiceBase.cs,MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/EmailConfirmationTokenService.cs) and registered inMMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs; ADC binds it viaMMCA.ADC.Identity.Application/Users/AuthenticationServiceSettings.csand consumes it inSendEmailConfirmationHandler.
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
Legalsection (SectionName,LegalAcceptanceOptions.cs:15). Its one setting,CurrentTermsVersion(:21), is the terms version every user must have accepted (for example2026-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
.ResolveCurrentVersionis 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, insideAddLegalAcceptanceat: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 exposesCurrentTermsVersionto 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
MachineClientssection (SectionName,MachineClientSettings.cs:22) byAddMachineClients(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):MaxAccessTokenMinutesis 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:
MinAccessTokenMinutesis 1 (:25).Enabled(:36) defaults tofalse; while it is false the token endpoint and every administration endpoint answer 404 and theMachineClientstable is in no model, so a host that never opts in sees no route and no migration (remarks:8-13).AccessTokenMinutes(:42) defaults toMaxAccessTokenMinutes; nothing renews the token, a program asks again.DataSourceName(:48) names the logical data source that owns theMachineClientstable (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
Useraggregate, remarks:14-17).MachineClientSettingsValidatorenforces 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(insideAddMachineClients,:37); read by MachineClientService, by EFMachineClientStore (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/MachineClients/EFMachineClientStore.cs:32), and byApplicationDbContextandDesignTimeDbContextHelperto 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
UserIdentifierTypealias and PiiAttribute onNameandEmail(:15-16). - Concept: a plain positional record crossing the consumer boundary; no new concept.
Roleis 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
Useraggregate. See ADR-140. - Where it's used: returned by
IServiceAccountProvisioner.FindAsyncand consumed by MachineClientService.IssueTokenAsync(MachineClientService.cs:103-121); ADC builds it inMMCA.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 (
PasswordRequiredCodealiasesAuthErrorCodes.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
*Errorsclass in this codebase (see AuthErrorCodes for the general shape); no new concept here. - Walkthrough: three error codes:
EmailNotConfirmedCode(EmailConfirmationErrors.cs:13),InvalidTokenCode(line 16) andPasswordRequiredCode(line 23).EmailNotConfirmed(source)(lines 33-36) returnsError.Unauthorized, distinct fromAuth.InvalidCredentialsso a UI can offer to resend the link.PasswordRequired(source)(lines 48-51) returnsError.Unauthorizedwhen 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.PasswordRequiredfollows 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.InvalidTokencollapsing 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,306forInvalidToken,:228forPasswordRequired), byAuthenticationServiceBase.csand ADC'sAuthenticationService.cs(the sign-in refusal), and byEmailConfirmationTokenService.cs; asserted against inConfirmEmailAccountProofTests.cs,EmailConfirmationHandlerBaseTests.cs,EmailConfirmationTokenServiceTests.cs,AuthErrorCodesAlignmentTests.cs, and ADC'sConfirmEmailHandlerTests.csandAuthenticationServiceTests.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 (TermsNotAcceptedCodealiasesAuthErrorCodes.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 buildError.Validationwith 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:
TermsNotAcceptedis returned byAuthenticationServiceBase.RegisterAsync(MMCA.Common/Source/Core/MMCA.Common.Application/Auth/AuthenticationServiceBase.cs:313);VersionNotCurrentby 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) isError.Unauthorizedfor 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) andInvalidRequest(:39) areError.Validationfor a grant type other thanclient_credentialsand a missing one.RoleNotAllowed(:49) refuses a role grantingusers:view-as,users:manage,roles:manageorclients:manage.PrivilegeCeiling(:59-64) isError.Forbiddenwith targetrolefor 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 codeUserAdministration.PrivilegeCeiling(403) inline and names no permission (doc comment:52-56).RoleRequired(:69) andNotFound(: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.TokenErroranswers 400 for the two grant-type codes and 401invalid_clientfor 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.InvalidTokenerror (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
PasswordRequiredand 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 withTryAddScopedinMMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Auth.cs:91.ConfirmEmailHandlerBasecallsValidateAsyncfirst (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/EmailConfirmation/ConfirmEmailHandlerBase.cs:107) andValidateAndConsumeAsynconce the account proof passes (:298); it is also consumed bySendEmailConfirmationHandlerBase.csand by ADC'sSendEmailConfirmationHandler.cs/ConfirmEmailHandler.cs, and named inMMCA.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 theUserIdentifierTypealias. - 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, viaNormalize), 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
AddLegalAcceptancedeliberately registers none (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Auth.cs:137), because where the accepted version lives is the consumer'sUseraggregate (seeILegalAcceptingUserinMMCA.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 asLegalAcceptanceService(MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/LegalAcceptanceService.cs), registers it in that module'sDependencyInjection.cs, and subclasses the controller base asLegalAcceptanceController.
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 inMMCA.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) mirrorsMachineClients:Enabled.IssueTokenAsync(grantType, clientId, clientSecret, ct)(:28) runs the grant and fails withMachineClients.InvalidClient,UnsupportedGrantTypeorInvalidRequest.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 untilPromoteAsync(: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:
CreateAsyncandRotateAsynctake an optionalFunc<string, bool>? callerHoldsPermissionthat answers whether the caller holds a given permission. Every permission the client's role grants must pass it, or the call is refused withUserAdministration.PrivilegeCeiling(param docs:44-49and:62-66).nullapplies 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 itsCallerHoldsPermission()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>, theUserIdentifierTypealias. - Concept: the consumer-supplied-store shape of ADR-116 (compare ILegalAcceptanceService): Common has no user entity, so the app implements this over its own
Useraggregate. A service account is a user whose IAuthUser.IsServiceAccountis 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 (remarksIServiceAccountProvisioner.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 atMMCA.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 withLegalAcceptanceErrors.VersionNotCurrent.Normalize(currentVersion, standing)(:50) re-derives the standing throughLegalAcceptanceDTO.Evaluate, taking only the accepted version and instant from the consumer's answer, so the result never depends on a consumer fillingCurrentVersionorIsCurrentcorrectly. - 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), andLegalAcceptancePolicyTests.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, theUserIdentifierTypealias. - 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, orAuth.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 byAddEmailConfirmation, so an app that wiresConfirmEmailHandlerBasegets 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 intoConfirmEmailHandlerBase(MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/EmailConfirmation/ConfirmEmailHandlerBase.cs:68), which callsVerifyCurrentPasswordAsync(:244-245),ClaimWithNewPasswordAsync(:267-268) andClearFailedAttemptsAsync(:181), and passed through by ADC'sConfirmEmailHandler(MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/ConfirmEmail/ConfirmEmailHandler.cs:30); covered byConfirmEmailAccountProofTests.cs,EmailConfirmationHandlerBaseTests.csand ADC'sConfirmEmailHandlerTests.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 commentIMachineClientStore.cs:5-9). - Walkthrough:
ListAsync(:15) returns every client, revoked ones included, oldest first.FindAsync(clientId, ct)(:21) returns a tracked instance, soSaveAsync(client, ct)(:33) persists changes made to it.AddAsync(:27) adds and saves a new client.RecordUseAsync(client, usedOn, ct)(:44) callsMachineClient.RecordUseand 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
RecordUseAsynckeeps 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 nosid,mfaorauth_timeand opens no refresh session; it carries the service account's standard claims and role permissions as a person's token does, plusclient_idandtoken_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:
ClientCredentialsGrantTypeis"client_credentials"(:51).ForbiddenPermissions(:58-64) listsViewAsUsers,ManageUsers,ManageRolesandManageClients: 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 oneInvalidClientresult: unparsable id or empty secret (:89), unknown client orAcceptsfalse (:96), and an account that is missing, mismatched or holds a forbidden role, re-read on every mint (:103-104). It then mints withGenerateShortLivedAccessTokenatAccessTokenMinutes(:109-121), records the use (:123) and returns aBearerresponse (: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) answersNotFoundfor an unknown client, then, when a ceiling is supplied, reads the role from the client's service account and refuses withPrivilegeCeilingwhen 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 fromSoftDeletedUserCache.MarkerDurationForover the longer of the machine and host access-token lifetimes (:260-263).IsForbiddenRole(:279) reads the role's permissions from the registry, andCallerHoldsEveryPermissionOf(: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'sJwtBearerOptions(: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 byMachineClientServiceRevocationMarkerTests.cs(MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Auth/MachineClients/), the API test hostMachineClientTestHost.cs(MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/Controllers/MachineClients/) and ADC'sMachineClientControllersTests.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
ResetPasswordHandlerBaseuse (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.
twoFactorStoreis null on a host that has not adopted two-factor authentication (:15-18), andtimeProviderdefaults 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 fromCheckLockoutAsyncwhen the address is locked (:36-40), then succeeds whenVerifyPasswordmatches the stored hash and salt (:42-45); otherwise it callsIncrementFailedAttemptsAsync(:47) and fails withError.Unauthorized("Auth.InvalidCredentials", "The password is incorrect.")(:48-49).ClaimWithNewPasswordAsync(:53) revokes every refresh session throughRefreshSessionRevocation.RevokeAllAsync(:63-65), then, when a two-factor store is present and the account has an enabled factor or a pending secret, callsDisableAsyncand returns its failure if it fails (:67-78), and finally hashes the new password and returnsuser.ChangePassword(newHash, newSalt)(:80-81).ClearFailedAttemptsAsync(:85-86) forwards toResetFailedAttemptsAsync. - Why it's built this way: the revocation is persisted before the account changes, in the
ResetPasswordHandlerBaseorder, 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 throughConfirmEmailHandlerBase; covered byConfirmEmailAccountProofTests.cs(MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Users/UseCases/EmailConfirmation/). - Caveats / not-in-source:
RefreshSessionRevocation.RevokeAllAsyncand 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) andStoredPermissionRoleAdministrationService, and registered inMMCA.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;nullmeans 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
IPermissionGrantCachebyPermissionGrantCache.cs, called byStoredPermissionRoleAdministrationService.csafter a grant or revoke, and registered inMMCA.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) andTransports. - 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 keepsFido2NetLibconfined toMMCA.Common.Passkeys(ADR-139, decision 1). - Where it's used: returned by IPasskeyCeremony
.VerifyRegistrationAsyncand 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
UserIdentifierTypealias (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) andSignIn = "signin"(line 13).UserIdisnullfor 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
Passkeyssection: 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 tofalse.RelyingPartyId(line 31) is the registrable domain the passkeys belong to (example.comalso coversapp.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 thePasskeyCredentialstable (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).
DataSourceNamefollows 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.csandDesignTimeDbContextHelper.cs(underMMCA.Common/Source/Core/MMCA.Common.Infrastructure); pinned byPasskeyModelGateTests.csandAddPasskeysTests.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; theFindAuthTime()principal extension that reads theauth_timeclaim. - 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 readsauth_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 withprincipal.FindAuthTime()(line 27); a principal with noauth_timenever qualifies, and a sign-in stamped slightly in the future (clock skew between hosts, comment at line 29) counts as recent because onlynow - signedInAt <= MaxSignInAgeis 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 resetsiatand carriesmfa; onlyauth_timemeasures the sign-in itself. - Where it's used: checked by both registration actions of
PasskeysControllerBase.csand byTwoFactorControllerBase.cs(underMMCA.Common/Source/Presentation/MMCA.Common.API/Controllers); the refusal is PasskeyErrors.StepUpRequired; pinned byAuthTimeClaimTests.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: neitherIPermissionRegistry(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, andDesignTimeDbContextHelper.cs(all underMMCA.Common/Source/Core/MMCA.Common.Infrastructure); registered inMMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Auth.cs; pinned byPermissionGrantModelGateTests.csandPermissionGrantCacheTests.csinMMCA.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
IPermissionRegistrydecorator 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):LayeredPermissionRegistrywrapsinnerwithout changing its contract, adding a second data source transparently to every caller ofIPermissionRegistry. - Walkthrough: the type is a primary-constructor class taking
innerandgrants(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 aHashSet<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'srolessequence 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
IPermissionRegistryimplementation inMMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs(3 sites) when database grants are enabled; exercised directly inMMCA.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 prefixedPasskeys.;PasskeysNotSupportedCodeis 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 optionalsource: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) andNotFound(line 75,Error.NotFoundError). - Why it's built this way:
AssertionFailedis 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), andPasskeysPanel.razor.csinMMCA.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,JsonElementand byte arrays, so theFido2package and its native dependencies live only inMMCA.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 ornullwhen 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:Enabledis true fails startup inCloudAdapterTripwire.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) mirrorsPasskeys:Enabled.BeginRegistrationAsync(userId, userName, displayName, ...)(lines 23-27) andCompleteRegistrationAsync(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, andCompleteSignInAsync(request, ipAddress, userAgent, ...)(lines 81-85) verifies the assertion and mints the token pair throughIAuthenticationService.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 byAddPasskeysTests.csandPasskeysIsolationTests.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) andRemoveAsync(line 47) each save. - Why it's built this way: scoping
FindAsyncby 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 inMMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs, consumed by PasskeyService; faked inPasskeyTestHost.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.
HasPermissionimplements: 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 byPermissionGrantCache.cs(2 sites) to build the IPermissionGrantCache snapshot, called by IRoleAdministrationService's implementationStoredPermissionRoleAdministrationService.cs(2 sites), and registered inMMCA.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 arepasskeys:challenge:plus a flow id ofFlowIdLength32 (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 forLifetime(lines 43-44).RedeemAsync(lines 56-83) rejects anything not exactly 32 lower-case hex characters (line 58), takeslock:plus the key (line 64) and returnsnullwhen contended (lines 65-69), reads withGetFromSharedStoreAsyncrather 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) takeslock:passkeys:user:{userId}, returningnullpast 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.csand 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-generatedLoggerMessagemethods (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) readsEnabled.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 aRegisterchallenge.CompleteRegistrationAsync(lines 72-115) redeems the challenge and refuses it unless the ceremony isRegisterand the account matches (lines 80-84), verifies with a uniqueness callback overFindByCredentialIdAsync(lines 87-93), builds the entity withPasskeyCredential.Create(lines 100-107) and adds it (line 113).ListAsync(line 118) andRenameAsync(line 125) are thin.DeleteAsync(lines 153-179) takes the account lock (line 155), answering aPasskeys.Busyconflict when it cannot (line 158), and refusesLastPasskeywhen one passkey remains and the account has no other sign-in method (lines 170-173).BeginSignInAsync(line 182) issues aSignInchallenge with no account.CompleteSignInAsync(lines 194-218) redeems aSignInchallenge (line 203), verifies (line 209) and hands the user id toSignInWithPasskeyAsync(lines 215-216). The privateVerifyAssertionAsync(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 withcredential.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;
UserHandleForis 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
UserIdentifierTypealias;TaskandCancellationTokenfrom 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 itsexp, 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: withoutClearMarkerAsync, 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:268and 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 itsUserAdministrationServiceandDeleteUserHandler(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 recordnested 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 atAuthSessionIssuer.cs:200and:285to 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 returnResult<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, andGuid SessionIdnames what would otherwise be an anonymous second tuple element. - Walkthrough: one positional declaration,
IssuedSession(string RefreshToken, Guid SessionId)(AuthSessionIssuer.cs:752).RefreshTokenis what goes back to the caller in the AuthenticationResponse;SessionIdis what the access token'ssidclaim carries, which is why the session must be opened before the token is minted (the comment atAuthSessionIssuer.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) andRotateSessionAsync(:350, constructed at:390); unwrapped byIssueAsync(:84-85) and byRotateAsync(:120-121), each of which passesSessionIdto the caller'smintAccessTokencallback and putsRefreshTokeninto 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 explicitproperty:target is what puts the marker on the generatedFirstNameandLastNameproperties 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
profileargument 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 atMMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/SignInLinks/SignInLinkTokenService.cs:53), and comes back on redemption in SignInLinkGrant.SendSignInLinkHandlerBaseissuesSignIn; an invitation is issued asInvitethrough 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, anmfaclaim when a second factor verified this request, and anauth_timeclaim 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 (summaryMMCA.Common/Source/Core/MMCA.Common.Application/Auth/Sessions/AuthSessionIssuer.cs:754-760). It is aprivate sealed classnested inside AuthSessionIssuer (AuthSessionIssuer.cs:766). - Depends on: ITokenService (the contract it implements and the inner instance it wraps,
AuthSessionIssuer.cs:766), AuthClaimTypes for thesid,mfaandauth_timeclaim 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 ownCreateAccessTokenhook. 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
innerservice (AuthSessionIssuer.cs:766).Guid? CurrentSessionId { get; set; }(:769) is the session arming switch: a session id stamps,nullmints 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) andRefreshTokenLifetime(:784) forward straight toinner, so the lifetime callers read is still the JWT settings' value.GenerateAccessToken(...)(:787-793) andGenerateShortLivedAccessToken(..., lifetime)(:796-803) both forward toinnerwithStamp(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'sadditionalClaimsinto a newList<Claim>(:822, so the caller's sequence is never mutated), then independently appendsAuthClaimTypes.SessionIdformatted assessionId.ToString("D", CultureInfo.InvariantCulture)whenCurrentSessionIdis set (:824-829, the"D"format being the canonical hyphenated Guid formClaimsPrincipalExtensions.FindSessionIdparses back, see ClaimsPrincipalExtensions),AuthClaimTypes.MultiFactorset to the raw method string whenCurrentMultiFactorMethodis set (:831-834), andAuthClaimTypes.AuthTimeas Unix seconds typedClaimValueTypes.Integer64whenCurrentAuthTimeis set (:836-842), and returns the extended list (:844). The three claims are independent: a token can carry any combination of them.GenerateRefreshToken()(:806) andGetPrincipalFromExpiredToken(string token)(:809-810) are plain forwards.
- Why it's built this way: putting the stamping behind an
ITokenServicerather 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 privateStampkeeps the two token kinds from drifting apart. The escape hatch still applies: an app that mints from its own injectedITokenServicereference produces a valid token with none of the three claims, and can restore them by overridingCreateAccessTokenForSession(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 protectedTokenServiceproperty (AuthenticationServiceBase.cs:124). All three switches are armed and disarmed by the four-argumentAuthSessionIssuer.MintForSession(AuthSessionIssuer.cs:173-190, with thefinallyat:184-189guaranteeing all three disarm even when the hook throws), which the base calls fromCreateAccessTokenForSessionwith its_multiFactorMethodand_authenticatedAtfields (AuthenticationServiceBase.cs:824;_authenticatedAtis read from the presented token'sauth_timeon 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) callGenerateShortLivedAccessTokenon their own injectedITokenService, not on this nested wrapper, so the short-lived stamping applies only to a short-lived token minted throughIAuthSessionIssuer.TokenServiceinside an armedMintForSession.
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 atMMCA.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:SignInLinksconfiguration 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]) andSystem.Diagnostics.CodeAnalysis([SuppressMessage]). - Concept introduced: a capability that is registered but off.
[Rubric §11, Security]assesses whether a security-sensitive feature fails closed.Enableddefaults tofalse(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 inComposeLink: 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 andRefererheaders, 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), defaultfalse.SignInUrl(:31), default empty, deliberately not required (matchingEmailConfirmationSettings.ConfirmationUrl, see EmailConfirmationSettings) so an unconfigured host still boots; with it empty no link can be composed and nothing is sent (doc:22-26). TheCA1056suppression (:27-30) explains why it is astring: the empty default is not a validSystem.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, withinRequestWindowMinutes(:53),[Range(1, 1440)], default 60.LifetimeFor(purpose)(:58-59): the invite lifetime forInvite, the sign-in lifetime otherwise.ComposeLink(email, token)(:74-77):nullwhenSignInUrlis blank, otherwise{SignInUrl}#email=...&token=...with both values passed throughUri.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
AddSignInLinkswith.Bind(...),.ValidateDataAnnotations()and.ValidateOnStart()(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Auth.cs:117-120); injected asIOptions<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:
InvalidLinkis "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) andInvalidLink(source)(:23-26):Error.Unauthorized, "The sign-in link is invalid or has expired. Please request a new one."SecondFactorRequiredCode = "Authentication.SignInLinkSecondFactorRequired"(:15) andSecondFactorRequired(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) andNotSupported(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:
NotSupportedis the default body of the sign-in-link member on IAuthenticationService (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/IAuthenticationService.cs:192); AuthenticationServiceBase<TUser> returnsInvalidLinkandSecondFactorRequiredfromSignInVerifiedEmailOwnerAsync(MMCA.Common/Source/Core/MMCA.Common.Application/Auth/AuthenticationServiceBase.cs:578,:591); RedeemSignInLinkHandlerBase<TUser, TCommand> returnsInvalidLinkfrom each failing branch (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/SignInLinks/RedeemSignInLinkHandlerBase.cs:145,:200,:234,:311,:363); and SignInLinkTokenService returns it fromValidateAndConsumeAsync(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 thesid/mfaclaims 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 theUserIdentifierTypealias. - 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 aFunc<Guid, string> mintAccessTokencallback: 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: theauth_timeoverload ofMintForSessionis abstract, with no default body, so every implementation has to stampauth_timerather than silently leaving passkey registration refused on its host (remarksIAuthSessionIssuer.cs:100-103). - Walkthrough:
TokenService(IAuthSessionIssuer.cs:35): the ITokenService an app mints through. While the issuer is minting for a session it appendssid(andmfawhen 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 sameAuth.InvalidRefreshTokenerror (:54-62).MintForSession(sessionId, multiFactorMethod, mintAccessToken)(:87): runs the callback withTokenServicearmed to stampsidand, when not null,mfa(:79-82).MintForSession(sessionId, multiFactorMethod, authenticatedAt, mintAccessToken)(:104): the same, also stampingauth_time:authenticatedAtwhen given (a refresh carrying the presented token's sign-in instant over unchanged), otherwise the instant of the sign-inIssueAsyncis opening, and none outside it (:89-93). It is an abstract member: an implementation that minted noauth_timewould 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 withSignOutAsync(: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 answerAuth.SessionNotFound; an already-revoked session writes nothing and answers the not-found failureAuth.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'ssid), 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 answerAuth.SessionNotFoundand 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
TryAddScopedinMMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:206; injected into AuthenticationServiceBase<TUser> (AuthenticationServiceBase.cs:83), which delegates to it fromTokenService(:124), refresh (RotateAsync,:455), sign-out (:482,:498), session listing (:510), sign-in history (:522), revocation (:537), issuance (IssueAsync,:749) andCreateAccessTokenForSession(the four-argumentMintForSession,:824).AuthControllerBasetakes it as a[FromServices]parameter in two actions: the anonymousEndSessionAsync(POST session/end, always204 No Content) callsSignOutByRefreshTokenAsync(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 callsRecordDeviceAsync(:327,:346). ADC'sAuthenticationServicetakes 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).profileis 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
TryAddScopedbyAddSignInLinks(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Auth.cs:123; the remarks at:112-113note that registering it issues nothing until the app wires the handlers and a controller and setsAuthentication: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 inSendSignInLinkInternalCommandHandler(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
Emptyinstance of seven nulls (:13) is compared with==(:33), which works becauseDeviceMetadatais asealed 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 aDeviceMetadatafromDeviceId,DeviceName,DeviceModel,DeviceManufacturer,DevicePlatform,DeviceFormFactorandDeviceType(:24-31), and returnsnullwhen it equalsEmpty(: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.MarkerDurationForof 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 atMaxEntries(: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 byStartedAtthenSignInIddescending, and takesMaxEntries(:72-78).SummarizeViewAs(:80): a grant row spans the grant; ended grants reportSignInEndReasons.ViewAsEnded(:84-87), past-expiry onesSignInEndReasons.Expired(:88-91); IP and user agent are null,IsCurrentis false, and the kind isSignInHistoryEntryKind.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'ssidis 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 itsSignInId, or its ownIdfor a chain's first row (:145-146, doc:122-126).Summarize(signIn, now, currentSignInId)(:149): last-active is the head'sCreatedAt, IP and user agent come from the head,IsCurrentmatches the resolved sign-in (:162), andDevicecomes fromhead.ToDeviceMetadata()(:163).DescribeEnd(head, now)(:166): a revoked head reports its instant and recorded reason as-is, because the session reasons andSignInEndReasonsshare their values (:168-173); otherwise a head pastExpiresAtreportsExpired, and a live one reports no end (:175).
- Why it's built this way: the shaping functions are pure and take
nowas 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 optionalILogger<AuthSessionIssuer>and an optional IViewAsGrantStore, all primary-constructor parameters (AuthSessionIssuer.cs:54-60, doc:42-53); RefreshSession, AuthenticationResponse, RefreshSessionSummaryResponse, SignInSummaryResponse, DeviceMetadata andError/Resultfrom 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 ispartialbecause 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 onlyRefreshSession.HashTokendigests; 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 throughIRefreshSessionStore.TryRotateAsync; and an expired session is not a reuse signal. Both paths share one carve-out (:26-29): a token rotated less than RefreshSessionSettings.ReuseGraceSecondsago (default 10) is a rotation race between sibling requests, answered409 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 asTokenService(:77), and_signInInstant, armed only whileIssueAsyncmints a new session's first access token so that token carriesauth_time(doc:69-73). - Lifetimes (
:79-83):AccessTokenLifetimeandRefreshTokenLifetimeread 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 actualexp; a host that bindsJwtSettingsthroughAddCommonAuthenticationfails 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 withTryGetValue(:100), saves (:105), then sets_signInInstanttonow(:109) and callsmintAccessToken(issued.SessionId)(:113) inside atrywhosefinallyclears it (:117-120). The comment at:97-98says why the order matters: the token carries the session's id insid, and a session has an id only once created; the comment at:107-108says 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 throughRefreshSession.Createwithnow + RefreshTokenLifetime(:501-508), runsEnforceSessionCapAsync(: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, thenId), and revokes from the front withReasonSessionCapuntil 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 throughRefreshSessionCleanupService.RotateAsync(:124):ResolveRotatableSessionAsync(:135), thenRotateSessionAsync(:143), each result unwrapped withTryGetValue, 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: ifIsReuseSignalis 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 answersRefreshSupersededErrorwith nothing revoked (:454-459); ifFindRecoverableSuccessorAsyncfinds 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 isRefreshSupersededError(:472-477); otherwiseRevokeFamilyOnReuseAsyncrevokes 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 asRotatedinside 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 throughsession.CreateSuccessor, which continues the presented session'sSignInIdso the sign-in history folds a rotation chain into one row (:543-551), then asks the store to claim the rotation viaTryRotateAsync(: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 throughIRefreshSessionStore.FindByIdUntrackedAsync(:568-570): a sign-out, cap eviction or reuse sweep of the same row fails alone (:571-577), a rotation inside the grace answersRefreshSupersededError(:579-582), and anything else (rotated longer ago than the grace, or unreadable) gets the replay answer throughRevokeFamilyOnReuseAsyncandAuth.InvalidRefreshToken(:587-589). Rotation replaces one session with one, so the cap is not re-evaluated (:523).IsReuseSignal(:604) andIsWithinRotationGrace(: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 theRotatedreason, with a positive grace andnow - RevokedAtunder it (:626-631). A row flagged as reuse, signed out or evicted never reaches the grace check, becauseIsReuseSignalfails it alone first, however recent.RevokeFamilyOnReuseAsync(:692) andRevokeLiveSessionsAsync(:704): the second revokes every un-revoked row with the given reason and returns how many it revoked (:710-720); the first uses it withReasonReuseDetected, saves, logs the user id and the count, and counts the event once on themmca.auth.refresh_reusemetric throughAuthSecurityMetrics.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) andRefreshSupersededError(: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 answersError.Conflict("Auth.RefreshSuperseded", ...)so the client keeps its session and retries with the winner's token (:396-405).MintForSession(:164and:173): the three-argument overload forwards withauthenticatedAt: null(:164-165); the four-argument one arms the nested SessionStampingTokenService with the session id, the second-factor method, andauthenticatedAt ?? _signInInstant(:177-179), runs the callback, and disarms all three in afinally(:184-189). A nullauthenticatedAtoutsideIssueAsyncmints noauth_timerather 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 throughToDeviceMetadata(:269-283).ListSignInsAsync(:292): delegates to SignInHistory.ReadAsyncwith 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-scopedFindByIdAsyncquery (:323), so another account's id and a missing id produce the sameAuth.SessionNotFound(:324-331); an already-revoked row writes nothing and answers the not-found failureAuth.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 answersAuth.SessionNotFound(:364-371), since a client reporting on a dead session has nothing left to describe (remarks:349-354); otherwisesession.RecordDevice(device)(:373), a failure returned as-is, then save (:379).
- Fields (
- 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. Theauth_timestamping 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> andAuthControllerBase(whose anonymousEndSessionAsyncis the caller ofSignOutByRefreshTokenAsync,MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/AuthControllerBase.cs:213). Constructed directly in the Common test suites, among themAuthSessionIssuerSignInHistoryTests.cs,AuthSessionIssuerTokenSignOutTests.cs,AuthSessionIssuerDeviceTests.cs,AuthSessionIssuerLostResponseRecoveryTests.csandAuthSessionIssuerReuseGraceTests.cs(MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Auth/Sessions/),AuthenticationServiceBaseTests.cs,AuthenticationServiceIdentityCompletionsTests.csandAuthenticationServiceLegalAcceptanceTests.cs(MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Auth/),PasskeyTestHost.cs(MMCA.Common/Tests/Core/MMCA.Common.Passkeys.Tests/) andAuthControllerBaseSessionDeviceTests.cs(MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/Controllers/Auth/), and in ADC'sAuthenticationServiceTests.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 byTotpTwoFactorService.csand exercised inMMCA.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
DomainEntityStatein group-02);NotEnrolled = 0is the default/no-op value, matching that convention. - Walkthrough: three values;
NotEnrolledmeans the account has no active second factor so nothing was challenged,VerifiedTotpmeans a time-based code from the authenticator app verified,VerifiedRecoveryCodemeans a single-use recovery code verified and was spent. - Why it's built this way: collapsing the challenge result to one enum lets
AuthenticationServiceBasedecide, in one switch, whether to continue sign-in unchanged (NotEnrolled) or stamp anmfaclaim on the issued token (the two verified cases). - Where it's used: returned by ITwoFactorAuthenticator.
ChallengeAsync, read byAuthenticationServiceBase.cs(7 sites) andTwoFactorAuthenticator.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
ViewAssection 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 tofalse; 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, grantusers:view-asto its staff role, add theViewAsGrantsmigration on the Identity database, and disclose staff access in its privacy notice.HostsGrantStore(line 49) defaults totrue; in a multi-service host only the Identity service keeps it, and the others set itfalseand learn that a grant ended from a marker in the sharedICacheService(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
HostsGrantStoresplit 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 theAuthControllerBase,UsersAdminControllerBaseandViewAsGrantsAdminControllerBasecontrollers inMMCA.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), withEmail(line 17) andFullName(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 areinitproperties that default tofalse. - 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 byMMCA.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 theotpauth://totp/...URI an authenticator app scans as a QR code; it is deliberately returned asstringrather thanSystem.Uri(the[SuppressMessage]at lines 33-36 explains that round-tripping throughUriwould 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 overloadVerifyCode(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:60for the step-reporting overload), consumed by the enrollment/regeneration handler bases inMMCA.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 inMMCA.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, ornullwhen 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:216says the account reader is the consumer's), and ViewAsService takes it as an optional constructor argument, so an enabled host that forgot it gets aViewAs.NotConfiguredfailure rather than a DI error. - Where it's used: called by ViewAsService.
StartAsync; implemented in ADC byViewAsSubjectResolver(MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/Administration/ViewAsSubjectResolver.cs:24) and registered in that module'sDependencyInjection.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) isError.Unauthorized, asking the caller to supply a code or a recovery code.TwoFactorInvalid(source)(lines 51-54) is alsoError.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) andTwoFactorEnrollmentMissing(source)(lines 67-70) are bothError.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) isError.Forbiddenwith codeAuthentication.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 renewsauth_time, so only a new sign-in clears it. - Why it's built this way:
ConflictversusUnauthorizedis used to distinguish "your account state does not support this action" from "your credentials did not verify", andForbiddenmarks "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.csandRegenerateRecoveryCodesHandlerBase.cs(MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/TwoFactor/), by TwoFactorAuthenticator andAuthenticationServiceBase.cs;RecentSignInRequiredis raised byTwoFactorControllerBase(MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/TwoFactor/TwoFactorControllerBase.cs:136,170). Asserted inTwoFactorHandlerBaseTests.cs,TwoFactorAuthenticatorTests.cs,TwoFactorControllerBaseTests.csandAuthErrorCodesAlignmentTests.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.NotEnrolledwhen the account has no active second factor (sign-in continues unchanged, nomfaclaim), the verified outcome when a code satisfies the challenge, or a failure: TwoFactorErrors.TwoFactorRequiredCodewhen a code was needed and none arrived, TwoFactorErrors.TwoFactorInvalidCodewhen 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
AuthenticationServiceBasedistinguish "no second factor configured" from "verified", which matters for whether it stamps anmfaclaim on the issued token. - Enrollment confirmation:
VerifyEnrollmentCodeAsync(userId, secret, code, cancellationToken)(ITwoFactorAuthenticator.cs:65-69) returns a plainbooland verifies a code against the account's PENDING secret under the same single-use time-step guard asChallengeAsync(doc comment lines 45-64). Thesecretit receives (param doc lines 57-61) is the pending secret as ITwoFactorStore holds it, in the protected form ITwoFactorSecretProtector.Protectproduced; the shipped implementation unprotects it before verifying.ChallengeAsyncanswers TwoFactorOutcome.NotEnrolleduntil 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 atTwoFactorAuthenticator.cs:90. - Where it's used: implemented by
TwoFactorAuthenticator(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/TwoFactor/TwoFactorAuthenticator.cs), called fromAuthenticationServiceBase.cs(2 sites), fromConfirmTwoFactorEnrollmentHandlerBase.cs:83(VerifyEnrollmentCodeAsync), and by the disable and recovery-code regeneration handler bases, and registered inMMCA.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) returnsResult<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
Resultreturn 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 inMMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Auth.cs:62; called byBeginTwoFactorEnrollmentHandlerBase.cs(protect) and TwoFactorAuthenticator (unprotect); exercised end to end inTwoFactorSecretProtectionEndToEndTests.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) returnsnullonly when the account itself does not exist; an account that never enrolled still returns a state withIsTwoFactorEnabled = 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. Thesecret(param doc lines 41-44) arrives already in its protected form (ITwoFactorSecretProtector); the store keeps it as given and returns it unchanged fromGetAsync.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/CompleteEnrollmentAsyncprevents 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:
AddTwoFactorAuthenticationdeliberately registers noITwoFactorStore(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 inMMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/TwoFactor/, and byTwoFactorControllerBaseandUsersAdminControllerBaseinMMCA.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
subis the viewed account, while theact_subandvagclaims 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 holdsusers: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;IsGrantActiveAsyncis called per request byViewAsGuardMiddleware(MMCA.Common/Source/Presentation/MMCA.Common.API/Middleware/ViewAsGuardMiddleware.cs:137), and the start and end endpoints live onUsersAdminControllerBaseandAuthControllerBase.
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'svagid.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 atnow, email filters compare case-insensitively against the display snapshots, and the page size is clamped toViewAsGrantListRequest.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 atMMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:221) and the test doubleInMemoryViewAsGrantStore(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) andViewAsGrantsAdminControllerBase(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 withViewAsGrant.NormalizeDisplayand applies a contains match againstStaffDisplayandTargetDisplay.ByWindow(line 49) keepsGrantedAt >= FromandGrantedAt < To(inclusive start, exclusive end).ByStatus(line 64) derivesLive(not ended,ExpiresAt > now),Ended(EndedAtset) andExpired(not ended,ExpiresAt <= now) at lines 67-69, mirroringViewAsGrant.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) andInMemoryViewAsGrantStore(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.
ViewAsActorandViewAsGrant(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 belowViewAsGrant.MaxLifetime, otherwiseMaxLifetime(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 throughViewAsGrant.Create(line 76), returnsViewAs.NotConfiguredas anError.Unexpected(a host wiring fault, not a caller mistake) when no resolver is registered (lines 82-87), then reads the subject (line 89) and runsRefuse(line 90). It rebuilds the grant with the display snapshots (line 99: the staff email fromStaffEmail, the viewed email from the subject), sweeps rows older thanRetentionDays(line 101) and adds the grant (line 102) BEFORE minting the token withGenerateShortLivedAccessToken(lines 109-115).EndAsync(line 121) answersViewAs.GrantNotFoundwhen 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 (mappedClaimTypes.Email, then rawemail, 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 holdsAdministrationPermissions.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 inMMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Auth/ViewAs/ViewAsServiceTests.cs,ViewAsTokenTests.csandViewAsGuardMiddlewareTests.cs. - Caveats / not-in-source:
ViewAsGrant.MaxLifetimeis 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:NeedsRehashlets the caller ask whether a hash that has just verified was derived with older parameters, andBurnVerificationCostspends 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 distinctbyte[]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, andVerifyPassword(: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 oneHashPassworduses now, and thefalsedefault 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 reachesVerifyPassword, 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 (oneHashPassword, discarded) is exactly that cost. PasswordHasher implements the member explicitly (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/PasswordHasher.cs:117), deriving atBurnIterationsover a fresh salt (:121), andBurnIterationsis defined as the currentIterations(: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 overridesNeedsRehashatMMCA.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.NeedsRehashcloses 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
VerifyPasswordon the login path (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/AuthenticationServiceBase.cs:207),HashPasswordon registration (:330),BurnVerificationCoston the branches that have no credential to verify (:967), and, after tokens are issued,NeedsRehashthenHashPasswordin its best-effort rehash step (:1018and:1023) when the app'sUserimplements 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), itsChangePasswordHandler(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
UserIdentifierTypealias (: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 untilexp, 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:5states the second motive: the interface is declared in Application and implemented against the app's ownUseraggregate 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:117callscontext.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:37andMMCA.Store/Source/Modules/Identity/MMCA.Store.Identity.Application/DependencyInjection.cs:43, both asTryAddScoped<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
ClaimsPrincipalfrom an expired-but-validly-signed access token. - Depends on:
System.Security.Claims(BCL,:1) and theUserIdentifierTypealias. 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 seeSystem.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, returningnullwhen 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 honorlifetime, 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) andRefreshTokenLifetime { get; }(:64), the latter the absolute refresh-token lifetime of BR-205. The comments at:54-57and:60-63state 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 actualexp. That derivation is visible in the concrete:TimeSpan.FromMinutes(_jwtSettings.AccessTokenExpirationMinutes)andTimeSpan.FromDays(_jwtSettings.RefreshTokenExpirationDays)(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/TokenService.cs:197and: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 signedexp. DeclaringGenerateShortLivedAccessTokenand 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 itsTokenServiceproperty, 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 forwardsGenerateRefreshTokenandGetPrincipalFromExpiredTokento 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 atViewAsGrant.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'sTokenServiceproperty, for exampleMMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/AuthenticationService.cs(access token plus thespeaker_idclaim). 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
Useraggregate 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'sUsershape, 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,nulluntil 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 atMMCA.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
Useraggregate 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 asNotFoundtargeting this interface), and it is the state ITwoFactorStore returns fromGetAsync(MMCA.Common/Source/Core/MMCA.Common.Application/Auth/TwoFactor/ITwoFactorStore.cs:34) against the concreteUser. MMCA.Store'sUserlists 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
Useraggregate 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'sUseraggregate (see User). - Concept introduced: the inverted user contract. Rather than the shared auth workflow depending on a concrete
Userclass,Userimplements 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 aUseraggregate 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'sbyte[]tuple and the EF-mappedvarbinarycolumns 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. Thefalsedefault 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
Useraggregates 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 toVerifyPasswordon 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'sUseroverrides the flag with a storedIsServiceAccount { get; private set; }(MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Domain/Users/User.cs:150, set totrueonly 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
Useraggregate 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 fromMMCA.Common.Shared.Abstractions(:1). - Concept: capability interfaces layered by workflow.
[Rubric §1, SOLID]assesses interface segregation, and this is the pattern applied twice over: aUserthat only ever authenticates satisfies IAuthUser; aUserwhose app offers self-service password change implements this one and getsPasswordHashandPasswordSaltalong 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>, IPasswordChangeableUseron 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 callsChangePasswordwith 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
Userthat 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 thePasswordHashthe sign-in flow inspects) and Result fromMMCA.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 itsChangePassword: 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). LikeChangePasswordit 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 rehashableand returns when the aggregate does not implement it (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/AuthenticationServiceBase.cs:1008), and IPasswordHasher'sNeedsRehashis a default interface member that returnsfalse(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:
RehashPasswordIfNeededAsyncin AuthenticationServiceBase<TUser> is the only caller, invoked on the login path right afterIssueTokensAsync(MMCA.Common/Source/Core/MMCA.Common.Application/Auth/AuthenticationServiceBase.cs:290). Inside a best-effort wrapper it checksNeedsRehashagainst the stored hash (:688), hashes the verified password (:693), callsRehashPassword(:694), logsPasswordRehashRejectedthrough 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 sameUserInvariantschecks as a password change and assigning both without adding a domain event (:442-457), in contrast toChangePassword, which raisesUserPasswordChanged(:429). The MMCA.StoreUserimplements it too (MMCA.Store/Source/Modules/Identity/MMCA.Store.Identity.Domain/Users/User.cs:30). The flow is covered byAuthenticationServicePasswordRehashTests(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
Useraggregate 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 thatnullmeans 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) andstring? 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 leftnull, 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>, IUserPreferencesand projects both properties into a response (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/GetPreferences/GetUserPreferencesHandlerBase.cs:21,:44); the write workflow constrainswhere 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
Useraggregate 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, andConfirmEmail()'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
IsEmailConfirmedon 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
Useraggregate 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 theAcceptTermsdoc 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) andDateTime? TermsAcceptedOn(:32, UTC) are read-only andnullwhen 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 anILegalAcceptingUser(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 theUserIdentifierTypealias. 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 (AddPasskeyswithPasskeys: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), andDefaultName = "Passkey"(:35). - State:
Iddefaults to a freshGuidand is what rename and delete address (:38);UserIdisrequired(:41).CredentialIdandPublicKeyarerequired byte[](:45,:48) inside a scoped#pragma warning disable CA1819(:43-49) whose justification cites EF'svarbinaryshape and the IAuthUser precedent.SignCount(:55),Name(:64) andLastUsedOn(:70) have private setters;Transports(:61) holds comma-separated hints such asinternalorhybrid, andCreatedOn(:67) is init-only. Create(...)(:83) returnsResult<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 intoDefaultName(:109). Transport hints are best effort: an empty or oversized list is dropped tonullrather than refusing the passkey (:182-187).RecordUse(uint presentedSignCount, DateTime usedOn)(:133) applies the counter rule and returnsPasskeys.SignCountInvalidas anUnauthorizederror (: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 withPasskeys.NameInvalid(:189-190).
- Width constants published for the EF mapping:
- 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
RecordUseguarantees the rule is applied before any write. Validation lives in the factory so an oversized value surfaces as a[Rubric §4, DDD]-shapedResultfailure 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 theAddPasskeyCredentialsmigration (MMCA.ADC/Source/Hosting/MMCA.ADC.Migrations.SqlServer.Identity/Migrations/20261112192534_AddPasskeyCredentials.Designer.cs). The rules are covered byPasskeyCredentialTests(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:capabilitypermission 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, matchingPermissionRegistryandRoleValue;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) andPermissionMaxLength = 128(:179) are published column widths.Id(:182) defaults to a freshGuid.RoleandPermission(:188,:194) arerequired init-only strings.GrantedAt(:197) isrequired;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 withPermissionGrant.RoleInvalidwhen the role is blank or over 64 characters (:219-225), andPermissionGrant.PermissionInvalidwhen 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]-shapedResultfailure. 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/PermissionMaxLengthconstants 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), theViewAsGrantStatusenum fromMMCA.Common.Shared.Auth.Responses(:2), and theUserIdentifierTypealias. 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 toMaxLifetime, 15 minutes, whatever the access-token lifetime is (:30, clamp at:126-129). The grant'sIdtravels in the view-as token as itsvagclaim (:33), withStaffUserIdasact_subandTargetUserIdassub(: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), therequiredReason(:42),GrantedAtandExpiresAt(:45,:48) are init-only;EndedAt(:51),StaffDisplay(:59) andTargetDisplay(:66) have private setters. - Two
Createoverloads: 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 becomesMaxLifetime, andExpiresAt = 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, andnullwhen blank.- Lifecycle:
IsActiveAt(now)(:172) is "not ended and not expired";StatusAt(now)(:181) derivesEnded,LiveorExpired;End(now)(:193) isEndedAt ??= 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).
- Constants:
- 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 throughIsActiveAt(:143), which ViewAsGuardMiddleware relies on. ViewAsGrantLogQuery folds its search needles withNormalizeDisplay(MMCA.Common/Source/Core/MMCA.Common.Application/Auth/ViewAs/ViewAsGrantLogQuery.cs:36,:41); EFViewAsGrantStore runsForgetDisplayOfduring erasure (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Auth/EFViewAsGrantStore.cs:161); andViewAsGrantsAdminControllerBaseprojectsStatusAtinto 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), theUserIdentifierTypealias, and from the BCLSystem.Security.Cryptography.SHA256,System.Text.Encoding, andConvert.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:IpAddressandUserAgentidentify the data subject's device and network, so both carry[Pii]andAnonymizeclears 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 implementIAnonymizable(MMCA.Common/Source/Hosting/MMCA.Common.Testing.Architecture/Rules/Governance/ArchitectureRules.Governance.cs:10).
- Hash at rest. The plaintext refresh token exists only in the response that hands it to the client; the row keeps
- 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 reasonsReasonRotated(:58),ReasonSignedOut(:61),ReasonReuseDetected(:64),ReasonSessionCap(:67, value"SessionCapExceeded"), andReasonAccountDeleted(:70, value"AccountDeleted", recorded when a session is revoked because its account was deleted and erased). Publishing the widths aspublic conston 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):Iddefaults to a freshGuid(:73);UserId,TokenHash,CreatedAtandExpiresAtarerequiredandinit-only (:76-85), so a session cannot be constructed without them and cannot be rewritten afterwards. Three revocation members carryprivate setand change only throughRevoke:RevokedAt(:88),ReplacedByTokenHash(:94),ReasonRevoked(:97).IpAddress(:105) andUserAgent(:112) are optional capture, each marked[Pii](:104,:111) and alsoprivate set: they are written once byCreateand afterwards only cleared byAnonymize, never set from outside. TheUserAgentcomment (:100-103) gives the reason for its marking: alongside the IP it fingerprints the data subject's device. The comment onIpAddress(: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) andIsActiveAt(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 returningResult<RefreshSession>in the framework's standard shape (see the primer on factory methods and the Result pattern). Two guards: a blank token fails withRefreshSession.TokenRequired(:140-146), and an expiry at or before creation fails withRefreshSession.ExpiryInPast(:148-154), bothError.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 oversizedUser-Agentheader from turning a login into a database error.HashToken(string refreshToken)(:180-184):Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(refreshToken))), guarded byArgumentException.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 no0xprefix, and thevarcharconversion 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), returningError.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 nullsIpAddressandUserAgentand returnsResult.Success(). UnlikeRevokeit 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.
- Width and reason constants (
- 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/Anonymizeas 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 withReasonSessionCapwhen a user is atRefreshSessions:MaxActiveSessionsPerUser(:427, documented at:409; default 10 atMMCA.Common/Source/Core/MMCA.Common.Application/Auth/RefreshSessionSettings.cs:35). ItsListActiveAsyncfilters withIsActiveAtand projectsIpAddressandUserAgentinto RefreshSessionSummaryResponse for the "your devices" list (AuthSessionIssuer.cs:205-214). RefreshSessionRevocation also revokes withReasonSignedOut(MMCA.Common/Source/Core/MMCA.Common.Application/Auth/RefreshSessionRevocation.cs:52). The erasure path isRefreshSessionRevocation.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 withReasonAccountDeleted(:87) and callsAnonymizeon 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.TryRotateAsyncrevokes withReasonRotatedand links the successor (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/IRefreshSessionStore.cs:195; the EF implementation does it as a conditionalExecuteUpdate,MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Auth/EFRefreshSessionStore.cs:353,:142). The table is mapped throughApplyRefreshSessionConfiguration(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Auth/RefreshSessionModelBuilderExtensions.cs:50), which the internalRefreshSessionModelContributorapplies only whenRefreshSessions:Enabledis set and the source is the oneRefreshSessions:DataSourceNamenames (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
Useraggregate 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(),:1and: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 aDelete(). But an app'sUsermay 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 writinguser.Delete()would bind to the base implementation and silently skip the app's version. Because the appUserlists this interface in its own base list, the interface map resolves to the most derivedDelete()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 isResult 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), thenerasable.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>, IErasableUseron 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 callsbase.Delete()and raises aUserDeleteddomain 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 hideDelete()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-typedUserId, 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 touchingHttpContext. - Depends on:
System.Security.ClaimsandIParsable<T>(BCL,:1) plus the solution-wideUserIdentifierTypealias (: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 onIHttpContextAccessor, 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) andIsInRole(: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-22steering callers toRolesorIsInRolefor membership checks.Roles(:46-61) is the interesting member: it reads every role claim throughUser.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.Rolewhen inbound claim mapping is on, or the rawrole/rolesclaim when it is off,ClaimsPrincipalExtensions.cs:92-94) and returns an empty sequence for a null principal (ClaimsPrincipalExtensions.cs:61-62), soUseris null-guarded even though the property is declared non-nullable (comment at:50-51). It then falls back to a single-element list built fromRolewhen 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-45justify 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 onlyRole, 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 aNullReferenceException. 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 returnsnullwhen the claim is missing or unparseable, which is how a module reads its own claim (the doc namesspeaker_id,:65) without Common ever knowing that claim exists.IsInRole(string roleName)(:83-84) isRoles.Any(role => string.Equals(role, roleName, StringComparison.OrdinalIgnoreCase)). - Why it's built this way: the remarks at
:79-82record the reasoning behindIsInRolechecking every claim rather than comparing againstRole. 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. TypingUserIdas 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 theRolesset 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.UserIdinto every save (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/Factory/DbContextFactory.cs:69, used at:297,:340,:370,:431and:482); and it backs the ownership check in OwnerOrAdminFilter and the framework's account controllers. - Caveats / not-in-source:
Roledeliberately reports only the first role claim; treat it as a display value and useRolesorIsInRolefor 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) andSystem.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 slowPasswordHasher; this secret is 256 bits ofRandomNumberGeneratoroutput, 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) andHashByteLength = 32(:21, the SHA-256 output size); the second is the length every stored hash is checked against.Generate()(:25) drawsSecretByteLengthbytes fromRandomNumberGenerator.GetBytesand base64url-encodes them through the privateBase64UrlEncode(: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 onnull, then returnsSHA256.HashDataover 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) returnsfalsefor an empty slot or a stored hash of the wrong length, and otherwise defers toCryptographicOperations.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:
MachineClientvalidates hash lengths againstHashByteLength(MMCA.Common/Source/Core/MMCA.Common.Domain/Auth/MachineClients/MachineClient.cs:79,138) and callsHashplusMatchesinAccepts(MachineClient.cs:116-118);MachineClientServicecallsGenerateandHashon create and rotate (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/MachineClients/MachineClientService.cs:165-166,210-211);MachineClientModelBuilderExtensionssizes both hash columns withHashByteLength(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 byGuid),MachineClientSecret,ResultandError; theUserIdentifierTypealias 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:PrimarySecretHashalways holds one,SecondarySecretHashholds 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 returningResult, 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 nullableSecondarySecretHash(:41), bothbyte[]under a scopedCA1819suppression because that is EF Core's nativevarbinaryshape (:36,42);SecretExpiresOn,RevokedOnandLastUsedOn(:45,48,51), all nullable UTC instants; and the computedIsRevoked => RevokedOn is not null(:54). Create(:63-99): throws on anullhash, trims the name and failsMachineClients.NameInvalidwhen it is empty or over 100 characters (:73-77), failsMachineClients.SecretHashInvalidwhen the hash is notHashByteLengthbytes (:79-83), and failsMachineClients.SecretExpiryInvalidwhen an expiry is not afterutcNow(:85-89). On success it assignsId = 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):falsefor a null or empty secret; otherwise hashes it once and runsMatchesagainst BOTH slots before evaluating anything else (:116-118), so the short-circuit overIsRevokedand the expiry check (:121) "leaks no timing" (:120). The expiry is exclusive: the secret works only whileutcNow < expiry.Rotate(byte[])(:130-146): failsMachineClients.Revokedon a revoked client, failsSecretHashInvalidon 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): failsRevoked, or the conflictMachineClients.NoSecondarySecretwhen 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) isRevokedOn ??= utcNow: idempotent, keeping the first instant.RecordUse(DateTime)(:177) stampsLastUsedOn. The privateRevokedhelper builds the sharedMachineClients.Revokedconflict error (:179-180).
- State:
- 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 (
AddMachineClientswithMachineClients:Enabled), in the Identity database alone (MachineClient.cs:17-18). - Where it's used:
MachineClientServicecallsAcceptsbefore minting a token (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/MachineClients/MachineClientService.cs:96), runsCreatetwice on create, first with adefaultservice-account id purely to validate the name and expiry before any account is provisioned, then for real (MachineClientService.cs:167,179), and callsRotate,PromoteandRevoke(:182,201,227).IMachineClientStoreis its persistence contract;EFMachineClientStorecallsRecordUse(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/MachineClients/EFMachineClientStore.cs:74) andMachineClientModelBuilderExtensionsmaps it. In ADC the table first appears in the Identity migration20261112192549_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
UserIdentifierTypealias (the per-moduleglobal usingidentifier alias, ADR-048). Four positional parameters, all BCL primitives. - Concept: the same cache-DTO rule PasswordResetEntry demonstrates: a value round-tripped through
System.Text.Jsonin a distributed cache must be a JSON primitive, so the token digest travels as Base64 text (TokenHashBase64,:170) rather than asbyte[], and the expiry as Unix seconds (ExpiresAtUnixSeconds,:173) rather than asDateTimeOffset.[Rubric §11, Security]applies through the same member name convention:TokenHashBase64, neverToken, 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
recordgives thewithexpression the attempt-counter rewrite relies on (entry with { FailedAttempts = attempts },MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/EmailConfirmationTokenService.cs:193). Beinginternalkeeps 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 byValidateAndConsumeAsync(:85), and rewritten byRecordFailedAttemptAsync(: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
JsonWebKeySetserved 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.IJwksProvideris 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.jsonstays 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 theJwksSettingsoptions binding (:240-243); the JWKS minimal-API endpoint calls it, and consuming services fetch the resulting document throughAddForwardedJwtBearerat 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 ownalg, 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) andES384 = 3(:35, ECDSA on P-384 with SHA-384 overEcPrivateKeyPem+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:SigningAlgorithmnever 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:
IsAsymmetricanswers true for every value except HS256 (MMCA.Common/Source/Build/Auth/JwtAlgorithms.cs:38),UsesEcKeytrue for ES384 only (:43),ToSecurityAlgorithmreturns the JOSEalgname (:49-56), andAcceptedForreturns 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:274and:265. Each fails with a namedInvalidOperationExceptionwhen its key material is missing: the asymmetric builder namesEcPrivateKeyPemorRsaPrivateKeyPemand the selected algorithm (:283-287), the HMAC builder throws throughJwtSettings.DecodeHmacSigningKey(:269). - The API layer branches on the same value when configuring in-process JWT bearer validation:
BuildValidationParameterstakes 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 atAddForwardedJwtBearerfor services that fetch the key through JWKS at runtime instead (:231-235).
- 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
- 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, andBuildValidationParametersin 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 theLoginProtectionconfiguration section (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/LoginProtectionSettings.cs:5-7). - Depends on:
System.ComponentModel.DataAnnotationsfor[Range](BCL,:1). Consumed by LoginProtectionService throughIOptions<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: fiveinit-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) andRegistrationRateLimitWindowMinutes(default 60,[Range(1, 1440)],:42-43).
- Account lockout:
- Why it's built this way:
sealedwithinit-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 asMaxFailedAttempts = 0fails the host at startup instead of quietly disabling lockout until someone notices in production. TheMaxLockoutSecondsupper 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
UserIdentifierTypealias (the per-moduleglobal usingidentifier 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 throughSystem.Text.Json, so every member is a JSON primitive. A value object such as Email or a rawbyte[]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 asbyte[]andDateTimeOffset.[Rubric §11, Security]also applies through one member name:TokenHashBase64, notToken. 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
recordgives the non-destructivewithexpression 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. Beinginternalkeeps 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 byValidateAndConsumeAsync(:100), and rewritten byRecordFailedAttemptAsync(: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
Jwtsection: 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, plusSystem.ComponentModel.DataAnnotationsfor[Required],[Range]and, critically, for theIValidatableObjectinterface (:1,:20), andSystem.Globalizationfor the invariant-culture failure message (:2,:168). - Concept introduced:
IValidatableObjectfor conditional requirements. Attributes describe a property in isolation, so they cannot say "this one is required only when that one has a particular value".IValidatableObjectis the options-validation extension point for exactly that case: the type implements a singleValidatemethod that yields oneValidationResultper 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 decodesSecretForKeyas 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), andValidateappends advice to replace the placeholder with a real secret from user-secrets or environment variables (:114-119). The same private check sits behind the publicDecodeHmacSigningKey(: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:MinimumRsaKeySizeBitsapplies 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 byValidate.[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 andValidaterun at boot, not on the first token issued (ADR-070). - Walkthrough: one static field, one constant, eleven
initproperties, two public methods and one private helper.SectionName = "Jwt"(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/JwtSettings.cs:23) andMinimumHmacKeyBytes = 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 setsJwt:SigningAlgorithmgets 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-inappsettings.json(:39-43);RsaPrivateKeyPem(:51) andRsaPublicKeyPem(:59), read under RS256 and PS256 (:46-50,:53-58);EcPrivateKeyPem(:65) andEcPublicKeyPem(:72), the P-384 pair read under ES384 (:61-64,:67-71). None carries[Required], because whether it is required is decided inValidate. 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), default3072, with[Range(2048, int.MaxValue)](:80) so a value below 2048 is itself a configuration error (:74-79).Issuer(:85) andAudience(:89): both[Required](:84,:88), because they matter in every mode.AccessTokenExpirationMinutes(:97), default15;RefreshTokenExpirationDays(:104), default7. 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 reasonCheckHmacSigningKeyreturns yields a failure namingSecretForKey(:114-119); under RS256 or PS256, a null or whitespaceRsaPrivateKeyPemyields a failure namingRsaPrivateKeyPemand the selected algorithm (:121-126); under ES384, a null or whitespaceEcPrivateKeyPemyields a failure namingEcPrivateKeyPem(: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 throwsInvalidOperationExceptioncarrying 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, ornullwith the decoded bytes: null or whitespace (:153-156), aFormatExceptionfromConvert.FromBase64String(:158-165), or fewer thanMinimumHmacKeyBytesdecoded 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 (EcPublicKeyPemfor ES384,RsaPublicKeyPemotherwise), and the message points atAddForwardedJwtBearerfor 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 throughIOptions<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 atMMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/PasswordHasher.cs:4, declared atMMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Auth/IPasswordHasher.cs:6, whoseNeedsRehashmember defaults tofalseso a custom hasher never triggers a rehash,MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Auth/IPasswordHasher.cs:28, and whoseBurnVerificationCostmember defaults to one discardedHashPassword,:39). Externals are BCL only:System.Buffers.Binary(BinaryPrimitives),System.Security.Cryptography(Rfc2898DeriveBytes,RandomNumberGenerator,CryptographicOperations) andSystem.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. AndVerifyPasswordaccepts 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, whichFixedTimeEqualsanswerstruefor. 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 atBurnIterations(:67), which is the current work factorIterations, 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 boundsMinIterations = 100_000(:52) andMaxIterations = 2_000_000(:58). One constant isinternalrather than private:BurnIterations(:67), set toIterations(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 withArgumentException.ThrowIfNullOrWhiteSpace(:72), draws a fresh salt fromRandomNumberGenerator.GetBytes(SaltSize)(:74, the cryptographic RNG and notRandom), derives 64 bytes at the currentIterations(:75), then lays out the versioned hash: the version byte, the iteration count viaBinaryPrimitives.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 returnsfalseimmediately unless the salt is exactlySaltSizebytes andTryReadIterationsrecognizes the hash (:99-102). It takes the trailingHashSizebytes as the expected digest (:104), recomputes the derivation over the stored salt at the stored work factor (:105), and returnsCryptographicOperations.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 oneComputePbkdf2Hashover a fresh salt atBurnIterations(: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 discardedHashPassword) would burn (MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Auth/IPasswordHasher.cs:30-40); the override ties the burn to the namedBurnIterationsconstant and skips building the versioned buffer.NeedsRehash(byte[] hash)(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/PasswordHasher.cs:130-136) answerstruefor a recognized legacy 64-byte hash and for a versioned hash whose stored count differs fromIterations(:134-135); unrecognized material answersfalse, 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 yieldsLegacyIterations(:145-149); a 69-byte hash whose first byte isFormatVersionyields 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 atHashSizeoutput, which is what keeps the write path and the verify path from drifting apart.
- Private constants carry the whole policy:
- 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
NeedsRehashtells 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 privateBurnPasswordVerificationCostat:958-966, which calls the port'sBurnVerificationCostat:965), and after a successful sign-in callsRehashPasswordIfNeededAsync(:302), which re-derives and saves the hash only when the user implementsIPasswordRehashableUserandNeedsRehashanswerstrue(: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); andResetPasswordHandlerBase<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
Useropts in throughIPasswordRehashableUser(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, throughBestEffortwithCancellationToken.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 theBurnIterationsdoc 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.csfile:ResolvePem(pem, path)turns an inline-PEM-or-path pair into PEM text, the algorithm-awareResolvePem(algorithm, rsaPem, rsaPath, ecPem)picks the material that algorithm reads, andCreatePublicKey(algorithm, pem, keyId)turns PEM text into a public-onlyAsymmetricSecurityKey(RSA or ECDSA) stamped with akid(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 theMMCA.Common.Authimport (:5). BCLFile, andAsymmetricSecurityKeyfromMicrosoft.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 consumeCreateAdditionalValidationKeyscannot 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 aCryptographicException(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 answersnulland a set path answersFile.ReadAllText(path)(:263). The comment at:262justifies 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, ornullwhen 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 toJwtKeyMaterial.CreatePublicKey, which imports into ausing-scopedRSAor P-384ECDsaand wraps the exported public parameters (MMCA.Common/Source/Build/Auth/JwtKeyMaterial.cs:74-96). AnRsaSecurityKeyholds parameters and needs no disposal; anECDsaSecurityKeyowns a fresh public-onlyECDsainstance (:80-81), which is whyJwksSettings.LoadFailuredisposes 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:
internalkeeps 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.BuildKeySetfor the current key (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/RsaJwksProvider.cs:51-52,:59) andJwksAdditionalKey.CreateValidationKeyfor 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 forAlgorithm(:219); JwtAlgorithms for the key-type check in the failure message (:240);System.ComponentModel.DataAnnotationsfor[Required]and[StringLength](:1);AsymmetricSecurityKeyfromMicrosoft.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 ownalgand 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 tostring.Empty. It is published as the JWKkidand 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 JWKalg, and must be asymmetric; RS256 and PS256 read the RSA material, ES384 readsEcPublicKeyPem(:214-218).RsaPublicKeyPem(:222), which wins overRsaPublicKeyPath(: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-awareJwksKeyMaterial.ResolvePemand throws anInvalidOperationExceptionnaming thekidand the material that algorithm reads when it is not set (:239-242), then returnsJwksKeyMaterial.CreatePublicKey(Algorithm, pem, KeyId)(:244). The result is anAsymmetricSecurityKey: anRsaSecurityKeyor anECDsaSecurityKey. Only public parameters are kept, so a private PEM supplied by mistake still yields only the public half (:230-236); an ECDSA result owns itsECDsainstance, 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 itsAlgorithmreads 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.Validatere-checks the key id, rejects duplicates, rejects a non-asymmetric algorithm and missing material, and loads every entry throughCreateValidationKeyat startup (:91-126,:135-152,:160-176) (ADR-070). - Where it's used:
JwksSettings.CreateAdditionalValidationKeysmaps every entry throughCreateValidationKey(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 callsCreateValidationKeyper entry itself, so it can publish each key under its ownAlgorithm(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), andinternal 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 BCLSHA256,Convert.ToHexStringandEncoding.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 throughEmailIdentity.KeySegment, so the normalization rule (and the scoped#pragma warning disable CA1308that 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) returnsstring.Emptyfor a null, empty or whitespace-only input (:38-39); otherwise it callsEmail.Create(email)(:41) and returns the normalizedValuewhenTryGetValuesucceeds, oremail.Trim().ToLowerInvariant()on failure (:43), under#pragma warning disable CA1308(:42-44) because that fallback intentionally matchesEmail's own RFC 5321 lowercase normalization.
- Why it's built this way:
internal statickeeps 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 callKeySegment; unit-tested directly byEmailIdentityTests(MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Auth/EmailIdentityTests.cs), andAuthCacheKeyPrivacyTests(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
Jwkssection 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 whenJwt:SigningAlgorithmis 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 implementsIValidatableObject(: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 fromMMCA.Common.Auth(:5). From the BCL and libraries:System.ComponentModel.DataAnnotationsfor[StringLength]andIValidatableObject(:1),System.Globalizationfor the invariant member names in failure messages (:2,:98),System.Security.Cryptographyfor theCryptographicExceptionthe load check catches (:3,:172), andAsymmetricSecurityKeyandECDsaSecurityKeyfromMicrosoft.IdentityModel.Tokens(:4,:165,:183). Consumed by RsaJwksProvider and TokenService throughIOptions<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 flipsEnabled. Thekidcontract is the subtle part:KeyIdis published as the JWKkidand must match thekidheader 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 stampingKeyIdonto every asymmetric token it signs (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/TokenService.cs:68-73,:98,:296). The same contract is whyValidaterejects 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. Thealgfollows the key: the current key is published with the algorithm ofJwt: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 tofalsewith 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) andRsaPublicKeyPath(: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 whenJwt:SigningAlgorithmis ES384, and is ignored for the RSA algorithms (:62-65).AdditionalKeys(:81), anIReadOnlyList<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 currentKeyId(: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), whenConfigurationFailurereports 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 makesValidateOnStartfail 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 whoseAlgorithmis not asymmetric, because a published key never validates HS256 (:137-140); for ES384 requiresEcPublicKeyPem(:142-147); for RS256 and PS256 requiresRsaPublicKeyPemorRsaPublicKeyPath(:149-151).LoadFailure(JwksAdditionalKey)(:160-176): loads the key the way every validator will, through JwksAdditionalKey.CreateValidationKey, disposes theECDsainstance 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), ornullwhen the key loads.CreateAdditionalValidationKeys()(:183-184): oneAsymmetricSecurityKeyper 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>inPublicationOnlymode (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/RsaJwksProvider.cs:31-32), returns an empty set whenEnabledis false (:44-47), resolves the current PEM by the current key's algorithm through JwksKeyMaterial (:51-52), publishes the current key underKeyIdfirst (:59) and every additional key after it (:63-66), and sets each JWK'salgfrom 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()inAddInfrastructure(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 tonew JwksSettings().KeyIdwhen 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 ownemailconfirm: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 viaIOptions<>(: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 BCLSHA256,RandomNumberGenerator,CryptographicOperations, andSystem.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. TheTokenKeydoc 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.KeySegmentinstead 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 ofIssueAsynccalls 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 aRetry-Afterbound, like the lockout. One place it departs from its password-reset sibling: redemption reads throughGetFromSharedStoreAsyncbut 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;_settingsis the snapshottedEmailConfirmationSettings(:50). The primary constructor takesICacheService,ICounterStore,IOptions<EmailConfirmationSettings>andTimeProvider(:42-46).IssueAsync(string email, UserIdentifierType userId, CancellationToken)(:53-88): increments the per-email request counter in the counter store with the configuredRequestWindowMinuteswindow (:59-62) and, once the count exceedsMaxRequestsPerEmail, fails withError.TooManyRequests("Authentication.ConfirmationThrottled", ...)whoseRetryAfteris 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 withBase64Url.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) andValidateAndConsumeAsync(:98-102), each(string email, string token, CancellationToken), both delegate to the privateValidateCoreAsyncwithconsume: falseandconsume: 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 whenconsumeis set.ValidateCoreAsync(:113-158): loads the entry withGetFromSharedStoreAsync(: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 returnsInvalidToken()when there is none (:124-127); aFormatExceptiondecoding the stored Base64 removes the unreadable record rather than leaving it to expire (:129-139); the comparison isCryptographicOperations.FixedTimeEqualsover the two digests (:141), withtoken ?? string.Emptyso a null token hashes rather than throwing; a mismatch records a failed attempt and returns the same generic failure (:141-145). On a match withoutconsumeit returns the entry'sUserIdand leaves the token live (:147-150). On a match withconsumeit 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'sUserId(:157).TokenKey,RequestKey,HashToken(:160-173):TokenKeyandRequestKeyeach call EmailIdentity.KeySegment(:168,:170), producingemailconfirm:token:{hex SHA-256}andemailconfirm:req:{hex SHA-256}keys;HashTokenis the shared SHA-256 helper for the token itself (:172-173).RecordFailedAttemptAsync(:175-196): computesattempts = entry.FailedAttempts + 1and the remaining lifetime fromExpiresAtUnixSecondsagainst the injected clock (:180-181). AtMaxValidationAttempts, or once the remaining lifetime is non-positive, it deletes the record (:183-187); otherwise it rewrites the entry withentry with { FailedAttempts = attempts }at the remaining TTL, not a fresh one (:189-195).InvalidToken()(:198-200) is the single failure factory built fromEmailConfirmationErrors.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
TimeProviderrather than readingDateTimeOffset.UtcNowlets 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 theEmailConfirmationSettingsbinding (: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 throughValidateAsyncstays 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 aRetry-Afterheader (:34-39), and the registration limit answers the same way with its window as the bound. Each account entering lockout is counted once on themmca.auth.lockoutmetric. - Depends on: ILoginProtectionService (the Application port,
MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/LoginProtectionService.cs:47); LoginProtectionSettings viaIOptions<>(:45, snapshotted at:69); ICacheService (:43) for the lockout flag and its expiry; ICounterStore (:44) for the attempt and registration counters; an optionalILogger<LoginProtectionService>defaulting toNullLogger(:46,:70); an optionalTimeProviderdefaulting toTimeProvider.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.Metricsfor the lockout counter (:1); and from the BCLSHA256andEncodingfor 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,AttemptsKeyandLockoutUntilKeyeach 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, soUser@x.com,user@x.comand" 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.KeySegmentthen 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:IpKeySegmenthashesClientAddressKey.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:LogKeyHashkeeps only the firstLogKeyHashLength = 12hex 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 toint.MaxValue(:168), driveslockoutSeconds = 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 innerMath.Min(excessAttempts, 30)clamps the shift exponent, and the comment explains why (:170-173): C# masks anintshift count to five bits, so1 << 31is negative and1 << 32wraps back to1, which would silently shrink the lockout for a sufficiently persistent attacker. Since1 << 30already exceeds the[Range(1, 3600)]cap on LoginProtectionSettings.MaxLockoutSeconds, deep excess always lands on the cap.
- Key normalization and hashing (
- Walkthrough
- Key builders:
LockoutKeyproduceslogin:lockout:{hex SHA-256 of the normalized address}(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/LoginProtectionService.cs:82),AttemptsKeyproduceslogin:attempts:{...}(:84),LockoutUntilKeyproduceslogin:lockout-until:{...}(:91), andRegistrationKeyproducesregistration:ip:{hex SHA-256 of the client's partition key}(:284, viaIpKeySegmentat:286-287). The expiry lives under its own key rather than in a richer lockout value, because a flag already cached astruemust 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);Lockoutsis themmca.auth.lockoutcounter, 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 throughGetFromSharedStoreAsync(: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 theIsCacheOutagefilter (:114), logged, and answered withResult.Success()(:116-117), so the check fails open rather than locking everyone out. When locked, it returnsError.TooManyRequests("Auth.TooManyAttempts", ...)withRetryAfterset to that remaining time (:125-129).RemainingLockout(long?)(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/LoginProtectionService.cs:137-146):nullwhen 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 theFailedAttemptWindowMinuteswindow (: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 reachesMaxFailedAttemptsit 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 tommca.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 reachesMaxRegistrationsPerIpPerHour, fails withError.TooManyRequests("Auth.RegistrationRateLimitExceeded", ...)whoseRetryAfteris the fullRegistrationRateLimitWindowMinuteswindow (:238-246). The comment gives both halves of that choice (:235-237): a rate limit is a 429 with aRetry-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 returnsResult.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 theRegistrationRateLimitWindowMinuteswindow (: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);LogFailedAttemptRecordedat Information (:308-310); andLogLockoutTrippedat Warning (:312-314), the last two carrying only the truncated key hash.
- Key builders:
- 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 theLoginProtectionSettingsbinding (: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 exampleMMCA.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 registrationRetry-Afteris 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 viaIOptions<>(: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 BCLSHA256,RandomNumberGenerator,CryptographicOperations, andSystem.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), soSetAsyncoverwrites (: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.
- Hashed at rest. Only
- Walkthrough
- Primary constructor takes
ICacheService cacheService,ICounterStore counterStore,IOptions<PasswordResetSettings> settings,IDistributedLock distributedLockandTimeProvider timeProvider(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/PasswordResetTokenService.cs:34-39), snapshottingsettings.Valueinto_settings(:47).TokenByteLength = 32(:41) is the one constant; two static timeouts govern the redeem lock,RedeemLockTimeToLiveof 10 seconds (:43) andRedeemLockWaitof 5 seconds (:45). TokenKeyandRequestKey(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 giveUser@x.comanduser@x.comindependent tokens and independent request counters while resolving to one account.TokenKeyproducespwdreset:token:{hex SHA-256 of the normalized address}(:55) andRequestKeyproducespwdreset:req:{...}(:57), so the address itself never appears in a key.HashTokenis 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 theRequestWindowMinuteswindow (:69-72), an atomic fixed window that opens on the first request and is never extended (:68), and once the count exceedsMaxRequestsPerEmailfails withError.TooManyRequests("Auth.ResetThrottled", ...)whoseRetryAfteris 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 withBase64Url.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 locklock:{key}with the 10-second TTL and a 5-second wait (:111-113). A null handle (contended or unavailable) returnsInvalidToken()(:114-117); otherwise it runsRedeemAsyncinside anawait usingover the handle, so the lock is released however the redemption ends (:119-122). The comment at:108-110states 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 withGetFromSharedStoreAsync(:133) and returnsInvalidToken()when there is none (:134-137). AFormatExceptiondecoding the stored Base64 removes the unreadable record rather than leaving it to expire (:139-149). The comparison isCryptographicOperations.FixedTimeEqualsover the two digests (:151), the same timing-side-channel defense PasswordHasher uses, withtoken ?? string.Emptyso 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'sUserId(:162).RecordFailedAttemptAsync(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/PasswordResetTokenService.cs:165-186): computesattempts = entry.FailedAttempts + 1and the remaining lifetime fromExpiresAtUnixSecondsagainst the injected clock (:170-171). AtMaxValidationAttempts, or once the remaining lifetime is non-positive, it deletes the record (:173-177). Otherwise it rewrites the entry withentry 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 oneAuth.InvalidResetTokenerror with one message. That uniformity is deliberate: distinct errors would make the endpoint an oracle for which addresses have an outstanding reset.
- Primary constructor takes
- 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
TimeProviderrather than readingDateTimeOffset.UtcNowlets 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 thePasswordResetSettingsbinding (:179-182). ForgotPasswordHandlerBase<TUser, TCommand> callsIssueAsyncand emails the resulting link (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/ForgotPassword/ForgotPasswordHandlerBase.cs:124); ResetPasswordHandlerBase<TUser, TCommand> callsValidateAndConsumeAsync(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
JsonWebKeySetfrom the PEM-encoded public keys configured via JwksSettings, the current key first and then every additional key, each published with its ownalg,ktyand key-type members (n/efor RSA,crv/x/yfor 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 optionalIOptions<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); andMicrosoft.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 aLazy<JsonWebKeySet>(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/RsaJwksProvider.cs:31-32), but the mode isLazyThreadSafetyMode.PublicationOnly, not the defaultExecutionAndPublication. The comment above it (:26-30) explains why, and it is worth internalizing: the defaultLazy<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.PublicationOnlycaches only a successful result and lets a later call retry; concurrent factory runs are harmless here becauseBuildKeySetis pure and keeps no key instance. That is[Rubric §29, Resilience]reasoning applied to one field declaration. A second, smaller point: the current key'salgis 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 publishedalgand the token header in agreement (ADR-149). - Walkthrough
- The primary constructor takes
IOptions<JwksSettings> optionsand an optionalIOptions<JwtSettings>? jwtOptions(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/RsaJwksProvider.cs:24), and theLazy<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 withoutJwtSettings, 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 emptyJsonWebKeySetwhen!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-50notes 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 throughJwksKeyMaterial.CreatePublicKey(currentAlgorithm, pem, settings.KeyId)(:59), then each additional key fromadditional.CreateValidationKey()underadditional.Algorithm(:63-66); the comment gives the ordering rule (:61-62): signing never uses an additional key, and a validator that ignoreskidand 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): anECDsaSecurityKeyis converted withJsonWebKeyConverter.ConvertFromECDsaSecurityKeyinside ausingover itsECDsa, because the JWK carries the public point and the instance is not kept (:74-81); anything else is converted withConvertFromRSASecurityKey(:84). The JWK is markedUse = "sig"(:87) andAlg = JwtAlgorithms.ToSecurityAlgorithm(algorithm)(:88), so consumers know each key's purpose and algorithm.
- The primary constructor takes
- 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 ispartialonly so the source-generated[LoggerMessage]method at its foot can be emitted (:343-344). - Depends on:
ITokenService(the port it implements) andIDisposable(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/TokenService.cs:29);JwtSettings,JwtSigningAlgorithmandJwksSettings, the two options bound throughIOptions<T>(:75,:79), withJwksSettings(Level 5) being what puts this type at Level 6;JwtAlgorithmsfor the accepted-algorithm list and the JOSEalgname (:93,:297) andJwtKeyMaterialfor PEM import (:326-327);IPermissionRegistry, a required constructor dependency (:32,:76) that supplies the role-to-permission map baked into every access token; and anILogger<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, andTimeProviderfor 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,GetPrincipalFromExpiredTokensetsValidateLifetime = falseon 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:ValidAlgorithmslimits validation to the list this issuer's key type accepts (:224), and the token header'salgis re-checked against the same list with an ordinal comparison after validation succeeds (:233-237). The list comes fromJwtAlgorithms.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 thatRsaJwksProviderpublishes (ADR-004). Under an asymmetric algorithm the refresh flow also accepts the additional keysJwksSettingspublishes (: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, requiredTimeProviderwith noTimeProvider.Systemfallback (:77,:87), resolved from whatever DI registration adds it in the container'sAddServicescall (the parameter doc says so at:58-61), so a test passes its own and can assertiat/nbf/expwithout waiting for wall-clock time to pass. A third,[Rubric §20, Policy and Enforcement Points]concept sits in the sharedMinthelper: every access token carries oneAuthClaimTypes.Permissionclaim per permissionIPermissionRegistrygrants 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 resolvesUnconfiguredPermissionRegistry, 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 inGetPrincipalFromExpiredToken(: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 injectedIPermissionRegistry(:32), theTimeProvider(:33), theILogger<TokenService>(:34), theSigningCredentialsused to sign and theSecurityKeyused to validate (:35-36), the list of additional validation keys defaulting to empty (:37), the list of algorithms validation accepts (:38), and two nullable ownedAsymmetricAlgorithmhandles, each anRSAor anECDsa(:42-43). The comment at:40-41explains whyIDisposableis 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) takesIPermissionRegistry permissionRegistryandILogger<TokenService> loggeras required parameters, null-guarded alongsidejwtOptions(:81-83) and assigned to_permissionRegistryand_logger(:86,:88).TimeProvider timeProvideris likewise a required parameter with no default (:77), assigned straight to_timeProviderwith 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 throughBuildAsymmetricCredentials; the key id it passes isjwksSettings?.Value.KeyIdfalling back to a defaultJwksSettingsinstance (:97-98), which is how the samekidends 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 throughCreateAdditionalValidationKeys(: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) andGenerateShortLivedAccessToken(..., TimeSpan lifetime)(:122-133) both delegate to the privateMint. The first passesAccessTokenExpirationMinutes(:119); the second rejects a zero or negative lifetime withArgumentOutOfRangeException(: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 withCultureInfo.InvariantCulture),jti(a fresh GUID, so a token is individually identifiable),iatas Unix seconds, and the standard name, email and role claims. The comment at:145-148is a design note worth internalizing:subis 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 throughClaimsPrincipalExtensionsinstead. Caller-supplied claims are appended (:159-162). Then, before the token is assembled, permission claims are added (:164-176):alreadyClaimedcollects anyPermissionclaim value already present inclaims(: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). AJwtSecurityTokenis then assembled with issuer, audience,notBeforefrom the injected clock andexpiresatnow + 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.AccessTokenLifetimeandRefreshTokenLifetime(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 asIssuerSigningKeyand the additional keys asIssuerSigningKeys(:222-223), validates (:231), applies the post-validationalgre-check and returnsnullwhen the token is not aJwtSecurityTokenor the header'salgis not in the accepted list (:233-237). The failure path is two catches. ASecurityTokenExceptionorArgumentException(bad signature, wrong issuer or audience, malformed input) returnsnullwithout 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-generatedLogUnexpectedValidationFailure(:253, declared at:343-344) and still answered withnull(: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) decodesSecretForKeythroughJwtSettings.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 throwsInvalidOperationExceptionhere too. The decoded bytes become oneSymmetricSecurityKeyused 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 missingEcPrivateKeyPemorRsaPrivateKeyPemand the selected algorithm (:283-287), and imports the private key throughImportKey(:289), which callsJwtKeyMaterial.ImportP384orImportRsa(: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 withWrapKey, which stamps the key id on anECDsaSecurityKeyor anRsaSecurityKey(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/TokenService.cs:296,:329-334), so every asymmetric token carries akidheader, and signs withJwtAlgorithms.ToSecurityAlgorithm(algorithm)(:297). The comment at:292-295gives the reason for thekid: 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 throughPublicHalfOf(: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 nestedtry/catchblocks 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.
- Fields (
- 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 underlyingRSAat end-of-request while the staticCryptoProviderCacheinMicrosoft.IdentityModel.Tokensstill held the cachedAsymmetricSignatureProviderwrapping it (:387-390), throwingObjectDisposedExceptionon the next RS256 sign. Singleton is correct because the constructor depends only on singletons (the JWT and JWKS options, the permission registry,TimeProviderand 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 resolvesIPermissionRegistryand the logger from the container alongside the JWT options. Consumed through the port in two places.AuthSessionIssuermints the tokens: itsAccessTokenLifetimereads 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:476and:520. The same file wraps this service in the privateSessionStampingTokenServicepass-through (:737), which appends theAuthClaimTypes.SessionId(sid) claim through theadditionalClaimsparameter (: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). Thesubclaim it writes is whatCurrentUserServiceandClaimBasedUserIdProviderread 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
UserIdentifierTypealias (ChangedBy,AuditHistoryEntryDTO.cs:42); BCLGuidandDateTime. - 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 recordofinit-only properties, the mandatory ones markedrequired.Id(:15), the identifier of the trail row.EntityType(:18), the full CLR type name of the changed entity, andEntityKey(:21), the invariant string form of its primary key.PropertyName(:27), nullable:nullon the summary row of a create or delete (:23-26).OldValue(:30) andNewValue(:33), both nullable strings.Operation(:36), one ofAdded,ModifiedorDeleted.ChangedBy(:42), nullable:nullwhen the save carried no identity, such as a background service or a seeder (:38-41).ChangedOn(:45), the UTC instant the change was recorded, andCorrelationId(: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
ChangedBynaming 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.ClaimTypesvalues (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 readersFindUserIdValue,HasMultiFactor,HasMultiFactorWithheldRoleandIsViewAs(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 oneconstholder 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 onePermissionclaim 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 inboundsubontoClaimTypes.NameIdentifierwhile a handler that materializes an identity straight from a token's claims leaves the rawsubin 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 newsid, 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 nomfaclaim 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") andMultiFactorMethodPasskey(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") andMultiFactorWithheldPermission(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 underAuthorization:MultiFactor:RequiredForRolesand the session carries nomfaclaim, and one for eachPermissionclaim 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 unlikeiatit 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 anauth_timewithin 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, whosesubis 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, whosesubis the client's service-account user.TokenUse(AuthClaimTypes.cs:140, value"token_use") is carried only by a machine token, with the valueTokenUseMachine(AuthClaimTypes.cs:146, value"machine"); a token without it was issued to a person. A machine token has no refresh token, nosid, noauth_timeand nomfa(AuthClaimTypes.cs:130-145, ADR-140).
- Walkthrough: fifteen
public const stringfields and nothing else (AuthClaimTypes.cs:24-146).constrather thanstatic readonlyso the values are usable in attribute arguments and in patterns that require compile-time constants, the same reason RoleNames usesconst. - Why it's built this way:
ADR-020 makes the
permission layer opt-in,
ADR-097 adds the
per-device session identity that
sidnames, the opt-in two-factor completion (ADR-116) addsmfaand its first two method values, ADR-139 adds the passkey method andauth_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:
Permissionis written by TokenService itself, one claim per permission the injectedIPermissionRegistrygrants 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).Subjectis written by TokenService asJwtRegisteredClaimNames.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,MultiFactorandAuthTimeare 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 tootporrecoveryand a passkey sign-in topasskey(MMCA.Common/Source/Core/MMCA.Common.Application/Auth/AuthenticationServiceBase.cs:626,901-902).sidis read back byFindSessionIdfor 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
Permissionclaim is written by every token the framework mints (TokenService.cs:164-176); a reader depending onPermissionbeing 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
Errorcode 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.EmailAlreadyExistsis 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), andMultiFactorRequiredis returned by the HTTP permission check for a role the host lists underAuthorization: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,TwoFactorInvalidandTwoFactorRecentSignInRequiredmust equal TwoFactorErrors's codes (AuthErrorCodesAlignmentTests.cs:37-40for the last),EmailNotConfirmedmust equal EmailConfirmationErrors's, andMultiFactorRequiredmust stay the literal"Authorization.MultiFactorRequired". The direction is reversed forEmailConfirmationPasswordRequired:EmailConfirmationErrors.PasswordRequiredCodeis defined as a reference to it (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/EmailConfirmation/EmailConfirmationErrors.cs:23). - Walkthrough: eight
public const stringfields.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 nomfaclaim, because the caller's role is listed underAuthorization: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), andTermsNotAcceptedis re-exposed asLegalAcceptanceErrors.TermsNotAcceptedCode(MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Legal/LegalAcceptanceErrors.cs:14); see LegalAcceptanceErrors.MultiFactorRequiredis 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).EmailConfirmationPasswordRequiredis what the confirmation page branches on to ask for a password (MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/ConfirmEmail.razor.cs:266), andTwoFactorRecentSignInRequiredis 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-7alphabet, 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,internalto 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 aslength * 5 / 8bytes (: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 digits2-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.VerifyCodecatchesArgumentExceptionand answersfalse(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/deviceand theDevicemember 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 asnull(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); andDeviceType, 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) toRefreshSession.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
Evaluatepredicate that combines them (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/PasswordComplexity.cs:5-18). - Depends on: nothing first-party; BCL
System.Text.RegularExpressionsand 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:
MinimumLengthis8(PasswordComplexity.cs:28) andMaximumLengthis128(PasswordComplexity.cs:31), bothconst intmeasured in UTF-16 code units, so they are usable in attribute arguments. Fourpublic static partial Regexproperties 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), andSpecialCharacter([^\p{L}\p{Nd}], anything that is neither a letter nor a decimal digit,:49-50).Evaluate(string? password)(PasswordComplexity.cs:52-57) returnstrueonly when the input is non-null, at leastMinimumLengthlong, and matches all four regexes. It deliberately does not checkMaximumLength: 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 callsEvaluate, 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 byMMCA.Common/Tests/Core/MMCA.Common.Shared.Tests/Auth/PasswordComplexityTests.cs. - Caveats / not-in-source: the server's length messages interpolate
MinimumLengthandMaximumLength(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 inCommonValidationRules.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
SetStoredPermissionsAsyncinto 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>andIReadOnlyList<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, ornullfor none) andChangedBy(the audit label stamped on granted rows) (:373-378).ApplySetAsyncdeconstructs 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 byApplySetAsync(: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.FixedTimeEqualsandMemoryMarshalfromSystem.Security.Cryptography,System.Buffers.BinaryandSystem.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 withCryptographicOperations.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&& !matchedguard records the first match without leaving the loop early (:64-72).matchedStepis 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) boundsdigitsto 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 scopedCA5350suppression 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 modulo10^digits, left-padding with zeros (:117-123).
- Why it's built this way: two-factor authentication is opt-in
(ADR-116); the algorithm
is
internalto 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 byMMCA.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:Enabledand 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 classderiving fromAttribute(: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:27Subject,:131Permission,:145SessionId,:162,181MultiFactor,:171ViewAsActor,:198,208MultiFactorWithheldRole,:224AuthTime); the solution-wideUserIdentifierTypealias; BCLSystem.Security.ClaimsandSystem.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 standardsubclaim 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
subontoClaimTypes.NameIdentifier, the longhttp://schemas.xmlsoap.org/...URI; - a handler that materializes an identity straight from a token's claims leaves the raw
subin place. SessionCookieAuthenticationHandler is exactly that case: it buildsnew 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
FindUserIdValuemakes both shapes resolve identically, and means a consumer that changes its claim mapping does not lose the current user (ClaimsPrincipalExtensions.cs:13-15).FindAuthTimeapplies the same two-shape rule toauth_time. Note the deliberate use of C#'s classicthis-parameter extension methods here rather than theextension(T)blocks the codebase uses for DI registration: these are plain static helpers on a BCL type.- the JWT bearer handler maps inbound
Walkthrough: thirteen extension methods, twelve on
ClaimsPrincipal?and one onClaim?, 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. Rawsubwins, the mappedNameIdentifieris the fallback, and a principal carrying neither yieldsnull.GetUserId(this ClaimsPrincipal?)(ClaimsPrincipalExtensions.cs:40-44) parses that value into the module'sUserIdentifierTypeand returnsnullwhen the claim is absent or unparsable. It parses throughIParsable<TSelf>.TryParseinCultureInfo.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 frominttoGuid.GetRoleValues(this ClaimsPrincipal?)(ClaimsPrincipalExtensions.cs:60-65) returns every role value the principal carries under any of three claim types: the standardClaimTypes.RoleURI, or the rawrole/rolesclaim 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 BCLClaimsPrincipal.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 BCLIsInRolecalls only decide which nav links are shown, not what the caller may do. The filter itself isIsRoleClaim()(ClaimsPrincipalExtensions.cs:64).IsRoleClaim(this Claim?, bool includeIdentityRoleClaimType = false)(ClaimsPrincipalExtensions.cs:85-101) is the role-claim predicate behindGetRoleValues: a null claim is not a role claim, and a claim of typeClaimTypes.Role,roleorroles(compared ordinally) is one. WithincludeIdentityRoleClaimTypeset it also matches the claim type the claim's own identity names as itsClaimsIdentity.RoleClaimType, which is whatClaimsPrincipal.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) isGetRoleValues().Contains(role, StringComparer.OrdinalIgnoreCase), guarded against a blank role.HasPermissionClaim(this ClaimsPrincipal?, string)(ClaimsPrincipalExtensions.cs:128-131) checks for an AuthClaimTypes.Permissionclaim 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 thesidclaim andGuid.TryParses it. The remarks make the degradation explicit (:137-141):nullis an ordinary answer, not an error, because tokens issued beforesidshipped 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) isprincipal?.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 onViewAsActor:truemeans 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 theMultiFactorclaim, ornullwhen 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 everyMultiFactorWithheldRolemarker in recorded order, or an empty list. The remarks are precise that a withheld role is not held:GetRoleValuesandHasRoledo 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 rawauth_timefirst and falls back toClaimTypes.AuthenticationInstant, the type the JWT bearer handler's inbound claim map renames it to (:215-219), then parses whole Unix seconds into aDateTimeOffset. It returnsnullfor 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 alongsidesub, 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. Thesidhalf 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 usesFindUserIdValue()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 onhttpContext.User?.Identity?.Namedirectly rather than onGetUserId()(MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/WebApplicationBuilderExtensions.RateLimiting.cs:191-197); AuthControllerBase usesFindSessionId()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> usesGetUserId()on the principal recovered from an expired access token during rotation andFindAuthTime()to carry the sign-in instant forward (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/AuthenticationServiceBase.cs:413,443);PasskeyStepUpjudges recent sign-in withFindAuthTime()(MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Passkeys/PasskeyStepUp.cs:27); and TestPrincipal writessubprecisely so test principals resolve the same way real ones do (MMCA.Common/Source/Hosting/MMCA.Common.Testing.UI/Infrastructure/TestPrincipal.cs:19,27).HasPermissionClaimbacks 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);HasMultiFactorbacks 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 throughIsRoleClaim(includeIdentityRoleClaimType: true)(MultiFactorRoleWithholding.cs:72);IsViewAsbacks 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
ClaimsPrincipalExtensionsin a different namespace (MMCA.Store/Source/Modules/Sales/MMCA.Store.Sales.UI/Extensions/ClaimsPrincipalExtensions.cs:9); do not confuse the two when reading ausinglist. Also noteGetUserIdreturns a nullable value type, sois { } userIdpattern-matching (as the framework's controllers use, for exampleMMCA.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);TwoFactorSettingsinjected asIOptions<TwoFactorSettings>;RecoveryCodeSetas 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 BCLTimeProvideras 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.TryMatchRecoveryCodenever 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 throughCryptographicOperations.FixedTimeEqualsrather than==orSequenceEqual(: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 classwith a primary constructor takingIOptions<TwoFactorSettings> settingsandTimeProvider timeProvider(:34), caching.Valueonce (:36).GenerateSecret()returnsBase32.EncodeofRandomNumberGenerator.GetBytes(_settings.SecretByteLength)(:39-40).BuildProvisioningUrirejects a blank secret or account name, URL-escapes the issuer and account name, and formats the standardotpauth://URI a QR code encodes: the algorithm is fixed atSHA1, while digit count and period are read from settings (:43-54). The remarks explain why it is composed in one visible place: theissuer:accountlabel and the redundantissuerparameter, which older authenticator apps read, are part of what a user's app has to accept (:26-30).VerifyCodecomes 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 throughout long matchedStep, initialized to0so every earlyfalseleaves it defined (:60-62). It returnsfalsefor a blank secret or code (:63-66), then decodes the stored secret withBase32.Decode, catchingArgumentExceptionand returningfalserather 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 callsTotp.Verifywith the injected clock's current UTC time (timeProvider.GetUtcNow().UtcDateTime), the configured period and digit count, and a window of_settings.VerificationWindowStepssteps on each side of now, every candidate compared in fixed time, writing the step the code matched intomatchedStep(:88-95), so the time step follows whicheverTimeProviderthe container holds. The window tolerates clock drift between the server and the user's authenticator app; the reported step is what letsTwoFactorAuthenticatorrefuse a replay of the same code inside that window. Thesecretit receives is plaintext: unprotecting the stored value is the caller's job (DataProtectionTwoFactorSecretProtector).GenerateRecoveryCodesproduces_settings.RecoveryCodeCountcodes, each a Base32-encoded random byte string of_settings.RecoveryCodeByteLengthbytes with the=padding trimmed, alongside their SHA-256 hashes computed byHashRecoveryCode(: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 aRecoveryCodeSet(:114); nothing persists the plaintext codes here.HashRecoveryCodenormalizes the code (keeps letters and digits, upper-cases) then SHA-256-hashes it to an upper-case hex string (:118-123).TryMatchRecoveryCodenormalizes and hashes the presented code once, skipsnullstored entries, then fixed-time-compares it against every stored hash, returning the matched hash (not the code) through anoutparameter (:126-155).NormalizeCodeis 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, aTryAddSingleton) as theITwoFactorServiceimplementation behindAddTwoFactorAuthentication(config)(DependencyInjection.Auth.cs:48), which also registersTimeProvider.SystemwithTryAddSingletonso a host that supplies its own clock keeps it (DependencyInjection.Auth.cs:57), and consumed byTwoFactorAuthenticatorfor both TOTP and recovery-code verification. - Caveats / not-in-source:
internal sealed, so it is reached only through theITwoFactorServiceabstraction; 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:
ResultandErrorfromMMCA.Common.Shared.Abstractions(RoleValue.cs:2), plusSystem.Collections.Frozenfrom the BCL (RoleValue.cs:1). Its doc comments point atRoleNamesfor the canonical strings (RoleValue.cs:9) and atICurrentUserService.IsInRolefor the comparison semantics it matches (RoleValue.cs:17). Conceptually a value object (seeValueObject) 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:- No
IEquatable<T>on the base (RoleValue.cs:18-24). The remarks cite Sonar S4035: an unsealed type implementingIEquatable<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 plainobject.Equalsoverride, 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-typedIEquatable<TSelf>plus==/!=on top, which is what ADC'sUserRoledoes (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Domain/Users/UserRole.cs:18,78-84). - It does not derive from
ValueObject, and that is a fitness-rule consequence, not an oversight.ValueObjectsAreImmutableSealedInSharedrequires every concrete class whose base type starts withMMCA.Common.Shared.ValueObjects.ValueObjectto 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 fromValueObjectwould fail that rule in every app. Keeping the base inMMCA.Common.Sharedwith 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 byEnumeration<TEnumeration>, whose own remarks nameRoleValueas 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 isOrdinalIgnoreCase, so an authorization check does not silently miss on"organizer"against"Organizer".- No
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 staticValidate(role, knownRoles, source)(RoleValue.cs:43) null-guards the supplied set (RoleValue.cs:45), then returnsResult.Success()when the role is known, otherwise aResultfailure carrying anErrorof kindInvariant, codedUser.Role.Invalid, with the caller's method name assourceandroleastarget(RoleValue.cs:47-53). The membership test is the privateIsKnown(RoleValue.cs:64-66) and it is more careful than it first looks: the fast path is the supplied set's ownContains(correct and O(1) for the intendedOrdinalIgnoreCasesets, with arole ?? string.Emptycoalesce so a null role becomes a clean failure rather than aNullReferenceException), and a miss falls back to an explicit case-insensitiveAnyscan, 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 genericBuildLookup<TRole>(params TRole[] roles)(RoleValue.cs:76) freezes the supplied singletons into a case-insensitiveFrozenDictionarykeyed byValue(RoleValue.cs:81-84), so a derived type can back itsFromString/IsValidmembers with interned instances instead of re-allocating on every parse.ToStringreturns the value (RoleValue.cs:88), andGetHashCodeuses the ordinal-ignore-case hash (RoleValue.cs:97) so it stays consistent withEquals, which is the contract any dictionary orHashSetkey 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" addIEquatable<T>to the base. The comparer-agnosticIsKnownfallback exists becauseValidateaccepts anyIReadOnlySet<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), theOrdinalIgnoreCasecase (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 throughBuildLookup(MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Domain/Users/UserRole.cs:21-34), exposesFromStringreturning aResult<UserRole>andIsValidover that frozen lookup (UserRole.cs:52-66), and adds a case-insensitiveIsOrganizerfor raw claim strings (UserRole.cs:76) plus the sealed-typeIEquatable<UserRole>and==/!=operators the base leaves to subclasses (UserRole.cs:78-90). Store'sUserRoleis a static class, not a subclass: it fixes Admin and Customer as string properties over anOrdinalIgnoreCaseset and calls the sharedRoleValue.Validatehelper for itsIsValid(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, theUser.Role.Invalidcode) without inheriting the type. Both key their known-role sets off theRoleNamesconstants, andPermissionRegistryBuilderkeeps 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>andError;Microsoft.AspNetCore.DataProtection(IDataProtectionProvider,IDataProtector); BCLCryptographicException. - 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).Unprotecttherefore returnsResult<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), returnsResult.Successwith the plaintext (:40-43), and catchesCryptographicException(:44-47) andFormatException(:48-51) into the same failure.Unreadable()(:54-58) buildsError.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 aResultrather than throwing. - Where it's used: registered with
TryAddSingletonbehindAddTwoFactorAuthentication(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
Protectwhen 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
ITwoFactorAuthenticatorimplementation 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);TwoFactorSettingsviaIOptions<T>(period and window size);IDistributedLock(serializing both code paths per account);TwoFactorErrors;TwoFactorOutcome; the framework'sResult<T>; theUserIdentifierTypealias. - 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 ofChallengeAsync's return:Result<TwoFactorOutcome>distinguishes "not enrolled" (a success carryingTwoFactorOutcome.NotEnrolled, not a failure) from a missing code, an invalid code, and the two ways a valid one can be accepted,VerifiedTotpversusVerifiedRecoveryCode. 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 classtakingITwoFactorService,ITwoFactorStore,ITwoFactorSecretProtector,ICacheService,IOptions<TwoFactorSettings>, andIDistributedLockas primary constructor parameters (:43-49), with two static lock timings:StepLockTimeToLiveof 10 seconds (:51) andStepLockWaitof 5 seconds (:53). It implementsChallengeAsync(userId, code, cancellationToken)(:56-87) andVerifyEnrollmentCodeAsync(:90-105).- Loads the user's
statefrom the store first (:61). If the state is missing orIsTwoFactorEnabledis false, the challenge succeeds trivially withNotEnrolled: "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.Unprotectsucceeds with a non-empty plaintext; the plaintext goes to theout long matchedStepoverload ofITwoFactorService.VerifyCode, and a match is not accepted outright but handed toAcceptTimeStepOnceAsyncwith 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 candidatesecretthat 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 failsVerifyCodeagainst the plaintext returnsfalse(:96-101); a match is passed through the sameAcceptTimeStepOnceAsyncand 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)}withStepLockTimeToLiveandStepLockWait, and answers a submission that cannot take it withTwoFactorErrors.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 throughITwoFactorService.TryMatchRecoveryCode(:130-139). A match is then consumed, not just verified:store.ConsumeRecoveryCodeAsyncpersists 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 returnsVerifiedRecoveryCode. 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 keytwofactor:laststep:{userId}that both paths lock on (:153). - The private
AcceptTimeStepOnceAsyncmakes a TOTP code single use (:167-188). It takes the distributed lock onlock:{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 withTwoFactorErrors.TwoFactorInvalid(:179-182), never a second success. Holding the handle in anawait usingblock, it delegates toAcceptIfNewerAsync(:184-187). - The private
AcceptIfNewerAsync(key, matchedStep, cancellationToken)(:190-207) reads the last accepted step withGetFromSharedStoreAsync, 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 withTwoFactorErrors.TwoFactorInvalid(:198-201). Otherwise the step is written back with a lifetime ofPeriodSeconds * (2 * VerificationWindowSteps + 2)seconds, long enough to outlast every step the verification window could still accept, and the challenge returnsVerifiedTotp(:203-206).
- Loads the user's
- 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 anIDistributedLockon the account's step key (ADR-108), and a submission that cannot take the lock is answered as invalid, the same shapePasswordResetTokenServiceuses (:27-35). - Where it's used: registered in DI
(
MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Auth.cs:66, aTryAddScoped) as theITwoFactorAuthenticatorbehindAddTwoFactorAuthentication(config); the resolved instance is passed toAuthenticationServiceBase<TUser>, which answersAuthentication.TwoFactorRequiredor mints themfaclaim depending on the outcome, mappingVerifiedTotpandVerifiedRecoveryCodeto 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);IDbContextFactoryand itsExecuteInTransactionAsyncfor the transactional unit;ErrorandResult<T>for the busy refusal;IRoleAdministrationServiceas 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 classwith a primary constructor takingIDbContextFactoryandIDistributedLock(:22).RoleBusyCode(:25,"PermissionGrant.RoleBusy"): the code an edit answers when another edit of the same role holds the lock.LockTimeToLiveis 30 seconds (:28), "comfortably above an edit's read and handful of writes: the crash guard, not the expected hold" (:27).LockWaitis 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 callsTryAcquireAsyncon the role's lock key with the TTL and wait (:51-53). Anullhandle answersError.Conflict(RoleBusyCode, ...)targeted at the role as the caller named it (:54-61). Otherwise the handle is disposed byawait usingarounddbContextFactory.ExecuteInTransactionAsync(edit, cancellationToken), whose result is returned as is (:63-66).LockKeybuilds"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
TryAddScopedbeside 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, whoseSetStoredPermissionsAsyncruns every set throughRunAsync(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/Administration/StoredPermissionRoleAdministrationService.cs:158-163). Exercised byMMCA.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 theIDistributedLockimplementation 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
IRoleAdministrationServiceimplementation 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);IPermissionGrantCacheandIPermissionGrantCacheInvalidator;PermissionGrantSettings(KnownRoles) viaIOptions<T>;PermissionRoleEditUnit(the per-role lock and transaction);AdministrationPermissions(ManageRoles); the framework'sResult<T>andErrorfactories. - 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 grantAdministrationPermissions.ManageRolesfrom 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).ListRolesAsyncgroups all stored grants by role, case-insensitively (:77-82), unions the result with the compiled and configured role universes via the privateRoleUniversehelper (:84), and returns oneRolePermissionsResponseper role pairing its compiled permissions (CompiledPermissions) with its stored ones (:86-92).GetCatalogAsyncreturns every known role alongside the full compiledcatalog.Permissionsdeliberately, not whatever happens to be stored: "widening it with whatever happens to be stored would let one typo legitimize itself" (:105-107).GetRoleAsyncfirst resolves the caller's spelling through the privateCanonicalRolehelper (:120), reads stored and compiled permissions under that canonical name, and returns not found when the privateIsKnownRolerule 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
IsKnownRolehelper is the single existence rule: a role exists when the registry compiles at least one permission for it, or when it belongs to theRoleUniverse(catalog roles, configuredKnownRoles, 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 toPermissionRoleEditUnit.RunAsyncas a lambda that builds aSetRequestand callsApplySetAsync(:156-165). Afinallyinvalidates 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
ApplySetAsyncis 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), asksRefuseSetfor 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 freshRolePermissionsResponsekeyed by the canonical role (:233-235). - The private
RefuseSetchecks the three refusals in order (:238-241):ManageRolesnamed (PermissionGrant.ManageRolesMustBeCompiled, checked before the catalog test so the message names the real reason,:254-263); any permission absent fromcatalog.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 asError.ForbiddenwithUserAdministration.PrivilegeCeilingand 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
RoleUniversehelper unions the compiled catalog's roles, the configuredKnownRoles, and whatever roles the store's own rows name, case-insensitively and sorted (:299-306). - The private
CompiledPermissionshelper 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
CanonicalRolehelper trims the name and looks it up case-insensitively in theRoleUniverse(catalog spelling first, then configuredKnownRoles); 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 aPermissionGranttable over the compiled registry;MMCA.Common/CLAUDE.md's Authorization section describes the same union-only layering throughLayeredPermissionRegistry"without changing the decorators' contract", the principle this service'sManageRolesrefusal 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 answersPermissionGrant.RoleBusy(409) (:47-52). A set stays a diff rather than a truncate-and-insert, so an unchanged submission writes nothing and theGrantedAtstamps of untouched rows survive (:41-44). - Where it's used: registered in DI
(
MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Auth.cs:206, aTryAddScoped) behindAddStoredPermissionGrants(config)(DependencyInjection.Auth.cs:183) as theIRoleAdministrationServiceimplementation; consumed throughRolesAdminControllerBase, which is itself gated onAdministrationPermissions.ManageRoles(MMCA.Common/CLAUDE.md, "Identity completions" section). - Caveats / not-in-source:
internal sealed, so it is reached only through theIRoleAdministrationServiceabstraction. Which predicate a caller passes ascallerHoldsPermissionis 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, theRolethe service-account user behind the client is created with, and an optionalSecretExpiresOn(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 grantingusers:view-as,users:manage,roles:manageorclients:manageis 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 tonullfor 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 throughMachineClientAdminService(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,LastUsedOnandHasSecondarySecret(MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/MachineClients/MachineClientResponse.cs:3-23). - Depends on: the
UserIdentifierTypealias forServiceAccountUserId(MachineClientResponse.cs:18, see the primer on identifier-type aliases); BCLGuid,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).ClientIdis the value a program presents asclient_id(:7); the three nullable instants mean "no expiry", "still active" and "never used" whennull(:11-13);HasSecondarySecretsays 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/tokenin the RFC 6749 section 5.2 shape, a singleerrormember, 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: noerror_descriptionis sent, so a refusal never says which half of the credential was wrong (MachineTokenErrorResponse.cs:8). - Walkthrough: the positional
Error(:11) and threepublic const stringcodes:InvalidClient("invalid_client",:14) for an unknown, revoked, expired, wrong-secret or refused-role client;UnsupportedGrantType("unsupported_grant_type",:17) for any grant other thanclient_credentials;InvalidRequest("invalid_request",:20) when no grant type is sent. - Why it's built this way: collapsing every authentication failure into
invalid_clientkeeps the endpoint from acting as an oracle for which client ids exist (ADR-140). - Where it's used:
MachineTokenControllerBase maps
MachineClientErrors codes to
400withUnsupportedGrantTypeorInvalidRequest, and every other failure to401withInvalidClient(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/tokenfor 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, alwaysBearer(:11);ExpiresIn, the lifetime in seconds as anint(: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
FlowIdand the WebAuthnOptionsthe browser hands tonavigator.credentials.create(registration) ornavigator.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 behindFlowIdis 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 rawJsonElementin thePublicKeyCredentialCreationOptionsJSONorPublicKeyCredentialRequestOptionsJSONshape with binary members base64url-encoded (:16-19). - Why it's built this way: carrying the options as a
JsonElementpasses 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 PasskeysControllerBaseBeginRegistrationAsyncandBeginSignInAsync(MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Passkeys/PasskeysControllerBase.cs:65-69,233-236); consumed in the UI byAuthUIService(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
FlowIdthe options were issued under, the browser's attestation asCredential, and an optionalName(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, thePublicKeyCredentialfromnavigator.credentials.createin theRegistrationResponseJSONshape (:10-13);Name, a label such as "Work laptop", defaulting tonull, 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 byAuthUIService(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,nullif 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
FlowIdthe options were issued under and the browser's assertion asCredential(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, thePublicKeyCredentialfromnavigator.credentials.getin theAuthenticationResponseJSONshape (: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 fromPasskeySignInButton(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 whoseDomainslist holds the address's domain. The sign-in page then starts the challenge atauth/oauth/{Provider}(MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/ExternalProviders/OidcDiscoveryResponse.cs:3-7,10). - Depends on: nothing; two
stringmembers,Provider(the provider name, which is also its scheme name and route segment) andDisplayName(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
DiscoverOidcProvideron 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 underauth/oauth/(MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/ExternalProviders/OidcReservedProviderNames.cs:5-12). - Depends on: nothing first-party; BCL
System.Collections.Frozen.FrozenSetandStringComparer.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), anIReadOnlySet<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) andcomplete,exchange,discover(controller route segments that would shadow a provider's challenge route,:6-9).IsReserved(name)(:22) is a membership test againstAll. - Why it's built this way: an OIDC provider named, say,
discoverwould register a challenge route that collides with the literalGET auth/oauth/discoveraction (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/OAuthControllerBase.cs:176), and one namedgooglewould 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
InvalidOperationExceptionat 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).OidcReservedProviderNamesTestspins the list to the controller by reflecting over every non-parameterized[Http*]template onOAuthControllerBase(the three built-in provider routes included) and asserting the set equalsAll, 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, andClientSecret, 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 MachineClientsControllerBaseCreateAsyncandRotateAsync(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") andManageWebhooks("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 stringholder 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 samearea:capabilitynaming 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 stringfields, 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 asManageUsersbecause creating a client creates a service-account user;ViewAuditTrail(:46) for reading recorded entity change history; andManageWebhooks(: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> (ManageUsersatMMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Administration/UsersAdminControllerBase.cs:67,ViewAsUserson its view-as action atUsersAdminControllerBase.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 grantsViewAsUsers,ManageUsers,ManageRolesorManageClients(MMCA.Common/Source/Core/MMCA.Common.Application/Auth/MachineClients/MachineClientService.cs:58-63); ViewAsService checksViewAsUserson the subject's role (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/ViewAs/ViewAsService.cs:193); StoredPermissionRoleAdministrationService refuses to grantManageRolesthrough a stored row, since it guards the role-administration surface itself (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/Administration/StoredPermissionRoleAdministrationService.cs:256-260), andRoleAdminEdit.razor.csdisables 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 aliasesManageUsers,ManageRoles,ViewAsUsersandManageClients(MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Shared/Authorization/IdentityPermissions.cs:26,41,52,64),IdentityPermissionGrantsgrantsViewAuditTrail(MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Shared/Authorization/IdentityPermissionGrants.cs:50), andIdentityUIModuleusesManageUsersandManageClientsas theRequiredPermissionof 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,IPermissionCataloganswers 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,
RolesandPermissions, bothIReadOnlyList<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), andAuthorizationExtensions(MMCA.Common/Source/Presentation/MMCA.Common.API/Authorization/AuthorizationExtensions.cs); registered alongside IPermissionRegistry in bothMMCA.Common.ApplicationandMMCA.Common.InfrastructureDependencyInjection.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 assessions: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(FrozenDictionaryandFrozenSet, BCL,PermissionRegistry.cs:1). - Concept introduced,
Frozen*collections for read-optimized immutable lookups.[Rubric §12, Performance & Scalability]assesses hot-path data-structure choices. AFrozenDictionaryorFrozenSetpays 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 usesStringComparer.OrdinalIgnoreCaseso role lookups are case-insensitive, while each permission set usesStringComparer.Ordinalso permission values must match exactly (PermissionRegistry.cs:34-37). - Walkthrough: a shared empty
FrozenSetsentinel and the frozen map field, plus twoIReadOnlyList<string>backing fields for the catalog,_rolesand_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.RolesandPermissions(PermissionRegistry.cs:55,58) implement IPermissionCatalog explicitly, with a comment explaining that the catalog'sPermissionsand the registry'sGetPermissions(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 theIPermissionCataloginterface.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
.Buildand 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 byStoredPermissionRoleAdministrationServiceand exposed throughPermissionCatalogResponse.
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 scopedIDE0028suppression: a collection expression cannot carry theOrdinalIgnoreCasecomparer that keeps role keys case-insensitive, and the concreteDictionarytype is kept forCA1859. A private_builtflag (PermissionRegistryBuilder.cs:18) records whether the builder has been sealed.Grant(role, params permissions)(PermissionRegistryBuilder.cs:32) guards its inputs (:34-35), throwsInvalidOperationExceptionifBuild()has already run (:37-41), filters blank permissions (:43), then either unions into the existing set or seeds a new ordinalHashSet(:45-52), and returnsthisfor 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 anIReadOnlyDictionary<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
Grantexception 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 throughAddPermissions(...), 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
Grantafter the first IPermissionRegistry resolve (which runsBuild()) 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 structDTO 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 forNewPasswordare deliberately not here; they live in the shared ChangePasswordRequestValidator inMMCA.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 passwordendpoint on UserAccountAuthControllerBase<TChangePasswordCommand, TChangePreferencesCommand> (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/UserAccountAuthControllerBase.cs:87,93), reached only through theIUserScopedCommand<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-13and its Store twin); validated by the sharedMMCA.Common/Source/Core/MMCA.Common.Application/Auth/Validation/ChangePasswordRequestValidator.cs:15, which requires a non-emptyCurrentPassword(:20-21) and includes the shared StrongPasswordRules<T> forNewPassword(: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 sendnullfor 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): anullfield 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'scommand.Request.Culture ?? user.PreferredCulture/command.Request.Theme ?? user.PreferredThemecoalesce (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, notrecord struct), which matters at the boundary: the controller binds it with[FromBody], so a completely absent body deserializes tonullrather 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
TCommandtype parameter (ChangePreferencesHandlerBase.cs:22,27). The handler base's remarks still give the reason as ADC marking its commandICacheInvalidatingwhile Store does not (ChangePreferencesHandlerBase.cs:16-18), but that difference no longer exists in source: both apps' commands implement onlyIUserScopedCommand<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 preferencesendpoint (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/UserAccountAuthControllerBase.cs:113,119), which hands it to the app's command through the abstractCreateChangePreferencesCommandfactory (UserAccountAuthControllerBase.cs:78-80,127); the generic constraint that ties the two together iswhere 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, insideUpdatePreferenceson theUseraggregate 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 privateUserPreferencesRequest(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 structrequest 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 aRefererheader, 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 withEmailConfirmation.PasswordRequiredunless 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:CurrentPasswordproves the caller owns the account as well as the mailbox, and confirms without changing the password (EmailConfirmationRequests.cs:31-35);NewPasswordlets 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 withCurrentPassword(EmailConfirmationRequests.cs:37-42).
Both are properties rather than positional parameters, following the
LoginRequest.TwoFactorCodeprecedent, 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
CurrentPasswordis verified, then a non-emptyNewPasswordis accepted when the user type supports a password change, and anything else answersPasswordRequired(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 aPasswordRequiredanswer changes nothing, so the token stays redeemable for the retry (ConfirmEmailHandlerBase.cs:27-42).Where it's used: shape-validated by ConfirmEmailRequestValidator, which caps
CurrentPasswordat the sign-in length limit, refuses a request carrying both passwords, and runs a suppliedNewPasswordthrough the sharedStrongPasswordRules<T>(MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Validation/EmailConfirmationRequestValidators.cs:43-54); handled throughConfirmEmailCommand(MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/ConfirmEmail/ConfirmEmailCommand.cs) by the shared ConfirmEmailHandlerBase; exposed by ADC'sEmailConfirmationController's anonymous, rate-limited, idempotentPOST confirm-email(inherited fromEmailConfirmationControllerBase.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:RequireConfirmedEmailstaysfalse,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 forPOST 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
Requestsfolder is at its width cap, as the doc comment says (RefreshTokenRequest.cs:14-16). - Concept: the minimal request shape from LoginRequest, here a
sealed recordcarrying only what the endpoint reads.[Rubric §11, Security]: the endpoint is anonymous and always answers204 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 RefreshTokenon asealed 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 atDELETE /auth/session-cookieand posts it server-to-server toauth/session/endwithin 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 withResult.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 Acceptedon every well-formed request (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/PasswordResetAuthControllerBase.cs:79,92).
- 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
(
- Walkthrough: one positional
string Email(ForgotPasswordRequest.cs:8-9); no body, no validation attributes, no normalization. Normalizing the address is the handler's job, throughEmail.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-passwordaction 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'sRequestPasswordResetAsync, 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 structDTO 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-onlyTwoFactorCodeproperty 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 generatedDeconstruct, 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 itnull(LoginRequest.cs:16-19). Omitting it on the first attempt is the normal flow: sign-in answersAuthentication.TwoFactorRequiredwhen 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'sPOST 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-onlyCodeVerifier, 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, theRefererheader, 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; theCodeVerifierproof key closes that gap. - Walkthrough: one positional
string Code(OAuthCodeExchangeRequest.cs:11-12) and one init-onlystring? 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), andnullfor 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
.ExchangeAsyncrejects 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 OAuthexchangeendpoint (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-completepage 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 structrequest 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 aRefererheader, 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.AcceptedTermsdefaults tofalseand 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 readsAcceptedTermsthere (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-limitedPOST sign-in-link/redeemaction 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 abstractCreateRedeemCommand(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 atMMCA.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 structDTO 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 anAuth.InvalidTokenfailure before it ever looks at the refresh token (AuthenticationServiceBase.cs:410-414,420-424); exposed by AuthControllerBase'sPOST 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 structshape 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'sValidateAndConsumeAsync(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 oneAuth.InvalidResetToken401 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 forNewPassword(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-passwordaction 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'sResetPasswordAsync(MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/AuthUIService.cs:296,305-306). ADC carries it in a ResetPasswordCommand, a plainICommandWithRequest<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-confirmationaction, which returns202 Acceptedon every well-formed request (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/EmailConfirmationControllerBase.cs:78-96, which ADC inherits throughMMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/Controllers/EmailConfirmationController.cs:29-34); carried bySendEmailConfirmationCommand(EmailConfirmationController.cs:37), handled by the shared SendEmailConfirmationHandlerBase. ADC's ownAuthController.RegisterAsyncschedules 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, throughEmail.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, idempotentPOST sign-in-linkaction on SignInLinkControllerBase<TSendCommand, TRedeemCommand>, which answers202 Acceptedon 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 abstractCreateSendCommandfactory (:61) constrained to ICommandWithRequest<out TRequest> (:38); handled by SendSignInLinkHandlerBase<TUser, TCommand>. ADC carries it inSendSignInLinkCommand(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'sIPermissionRegistryare 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> Permissionson asealed record(AdministrationRequests.cs:25); no body. - Where it's used: bound as the body of
RolesAdminControllerBase's
SetPermissionsaction (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'sRoleAdminService(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> Roleson asealed record(AdministrationRequests.cs:14); no body. - Where it's used: bound as the body of
UsersAdminControllerBase<TUserDto>'s
SetRolesaction (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'sUserAdminService(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? Reasonon asealed 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) throughViewAsGrant.Createbefore 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-asaction, gated byAdministrationPermissions.ViewAsUsersand 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 passesrequest?.Reasonto 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 threeIUserScopedCommand<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 recordwith init-only properties, not positional parameters (AdministrationRequests.cs:40-68), which suits[FromQuery]binding of many optional values.DefaultPageSize = 20andMaxPageSize = 100(:43,46).StaffandViewedare case-insensitive "contains" text against the staff and viewed email (:49,52), matched against the stored display snapshots after folding the needle withViewAsGrant.NormalizeDisplay(ViewAsGrantLogQuery.cs:34-47).Fromis inclusive andToexclusive on the granted-at instant, both UTC (AdministrationRequests.cs:55,58;ViewAsGrantLogQuery.cs:49-59).Statusfilters on the status derived at the time of the read, not a stored column (AdministrationRequests.cs:61;ViewAsGrantLogQuery.cs:19-20,31).PageNumberdefaults to 1 and values below 1 read page 1;PageSizedefaults toDefaultPageSizeand is clamped into 1 toMaxPageSize(: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'sGETlist 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:
AddressfromMMCA.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 structrequest shape introduced byLoginRequest; see that section for the value semantics.[Rubric §9, API & Contract Design]assesses whether the wire contract is explicit and evolvable. The optionalAddress? Address = nullparameter (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 nullableAddress, andbool AcceptedTerms = false(RegisterRequest.cs:26).AcceptedTermsis 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).RegisterAsyncrefuses the request withLegalAcceptanceErrors.TermsNotAcceptedonly when the host configured aCurrentTermsVersionand 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 overridingCreateUserstampsCurrentTermsVersionon 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'sRegisterRequestValidatorcomposes reusable rule sets over the four strings and appliesAddressValidatoronlyWhenthe address is non-null (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Validation/RegisterRequestValidator.cs:31-38), whileAuthenticationServiceBase<TUser>hands the whole request to an abstractCreateUser(RegisterRequest request, byte[] passwordHash, byte[] passwordSalt)that each app implements against its ownUseraggregate (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/AuthenticationServiceBase.cs:764). Note thatPasswordis a plainstringon the contract and never travels past the hashing call:RegisterAsyncturns it into a hash and salt pair, and that pair, not the password, is what reachesCreateUserand 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), theregisterendpoint onAuthControllerBase, 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'CreateUseroverrides show why the address is optional: Store passesrequest.Addressstraight intoUser.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 defaultUserRole.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, andAccessTokenExpiry, 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 structDTO.[Rubric §15, Best Practices & Code Quality]assesses consistent conventions and immutability, and[Rubric §9, API & Contract Design]assesses well-shaped request/response contracts. A positionalrecord structis a value type with a compiler-generated constructor, deconstruction, value equality, andToString;readonlymakes 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 explicitAccessTokenExpiry(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 thannull, and OAuthControllerBase therefore detects a missing exchange entry by testingstring.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
IssueTokensAsynchelper 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
RolePermissionsResponsewhich 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,RolesandPermissions, bothIReadOnlyList<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.GetCatalogAsyncfrom the registered roles and the compiledPermissionRegistry'sPermissions(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/Administration/StoredPermissionRoleAdministrationService.cs:98-107); declared as the 200 response ofGET .../catalogonRolesAdminControllerBase(MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Administration/RolesAdminControllerBase.cs:107-110); fetched client-side byRoleAdminServicefor 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 Acceptedbody ofauth/registerwhen 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
201with empty token fields the endpoint answers202with 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 IdentityAuthControllerinherits 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
StoredPermissionRoleAdministrationServicebuilds fromPermissionRegistryand its permission-grant store. - Concept:
RegisteredPermissionsversusStoredPermissionsis 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 onRolesAdminControllerBase(MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Administration/RolesAdminControllerBase.cs:85-152); consumed byRoleAdminServiceand 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
.EndReasoncarries, 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
ExpiredandViewAsEndedare the two values no session revocation writes (SignInEndReasons.cs:4-7). - Walkthrough: six
const stringmembers, 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
ViewAsEndedvalue. - Where it's used: written by SignInHistory, which stamps
ViewAsEndedorExpiredon a view-as row andExpiredon 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 UISignInHistoryTablecomponent, 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:
EndReasonis typedstring?, 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'sJsonStringEnumConverter<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
Kindparameter of SignInSummaryResponse, defaulting toSignIn(MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Responses/SignInSummaryResponse.cs:49); set toViewAsby SignInHistory when it summarizes a grant (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Sessions/SignInHistory.cs:102); read by the Common UISignInHistoryTableto 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.HandleAsyncafter a successful enrollment (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/TwoFactor/ConfirmTwoFactorEnrollmentHandlerBase.cs:105) and byRegenerateRecoveryCodesHandlerBase.HandleAsyncafter 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 structDTO shapeAuthenticationResponseintroduces. - Concept: the same value-type carrier convention as
AuthenticationResponse; no new concept. - Walkthrough: two positional parameters,
SharedKeyandProvisioningUri, 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.HandleAsyncat 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 structDTO 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), andRecoveryCodesRemaining, 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
GetStatusAsyncendpoint onTwoFactorControllerBase, 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 byTwoFactorUIService.GetStatusAsync(MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Auth/TwoFactor/TwoFactorUIService.cs:32,41) and held as page state by theTwoFactorAccountpage (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
nullmeans "leave unchanged", the response'snullmeans 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 arecord(not arecord 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
Useraggregate 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 sharedGET preferencesendpoint 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 readsauth/preferencesinto its own UI-sideUserPreferencesrecord 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
UserIdentifierTypealias (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 theact_subandvagclaims;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
ExpiresAtas the expiry (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/ViewAs/ViewAsService.cs:101-117); declared as the 200 response ofStartViewAsAsynconUsersAdminControllerBase(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'sJsonStringEnumConverter<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 returnsEndedonce an end instant is set, otherwiseLiveuntil expiry andExpiredafter (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 onEndedAtandExpiresAt(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 UISupportAccessLogpage (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
IsCurrentflag is computed from thesidclaim 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: aTokenHash(MMCA.Common/Source/Core/MMCA.Common.Domain/Auth/RefreshSession.cs:88) and the rotation linkReplacedByTokenHash(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 neitherTokenHashnorReplacedByTokenHash(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.CreatedAtandExpiresAt(DateTime, both UTC) say when this device signed in and when the session stops being usable even if never revoked (:14-15).IpAddressandUserAgentare 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 alwaysfalsefor a caller whose token predates thesidclaim, because nothing then identifies the caller's own device.Device(DeviceMetadata?, defaulting tonull) is the device metadata a native client reported for this session throughPUT auth/sessions/current/device, andnullfor every browser session (:23-27). It is informational likeUserAgent, 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.
IsCurrentis 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 acurrentSessionIdargument (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Sessions/AuthSessionIssuer.cs:281), and the interface documents that passingnullsimply 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, fillingDevicefrom the session (AuthSessionIssuer.cs:261-283); AuthenticationServiceBase<TUser>.GetSessionsAsyncdelegates to it (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/AuthenticationServiceBase.cs:505-512). UserSessionsAdministrationService.GetSessionsAsyncbuilds the same projection for an administrator's view of another account, withIsCurrent: falseon every row (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Administration/UserSessionsAdministrationService.cs:48-61), served byUsersAdminControllerBase(MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Administration/UsersAdminControllerBase.cs:105). Returned to the account holder by theGET my-sessionsendpoint on AuthControllerBase, which supplies the caller's own session viaUser.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 fromDevicewithUserAgentas the fallback (MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Auth/Sessions.razor.cs:43,148-150,267). - Caveats / not-in-source:
IpAddressandUserAgentare whatever the client sent at issue time and are stored verbatim, andDeviceis 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.RegisterAsynckeeps returning a result of AuthenticationResponse, and a token-less success means the confirmation is pending; that is what lets the register endpoint answer202instead of201without 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 anAuthenticationResponsewith empty tokens andDateTime.MinValueexpiry.IsConfirmationPending(this AuthenticationResponse)(:44-45): an extension method returningstring.IsNullOrEmpty(response.AccessToken), so it is true forConfirmationPendingand for any value without an access token,defaultincluded (: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
ConfirmationPendingexactly 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 answers202with a RegistrationPendingResponse (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/AuthControllerBase.cs:142-149); produced client-side by AuthUIService when the API answers202, 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
EndReasoncarries. - 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).StartedAtandLastActiveAt: the earliest retained session and the last token refresh (:16-17).IpAddressandUserAgent: recorded on the newest session, informational (:18-19).EndedAtandEndReason: when and why it ended, bothnullwhile it is live (:20-26).IsCurrent: the sign-in the calling token belongs to, alwaysfalsein an administrator's view of another account (:27-30).Kind(defaultSignIn): a sign-in or a view-as row, documented as the extension point for other account-access events (:31-35).Device(defaultnull): reported native device metadata from the newest session,nullfor 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
Kindand 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 byGET my-sign-inson AuthControllerBase (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/AuthControllerBase.cs:369-379) and byUsersAdminControllerBase(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 UISignInHistoryTablecomponent (MMCA.Common/Source/Presentation/MMCA.Common.UI/Components/Auth/SignInHistoryTable.razor.cs:30,71-87). - Caveats / not-in-source:
EndReasonis astring?, 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
UserIdentifierTypealias (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'svagclaim);StaffUserIdandTargetUserId;StaffDisplayandTargetDisplay, email snapshots taken when the grant was issued andnullonce that account was erased (or for a grant issued before the snapshot) (:9-17);Reason;GrantedAt,ExpiresAtandEndedAt; andStatus, 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 computesStatuswithStatusAt(now)against one read instant (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Administration/ViewAsGrantsAdminControllerBase.cs:75-90); fetched by the Common UIViewAsGrantsServiceand rendered on theSupportAccessLogpage. - 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 stableUid, aSummary, 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 aVTIMEZONEblock 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 timestampsDateTimeOffsetand 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 plainZ-suffixed timestamps with noVTIMEZONEmachinery at all (IcsEvent.cs:5-7). TheUidcarries 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 recordwith six parameters and no body.Uid,Summary,StartsAtUtc,EndsAtUtcare required by position;DescriptionandLocationdefault tonull(IcsEvent.cs:16-21), which is how the builder decides to omit the corresponding lines entirely rather than emit an empty one. Arecord(reference type) rather than thereadonly record structthat 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 (itsToUtchelper atMMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Application/Sessions/UseCases/ExportCalendar/CalendarExportMapper.cs:45) and composes theUidassession-{id}@atldevcon(CalendarExportMapper.cs:29-42, the id at:38). The mapped entries reachExportSessionCalendarHandler(.../ExportCalendar/ExportSessionCalendarHandler.cs:52-55) andExportEventCalendarHandler(.../ExportCalendar/ExportEventCalendarHandler.cs:46-53). - Caveats / not-in-source: nothing in the type enforces that
StartsAtUtcandEndsAtUtcreally carry a zero offset, that the end follows the start, or that theUidis 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 conventionMMCA.{App}.{Module}.{Layer}(MMCA.Common/Source/Core/MMCA.Common.Shared/Conventions/ModuleNameConventions.cs:10-51).MMCA.Store.Sales.Domain.Ordersgives"Sales";MMCA.ADC.Conference.Application.Sessionsgives"Conference"; a type outside that shape givesnull. - Depends on: nothing first-party;
System.Array.FindIndex/Array.Existsandstring.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 toMMCA.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:
NonDomainLayerSegmentsis a privatestatic readonly string[]holdingApplication,Infrastructure,API,UI(ModuleNameConventions.cs:17). What is absent is the load-bearing part, and the comment says so:Sharedis deliberately not in the list, so framework namespaces such asMMCA.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,
Domainat 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 >= 1is the guard: a namespace that starts withDomainhas nothing preceding it to name. - Rule two, the other layer segments, only at the fourth segment or later (
:48-50). ThelayerIndex >= 3test is what makesMMCA.Common.Application.*returnnullrather than the phantom"Common": in that namespaceApplicationsits at index 2, below the threshold, while inMMCA.ADC.Conference.Applicationit 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 theDomainrule 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>andLoggingCommandDecorator<TCommand, TResult>each resolve it into aprivate 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 isstaticon 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 internalNamespaceConventionswrapper delegates straight to it (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/NamespaceConventions.cs:20-21), and that wrapper is whatEntityTypeConfiguration<TEntity, TIdentifierType>uses for the SQL Server schema name (falling back todbo,.../Configuration/EntityTypeConfiguration/EntityTypeConfiguration.cs:66) and the Cosmos container name (.../DataSources/Engines/CosmosDataSourceEngine.cs:95), and whatEntityDataSourceRegistryuses 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 tonullrather 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 theLoggingCommandDecoratortests 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
rowversionbyte array carried byIConcurrencyAware) and the HTTP entity tag that represents that token on the wire. It owns three header constants plus aFormat/TryParsepair (MMCA.Common/Source/Core/MMCA.Common.Shared/Http/ConcurrencyETag.cs:24-105). - Depends on: nothing first-party at runtime (the doc comment references
IConcurrencyAwareatConcurrencyETag.cs:7). BCL only:Convert.ToBase64String,Convert.TryFromBase64Chars,ReadOnlySpan<char>, and[NotNullWhen]fromSystem.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 afields=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 whatIf-Matchasks. 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 ruleIdempotencyHeadersfollows, and the doc comment says so: it lives in Shared "because both ends of the exchange need it: the API reads anIf-Matchvalue 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), andWildcard = "*"(:33), theIf-Matchvalue that matches any current version. Format(byte[] rowVersion)(:40) null-guards (:42) and returnsstring.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), returnsfalsefor 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-insensitiveW/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), callsConvert.TryFromBase64Charsand 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
falseis spelled out in the doc (:52-56): a blank value, the wildcard, and anything that is not base64 all returnfalse, and the caller decides which of those is an error in its context. That is what letsSupportsIfMatchAttributetreat a wildcard as "no precondition" while treating unparsable input as a 400.
- Three constants name the protocol:
- Why it's built this way:
ADR-035 is the governing
record. It picks the header as the one transport because HTTP already defines
ETagandIf-Matchfor 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 inMMCA.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) writesResponse.Headers[ConcurrencyETag.ETagHeaderName] = ConcurrencyETag.Format(rowVersion)(ApiControllerBase.cs:144), whichEntityControllerBase<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);SupportsIfMatchAttributereads the request header (MMCA.Common/Source/Presentation/MMCA.Common.API/Concurrency/SupportsIfMatchAttribute.cs:155), compares against the wildcard (:110) and decodes withTryParse(:116). Client side,EntityServiceBase<TEntityDTO, TIdentifierType>formats the tag (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Api/EntityServiceBase.cs:217) and attaches it asIf-Matchby 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'sEventService(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) andLivePollUIService(MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.UI/Services/SessionLive/LivePollUIService.cs:137). Framework coverage isConcurrencyETagTests(MMCA.Common/Tests/Core/MMCA.Common.Shared.Tests/Http/ConcurrencyETagTests.cs:16,21,33,47), and ADC's integration bases build theirIf-Matchvalues through the same helper (MMCA.ADC/Tests/Integration/MMCA.ADC.Conference.IntegrationTests/Infrastructure/ConferenceIntegrationTestBase.cs:60,70,74). - Caveats / not-in-source: the
ETagthis type renders exists to be echoed back on the next write. Nothing here implements conditional GET: no code path compares an inboundIf-None-Matchagainst 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) andX-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 inMMCA.Common.API, the service bases that write it ship inMMCA.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 inMMCA.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 ruleConcurrencyETagand the auth request DTOs follow. - Walkthrough: a
static classwith twoconst stringfields and nothing else (IdempotencyHeaders.cs:13-26).constrather thanstatic readonlyso the values can appear in attribute arguments and constant patterns, matchingAuthClaimTypesandRoleNamesin 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: trueso 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,
IdempotencyFilterre-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);NotificationsControllerreads 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'sSessionQuestionUIService(MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.UI/Services/SessionLive/SessionQuestionUIService.cs:72) andLivePollUIService(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 inMMCA.Common.Shared, the same placement rule asIdempotencyHeadersandConcurrencyETag. - Walkthrough:
AliasSeparatoris the'~'char (QueryFilterKeys.cs:23) andSearchTagis the tag a list page's search box uses,"search"(:26).Alias(property, tag)(:34) rejects a null or blank argument and returnsproperty~tag, for exampleName~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), andQueryFilterServicestrips the tag withPropertyOfbefore validating the property (MMCA.Common/Source/Core/MMCA.Common.Application/Services/Filtering/QueryFilterService.cs:122,203). Framework coverage isQueryFilterAliasedKeyTests(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 completeVCALENDARdocument as a string (MMCA.Common/Source/Core/MMCA.Common.Shared/Calendars/IcsCalendarBuilder.cs:22-41). - Depends on:
IcsEvent;System.Text.StringBuilder,System.Text.Encoding, andSystem.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 takesdtStampas a parameter rather than reading a clock, and the doc comment states the consequence: "Deterministic by design: the caller suppliesdtStamp, so identical inputs produce identical output" (IcsCalendarBuilder.cs:9-10). That makes the whole document byte-assertable, which is exactly what the suite inMMCA.Common/Tests/Core/MMCA.Common.Shared.Tests/Calendars/IcsCalendarBuilderTests.csdoes, 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 toMMCA.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 (ThrowIfNullOrWhiteSpaceon the product id,ThrowIfNullon the events,:24-25), then writes the fixed calendar preambleVERSION:2.0, an escapedPRODID,CALSCALE:GREGORIAN, andMETHOD: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, whichIcsCalendarBuilderTests.cs:151pins.AppendEvent(:43) writes the five mandatoryVEVENTlines:UID,DTSTAMP,DTSTART,DTEND,SUMMARY(:46-50).DESCRIPTIONandLOCATIONare 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 throughUtcDateTimeand formatsyyyyMMdd'T'HHmmss'Z'underInvariantCulture(: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-nsequence (: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 emitsCRLFplus a single space and resets the counter to1(: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 inCRLF(: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
IcsEventUTC contract: avoid the parts of the specification whose correctness would need continuous maintenance. - Where it's used: ADC's Conference module only, from
ExportSessionCalendarHandlerfor a single session (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Application/Sessions/UseCases/ExportCalendar/ExportSessionCalendarHandler.cs:52-55) andExportEventCalendarHandlerfor a whole event (.../ExportCalendar/ExportEventCalendarHandler.cs:46-53), both passingCalendarExportMapper'sProductIdconstant-//MMCA//AtlDevCon//EN(.../ExportCalendar/CalendarExportMapper.cs:17). - Caveats / not-in-source: both ADC handlers now pass an injected
TimeProvider'sGetUtcNow()fordtStamp(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
Isoverloads that classify anError, aResultor a rawHttpResponseMessage(MMCA.Common/Source/Core/MMCA.Common.Shared/Http/CommitOutcomeUnknown.cs:5-11,28-63). - Depends on:
ErrorandResultfromMMCA.Common.Shared.Abstractions(CommitOutcomeUnknown.cs:1); BCLSystem.Net.Http.HttpResponseMessageand LINQAny. - 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 sameIdempotency-Keyre-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 Detailserrorsarray that a parsedResultcarries (: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 asIdempotencyHeaders" (:22-23; seeIdempotencyHeaders). - Walkthrough:
Code = "Transaction.CommitOutcomeUnknown"(CommitOutcomeUnknown.cs:31) is the code the body'serrorsarray carries.HeaderName = "X-Commit-Outcome"(:34) andHeaderValue = "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 withCode.Is(Result)(:53-54) is true only for a failed result where any error satisfiesIs(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 matchesHeaderValuecase-insensitively (StringComparison.OrdinalIgnoreCase,:62), while the code comparison inIs(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'sEnableRetryOnFailurepath (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 threeIsoverloads 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 aTransactionCommitAmbiguousExceptionnaming what committed and what rolled back (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/Factory/DbContextFactory.cs:782). Server side,GlobalExceptionHandlerroutes that exception (MMCA.Common/Source/Presentation/MMCA.Common.API/Middleware/GlobalExceptionHandler.cs:112-115) toWriteCommitOutcomeUnknownAsync(GlobalExceptionHandler.cs:139), which sets a 500, writes the header (:144), usesMessageas the detail (:150) and puts anError.UnexpectedcarryingCodeinto theerrorsarray (:152-154). Because that array is the lossless shape ofProblemDetailsResultReader, the client gets the code back intact, whichCommitOutcomeUnknownHandlingTestspins by parsing the handler's output withParseProblemDetailsand assertingIs(error)andErrorType.Unexpected(MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/Middleware/CommitOutcomeUnknownHandlingTests.cs:34-48). Three client layers honor the never-resend rule:AuthenticatedServiceBase'sIsRetryableResponsereturnsfalsefor 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 AspireExtensionswraps the retry'sShouldHandleso 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); andOfflineWriteQueue'sClassifysettles the entry asOfflineWriteOutcome.Rejectedrather 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 isCommitOutcomeUnknownTests(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
Errorlist and failedResultthe server started from (MMCA.Common/Source/Core/MMCA.Common.Shared/Http/ProblemDetailsResultReader.cs:59-510). - Depends on:
Error,ResultandErrorTypefromMMCA.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
Resultcarrying typedErrors, and ADR-013 makes that the whole point: business failures are values, not exceptions. HTTP does not carryResults, soApiControllerBaseprojects 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 anHttpRequestExceptionwhere 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 usableError. Its placement is the same ruleIdempotencyHeadersandConcurrencyETagfollow, stated in the doc comment: the client half of the round trip isMMCA.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 theErrorTypefrom the status code, which is "one-to-one for every status the API emits except 400 Bad Request" (:53-54), where bothValidationandInvariantland and the reverse picksValidation(:54-56). - Walkthrough:
- Three public
const stringcodes name the synthesized failures:StatusErrorCodePrefix = "Http."(:66),EmptyResponseCode = "Http.EmptyResponse"(:72), andMalformedResponseCode = "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. StatusCodeToErrorTypeis aFrozenDictionary<int, ErrorType>(:97-109), documented as "the exact reverse ofErrorHttpMapping.ErrorTypeToStatusCode" (:92-93). It maps nine statuses one-to-one, including503toErrorType.Unavailable(:101) and429toErrorType.TooManyRequests(:107), the reverses of the forward map'sUnavailableandTooManyRequestsentries (MMCA.Common/Source/Presentation/MMCA.Common.API/Middleware/ErrorHttpMapping.cs:34,33). That forward map really does collapse two types onto 400 (ValidationandInvariant, atErrorHttpMapping.cs:25,26), which is exactly why the reverse is lossy there and picksValidation. 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 toValidation(:93-95).FromHttpStatusCode(int)(:133) is the public reverse mapping: a dictionary hit wins (:135-138), any other 4xx becomesValidation, anything else (every other 5xx included) becomesUnexpected(: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 anHttpResponseMessage, 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); aJsonExceptionis 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 theerrorsmember: an array goes toReadErrorArray(:191-193), an object toReadValidationDictionary(:195-197). Parsed errors win only when the list is non-empty (:200-203); otherwise it falls through to a synthesized error carryingdetailortitle(: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 ownstatusmember 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 throughReadErrorObjectand, notably, still salvages a degraded array of plain strings (:365-370).ReadErrorObject(:376) readscode,message,type,sourceandtarget, with a three-step fallback for the message (message, thencode, then the generic default) so anErroris never constructed with an empty one (:382-387).ReadValidationDictionary(:390) handles the standard ASP.NET Core shape. The key becomesValidation.{propertyName}, or bareValidationfor an object-level rule with an empty key (:397-399), and the property name is carried separately asTarget(:400). A value may be an array of messages or a single one, and both paths funnel throughAddValidationError(: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.TryParsewithignoreCase: trueplusEnum.IsDefined(:439-440). Without the second checkTryParsewould 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 failedResult.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 isHttp.followed by a number (StatusErrorCodePrefix, parsed withNumberStyles.None,:236-237) AND the message equals the reader's English default sentence for that status (:238, via the privateDefaultMessage,: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 throwsArgumentNullExceptionon a null error (:233) and yields0for the status when it returnsfalse(:235).ReadAsync(:256) short-circuits on a 2xx toResult.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 codedEmptyResponseCode(:306-313), a body that deserializes tonullis the same failure with a different message (:318-324), and aJsonExceptionbecomesMalformedResponseCode(: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
ReadAsyncoverloads carry aSuppressMessagefor analyzerRS0026("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 anHttpRequestExceptionback tonull(: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".
- Three public
- 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 aDomainInvariantViolationExceptionbefore falling back toEnsureSuccessStatusCode, 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 twoSendRequestAsyncdispatches of its base (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Api/AuthenticatedServiceBase.cs:186,214, documented at:150,168,194),ChildEntityServiceBaseuses 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 exampleUserService(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) andSessionQuestionUIService(MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.UI/Services/SessionLive/SessionQuestionUIService.cs:34,53,79). The round trip is pinned end to end byProblemDetailsRoundTripTests, which serializes a real failure through the API edge and reads it back withParseProblemDetails(MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/Controllers/ProblemDetailsRoundTripTests.cs:48,72,87,126). - Caveats / not-in-source:
ErrorHttpMappingisinternaltoMMCA.Common.API(MMCA.Common/Source/Presentation/MMCA.Common.API/Middleware/ErrorHttpMapping.cs:14) and this reader lives inMMCA.Common.Shared, so the two dictionaries cannot reference each other. Nothing in the type system keeps the reverse map aligned when a newErrorTypeor 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
ImportReportDTOandImportRowErrorDTO.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, defaultfalse. It writes nothing and answers200with a report whoseDryRunistrue. - Commit: a synchronous commit answers
200with a report whoseDryRunisfalse; a queued commit answers202with the application's own run DTO. - File-level failure: a malformed file, missing columns or a file over the size cap is a
400Problem Details, never a report, because a report describes rows and an unreadable file has none. A row-level problem is anImportRowErrorDTOinsideImportReportDTO.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.- Dry run: asked for through a form or query field named
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 isImportReportDTOTests(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 signatureStronglyTypedIdValueParser<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 untypedDelegate. - Where it's used: bound once per closed
TValuebyStronglyTypedIdValueParser<TValue>'sBuild(), and invoked byStronglyTypedId.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-
TValuecache of a parser delegate, exposed as the single static fieldInstance(StronglyTypedId.cs:173-221). - Depends on:
StronglyTypedIdValueParserDelegate<TValue>. - Concept introduced, the two supported primitive shapes. A wrapped primitive parses one of two
ways:
stringtakes a direct identity path, the route segment IS the value (ParseString,:203-207), and every other supported primitive implementsIParsable<T>and is bound through reflection toParseParsable<TParsable>(:209).stringdoes implementIParsable<string>too, but parsing a string is the identity, soBuild()takes the direct path ahead of the reflective binding (comment at:188-189).Build()(:186) returnsnullfor aTValuethat is neither, which is what letsStronglyTypedId.CanParseValues<TValue>()answer "unsupported" without throwing. - Walkthrough:
Instance(:180) runsBuild()once, at type-initialization time for the closed generic.Build()checkstypeof(TValue) == typeof(string)first (:190-191), then testsIParsable<>.MakeGenericType(typeof(TValue)).IsAssignableFrom(typeof(TValue))(:193-194) and returnsnullwhen neither holds. For theIParsablebranch it reflects the privateParseParsablemethod off itself, closes it overTValue, and binds it withCreateDelegate(: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) andCanParseValues(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:
ErrorfromMMCA.Common.Shared.Abstractions(:1), the domain error it copies from. - Concept introduced: none new; it is the row-level leg of the contract
ImportConventionsdocuments, and it reuses the Result pattern'sErrorrather 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 toCsvRow.LineNumber(:51-54).Column(:58) names the offending column, or isnullfor a whole-row error.Code(:61) andMessage(:64) are bothrequired. The factoryFromError(Error, int, string?)(:74) null-guards the error (:76) and copies itsCodeandMessageinto a new instance (:78-84), so a validator that already produced anErrorturns 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
400Problem Details. - Where it's used: carried by
ImportReportDTO.RowErrors. Framework coverage isImportReportDTOTests(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.TSelfis the curiously-recurring self type,TValuethe 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 toStronglyTypedId.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 anOrderIdand any otherGuid), a type implementing this interface is a real value type the compiler tells apart fromGuidorint, 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 onlyFrom, and route-model binding works through the inheritedIParsable<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 ofIParsable<TSelf>, so a wrapper never writes them:Parse(:172-173) andTryParse(:184-188) both delegate straight toStronglyTypedId's staticParse/TryParseoverloads, closed overTSelf, 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 usingaliases 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 constraintwhere TSelf : struct, IStronglyTypedId<TSelf, TValue>recurs acrossStronglyTypedId,StronglyTypedIdMappings<TSelf, TValue>,StronglyTypedIdTypeConverter<TSelf, TValue>andStronglyTypedIdConverter<TSelf, TValue>. Framework coverage:StronglyTypedIdFixtures(MMCA.Common/Tests/Architecture/MMCA.Common.Architecture.Tests/StronglyTypedIdFixtures/StronglyTypedIdFixtures.cs) andTestIdentifiers(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 aConcurrentDictionary<Type, Type?>caching the wrapped primitive per identifier type, with anullentry 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 theIParsable.Parseleg: it null-guards (:235), then throwsFormatExceptionwhenTryParsefails (:237-240), naming the offending text and target type in the message.TryParse<TSelf, TValue>(string?, IFormatProvider?, out TSelf)(:254) fetchesStronglyTypedIdValueParser<TValue>.Instance, invokes it with the invariant culture as the default provider (:259), and on success callsTSelf.From(value)(:261) to wrap the parsed primitive. AnullInstance(an unsupportedTValue) falls through tofalse(:265-266).CanParseValues<TValue>()(:276) is a one-line capability check over the sameInstance.GetValueType(Type)(:288) andIsStronglyTypedId(Type)(:299) answer "does this type implement the contract for itself" viaResolveValueType(:326), which walkstype.GetInterfaces()for a closedIStronglyTypedId<,>whose first generic argument equals the type being asked about (:328-336): the same self-referencing guardEnumerationJsonConverterFactoryapplies elsewhere in the framework, per the doc comment (:283-284).TryDescribe(Type, out Type?, out Type?)(:309) unwrapsNullable<T>first (:316) so a caller inspecting anOrderId?property gets the same answer as one inspectingOrderId.
- 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.cscallsParse/TryParsethrough the default interface methods;StronglyTypedIdJsonConverterFactory'sCanConvert/CreateConvertercallIsStronglyTypedId/GetValueType;StronglyTypedIdTypeConverter.ConvertFromcallsTryParse;StronglyTypedIdFilterStrategyandStronglyTypedIdRegistrycall the type-detection surface. Framework coverage isStronglyTypedIdTests(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 classso an application adds its own counts on a derived record (ImportReportDTO.cs:3-6,12). - Depends on:
ImportRowErrorDTOforRowErrors. - Concept introduced: none new; the report half of the contract
ImportConventionsdocuments. - Walkthrough:
DryRun(:15) andTotalRows(:18, data rows with the header excluded) arerequired.Added(:21),Updated(:24),Unchanged(:27, rows that matched a record already holding the same values) andRejected(:30) are optional counts; on a dry runAddedandUpdatedcount what would have happened. Every rejected row has at least one entry inRowErrors(:29).RowErrors(:33) defaults to[], in file order, so the remark at:8-10holds: it serializes as an array, nevernull, 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
TicketRosterImportReportderives 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 ownTicketRosterImportResultDTOmapped from that report, not anImportReportDTO. Framework coverage isImportReportDTOTests(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 byStronglyTypedIdJsonConverterFactory(StronglyTypedIdJsonConverterFactory.cs:38-70). - Depends on:
System.Text.Json.Serialization.JsonConverter<T>from the BCL;StronglyTypedId.TryParsefor 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 callsTSelf.From(:366-368), sodefaultstands in for anullprimitive rather than throwing.Write(:371) serializesvalue.Valuedirectly.WriteAsPropertyName(:379) andReadAsPropertyName(:387) handle the identifier-as-dictionary-key case: the wrapped primitive becomes the JSON member name viaConvert.ToString(:382-383), and reading it back throwsJsonExceptionon failure rather than silently defaulting (:390-391), documented as makingDictionary<OrderId, T>serialize exactly likeDictionary<int, T>. - Why it's built this way: ADR-115.
- Where it's used: instantiated by
StronglyTypedIdJsonConverterFactory.CreateConverterviaActivator.CreateInstance; nothing outside the defining file references it directly. Framework coverage isStronglyTypedIdSerializationTests(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) andToIdentifier(TValue)wraps a primitive throughTSelf.From(value)(:48). There are no nullable overloads: a mapper that needs "not set" handles thenullitself. - 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.TypeConverterfor 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.TryParsefor the string-to-identifier path;System.ComponentModel.TypeConverterfrom the BCL. - Concept introduced: none new; the
TypeConverterleg of the wrap/unwrap patternStronglyTypedIdConverter<TSelf, TValue>applies for JSON. - Walkthrough:
CanConvertFrom/CanConvertTo(:461, 467) acceptstringandTValuein addition to whatever the base converter accepts.ConvertFrom(:473) pattern-matches:nullpasses through, aTValuewraps viaTSelf.From, a parsablestringwraps viaStronglyTypedId.TryParse, and an unparsablestringthrowsFormatExceptionnaming the text and target type (:474-482).ConvertTo(:485) unwraps aTSelfto itsTValueor to a culture-formatted string, and null-guardsdestinationTypeexplicitly rather than delegating that check to the base class (:500-502). - Where it's used: registered per identifier type by
StronglyTypedIdTypeConverters.Register. Framework coverage isStronglyTypedIdTypeConverterTests(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
JsonConverterFactorythat detects any strongly typed identifier and handsSystem.Text.Jsona closedStronglyTypedIdConverter<TSelf, TValue>for it, so no per-identifier-type converter registration is needed (StronglyTypedIdJsonConverterFactory.cs:22-71). - Depends on:
StronglyTypedId.IsStronglyTypedId/GetValueTypefor 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 toStronglyTypedId.IsStronglyTypedId.CreateConverter(Type, JsonSerializerOptions)(:530) resolves the wrappedTValuewithGetValueType, returnsnullwhen it is not an identifier, and otherwiseMakeGenericTypes the nested converter and instantiates it withActivator.CreateInstance(:532-538). - Why it's built this way: ADR-115.
- Where it's used: registered in
MMCA.Common.API'sDependencyInjection(MMCA.Common/Source/Presentation/MMCA.Common.API/DependencyInjection.cs) and consulted byStronglyTypedIdSchemaTransformer(MMCA.Common/Source/Presentation/MMCA.Common.API/OpenApi/StronglyTypedIdSchemaTransformer.cs). Framework coverage isStronglyTypedIdSerializationTests(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/IsStronglyTypedIdfor detection;StronglyTypedIdTypeConverter<TSelf, TValue>, attached viaTypeDescriptor.AddAttributes. - Concept introduced: none new; the assembly-scan companion to the per-type converter.
- Walkthrough:
Register(Type)(:89) resolves the wrapped value type or throwsArgumentExceptionnaming the offending type (:93-96), builds the closedStronglyTypedIdTypeConverter<,>and attaches it withTypeDescriptor.AddAttributes(identifierType, new TypeConverterAttribute(converterType))(:100). For a value-type identifier it then callsTypeDescriptor.Refreshon the closedNullable<TId>(:108-111). The comment gives the failure this prevents (:102-107): MVC binds an optionalTId?query-string parameter throughNullable<TId>'s converter, andTypeDescriptorcaches thatNullableConverterwith 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 treatsTId?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) callsRegisterfor every candidateGetIdentifierTypesyields and returns the count.GetIdentifierTypes(Assembly)(:143) tolerates a partially loadable assembly: it catchesReflectionTypeLoadExceptionand falls back to the partialTypesarray (: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 satisfyingIsStronglyTypedId(:158-164). - Why it's built this way: ADR-115.
- Where it's used: called from
MMCA.Common.Infrastructure'sDependencyInjection(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs) and byStronglyTypedIdRegistryfor its own assembly-scan constructor. Framework coverage isStronglyTypedIdTypeConverterTests(MMCA.Common/Tests/Core/MMCA.Common.Shared.Tests/Identifiers/StronglyTypedIdTypeConverterTests.cs) plusStronglyTypedIdApiTests(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.GetIdentifierTypesfor the scan constructor;StronglyTypedId.IsStronglyTypedId/GetValueTypefor 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, flattensGetIdentifierTypesacross them, deduplicates the result, and orders it byFullName(:696-703) for a stable enumeration order across runs. The explicit-list constructor (:712) validates every entry withIsStronglyTypedIdand throwsArgumentExceptionnaming 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 viaGetValueType, 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'sDependencyInjection(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs) and byStronglyTypedIdModelConfiguration(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Conventions/StronglyTypedIdModelConfiguration.cs) andApplicationDbContext(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/ApplicationDbContext.cs) for EF value-converter wiring. Framework coverage isStronglyTypedIdTests(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 structcarrying theVersionstring the user is accepting (MMCA.Common/Source/Core/MMCA.Common.Shared/Legal/AcceptLegalTermsRequest.cs:12). - Depends on: nothing first-party; BCL
stringonly. - 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
Versionparameter (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]byLegalAcceptanceControllerBase(MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Legal/LegalAcceptanceControllerBase.cs:100) and constructed byLegalAcceptanceUIServicewhen the gate posts an acceptance (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Legal/LegalAcceptanceUIService.cs:53). Framework coverage isLegalAcceptanceControllerBaseTests(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,AcceptedOnand the derivedIsCurrentflag (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 areinit-only andIsCurrentis never set by callers: the static factoryEvaluatederives 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).IsCurrentis 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 throughILegalAcceptanceService(ILegalAcceptanceService.cs:18). The UITermsAcceptanceGateconsumes it to decide whether to show the acceptance dialog. Unit coverage isLegalAcceptanceDTOTests(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
Errorin the Application layer and the Blazor client must recognise it without referencing Application, the same placement ruleAuthErrorCodesfollows.[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
VersionNotCurrentCodebyLegalAcceptanceErrors(MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Legal/LegalAcceptanceErrors.cs:17), and matched byTermsAcceptanceGateto 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"andPath = "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
MessageHeadersdoes for broker headers.[Rubric §15, Best Practices & Code Quality]covers the single-source-of-truth angle. - Walkthrough:
Actionis the template relative to a controller routed atUsers(the data-export precedent):GETreads the caller's standing,POSTrecords an acceptance (LegalAcceptanceRoutes.cs:9-13).Pathis the full relative path the client calls (:16). - Where it's used:
[HttpGet]/[HttpPost]onLegalAcceptanceControllerBase(MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Legal/LegalAcceptanceControllerBase.cs:59,93) and the two HTTP calls inLegalAcceptanceUIService(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, anAvailableflag, an opaqueDatapayload, and anUnavailableReason(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 ofUserDataExportDTO.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, reportingAvailable = 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.SectionNameandAvailablearerequired(UserDataExportDTO.cs:65,72), so a section envelope cannot be constructed without answering both questions.Datais typedobject?for the same reasonUserDataExportDTO.Subjectis: the framework owns the envelope, the contributor owns the payload shape, andSystem.Text.Jsonserializes anobject-typed property by its runtime type (UserDataExportDTO.cs:74-78). The fourth property carries the section's most security-sensitive rule:UnavailableReasonis "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 theAvailableflag 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-sectiontry/catch: from a successfulUserDataExportSectionResult(MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/ExportUserData/ExportUserDataHandlerBase.cs:205-211) and from thecatchthat degrades a throwing contributor (ExportUserDataHandlerBase.cs:213-226), where the reason is the fixed string onUserDataExportSectionDefaultsrather than anything derived from the exception (:224) and the exception detail goes to the log instead (:218). The envelopes are collected intoUserDataExportDTO.SectionsatExportUserDataHandlerBase.cs:123-126,135. The contributors themselves implementIUserDataExportSection(ExportUserDataHandlerBase.cs:63). - Caveats / not-in-source: nothing prevents an envelope from setting
Available = trueand a non-nullUnavailableReasonat the same time, orAvailable = falsewith 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 stringmessage-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
ConcurrencyETagandIdempotencyHeadersfollow 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), andCorrelationId = "MMCA-Correlation-Id"(:41). Each doc comment states when the header is absent:TenantIdfor a tenant-less publish,UserIdfor work raised by the system rather than a user,UserRolesandUserPermissionswhen the actor holds none.UserPermissionsis 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:
BrokerMessageBussets these headers on publish (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/BrokerMessageBus.cs), andConsumerOriginRestorereads them back to rehydrate the tenant/actor context for a handler (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Consumers/ConsumerOriginRestore.cs). Framework coverage isBrokerMessageBusTests(MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Messaging/BrokerMessageBusTests.cs) andIntegrationEventConsumerContextTests(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 stringnaming 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:
FeatureFlagAttributeandFeatureFlagLifetime(bothMMCA.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 theMicrosoft.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 annotationNotificationFeaturescarries (MMCA.Common/Source/Core/MMCA.Common.Shared/Notifications/NotificationFeatures.cs:11). - Walkthrough: a
static classcontaining 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 andOwneras a named one; aPermanentflag must not name aRemoveBydate, unlike aTemporaryone (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:FeatureFlagLifecycleTestsBasefails the build on a flag that carries no declaration or on aTemporaryone past itsRemoveBy(MMCA.Common/CLAUDE.md, "FeatureGate" bullet), andFeatureFlagRegistryreports 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 byFeatureFlagLifecycleTestsandFeatureFlagRegistryTests(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.jsonfiles 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 ownFeatureManagemententry.
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
UserDataExportSectionDTOenvelopes (MMCA.Common/Source/Core/MMCA.Common.Shared/Privacy/UserDataExportDTO.cs:15-49). - Depends on:
UserDataExportSectionDTO; theUserIdentifierTypealias (ADR-085);System.Runtime.Serializationattributes (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 notIQueryCacheable, 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 anObjectResult(MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Privacy/DataExportControllerBase.cs:103-113).[Rubric §9, API & Contract Design]:FormatVersionversions "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, andUserIdarerequired(:22,26,30), so the envelope cannot be constructed without them.Subjectisobject?(: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 anobject-typed property serializes by its runtime type underSystem.Text.Json(:32-38). That last clause is the mechanism that makes the erasure of the static type harmless.nullis legal and means the app publishes no subject fields.Sectionsdefaults 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>implementsIQueryHandler<TQuery, Result<UserDataExportDTO>>(ExportUserDataHandlerBase.cs:66), stampsCurrentFormatVersion = "1.0"into it (ExportUserDataHandlerBase.cs:74,131), and takesGeneratedOnfrom an injectedTimeProviderrather 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 ownGeneratedOnso 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 ownUsersDataExportController(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'sAbstractValidator<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 answers202 Acceptedunconditionally (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 a400, 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 explicitWithMessage(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 inMMCA.Common.Application, with the comment explaining why it must happen here rather than in the per-module scan (DependencyInjection.cs:67-69). The resolvedIValidator<ForgotPasswordRequest>is then consumed indirectly: an app's forgot-password command implementsICommandWithRequest<ForgotPasswordRequest>(MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/ForgotPassword/ForgotPasswordHandlerBase.cs:71), andCommandRequestValidator<TCommand, TRequest>bridges the command'sRequestproperty to this validator (MMCA.Common/Source/Core/MMCA.Common.Application/Validation/CommandRequestValidator.cs:37-39), auto-registered for every such command atMMCA.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.SecurityAlgorithmsfor 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 exactlyAsymmetric, an HMAC validator exactlySymmetric, 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 JOSEalgvalue and throwsArgumentOutOfRangeExceptionfor an undefined value.AcceptedFor(JwtAlgorithms.cs:61-62): the accepted list for a configured algorithm,AsymmetricorSymmetricbyIsAsymmetric.
- 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-processBuildValidationParameters(WebApplicationBuilderExtensions.Authentication.cs:227-229,247-248,261-262); the issuerTokenService, which picks its validation list and signingalghere (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/TokenService.cs:93,95,279,297);RsaJwksProvider, which stampsalgon 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'sJwtTokenGenerator(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):Emailmust be non-empty and a valid address,Tokenmust be non-empty (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Validation/SignInLinkRequestValidators.cs:29-34). - Depends on:
RedeemSignInLinkRequest;FluentValidation'sAbstractValidator<T>. - Concept: the shape-only posture
ForgotPasswordRequestValidatorintroduced, 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 bySignInLinkTokenService, which answers every miss with the sameSignInLinkErrorsfailure. - Walkthrough: a block-bodied constructor with two independent
RuleForchains (SignInLinkRequestValidators.cs:29-34), each stage carrying an explicitWithMessage, sharing the file withSendSignInLinkRequestValidator. - 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 throughCommandRequestValidator<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'sAbstractValidator<T>. - Concept: the shape is the one
ForgotPasswordRequestValidatorintroduced. 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 asIValidator<RefreshTokenRequest>intoAuthenticationValidators(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:
Emailmust 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'sAbstractValidator<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 withConfirmEmailRequestValidator. - 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.csis 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):Emailmust 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'sAbstractValidator<T>. - Concept: the enumeration-safe posture
ForgotPasswordRequestValidatorintroduced, 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 withRedeemSignInLinkRequestValidator. - 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 throughCommandRequestValidator<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:
Codemust be non-empty and no longer thanMaxCodeLength(MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Validation/TwoFactorCodeRequestValidator.cs:22-24). - Depends on:
TwoFactorCodeRequest;FluentValidation'sAbstractValidator<T>. - Concept: presence and a length ceiling only, the shape-only posture
ForgotPasswordRequestValidatorintroduced, 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 chainingNotEmpty().MaximumLength(MaxCodeLength)onCode(: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'sAbstractValidator<T>and itsIncludecomposition. - Concept: the
IncludecompositionResetPasswordRequestValidatorintroduces, applied to the third password-writing path.[Rubric §11, Security]: the doc comment states the intent, the new password goes through "the sameStrongPasswordRules{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 codeChangePassword.CurrentPassword.Required(ChangePasswordRequestValidator.cs:20-21).Include(new StrongPasswordRules<ChangePasswordRequest>(x => x.NewPassword, codePrefix: "ChangePassword.NewPassword"))(ChangePasswordRequestValidator.cs:23). With acodePrefixeach policy rule answers under{codePrefix}.{Rule}(for exampleChangePassword.NewPassword.MinLength), the shape the sharedWithRuleCodehelper 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 offLoginRequestValidator. - Where it's used: registered by
AddApplication()(the class remarks say so,ChangePasswordRequestValidator.cs:14) through the framework assembly scanservices.AddValidatorsFromAssemblyContaining<ClassReference>()(MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.cs:70). It reaches the pipeline throughCommandRequestValidator<TCommand, TRequest>for a command that implementsICommandWithRequest<ChangePasswordRequest>. The framework handler's own constraint is onlyIUserScopedCommand<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'sChangePasswordCommanddoes (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/ChangePassword/ChangePasswordCommand.cs:13). Covered byMMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Auth/Validation/ChangePasswordRequestValidatorTests.cs, and its registration byMMCA.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; BCLRSA,ECDsaandCryptographicException;Microsoft.IdentityModel.TokensRsaSecurityKey,ECDsaSecurityKeyandAsymmetricSecurityKey. - Concept: the algorithm-family split
JwtAlgorithmsintroduces, 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:
P384OidandP384FriendlyNames(JwtKeyMaterial.cs:16,18): the curve is matched by OID1.3.132.0.34or 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 anRSA, 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 forECDsa, plus aCryptographicExceptionnaming the actual curve when the key is not on P-384.CreatePublicKey(JwtKeyMaterial.cs:74-96): imports with the right loader, then exportsincludePrivateParameters: falseinto a fresh key, so a private PEM supplied by mistake still yields only the public half; stampsKeyIdwhen one is given.StrengthShortfall(JwtKeyMaterial.cs:109-132): returns a description of the shortfall (an RSA modulus belowminimumRsaKeySizeBits, or an EC key off P-384) ornull. It also returnsnullwhen the PEM cannot be read (ArgumentExceptionorCryptographicException), because reading the key is the loader's check, not this one (JwtKeyMaterial.cs:105-107).IsP384andCurveName(JwtKeyMaterial.cs:134-146):IsP384requires a named curve matched by OID (ordinal) or friendly name (ordinal ignore-case);CurveNamefalls 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
TokenServiceloads its signing and validation keys throughImportP384/ImportRsa(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/TokenService.cs:326-327); the in-process validator builds its key withCreatePublicKey(MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/WebApplicationBuilderExtensions.Authentication.cs:245), as doesJwksSettingsfor each additional rotation key (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/JwksSettings.cs:291); and the startup options validator measures every configured PEM withStrengthShortfallagainst the floor set byJwt: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 onEmail, presence onToken, and the shared strong-password policy onNewPassword(MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Validation/ResetPasswordRequestValidator.cs:16-23). - Depends on:
ResetPasswordRequest;StrongPasswordRules<T>;FluentValidation'sAbstractValidator<T>and itsIncludecomposition. - 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'sIncludemerges 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 sameStrongPasswordRules<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).EmailgetsNotEmpty().EmailAddress()(:16-18), matching the forgot-password half so the two steps agree on what an address is.TokengetsNotEmpty()with a reset-specific message (:20-21); no format check, because the token's validity is a lookup, not a shape. ThenInclude(new StrongPasswordRules<ResetPasswordRequest>(x => x.NewPassword))(:23) grafts the seven policy rules onto theNewPasswordfield (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 throughCommandRequestValidator<TCommand, TRequest>for any command implementingICommandWithRequest<ResetPasswordRequest>, the constraintResetPasswordHandlerBase<TUser, TCommand>declares (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/ResetPassword/ResetPasswordHandlerBase.cs:51). The request arrives atPasswordResetAuthControllerBase<TForgotPasswordCommand, TResetPasswordCommand>(MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/PasswordResetAuthControllerBase.cs:108), which is why a policy failure surfaces as the documented400(PasswordResetAuthControllerBase.cs:104) while a bad token collapses to401(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:
Permissionsmust be non-null, and each entry must be non-empty and withinPermissionGrant.PermissionMaxLength(MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Validation/AdministrationRequestValidators.cs:34-40). - Depends on:
SetRolePermissionsRequest;PermissionGrant(forPermissionMaxLength);FluentValidation'sAbstractValidator<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 emptyPermissionslist 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 isnull, 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 byRuleForEach(x => x.Permissions).NotEmpty().MaximumLength(PermissionGrant.PermissionMaxLength)(:41-44), each stage carrying an explicitWithMessage. It shares its file withSetUserRolesRequestValidator, 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.ManageRolespermission can never itself become a stored grant, isStoredPermissionRoleAdministrationService'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:
Rolesmust be non-null, and each entry must be non-empty and withinPermissionGrant.RoleMaxLength(MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Validation/AdministrationRequestValidators.cs:15-21). - Depends on:
SetUserRolesRequest;PermissionGrant(forRoleMaxLength);FluentValidation'sAbstractValidator<T>. - Concept: the mirror of
SetRolePermissionsRequestValidatorone level up in the same file: an empty list is a legitimate intent (stripping every role from an account) whilenullis 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 byRuleForEach(x => x.Roles).NotEmpty().MaximumLength(PermissionGrant.RoleMaxLength)(:22-25), each with an explicitWithMessage. - Why it's built this way: the same administration surface
SetRolePermissionsRequestValidatorguards; 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 mostNameMaxLength(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 techniqueResetPasswordRequestValidatorintroduces, taken to its limit: four of the five statements areIncludecalls, 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 ownRegister.{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 policyChangePasswordRequestValidatorapplies to a new password.- Two
RequiredStringRules<RegisterRequest>for the names, each bounded byNameMaxLength(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).Whenis 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:AcceptedTermsis 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 asIValidator<RegisterRequest>intoAuthenticationValidators(MMCA.Common/Source/Core/MMCA.Common.Application/Auth/AuthenticationValidators.cs:35,69), and run at the top of the registration workflow inAuthenticationServiceBase<TUser>(MMCA.Common/Source/Core/MMCA.Common.Application/Auth/AuthenticationServiceBase.cs:302). Covered byMMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Auth/Validation/RegisterRequestValidatorTests.cs, with registration asserted inMMCA.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:Emailmust be non-empty, at mostEmailMaxLengthcharacters and a valid address;Passwordmust be non-empty and at mostPasswordMaxLength(1024) characters; the optionalTwoFactorCodeis only bounded in length (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Validation/LoginRequestValidator.cs:24,30,34-44). - Depends on:
LoginRequest;RegisterRequestValidatorfor the email bound andTwoFactorCodeRequestValidatorfor the code bound;PasswordComplexityas the reference the password bound sits above;FluentValidation'sAbstractValidator<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).EmailMaxLengthis the registration bound itself (LoginRequestValidator.cs:24, aliasingRegisterRequestValidator.EmailMaxLength, 100, atMMCA.Common/Source/Core/MMCA.Common.Application/Auth/Validation/RegisterRequestValidator.cs:23), and 1024 sits well abovePasswordComplexity.MaximumLength(128,MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/PasswordComplexity.cs:24), so no settable password is refused here. Notice what is absent: noStrongPasswordRules<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 whyResetPasswordRequestValidatorincludes it and this one does not. - Walkthrough: two public constants,
EmailMaxLength(LoginRequestValidator.cs:24) andPasswordMaxLength = 1024(LoginRequestValidator.cs:30), then a block-bodied constructor with three independentRuleForchains (LoginRequestValidator.cs:32-45), each stage given an explicitWithMessage.EmailrunsNotEmpty,MaximumLength,EmailAddress(:34-37);PasswordrunsNotEmpty,MaximumLength(:39-41);TwoFactorCoderuns onlyMaximumLengthagainstTwoFactorCodeRequestValidator.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 withstring.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 asIValidator<LoginRequest>intoAuthenticationValidators, 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 whatAuthenticationServiceBase<TUser>consumes.PasswordMaxLengthis also the capConfirmEmailRequestValidatorapplies to a supplied current password (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Validation/EmailConfirmationRequestValidators.cs:43-46). Covered byMMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Auth/Validation/LoginRequestValidatorTests.cs. - Caveats / not-in-source:
AuthenticationValidatorsalso requires anIValidator<RegisterRequest>(AuthenticationValidators.cs:35,69), which the framework's ownRegisterRequestValidatorsupplies (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-levelRegisterRequestValidator, 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:
Emailmust be non-empty and a valid address,Tokenmust 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 suppliedCurrentPasswordis length-capped, a suppliedNewPasswordmust meet the strong-password policy, and the two are never accepted together (EmailConfirmationRequestValidators.cs:43-54). - Depends on:
ConfirmEmailRequest;LoginRequestValidatorforPasswordMaxLength;StrongPasswordRules<T>(MMCA.Common/Source/Core/MMCA.Common.Application/Validation/CommonValidationRules.cs:248);FluentValidation'sAbstractValidator<T>. - Concept: the same "validation that deliberately stops short" posture
ForgotPasswordRequestValidatorintroduces: 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.csusage 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 splitLoginRequestValidatordraws: 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 sameStrongPasswordRulesa 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 withEmailConfirmation.PasswordRequiredunless 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 explicitWithMessage, sharing the file withSendEmailConfirmationRequestValidator.EmailandToken(:36-41): two independentRuleForchains.CurrentPassword(:43-46):MaximumLength(LoginRequestValidator.PasswordMaxLength), onlyWhenit is not null.NewPasswordmust beEmpty()wheneverCurrentPasswordis non-empty (:48-50), with the message "Enter either your current password or a new password, not both."- A
Whenblock (:52-54) thatIncludesStrongPasswordRules<ConfirmEmailRequest>onNewPasswordonly 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 whenRequireConfirmedEmailis configured and theUserimplementsIEmailConfirmableUser(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 throughCommandRequestValidator<TCommand, TRequest>for any command implementingICommandWithRequest<ConfirmEmailRequest>, the constraintConfirmEmailHandlerBase<TUser, TCommand>declares (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/EmailConfirmation/ConfirmEmailHandlerBase.cs:70). Covered byMMCA.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 statichelper with one predicate,IsStored(IAuthUser), which answers whether an account carries stored password material: a non-emptyPasswordHashAND a non-emptyPasswordSalt(MMCA.Common/Source/Core/MMCA.Common.Domain/Auth/Credentials/PasswordCredential.cs:13-14). - Depends on:
IAuthUser(itsPasswordHashandPasswordSaltmembers). - 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
internaltoMMCA.Common.Domain, and the Domain project opens its internals toMMCA.Common.Application(and to the Domain tests) throughInternalsVisibleTo(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 asHasStoredCredential(MMCA.Common/Source/Core/MMCA.Common.Application/Auth/AuthenticationServiceBase.cs:937), whichCanSignInWithPasswordcombines with the service-account check (AuthenticationServiceBase.cs:943-944).RedeemSignInLinkHandlerBaseasks it before confirming an existing unconfirmed account, and only an account that holds a password goes on to theIPasswordClearableUserbranch (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.AcquireAsyncreturns. 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; implementsSystem.IDisposable; wraps aSystem.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 rawSemaphoreSlimrequiresWaitAsyncandReleaseto be paired by hand, and the pairing has to survive an exception in between; forgetting thefinallydeadlocks every later caller on that semaphore permanently. Returning a handle turns the pairing into ausingstatement, which the compiler expands to atry/finallyfor you. The caller's whole contract becomes one line, and the doc comment says so: "Await the call inside ausingstatement so the release happens even when the guarded work throws" (KeyedSemaphoreStripe.cs:53-55).[Rubric §12, Performance & Scalability]: making it areadonly record structmeans 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 aninternalconstructor so only the enclosing stripe set can hand out a live handle (KeyedSemaphoreStripe.cs:82).Disposeis_stripe?.Release()(KeyedSemaphoreStripe.cs:85). The null-conditional is load-bearing rather than defensive noise: a struct always has a parameterlessdefaultform that no constructor ever ran for, sodefault(Releaser).Dispose()is reachable C# and must be a no-op instead of aNullReferenceException. The doc comment states that guarantee (KeyedSemaphoreStripe.cs:84). - Why it's built this way: synchronous
IDisposablerather thanIAsyncDisposablebecauseSemaphoreSlim.Releasedoes not block. Contrast the distributed path, whereInProcessDistributedLockreturns anIAsyncDisposable?(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 ausing:MemoryCacheServiceatMMCA.Common/Source/Core/MMCA.Common.Infrastructure/Caching/MemoryCacheService.cs:181(itsGetOrCreateAsyncimplementation),CookieSessionRefresheratMMCA.Common/Source/Presentation/MMCA.Common.API/SessionCookies/CookieSessionRefresher.cs:167, andIdempotencyFilteratMMCA.Common/Source/Presentation/MMCA.Common.API/Idempotency/IdempotencyFilter.cs:225.ICacheServicedeclaresGetOrCreateAsyncwith 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: itsTryAcquirePopulateLockAsyncreturnsKeyedSemaphoreStripe.Releaser?(MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Decorators/CachingQueryDecorator.cs:179, acquiring at:182or, 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
UserIdentifierTypealias (IUserAdminDTO.cs:25), so the account identifier is the DTO's ownId. - 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.cscannot know each app's concrete user-list DTO, so it depends on this interface instead; each app's own list DTO implements it.IsLockedis deliberately one boolean over two different underlying representations: the doc comment states ADC reads it offLockedOn is not nullwhile 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), andIsLocked(:37, whether the account is shut out of sign-in). The account identifier is inherited asIdfromIBaseDTO<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 byMMCA.Common.UI'sDependencyInjection.cs; implemented by ADC'sUserListDTO(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
Passkeysconfiguration 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>andValidateOptionsResultfromMicrosoft.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.Validatereturns success immediately whenEnabledis 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 whenUri.TryCreateparses it as absolute, the scheme ishttpsorhttp, 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 requiresRelyingPartyId(:34-37) andRelyingPartyName(:39-42), requires at least one entry inOrigins(:44-47) and adds one failure per entry thatIsAbsoluteOriginrejects, quoting the offending value (:48-53), and requiresDataSourceName(: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
TryAddEnumerablenext toValidateOnStart()(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 sealedpositional record a sign-in-link token is cached as:TokenHashBase64,Purpose, optionalFirstNameandLastName,FailedAttempts, andExpiresAtUnixSeconds(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:
FirstNameandLastNamecarry the provisioning name an invitation brings and are null for a plain sign-in link (SignInLinkTokenService.cs:208-209).ExpiresAtUnixSecondsexists so a rewrite after a wrong guess can keep the original lifetime (SignInLinkTokenService.cs:211); the service rewrites withentry 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 designSignInLinkTokenServicesays 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 aSignInLinkProfile(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
SemaphoreSlimstripes, and the caller gets back aReleaserto 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 aConcurrentDictionary<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); 256SemaphoreSliminstances is a fixed, small, one-time allocation.- The parameterless constructor chains to the width-taking one (
:30-33). The real constructor validates withArgumentOutOfRangeException.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. Widthis 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-DefaultWidthcollision" (MMCA.Common/Tests/Presentation/MMCA.Common.API.Tests/SessionCookies/CookieSessionRefresherTests.cs:740,771).AcquireAsync(:60) resolves the stripe, awaitsWaitAsync(cancellationToken)withConfigureAwait(false)per ADR-049 (:63), and wraps the semaphore in aReleaser(: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.Ordinalis 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 touint, rather than passed toMath.Abs, becauseint.MinValuehas no positive counterpart andMath.Abswould 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 whyIDistributedLockis preferred when present (MMCA.Common/Source/Presentation/MMCA.Common.API/Idempotency/IdempotencyFilter.cs:35-38).Where it's used: four holders, all
staticor 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 theQueryCacheKeyLocksholder behindCachingQueryDecorator<TQuery, TResult>(MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Decorators/CachingQueryDecorator.cs:263-266).InProcessDistributedLockcites 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
IAuthUserwith 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;ResultfromMMCA.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, whichPasswordCredentialreads as "no password" (IPasswordClearableUser.cs:13-17). - Walkthrough: the same opt-in capability pattern as
IPasswordChangeableUserandIPasswordRehashableUser: 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 itsUsertype. - Where it's used:
RedeemSignInLinkHandlerBase.ConfirmExistingAccountAsyncchecksPasswordCredentialfirst, refuses with the generic invalid-link error (and logs) when the user is notIPasswordClearableUser, revokes every session, then callsClearPassword()before confirming and saving (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/SignInLinks/RedeemSignInLinkHandlerBase.cs:300-335). ADC'sUserimplements 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 byMMCA.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:
RolePermissionsResponseandPermissionCatalogResponse(both inMMCA.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 onGetCatalogAsync(:57-61) state that the permission list it returns is the compiled catalog, so an editor built from that response can never submit anythingSetStoredPermissionsAsyncwould refuse as unknown, and the parameter doc onSetStoredPermissionsAsync(:70-74) adds the one hard exclusion: no submitted list may includeAdministrationPermissions.ManageRoles, so a role editor can never grant a role the permission to edit roles. The interface remarks name the two validation refusals,PermissionGrant.ManageRolesMustBeCompiledandPermissionGrant.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 withUserAdministration.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 oneRolePermissionsResponseper 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 optionalchangedByprincipal name on the rows it creates.callerHoldsPermissionis 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;nullapplies 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 theManageRolesexclusion 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 byRolesAdminControllerBase(MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Administration/RolesAdminControllerBase.cs), which passes itsCallerHoldsPermission()ceiling on every set (RolesAdminControllerBase.cs:160), and, through it, by each app's admin roles controller, for exampleMMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/Controllers/AdminRolesController.cs; registered throughMMCA.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
UserIdentifierTypealias, and Result and its generic form. Generic overTUserDto, 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 onSetLockedAsync(: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'sRevokeAllAsyncover 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 anErrorType.Unavailablefailure (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:UsersAdminControllerBaseuses it "to refuse administering an account whose role grants a permission the caller does not hold" (:35-39), and the controller calls it atMMCA.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
TUserDtoso 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'sUserAdministrationService, for exampleMMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/Administration/UserAdministrationService.cs:37-43, and registered throughMMCA.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
TUserconstraint),System.Linq.Expressions.Expression, theUserIdentifierTypealias, 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 withIsCurrentfalse 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 withIsCurrentfalse. 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 anExpression<Func<TUser, bool>>that holds for an account with at least one live session or, withsignedInfalse, 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 atUserSessionsAdministrationService.MaxSignedInUsersAcrossDataSources, and above that bound it fails withUserSessionsAdministrationService.SignedInFilterTooLargeCoderather 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 byUsersAdminControllerBase(MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Administration/UsersAdminControllerBase.cs) and by ADC'sUserListEntityQueryService, which callsGetSignedInFilterAsync<User>andCountLiveSessionsAsyncover 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
Emailvalue object fromMMCA.Common.Shared.ValueObjects.Contact(IEmailIdentifiedUser.cs:1). - Concept: the same opt-in capability shape as
IPasswordClearableUserandIEmailConfirmableUser, but required rather than optional: the workflows that look an account up by address constrainTUserto 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'sUsertype. - Walkthrough: the remarks carry the one implementation rule. Implement the member with the
aggregate's own mapped
Emailproperty 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.Createstores the address trimmed and lower-cased, so the comparison is exact (IEmailIdentifiedUser.cs:12-17). The predicate itself isUserEmailLookup.HasEmail<TUser>,user => user.Email == email(MMCA.Common/Source/Core/MMCA.Common.Application/Users/UserEmailLookup.cs:28-30), and the read isFindUntrackedByEmailAsync, 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
TUserconstraint onAuthenticationServiceBase<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) andRedeemSignInLinkHandlerBase(MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/SignInLinks/RedeemSignInLinkHandlerBase.cs:68). Covered byMMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Users/Lookup/UserEmailLookupTests.csand, for the SQL translation,MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Persistence/Conversions/UserEmailLookupTranslationTests.cs. - Caveats / not-in-source: ADC's
Userdoes not list this interface (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Domain/Users/User.cs:38-39), and both ADC and Store pinMMCA.Common.Domainat1.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
sealedimplementation ofISignInLinkTokenServiceoverICacheService: 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 atSignInLinkTokenService.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).
- 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,
- Walkthrough:
IssueAsyncincrementssigninlink:req:{address}throughICounterStore.IncrementAsyncwith aRequestWindowMinuteswindow and, once the count passesMaxRequestsPerEmail, returnsError.TooManyRequests("Authentication.SignInLinkThrottled", ...)withRetryAfterset 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:64states 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 fromLifetimeFor(:83), and caches aSignInLinkEntryunder that lifetime (:85-93).ValidateAndConsumeAsynchashes the presented token once (:104), then walks both purposes, sign-in and invite (Purposes,:53). Each record is read withGetFromSharedStoreAsync, 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 isCryptographicOperations.FixedTimeEquals(:126); on a match the record is removed from the cache AND the address's request counter is reset throughICounterStore.ResetAsync, so the signed-in owner is not left throttled (:128-131), and the result is aSignInLinkGrantcarrying the purpose and any invitation profile (:133). With no match, every outstanding record gets a failed attempt (:139-142) and the caller receives one genericSignInLinkErrors.InvalidLink(:144).RecordFailedAttemptAsyncremoves 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, soUser@x.comanduser@x.comshare 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 noIDistributedLock: 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 inSignInLinkSettings: 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 bindsAuthentication:SignInLinkswithValidateDataAnnotations().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 setsAuthentication:SignInLinks:Enabled(DependencyInjection.Auth.cs:111-114). Consumers resolve the interface, not this class. Tests construct it directly inMMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Auth/SignInLinkTokenServiceTests.csand inMMCA.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
Fido2verifier (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,Fido2VerificationExceptionand its request/response types) andSystem.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 asFido2VerificationExceptionand returned as a validationResultcarrying 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 thefield ??=backing-field form; the comment says why: "a host with passkeys disabled never reads the relying-party settings" (:22).Create(:133-143) mapsRelyingPartyId,RelyingPartyNameand the origins, each cut back withGetLeftPart(UriPartial.Authority)into a case-insensitive set (:139-141), and passesmetadataService: 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 callsMakeNewCredentialAsyncwith 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 emptyAllowedCredentialslist, so the authenticator offers whichever discoverable passkeys it holds for the relying party, and withUserVerificationRequirement.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) callsMakeAssertionAsyncwith the stored public key and signature counter, and an ownership callback that requires the assertion's user handle to equal the stored credential'sUserHandlebyte for byte (:120-121). It returns the new signature counter (:125).TransportName(:162-171) maps eachAuthenticatorTransportto the WebAuthn spelling the browser reports (usb,nfc,ble,smart-card,hybrid,internal), falling back toToString().
- Why it's built this way: discoverable credentials with an empty allow list give a usernameless
sign-in, and
AttestationConveyancePreference.Nonewith 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
IPasskeyCeremonyby 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 byMMCA.Common/Tests/Core/MMCA.Common.Passkeys.Tests/Fido2PasskeyCeremonyUserVerificationTests.cs. - Caveats / not-in-source:
internal sealed, reached only throughIPasskeyCeremony.
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 andILogger(primary constructor,:62-67);TUserconstrained to AuditableAggregateRootEntity<TIdentifierType> overUserIdentifierType(:68); RefreshSessionRevocation; Result andError. - 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 onlyMapToDto,IsLocked,ApplyLockState,GetRole,ApplyRoleandCreateExactlyOneRoleError(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 answersLockMarkerNotWrittenCode(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) andGetRoleAsync(:93-105) read throughGetReadRepositoryand returnMapToDto(user)orGetRole(user), or a not-found error built byNotFound, which stamps the calling method as source andtypeof(TUser).Nameas target (:275-276).SetLockedAsync(:114-159) loads through the trackingGetRepository(:119-126), recordswasLocked = IsLocked(user)(:128), callsApplyLockStatewith 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 theLockMarkerNotWritten()failure, built withError.Unavailableand the sourceSetLockedAsync(: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'sCreateExactlyOneRoleError(:174-177), runsValidateRequestedRolebefore the account is loaded (:179-183), loads it, applies the role, and comparesGetRolebefore 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) returnstrueonceMarkDeletedAsynccompletes and, on any exception except cancellation, logs a warning and returnsfalse, 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 ispartial.
- Why it's built this way: the remarks on
CreateExactlyOneRoleErrorexplain 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 overUserandUserAdminDTO); reached throughUsersAdminControllerBase; tested byUserAdministrationServiceBaseTests(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
IUserSessionsAdministrationServiceimplementation, 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, theUserIdentifierTypealias, and Result andError. - 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 readstimeProvider.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 classwith a primary constructor takingIRefreshSessionStore,TimeProvider, and an optionalViewAs.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), andSignedInFilterTooLargeCode = "UserSessions.SignedInFilterTooLarge"(:33). GetSessionsAsync(:41-65) loads the user's un-revoked rows withGetUnrevokedByUserAsync, keeps those whereUserIdmatches andIsActiveAt(now)holds (the store returns expired-but-unrevoked rows on purpose, so expiry is filtered in memory), orders byCreatedAtthenIddescending, and projects each to aRefreshSessionSummaryResponsewithIsCurrent: falseand the row'sToDeviceMetadata()(:60-61). No user lookup is made, so an unknown user is an empty list rather than a 404, revealing nothing theGET Admin/Users/{userId}endpoint does not (:35-40).GetSignInsAsync(:72-85) delegates toSignInHistory.ReadAsyncwith the store, the user, the clock's now,currentSessionId: nulland 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 forQueryUserIdsWithLiveSessions(typeof(TUser), now)(:95), an unexecuted query that composes into a query over the user entity and isnullwhenever 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 returnsuser => composed.Contains(user.Id)or its negation (:96-101). Otherwise it readsGetUserIdsWithLiveSessionsAsync(now, MaxSignedInUsersAcrossDataSources + 1), one more than the bound so a cut list is detectable (:103-106), fails withError.Validation(SignedInFilterTooLargeCode, ...)when the count exceeds the bound (:107-113), and otherwise returns the same predicate shape over a materializedList<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 callsCountLiveSessionsByUserAsync(userIds, now)(:135).
- Two public constants bound the cross-source fallback:
- 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
TryAddScopedatMMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:210; exercised byUserSessionsAdministrationServiceTestsandUserSessionsAdministrationServiceSignedInTestsunderMMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Auth/Administration/, and byViewAsSignInHistoryTests(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.Passkeyspackage, anAddPasskeys(configuration)extension member onIServiceCollectionthat 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 theTryAdd*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": withPasskeys:Enabledfalse every passkey endpoint answers 404 and no context maps thePasskeyCredentialstable, 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
PasskeySettingsto itsSectionNamewithValidateOnStart()and addsPasskeySettingsValidatorthroughTryAddEnumerable(:41-44), so a bad section fails the host at startup (ADR-070); - registers
Fido2PasskeyCeremonyas a singletonIPasskeyCeremony, because "the verifier holds only the bound relying-party settings" (:46-47); - registers
PasskeyChallengesandIPasskeyServiceas scoped, because the service reads the request's passkey store and signs in through the app's scoped authentication service (:49-52); - adds
TimeProvider.SystemwithTryAddSingleton, so a host's own clock registration wins (:53).
- binds
- 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, thePasskeyCredentialsmigration on the Identity database (DesignTimeDbContextOptions.EnablePasskeys), and an appAuthenticationServicederiving fromAuthenticationServiceBase. The passkey store comes fromAddInfrastructure, and the challenges need the shared cache and the distributed lockAddCachingregisters (:28-35; ADR-108). Every registration uses aTryAdd*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
MachineClientsconfiguration 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/MaxAccessTokenMinutesbounds); IServiceAccountProvisioner;IServiceProviderandIServiceProviderIsService(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 rootIServiceProviderin its primary constructor (:15) and, whenEnabledis true, asksIServiceProviderIsServicewhetherIServiceAccountProvisioneris 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).AccessTokenMinutesoutsideMinAccessTokenMinutestoMaxAccessTokenMinutesfails, with the message built throughstring.Create(CultureInfo.InvariantCulture, ...)(:23-28).- A blank
DataSourceNamefails (:30-33). Neither this check nor the lifetime check depends onEnabled. - The provisioner check runs only when
Enabledis true and the container exposesIServiceProviderIsService; 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 flipsMachineClients:Enabled. - Where it's used: registered with
TryAddEnumerableas anIValidateOptions<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
IUserIdProviderthat 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) andClaimsPrincipalExtensionsforFindUserIdValue(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 anIUserIdProviderreturns; the built-in provider readsClaimTypes.NameIdentifier. This framework mints the user id only intosub(seeTokenService,MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/TokenService.cs:151), and whether that survives assubor arrives mapped toNameIdentifierdepends 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 returningconnection?.User.FindUserIdValue(). Two null paths are handled without a branch: a null connection short-circuits tonull, andFindUserIdValueis an extension on a nullableClaimsPrincipalthat returnsnullwhen 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 withCultureInfo.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 makesSignalRPushNotificationSenderreach the right sockets onNotificationHub(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Notifications/Push/SignalRPushNotificationSender.cs:17-21for the single-user send and:25-34for 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 rawClaimsPrincipal, 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) andClaimsPrincipalExtensionsfor the identity read (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Context/CurrentUserService.cs:4-5); externals areMicrosoft.AspNetCore.Http.IHttpContextAccessor,System.Security.ClaimsandSystem.Globalization. The claims it reads are the onesTokenServicewrites. - 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 referenceHttpContext, so the port lives in Application and this HTTP-aware implementation lives in Infrastructure, which is the only placeIHttpContextAccessorappears.[Rubric §12, Performance & Scalability]explains theLazy<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 underCultureInfo.InvariantCulture, so they must be read invariantly too, or a request running under a culture with different separators misreads decimal, double andDateTimeclaims. Both parse paths say so explicitly (:40, with the comment at:38-39, and the identifier parse insideClaimsPrincipalExtensions.GetUserIdatMMCA.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 toClaimsPrincipalExtensions.GetUserId, which readssubfirst and falls back to the mappedClaimTypes.NameIdentifier(MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/ClaimsPrincipalExtensions.cs:26-28) before parsing intoUserIdentifierType. 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 firstClaimTypes.Roleclaim.User(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Context/CurrentUserService.cs:26) returns the principal, substituting a fresh emptyClaimsPrincipalwhen 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 aNullReferenceException.UserIdandRole(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Context/CurrentUserService.cs:29,:31) are one-line projections of the two lazies, both nullable, bothnullwhen unauthenticated.GetClaimValue<T>(string claimType)(MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Context/CurrentUserService.cs:35-42) is constrained toT : struct, IParsable<T>and calls the static abstractT.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 returnsnullfor an absent or unparsable claim, and unlikeUserId/Roleit is a fresh lookup on every call.
- The primary constructor takes
- 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-rolledFindFirst("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 isDbContextFactory, which takes it as a constructor dependency (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/Factory/DbContextFactory.cs:53,:57) and passesUserIdinto 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.
RolesandIsInRoleare 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 requestHttpContextis null andUserIdis thereforenull, which means a save performed by a background worker stamps no acting user; nothing in this file substitutes a system identity.