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

Onboarding guide

24. ADC Identity Module (Users, Profiles, GDPR Export/Erasure)

What this chapter covers. This is the Identity bounded context of MMCA.ADC, the module that owns who a person is across every ADC surface: web, WebAssembly, and MAUI. It is a leaf in the module dependency graph (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/IdentityModule.cs:10) but it touches every layer end to end, so this chapter doubles as a compact tour of one full vertical slice built on the framework taught in groups 1 through 15. The single aggregate is User, and around it sit the credential lifecycle, the role vocabulary (RoleNames), the change-password / password-recovery / email-confirmation / change-preferences / avatar use cases, the administration surface an operator works from (lock, unlock, change the role an account holds, edit what a role may do), the two privacy use cases that make ADC compliant (data-subject export and erasure), the persistence and EF configuration, the REST controllers, the gRPC contract that lets a peer service ask Identity a question, the integration events that keep the User-to-Speaker link consistent across the service split, and the Blazor profile, user-administration and role-administration UI. The per-type sections follow; this overview shows how the pieces fit and how a request flows through them.

Almost everything here is an instantiation of upstream framework machinery, cross-referenced rather than re-taught (the conventions themselves are introduced once in the primer): the Result pattern (G01), the AuditableAggregateRootEntity<TIdentifierType> entity chain plus the IAnonymizable and PiiAttribute governance markers (G02), the outbox spine with BaseIntegrationEvent (G04), the CQRS command/query handler pipeline (G05), the shared auth engine (AuthenticationServiceBase<TUser>, RoleValue, HasPermissionAttribute, IRefreshSessionStore, SoftDeletedUserCache, IPasswordResetTokenService) from G08, and the hoisted user use-case bases from G14 (ChangePasswordHandlerBase<TUser, TCommand>, ForgotPasswordHandlerBase<TUser, TCommand>, ResetPasswordHandlerBase<TUser, TCommand>, GetUserPreferencesHandlerBase<TUser>, DeleteUserHandlerBase<TUser, TCommand>, ExportUserDataHandlerBase<TUser, TQuery>) alongside the IModule composition system. The lenses this chapter most strongly embodies are [Rubric §4, Domain-Driven Design] (a behavior-rich aggregate that guards its own invariants), [Rubric §11, Security] (credential handling, RS256 JWTs, permission-based authorization, a fail-closed OAuth link gate, single-use reset tokens), and [Rubric §30, Compliance / Privacy / Data Governance] (the export and erasure flows). The // BR-NN markers quoted below are the in-code business-requirement references, catalogued in the ADC business-requirements guide; the privacy promises they implement live in MMCA.ADC/PRIVACY.md.

Projects, one bounded context

The module is split along the standard Clean Architecture layering ([Rubric §3, Clean Architecture]), each project pinned by a trivial AssemblyReference / ClassReference anchor pair (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Domain/AssemblyReference.cs:5, :11) that Scrutor scanning and the architecture-fitness tests use to name the assembly. MMCA.ADC.Identity.Domain holds the User aggregate (User.cs:37), the UserRole value type (UserRole.cs:18), the UserInvariants rule class (UserInvariants.cs:9), the reserved-address helpers SyntheticAccounts and ServiceAccounts (ServiceAccounts.cs:13); it declares no domain event of its own, depends only on MMCA.Common.Domain and MMCA.Common.Shared, and knows nothing of EF or ASP.NET. MMCA.ADC.Identity.Application holds the use-case handlers, the roster mapper UserListDTOMapper (Users/DTOs/UserListDTOMapper.cs:14), the attendee keyset read AttendeeKeysetSpecification (Users/Specifications/AttendeeKeysetSpecification.cs:13), and the cross-module service implementations (the register and change-password request validators are framework types in G08, RegisterRequestValidator and ChangePasswordRequestValidator, registered by AddApplication(), MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Validation/RegisterRequestValidator.cs:15-20); its DependencyInjection registers explicitly the services the convention scan would not pick up: AuthenticationService as the module's IAuthenticationService (:35), the shared SoftDeletedUserValidator<TUser> closed over User (:37), AttendeeQueryService as the module's IAttendeeQueryService (:38), VerifiedUserLookupService as its IVerifiedUserLookupService (:39), UserAdministrationService as its IUserAdministrationService<UserAdminDTO> (:43), the framework ports ViewAsSubjectResolver (:47) and ServiceAccountProvisioner (:51), UserListEntityQueryService as the roster's IEntityQueryService<User, UserListDTO, UserIdentifierType> (:56, rationale at :53-55), and LegalAcceptanceService as its ILegalAcceptanceService (:60) (MMCA.ADC.Identity.Application/DependencyInjection.cs:35-60); it then contributes the three export sections in the order they appear in the exported document (:62-68), and leaves handlers, mappers, validators, and domain-event handlers to ScanModuleApplicationServices<ClassReference>() (:72). MMCA.ADC.Identity.Infrastructure declares no context class of its own (one sealed context per engine is composed by the host, ADR-006); it holds the UserConfiguration EF mapping that brings User into that model and the IdentityModuleDbSeeder, both discovered by assembly scanning, plus the SkiaSharp avatar codec SkiaSharpImageProcessor, the one service its registration hook adds by hand: AddModuleIdentityInfrastructure binds it as a singleton behind the Application-owned IImageProcessor port, because it is stateless and its native library loads on the first upload rather than at registration (MMCA.ADC.Identity.Infrastructure/DependencyInjection.cs:23-25, rationale at :16-19). MMCA.ADC.Identity.API holds the REST controllers, the IdentityModule descriptor (IdentityModule.cs:12), and the IdentityErrorResources anchor whose .resx siblings translate domain error codes into the supported languages (IdentityErrorResources.cs:11, rationale at :3-9, ADR-027). MMCA.ADC.Identity.Shared is the contract package every other layer (including the WebAssembly client) can reference without dragging in the domain: it carries the DTOs (UserListDTO at UserListDTO.cs:16, UserAvatarDTO at UserAvatarDTO.cs:6, and the export family headed by UserDataExportSubjectDTO at UserDataExportSubjectDTO.cs:16), the IAttendeeQueryService cross-module interface (MMCA.ADC.Identity.Shared/Users/IAttendeeQueryService.cs:17, tagged [ServiceContract] at :16), the IVerifiedUserLookupService contract Engagement asks (IVerifiedUserLookupService.cs:16), the UserRegistered, UserDeleted, UserEmailVerified and TicketHolderInvited integration events, the ClaimNames JWT claim vocabulary beside RoleNames (ClaimNames.cs:19), and the IdentityPermissions / IdentityPermissionGrants capability constants and grant map (MMCA.ADC.Identity.Shared/Authorization/IdentityPermissions.cs:10, IdentityPermissionGrants.cs:17). MMCA.ADC.Identity.UI sits in the same module folder and holds the Blazor pages; two further projects live under MMCA.ADC/Source/Services/ instead, because they exist only for the extracted topology: MMCA.ADC.Identity.Contracts (the gRPC adapter) and MMCA.ADC.Identity.Service (the extracted process host). The identifier alias for this context is UserIdentifierType = int, a database-generated identity (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Shared/MMCA.ADC.Identity.GlobalUsings.IdentifierType.cs:2), while the cross-context LinkedSpeakerId is a nullable SpeakerIdentifierType (User.cs:87, ADR-048).

User (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Domain/Users/User.cs:37) is the only aggregate root in the module, and it carries more responsibility than most: it is the credential store (PasswordHash plus a per-user PasswordSalt, both byte[], User.cs:69, :73), the profile (Email, FirstName, LastName, each marked [Pii], User.cs:56, :60, :64), the preference store (PreferredCulture / PreferredTheme, :106, :109, ADR-027 / ADR-028), the avatar URL holder (:118, also [Pii], BR-116a, ADR-045), the external-OAuth link (LoginProvider / ProviderKey, :99, :103), and the 1:1 cross-context LinkedSpeakerId pointing at a Conference speaker (:87, BR-207 / BR-208 / BR-209), itself [Pii] because it points the account at a named public speaker profile, so Anonymize clears it (:80-86), and stamped with SpeakerLinkChangedOn so a link or unlink event that arrives after a newer one is dropped (:89-95). Note what the aggregate deliberately does not hold: refresh tokens and the MAUI device metadata. Both live on per-device rows in the framework's RefreshSessions table, hashed at rest (BR-205 / BR-206, stated on the type itself at User.cs:13-18, ADR-097). Every property has a private setter, so state changes only through the aggregate's own methods: encapsulation as a compile-time guarantee ([Rubric §4, Domain-Driven Design], [Rubric §1, SOLID]). Its interface list is what binds the aggregate to the shared G08 user workflows, IPasswordChangeableUser, IPasswordRehashableUser (through which the sign-in flow upgrades an outdated hash, RehashPassword at :588), IPasswordClearableUser (through which the sign-in-link flow removes a password set before the address was confirmed, ClearPassword at :613), IUserPreferences, and IErasableUser, joined by IEmailConfirmableUser for the confirmation flag (IsEmailConfirmed, :52), ILegalAcceptingUser for the accepted Terms of Service version and instant (AcceptedTermsVersion, :136, TermsAcceptedOn, :142) and IEmailIdentifiedUser, all listed at :38-39 with the reasoning at :21-28. The soft-delete is the inherited one and raises no domain event: an erasure is announced only by the UserDeleted integration event that DeleteUserHandler raises on this aggregate (:26-28). The last interface in the list, IAuditedEntity (:39), is the one non-behavioral marker: it opts the aggregate into a recorded change history, because an account record is where a support or compliance question is actually asked (who changed this attendee's email, when was this account raised to Organizer, who anonymized it) and the plain audit fields answer only "who touched it last" (:30-33). One flag marks a row that is not a person: IsServiceAccount (:150) is set only by CreateServiceAccount, and the framework refuses such an account on every interactive sign-in path and as a view-as target, while the attendee broadcast skips it (:144-149, ADR-140).

It follows the standard framework shape: a private EF constructor (User.cs:180), a private state constructor (:190), and static factory methods returning Result<T>. Create (:224) validates every invariant with Result.Combine(...) before constructing anything, so an invalid user is unrepresentable; CreateExternal (:275) builds an OAuth account with empty credential arrays; CreateFromInvitation (:324) builds the Attendee account a ticket-holder invitation link provisions on its first redemption, with no local password and its address already confirmed, because the link that creates it was delivered to that mailbox (:306-311); and CreateServiceAccount (:362) builds the passwordless account a machine client signs as, under a generated ServiceAccounts address. A subtlety worth carrying forward: none of the factories raises a registration event. The Id is database-generated ([IdValueGenerated] at :36, Id set to default until EF assigns it), so the cross-module UserRegistered is raised by the registration and provisioning workflows only after the insert has executed and a real id exists (:209-215, :316-318). The behavior methods each guard their own rule: ChangePassword (:563) re-validates the new hash and salt and raises no domain event, because the handlers that change or reset a password revoke the live sessions themselves (:556-558); UpdatePreferences (:532) validates against the supported-culture allowlist and the light/dark theme values; AcceptTerms (:418) validates the version and is idempotent for the version already on record; ConfirmEmail (:398) and LinkExternalProvider (:451) record a proven address and announce it through UserEmailVerified, skipped for an account that has not been saved yet because its creation is announced by UserRegistered once the id exists (RaiseEmailVerified, :464); LinkSpeaker / UnlinkSpeaker (:483, :505) apply Conference's link events and ignore a stale one; Lock / Unlock (:626, :631) and ChangeRole (:644) serve administration; and Anonymize (:667) performs the erasure described below.

The Domain project carries one more type that is not part of the aggregate. SyntheticAccounts (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Domain/Users/SyntheticAccounts.cs:20) names the reserved email domain the conference-day k6 load test registers its accounts under, loadtest.adc.invalid (:23), and classifies an address with IsSynthetic, trimmed and case-insensitive (:30-31). Those accounts are ordinary Attendees on every request path, so the test measures the real login and bookmark paths, but the two side effects that would leak outside the test skip them: registration schedules no confirmation email (MMCA.ADC.Identity.API/Controllers/AuthController.cs:83), so a run never spends the SMTP relay's quota or sender reputation, and AttendeeQueryService leaves them out of the attendee audience that organizer broadcasts fan out to, in the page and the count alike (AttendeeQueryService.cs:44, :77). The domain sits under the RFC 2606 .invalid name, which can never be deliverable, so no real attendee can match the rule, and the k6 script spells the same domain, so the two change together (SyntheticAccounts.cs:3-19).

UserInvariants (UserInvariants.cs:9) is the co-located static rule class whose methods each return a Result, several of them delegating to the shared CommonInvariants (UserInvariants.cs:40-46). Centralizing each rule as a named, side-effect-free method is what makes the domain exhaustively unit-testable ([Rubric §14, Testability]), and its const length limits (FirstNameMaxLength = 100, LastNameMaxLength = 100, EmailMaxLength = 100, DeviceFieldMaxLength = 256, UserInvariants.cs:12-21) are the same constants UserConfiguration uses for the EF column widths (UserConfiguration.cs:23, :29, :33) and SendSignInLinkInternalCommandValidator uses for an invitation's address and names (SendSignInLinkInternalCommandValidator.cs:22, :31, :35), so the domain rule, the invitation contract, and the schema cannot drift apart. The registration request is checked by the framework RegisterRequestValidator instead, whose own 100-character limits (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Validation/RegisterRequestValidator.cs:23, :26) match these by value, not by reference. UserRole (UserRole.cs:18) is a value object over the shared RoleValue base that fixes the ADC role set to three members: Organizer (:21), Attendee (the registration default, :24), and ContentEditor (:31), each wrapping the matching RoleNames constant so the stored value and the JWT claim spell the role identically, a strict capability subset that curates the session catalog but cannot change event structure, rooms, feedback questions, run session selection, or read the user list (:26-31). Its IsOrganizer(string?) helper (:76) does a case-insensitive compare, because raw JWT role claims may carry any casing, and it is the exact check the delete and export authorization gates use.

Authentication: a thin subclass over the shared engine

The login / registration / refresh / revocation workflow is not re-implemented here. It lives in AuthenticationServiceBase<TUser> (G08), which owns the validate-first flow, the lockout and rate-limit protection (ADR-029), and the BR-205 / BR-206 refresh-session rotation with reuse detection (ADR-050); the ADC subclass documents that division of labor at MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/AuthenticationService.cs:20-51. AuthenticationService (AuthenticationService.cs:52) fills in only the context-specific pieces: CreateUser supplies the Attendee default role (BR-45, :209-217) and, when a Terms of Service version is configured, stamps it on the new account (:219-228), CreateAccessToken attaches the app claims (:232-233) built by AdditionalClaims: speaker_id when the user is linked to a speaker (BR-209) and email_verified=false while the address is unconfirmed (:557-566), OnUserRegisteredAsync raises the UserRegistered integration event (:249-255), ValidateLoginCandidateAsync and ValidateRefreshCandidateAsync refuse an account an administrator has locked, after the password check so the distinct message cannot be read by anyone sweeping addresses (:92-123), and CheckEmailConfirmed adds the privileged-account rule: an account that can change conference content (Organizer, ContentEditor, or linked to a speaker) must have a confirmed address to sign in or refresh, while an attendee still signs in unconfirmed (:125-163). ExternalLoginAsync drives the OAuth find-by-provider, else link-by-email, else create flow (:290, body ExternalLoginCoreAsync at :303, ADR-036); that flow applies the same administrator lock and privileged-account rule to both existing-account branches before anything is saved, so they bind every sign-in path and not only the password and refresh hooks (:379-390, CheckExistingExternalAccount at :423-443). Session issuance is deliberately not among its constructor dependencies: access-token minting, refresh-session rotation and the per-user session cap live in the framework IAuthSessionIssuer that AddInfrastructure registers, so the token lifetimes and the cap are configuration (the Jwt and RefreshSessions sections) rather than arguments of this service (:57, :66, rationale at :45-50). The shared AuthenticationValidators bundle (:56) and IOptions<EmailConfirmationSettings> (:58) are handed straight to the base as well (:65, :68), while the IInternalCommandScheduler (:59) stays with the subclass for the external sign-up described next.

Three details in that class are worth reading closely. First, atomicity: RegisterAsync wraps the whole base workflow in UnitOfWork.ExecuteInTransactionAsync (AuthenticationService.cs:88), so the user insert (first save) and the outbox row for UserRegistered (raised in OnUserRegisteredAsync once the id exists, :249-255) commit together. The event is not fire-and-forget after the fact, it is captured by the outbox inside the same transaction (ADR-003); the class remarks spell out the failure the design removes, namely a serialized UserId = 0 payload that the cross-service Conference consumer cannot resolve (:35-43). The external-login path does the same through ExternalLoginAsync (:290, transaction at :298, with the event raised only for a brand-new account by RecordNewAccountAsync, :464-493), and when the provider did not vouch for the address that same second save also writes a scheduled SendEmailConfirmationCommand row, so the confirmation request commits with the account or not at all (:452-457, :478-489). The two paths differ in one payload field: a local registration raises the event with EmailVerified: false, because an address typed into a form proves nothing, so Conference logs any speaker whose email matches for an organizer to link by hand instead of auto-linking (:243-246, :252), while the OAuth path carries the provider's own verified-email assertion, which is what decides whether that auto-link may run at all (:264-266, :475-476). That assertion arrives as the emailVerified argument of ExternalLoginAsync, which the framework's OAuth controller reads from the external-login principal and which fails closed, absent or unparseable reading as false (:274-280); the host maps Google's and Apple's verification assertion onto that one email_verified claim, while GitHub's payload asserts nothing, so GitHub logins read as unverified by design (MMCA.ADC/Source/Services/MMCA.ADC.Identity.Service/Program.cs:152-156). Second, the link-by-email gate: linking an external identity to an existing local account on nothing but an email match would be an account-takeover path through any provider that hands out unverified emails, so TryLinkProviderToExistingAccount (AuthenticationService.cs:505) applies three refusals in order. It refuses outright when the address already resolves to an account linked to any external login (a different provider, or the same provider under a different key), because the aggregate stores one provider pair and re-linking would strand the original login or hand the account to another provider account (Auth.ExternalProviderAlreadyLinked, :511-523); it returns Auth.ExternalEmailNotVerified when the provider did not assert the address as verified (:525-536); and it refuses an account that already signs in with a password (Auth.ExternalLinkRequiresLocalSignIn, :538-551), because the assertion proves only the provider side of the address and nothing proves the local row's address was ever confirmed, so only an account with no local credentials is claimable by an email match. When an existing, unconfirmed account is reached and the provider asserted that account's own address as verified, the assertion is the proof the confirmation rule asks for, so the account is confirmed through the aggregate instead of refused (:434-442). Identity signs its tokens with RS256 and publishes the public key at /.well-known/jwks.json; peer services validate tokens by fetching that document rather than sharing a secret (Program.cs:33-37, ADR-004, [Rubric §11, Security]). The audience those peers expect is configuration with one named contract: JwtAudience owns the Jwt:Audience key (JwtAudience.cs:17) and a RequireConfigured guard that throws when the value is absent or blank (:25-29), and the Conference, Engagement and Notification hosts each pass their bearer setup through it (MMCA.ADC/Source/Services/MMCA.ADC.Conference.Service/Program.cs:340, MMCA.ADC.Engagement.Service/Program.cs:194, MMCA.ADC.Notification.Service/Program.cs:184). The value deliberately has no hardcoded fallback: a host that silently used one would boot with an audience nobody configured and answer every request with a 401 that reads like a token problem instead of a wiring problem, so a missing key fails at startup instead (JwtAudience.cs:8-13). Third, one EmailExistsAsync override deserves its own note, because the reason is the opposite of the obvious one: it passes ignoreQueryFilters: true (AuthenticationService.cs:198-199) not to keep an erased address reserved. Erasure always pairs Delete with Anonymize, which rewrites the address to a placeholder, so a real erased email is re-registrable by design (GDPR), and the unique Email index is filtered on [IsDeleted] = 0 anyway, so a soft-deleted row no longer blocks the insert. The filter bypass stays so the pre-insert check reports a live conflict instead of letting a legacy or placeholder row surface as a save-time surprise (:189-196).

The HTTP surface is equally thin. AuthController (MMCA.ADC.Identity.API/Controllers/AuthController.cs:31) extends UserAccountAuthControllerBase<TChangePasswordCommand, TChangePreferencesCommand> (G12), which supplies the login / register / refresh / revoke actions inherited from AuthControllerBase plus the three self-service account actions (PUT password, PUT preferences, GET preferences, AuthController.cs:18-25); the ADC subclass adds only two overrides and two command factories. RegisterAsync (:58) captures the client IP for registration rate limiting and the user-agent that names the new refresh session (BR-213, :62-66) and carries the per-IP auth-ip fixed window; LoginAsync re-declares the same window as a password-spray guard, because the per-email lockout alone cannot throttle one source spraying one password across many addresses. CreateChangePasswordCommand and CreateChangePreferencesCommand are the only wiring the base needs to dispatch ChangePasswordCommand (ChangePasswordCommand.cs:12) and ChangePreferencesCommand (ChangePreferencesCommand.cs:11) through the G05 decorator pipeline; both are user-scoped commands, implementing the framework IUserScopedCommand<TRequest> over the caller's own id (ChangePasswordCommand.cs:13, ChangePreferencesCommand.cs:12). The three handlers on that path are all body-less subclasses of a G14 base whose only purpose is that the source reported on every error stays the ADC class name, which clients match on: ChangePasswordHandler (ChangePasswordHandler.cs:24, ADR-032), ChangePreferencesHandler (ChangePreferencesHandler.cs:17), and GetUserPreferencesHandler (GetUserPreferencesHandler.cs:8-13). The password one is body-less but not dependency-less: it hands the base the IRefreshSessionStore, the ILoginProtectionService and a TimeProvider (ChangePasswordHandler.cs:28-30) so a successful change revokes every live session on the account, because otherwise a stolen refresh chain outlives the credential the user just replaced, which is the one remediation a compromised account has (:19-22). OAuthController (OAuthController.cs:21) is a body-less subclass of OAuthControllerBase (G12) that drives the Google/GitHub/Apple challenge, callback, complete, single-use-code-exchange flow with tokens never riding the redirect URL, and with the class-level routing and versioning attributes re-declared locally because they are not reliably inherited (:10-19); it is an ADC-only feature, since MMCA.Store uses local credentials only. UserClaimsController (UserClaimsController.cs:16) reflects the authenticated JWT's claims back to the client (:28-38). UsersController (UsersController.cs:105) hosts the rest: the three avatar endpoints, the organizer roster at GET Users/paged (:157-161), and the account delete (:187). Its roster endpoint is gated by capability rather than by role name, [HasPermission(IdentityPermissions.UsersRead)] (:158), and the identity:users:read grant (MMCA.ADC.Identity.Shared/Authorization/IdentityPermissions.cs:13) is handed to Organizer, and to no other role, through IdentityPermissionGrants.Apply in AddModuleIdentityAPI (MMCA.ADC.Identity.API/DependencyInjection.cs:44, map at IdentityPermissionGrants.cs:36-38, ADR-020). That roster rides the generic paged entity path: the action hands the standard filter bag, sort, and paging values to an injected IEntityQueryService<User, UserListDTO, UserIdentifierType> (UsersController.cs:106, :161-176), clamping the page size at 500 before the query runs (:54, :174, BR-11), and writes the same pagination header the framework's paged endpoint writes (:180-182). The service behind it is UserListEntityQueryService (MMCA.ADC.Identity.Application/Users/UserListEntityQueryService.cs:44), a subclass of the framework EntityQueryService<User, UserListDTO, UserIdentifierType> (:50-51) whose field contract is the UserListDTO property names minus ActiveSessionCount (:60-62, :68), so every grid operator works while nothing outside the DTO (the password hash and salt, the device fields) is reachable as a filter or sort key (:16-19); its rows come from UserListDTOMapper (UserListDTOMapper.cs:14), which projects only the id, email, names, role, CreatedOn and LockedOn (:21-30). The live session count is the one roster column that is not an entity column, so the service handles it around the generic query. The grid's signed-in filter arrives under the ActiveSessionCount key as > 0 or = 0, is lifted out of the filter bag, and becomes a read specification over the ids that IUserSessionsAdministrationService.GetSignedInUserIdsAsync reports (UserListEntityQueryService.cs:84-115, :157-173); any other operator or value is the validation failure User.InvalidSignedInFilter (:93-100). The count itself is filled from one CountLiveSessionsAsync call over the page's ids, an absent id reading 0 (:180-201), so the roster costs one session query per page rather than one per row ([Rubric §12, Performance and Scalability]).

Password recovery: the anonymous half of the credential lifecycle

PUT /Auth/password only serves a user who can already sign in. The recovery pair that serves one who cannot is a second, anonymous vertical, and it is assembled the same way: two ADC command records over two G14 workflow bases, exposed by a sibling controller. ForgotPasswordCommand (MMCA.ADC.Identity.Application/Users/UseCases/ForgotPassword/ForgotPasswordCommand.cs:20) carries nothing but the address, and the record's own summary states the two properties that follow from that (:7-11): it is anonymous by design, because a caller who has lost the credential has no user identifier to scope the command to, and every outcome is reported as success so the response cannot be used to enumerate registered addresses. It is also an internal command, Identity.ForgotPassword.v1 (:19-21): the endpoint dispatches it inline and the handler only schedules it, so the lookup, the token issue and the send run when the processor executes the row, and a mail outage defers the email instead of losing it (:12-17, ADR-114). ForgotPasswordHandler (ForgotPasswordHandler.cs:21) inherits ForgotPasswordHandlerBase<TUser, TCommand>, which schedules that row (the scheduler is a constructor dependency, :26, :29) and, when it executes, mints the single-use token through IPasswordResetTokenService and mails it through IEmailSender under PasswordResetSettings; ADC overrides exactly one member, the untracked lookup by address (:32-36), which mirrors the one AuthenticationService already uses for login.

The redemption half is ResetPasswordCommand (ResetPasswordCommand.cs:10), which carries the address, the token, and the new password as a plain ICommandWithRequest<ResetPasswordRequest> (:9-11). ResetPasswordHandler (ResetPasswordHandler.cs:24) is a body-less subclass of ResetPasswordHandlerBase<TUser, TCommand> kept only so the reported error source stays ResetPasswordHandler (:13-17); it takes ILoginProtectionService as a constructor dependency (:22) because the base clears the account's lockout after a successful reset, so a user who locked themselves out by guessing can use the new credential immediately. Both actions are exposed by PasswordResetController (PasswordResetController.cs:28), a subclass of PasswordResetAuthControllerBase<TForgotPasswordCommand, TResetPasswordCommand> that supplies only the two command factories (:36, :39) and inherits the anonymous posture, the auth-ip rate limiting, and the idempotency from the base (:12-18). It is routed to the same Auth prefix as AuthController (:26) and is a sibling controller rather than more actions on that class, because AuthController already occupies the single inheritance chain, and riding the existing /Auth route means the YARP Gateway needs no change (:19-24). The link the email carries is host configuration, not code: the AppHost calls WithUiLinks(ui) on the Identity service, which sets PasswordReset__ResetUrl to the UI's /reset-password page (MMCA.Common/Source/Hosting/MMCA.Common.Aspire.Hosting/IdentityLinkExtensions.cs:84), because the UI port is dynamic under Aspire and the appsettings default would otherwise address a host that is not listening (MMCA.ADC/Source/Hosting/MMCA.ADC.AppHost/Program.cs:472-478). The storage decision behind the token itself (cache-backed, rather than columns on the user row or a self-contained signed payload) is recorded in ADR-091 ([Rubric §11, Security]).

Email confirmation: proving the address is reachable

ADC asks a new account to prove its address, and deliberately does not gate sign-in on the answer: Authentication:EmailConfirmation:RequireConfirmedEmail is false (MMCA.ADC.Identity.API/Controllers/EmailConfirmationController.cs:13-18). The aggregate carries the one bit, IsEmailConfirmed (User.cs:52), behind IEmailConfirmableUser (:39); it is flipped by the idempotent ConfirmEmail() (:398), set directly when an OAuth provider already asserts a verified address (:300, :451-456), and reset during erasure (:701). EF maps it as a required column with a false default, so a row written by anything that does not set it stays valid and the migration can backfill the accounts that existed before the flag did (UserConfiguration.cs:107-112).

Both halves are ADC specializations over framework bases. SendEmailConfirmationCommand (.../UseCases/SendEmailConfirmation/SendEmailConfirmationCommand.cs:20) carries one address and serves two entry points: the endpoint dispatches it inline, and registration schedules it as an IInternalCommand named Identity.SendEmailConfirmation.v1 (:19), so a mail outage or a crash right after the 201 defers the send instead of losing it, and its one-string payload round-trips through the JSON the durable queue requires (:12-17, ADR-114). SendEmailConfirmationHandler (SendEmailConfirmationHandler.cs:28) inherits the framework SendEmailConfirmationHandlerBase<TUser, TCommand> and overrides exactly one member, the untracked lookup by address (:40-44), the same one ForgotPasswordHandler and AuthenticationService already use; every outcome is a success so the response cannot be used to enumerate registered addresses, and the base only schedules the command from an inline dispatch, so the processor sends it and a failed send retries the row (:13-22). The redemption half overrides nothing at all: ConfirmEmailCommand (ConfirmEmailCommand.cs:11) is anonymous by design because the link is followed from an email client with no session (:6-9), and ConfirmEmailHandler (ConfirmEmailHandler.cs:25) lets the base validate and consume the token, load the account the token names, and call the aggregate idempotent ConfirmEmail, so a token that is wrong, expired or already spent is answered as invalid, which is also what an attacker guessing tokens sees (:12-17).

EmailConfirmationController (EmailConfirmationController.cs:34) exposes the pair anonymously on the same Auth prefix as PasswordResetController, and for the same reason: AuthController already occupies the single inheritance chain, and riding the prefix means both endpoints reach the gateway through the existing /Auth route with no gateway change (EmailConfirmationController.cs:20-25). Both actions, their anonymous posture, their auth-ip rate limiting and their idempotency come from the framework EmailConfirmationControllerBase<TSendCommand, TConfirmCommand>; the class at :29 supplies only the two ADC command records (:12-19). The signed-in half of the reminder is EmailConfirmationReminder (MMCA.ADC.Identity.UI/Components/EmailConfirmationReminder.razor.cs:15): one dismissible content-header line with a resend action, nothing that blocks the page. It reads the token's email_verified claim, named by ClaimNames.EmailVerified (ClaimNames.cs:19), which the server issues only as "false", so a confirmed account renders nothing and the line clears on the next token refresh after the address is confirmed.

ADC also signs a person in without a password. SignInLinkController (MMCA.ADC.Identity.API/Controllers/SignInLinkController.cs:29) publishes POST /Auth/sign-in-link and POST /Auth/sign-in-link/redeem (UC-54, BR-271, BR-275) as one more sibling on the Auth prefix, for the same single-inheritance-chain reason; the actions, the anonymous posture, the auth-ip rate limiting and the idempotency come from the framework SignInLinkControllerBase<TSendCommand, TRedeemCommand>, the class supplies only the two command records, and nothing is sent or redeemed unless Authentication:SignInLinks:Enabled is set. SendSignInLinkCommand (MMCA.ADC.Identity.Application/Users/UseCases/SendSignInLink/SendSignInLinkCommand.cs:20) carries the address and is answered with success whether or not it holds an account (anti-enumeration). Like ForgotPasswordCommand it is an internal command, named Identity.RequestSignInLink.v1 so it is not confused with the invitation's Identity.SendSignInLink.v1: the endpoint dispatch only schedules it, and the lookup, token issue and send run on the processor (SendSignInLinkCommand.cs:12-21, ADR-114). SendSignInLinkHandler (SendSignInLinkHandler.cs:44) emails a 15-minute single-use link through the framework SendSignInLinkHandlerBase<TUser, TCommand>, overriding the same untracked lookup by address ForgotPasswordHandler uses, and it never creates an account: for an address with none it asks Engagement whether an invitation still stands and, when one does, schedules the invitation again rather than sending anything inline. RedeemSignInLinkCommand (RedeemSignInLinkCommand.cs:19) carries the address, the token and the Terms acceptance flag plus the IP and user-agent the new refresh session records, and it is ITransactional for the reason registration is: redeeming an invitation for an address with no account inserts the account and then raises UserRegistered once the id exists. RedeemSignInLinkHandler (RedeemSignInLinkHandler.cs:46) subclasses the framework RedeemSignInLinkHandlerBase<TUser, TCommand>, which spends the token first, resolves the account, confirms the address and opens the session; ADC supplies the account lookup, the account an invitation creates (User.CreateFromInvitation), and two integration events: UserRegistered with EmailVerified true for a provisioned account, which also drives the BR-207 speaker auto-link, and exactly one UserEmailVerified per redemption (BR-272).

The invitation itself starts in Engagement. Its send-invites use case publishes TicketHolderInvited (MMCA.ADC.Identity.Shared/Users/IntegrationEvents/TicketHolderInvited.cs:32, wire name Identity.TicketHolderInvited.v1) through its outbox in the same transaction that stamps the tickets as invited, so a re-run never emails the same order twice; the contract lives in Identity's Shared project because that project is the leaf that references no other module. The names travel because an invitation may create the account, and they are the only personal data the invite needs. TicketHolderInvitedHandler (MMCA.ADC.Identity.Application/Users/IntegrationEventHandlers/TicketHolderInvitedHandler.cs:36), a ScopedIntegrationEventHandlerBase<TIntegrationEvent> subclass, only schedules: it enqueues SendSignInLinkInternalCommand (SendSignInLinkInternalCommand.cs:34, named Identity.SendSignInLink.v1), whose InviteId is the event's MessageId, so a redelivered event schedules a row the send handler recognizes as already sent, and a mail outage defers the invitation instead of failing the delivery (ADR-114). Every member of that record is a JSON primitive or an enum, because the durable queue round-trips the payload through System.Text.Json. SendSignInLinkInternalCommandHandler (SendSignInLinkInternalCommandHandler.cs:41) executes the row after SendSignInLinkInternalCommandValidator (SendSignInLinkInternalCommandValidator.cs:13) has checked it, and the message is InviteEmail (InviteEmail.cs:15): English only, because the recipient may have no account and so no stored culture, with every roster value HTML-encoded because it was typed into a third-party ticketing system. The app-store links it lists come from InviteEmailSettings (InviteEmailSettings.cs:8, the Invites section), and a link left unset is simply not listed.

Proven ownership closes the loop. UserEmailVerified (MMCA.ADC.Identity.Shared/Users/IntegrationEvents/UserEmailVerified.cs:31, wire name Identity.UserEmailVerified.v1) carries the account id and the address, and Engagement subscribes to link that address's tickets to the account. It is raised in three places, each through the outbox in the same save as the state it announces: the aggregate's ConfirmEmail transition, its LinkExternalProvider, and the redeem handler for every redemption the aggregate did not already announce; a consumer must therefore be idempotent. The tickets linked this way appear in the account's data-subject export as UserDataExportTicketDTO rows (MMCA.ADC.Identity.Shared/Users/DataExport/Tickets/UserDataExportTicketDTO.cs:8, BR-274). On the extracted host, the broker subscriptions behind all of this are declared in IdentityBrokerConsumers (MMCA.ADC/Source/Services/MMCA.ADC.Identity.Service/IdentityBrokerConsumers.cs:16), kept out of Program.cs so the subscription list can be asserted without booting the host; every subscription lands on the host's one queue (MessageBus:QueueName).

Administration: accounts, roles, and the capability map

Four further endpoints are framework controllers with an ADC route and nothing else. AdminMachineClientsController (MMCA.ADC.Identity.API/Controllers/MachineClients/AdminMachineClientsController.cs:20) lists, creates, rotates, promotes and revokes the client credentials programs sign in with at Admin/MachineClients, gated by the base on clients:manage, which ADC grants to Organizer only; a client may be backed by ContentEditor or Attendee, and the framework refuses Organizer, whose administration capabilities a machine client must never carry (ADR-140). MachineTokenController (MachineTokenController.cs:20) is the OAuth 2.0 client-credentials endpoint at auth/token: anonymous, throttled by auth-ip on the base, reached through the Gateway's /Auth route, and never a token-issuing path of the web head's same-origin proxy, because a program calls the Gateway directly. The account a client signs as is a User row built by User.CreateServiceAccount and managed by ServiceAccountProvisioner (MMCA.ADC.Identity.Application/Users/Administration/ServiceAccountProvisioner.cs:25), which publishes no UserRegistered and sends no confirmation email, and reads an account back for minting only when it is a live service account, stating each refusal (a person, a locked account, a deleted account) in its own predicate. AdminViewAsGrantsController (MMCA.ADC.Identity.API/Controllers/AdminViewAsGrantsController.cs:20) is the support access log at Admin/ViewAsGrants: every read-only view-as grant, who viewed whom, why, when and how it ended, newest first and paged, gated on users:manage and hosted here because Identity holds the grant store (ADR-137). The subject of a view-as token comes from ViewAsSubjectResolver (MMCA.ADC.Identity.Application/Users/Administration/ViewAsSubjectResolver.cs:24), one untracked projected row that reads soft-deleted rows too, so the framework refuses a deleted account as deleted rather than missing, and that builds the display name the way User.FullName does. AuditHistoryController (MMCA.ADC.Identity.API/Controllers/AuditHistory/AuditHistoryController.cs:19), at Admin/Identity/AuditHistory, pages the recorded change history of one User, newest change first, gated on audit:view by the base; each service host mounts its own, because the reader reads that service's own database (ADR-075). PasskeysController (MMCA.ADC.Identity.API/Controllers/Passkeys/PasskeysController.cs:21), at auth/passkeys, lists, registers, renames and deletes a signed-in account's passkeys and serves the anonymous passkey sign-in (WebAuthn, ADR-139); every action answers 404 unless Passkeys:Enabled is true on the Identity service, and ADC ships it switched off, with only the Development configuration and the AppHost turning it on.

The organizer-facing administration surface is a framework surface with ADC vocabulary plugged into it. UsersAdminController (UsersAdminController.cs:27) subclasses the framework UsersAdminControllerBase<TUserAdminDTO> routed at the literal Admin/Users (:23), so the fixed action templates publish /Admin/Users/paged, /Admin/Users/{userId}, /Admin/Users/{userId}/lock and the rest (:10-14), every action gated on the users:manage capability by the base rather than on a role name (:16-19). Its only own members are two overrides that exist to declare idempotency intent for the architecture suite, both [NonIdempotent] with the reason spelled out: locking is already idempotent in the domain, so a replayed response protects nothing, and caching one would answer a later unlock-then-lock cycle from the cache and report a state the account is not in (:33, :42). AdminRolesController (AdminRolesController.cs:36) is the same shape at Admin/Roles (:34), gated on roles:manage (:16-22), and it supplies no ADC service at all: the host AddStoredPermissionGrants call registers a complete role-administration service over the framework own registry and grant store, and a set edits stored rows only, so nothing reachable there can take away a capability the host compiled in (:23-29).

The ADC half is UserAdministrationService (MMCA.ADC.Identity.Application/Users/Administration/UserAdministrationService.cs:37), the module IUserAdministrationService<TUserDto> closed over UserAdminDTO: it supplies only the account-to-DTO projection (:46), how a lock is read and applied (:58, :62), and the single-role rules (:85, :92-95), while loading, saving and logging stay in the framework base it extends (:20-24, :43). The roster is not here: it is the generic paged entity endpoint GET Users/paged described above (:13-15). Two decisions in it are worth reading. A lock revokes the live sessions: a lock that only refused the next sign-in would leave the account working for the remaining lifetime of every access token it already holds, and its refresh sessions would keep minting new ones, so the framework base revokes the account's refresh sessions over IRefreshSessionStore on a lock and on a role change alike, and writes the soft-deleted user marker that refuses the locked account's already-issued access tokens (:20-24, :41, :43). One role, not a set: the framework contract takes a role list because an app may hold several, and ADC User stores exactly one, so a request carrying zero or two is a validation failure rather than something to silently truncate, and an unknown role is refused before the account is loaded (:27-29, :84-89). UserAdminDTO (UserAdminDTO.cs:25) is the row it projects, a DTO of its own rather than more fields on UserListDTO because the two are reached through different permissions: identity:users:read serves the organizer roster, users:manage serves the administration screens, device metadata stays out of both, and no credential material is ever projected (:11-14). UserListDTO does answer the framework IUserAdminDTO so the shared list component can render it, mapping the lock state off LockedOn explicitly rather than renaming the wire contract (UserListDTO.cs:12-16, :42, :53), and it carries the live ActiveSessionCount the roster service fills per page (:50). On the aggregate the lock itself is a nullable instant, LockedOn (User.cs:125), with IsLocked computed from it rather than stored so the state and the instant it started cannot disagree (:155-164), moved by Lock and Unlock (:626, :631), while the role is changed through the validating ChangeRole (:644).

The capability map is the third piece. IdentityPermissions declares identity:users:read (IdentityPermissions.cs:13) and then deliberately aliases two framework strings rather than coining ADC names, UsersManage (:26) and RolesManage (:41), because the framework admin controller bases gate their actions on those exact capability strings (:19-21, :32-34). Both aliases stay out of the module's All list, which holds only the capabilities ADC itself defines (:49-52, rationale at :43-48), so IdentityPermissionGrants grants All plus the two framework capabilities by name to Organizer and to no other role (IdentityPermissionGrants.cs:32-38, rationale at :25-30), which is the strict-subset property ContentEditor is defined by (:19-24); RolesManage is granted in compiled code and never from a stored row, because it is the only protection on the screen that edits stored rows and a deleted row could otherwise lock every operator out of the surface that would restore it (IdentityPermissions.cs:36-39). The extracted Identity host applies more than its own map: TokenPermissionGrants (MMCA.ADC/Source/Services/MMCA.ADC.Identity.Service/Authorization/TokenPermissionGrants.cs:34) calls every module map (:53-59, wired at Program.cs:267, with the stored half added at :277), because TokenService emits one permission claim per permission the minting host registry grants the account role, and a downstream service (or the Blazor sidebar) reads that claim instead of its own registry: a token minted with only Identity grants would deny in the UI and in the CQRS pipeline what the owning service allows at its endpoint (:14-25). Nothing is restated there, each map is called where its module declares it, and only the contracts assemblies come along, which keeps another module entity configurations out of this service database model (:26-32); grants accumulate and union, so applying a map alongside the module own registration is additive and order-independent (:38-42). [Rubric §11, Security] and ADR-020 are the lenses here: the endpoint decides on a capability, the role is only the key that map is keyed by, and the map itself is editable at runtime without a deploy.

The privacy pair: export and erasure

Two use cases make this module the codebase's clearest [Rubric §30, Compliance / Privacy / Data Governance] story, and both are thin ADC specializations of a G14 base. The erasure workflow lives in DeleteUserHandlerBase<TUser, TCommand>; DeleteUserHandler (MMCA.ADC.Identity.Application/Users/UseCases/DeleteUser/DeleteUserHandler.cs:37) keeps the class name so the reported error source stays stable for clients, and supplies the ADC-specific pieces (:22-35) over a DeleteUserCommand that carries the target id plus the caller's own id and role (DeleteUserCommand.cs:18). HasDeletePrivilege (:51-52) says the Organizer role bypasses the ownership rule, delegating to UserRole.IsOrganizer so the claim's casing does not matter. The base itself revokes the refresh sessions, blanks the erased account's email on the view-as support log's grants, and writes the soft-deleted marker that refuses the account's already-issued access tokens, which is why the refresh-session and grant stores are required constructor dependencies (:28-35, :37-45). OnAfterSoftDeleteAsync (:55) does two things. It raises the cross-service UserDeleted integration event on the aggregate (:71), so the outbox row is written by the very SaveChangesAsync that commits the erasure: Engagement holds a DisplayName snapshot on its leaderboard opt-in and Conference holds the account's feedback text and the email on its linked speaker profile, each in its own process with its own database, so only an integration event through the outbox reaches them and the fact and its announcement must not be able to come apart (:24-27, :65-70). Its payload is deliberately just the user id and a timestamp, because carrying a name or email would publish onto a persistent broker the very personal data the erasure exists to remove (MMCA.ADC.Identity.Shared/Users/IntegrationEvents/UserDeleted.cs:21-25, record at :26-29, wire name pinned by [EventName("Identity.UserDeleted.v1")] at :25). It then schedules the erasure of the avatar photo, which is personal data too: rather than queueing a best-effort post-commit call, the hook enqueues a durable DeleteAvatarBlobInternalCommand row (:73-83, :88-92, BR-116a, ADR-114). The hook runs inside the erasure transaction, so the instruction is enrolled and commits with the anonymized aggregate or rolls back with it, and a scheduling failure fails the erasure rather than committing a partial one the caller was told had succeeded (:94-97). That is the whole reason for the change: the best-effort call it replaces lost the instruction whenever storage was unreachable or the host died in the post-commit tail, which for an erasure request is a photo of a real person surviving the deletion the account was promised (.../DeleteAvatarBlob/DeleteAvatarBlobInternalCommand.cs:8-14). Note the ordering detail at DeleteUserHandler.cs:61-63: the blob name is captured before Anonymize clears the URL. The erasure itself lives in User.Anonymize() (User.cs:667), which irreversibly overwrites the personal fields with placeholders in place rather than hard-deleting the record (:656-665). Keeping the row lets cross-context scalar references (bookmarks, notifications) and the audit trail survive; the replacement email embeds the user id (deleted-{Id}@anonymized.invalid, :672) so the unique-email invariant still holds across many erased accounts, and the operation is idempotent (an already-anonymized user short-circuits at :678-682). This is the anonymize-in-place model of ADR-005, backed by the IAnonymizable marker, and it satisfies the data-subject erasure PRIVACY.md section 11 describes (User.cs:656-660).

The data-subject access request (PRIVACY.md section 12, MMCA.ADC.Identity.Application/DependencyInjection.cs:62) is assembled the same way. ExportUserDataHandler (MMCA.ADC.Identity.Application/Users/UseCases/ExportUserData/ExportUserDataHandler.cs:33) inherits ExportUserDataHandlerBase<TUser, TQuery>, which owns the owner-or-privileged authorization, the account load, and the section fan-out; ADC contributes exactly two things (:9-14) on top of an ExportUserDataQuery shaped like the delete command (ExportUserDataQuery.cs:12-15): HasExportPrivilege, again UserRole.IsOrganizer (:38), and BuildSubjectSnapshotAsync (:41), which projects the account's own portable fields into a UserDataExportSubjectDTO (:48-74). Credentials are deliberately excluded: no password hash, no salt, no refresh material, no provider key (MMCA.ADC.Identity.Shared/Users/DataExport/UserDataExportSubjectDTO.cs:3-8). One small correctness detail sits at :67-73: SQL Server hands audit timestamps back as Kind=Unspecified, so the handler re-stamps them UTC, which is the only reason the exported JSON carries the Z marker the DTO documents. The subject snapshot is the Subject of the shared envelope UserDataExportDTO, and beside it travel one UserDataExportSectionDTO per registered IUserDataExportSection. ADC registers three, in document order (MMCA.ADC.Identity.Application/DependencyInjection.cs:66-68): EngagementUserDataExportSection (.../ExportUserData/EngagementUserDataExportSection.cs:19) reads bookmarks, submitted session questions, the points ledger, check-in history, and leaderboard participation through IUserEngagementExportService (:30-32) and shapes them into UserDataExportEngagementSectionDTO (:34-68) over the per-row records UserDataExportBookmarkDTO, UserDataExportSubmittedQuestionDTO, UserDataExportPointsEntryDTO, and UserDataExportCheckInDTO, turning enum values into their readable names because a data subject reads this document (:49-51, :58-60); NotificationUserDataExportSection (.../ExportUserData/NotificationUserDataExportSection.cs:18) does the same for inbox rows through IUserNotificationExportService (:29-31), into UserDataExportNotificationSectionDTO and its UserDataExportNotificationDTO items (:33-44); and ConferenceUserDataExportSection (.../ExportUserData/ConferenceUserDataExportSection.cs:19), registered last, reads the session and event feedback answers the user authored through Conference's IUserConferenceExportService (:30-32; in-process inside the Conference service, a gRPC adapter everywhere else, :8-11) into UserDataExportConferenceSectionDTO, whose two lists hold UserDataExportFeedbackAnswerDTO rows (:34-50); without it the export left the free-text feedback out silently (M244, :11). A feedback row carries a SessionId or an EventId with the other left null, and the answer travels in full because it is the user's own text or rating (MMCA.ADC.Identity.Shared/Users/DataExport/UserDataExportFeedbackAnswerDTO.cs:3-6, :14, :17, :20). All three return a UserDataExportSectionResult Complete(...) (EngagementUserDataExportSection.cs:70, NotificationUserDataExportSection.cs:46, ConferenceUserDataExportSection.cs:52), and none catches transport failures (:12-16, :11-15 and :13-16 in the same three files): that is the point. The base wraps every section, so a peer that stays unreachable after the standard Polly resilience pipeline degrades to Available = false and the export still succeeds, which is [Rubric §29, Resilience] and [Rubric §7, Microservices Readiness] applied to a compliance workflow. The endpoint itself is a four-line subclass: UsersDataExportController (MMCA.ADC.Identity.API/Controllers/UsersDataExportController.cs:26) extends DataExportControllerBase<TQuery>, which owns the action, its authorization, the PrivacyFeatures.DataExport gate and the file-download response, and it is routed at the literal Users (:24) so the published path stays /Users/{userId}/export even though the base fixes the action template (:19-22).

Avatars: the third mutating slice

The avatar trio is a small but complete example of a file-handling slice ([Rubric §11, Security] at the content boundary, ADR-045). UsersController caps the upload in two places: declaratively via [RequestSizeLimit(MaxAvatarRequestBytes)] (UsersController.cs:159), which is the 2 MB image budget plus 64 KB of headroom for the multipart boundary and part headers so a file at exactly the limit is not rejected by Kestrel with a bare 413 before the friendly error can run (:51, :44-50), and imperatively via an explicit length check that returns an Avatar.InvalidUpload validation error (:98-104, BR-116a). The POST also carries [Idempotent] (:86), because the upload replaces the caller's avatar rather than appending one, so replaying the stored URL for a repeated Idempotency-Key saves a re-encode and keeps a flaky mobile upload from looking like a failure (:79-83). SetUserAvatarHandler (MMCA.ADC.Identity.Application/Users/UseCases/SetUserAvatar/SetUserAvatarHandler.cs:27) handles a SetUserAvatarCommand that carries the bytes as a ReadOnlyMemory<byte> (SetUserAvatarCommand.cs:10) and is built on MutateEntityPayloadHandlerBase<TCommand, TEntity, TIdentifierType, TResultPayload> (:34). It never trusts the client-declared content type: it sniffs magic bytes through the shared ImageContentSniffer before the aggregate is even loaded, so an unsupported upload gets the format error whether or not the account exists (:52-69), re-encodes to a canonical 256x256 JPEG via IImageProcessor (:29, :37, :103), uploads under a randomized blob name through IFileStorageService (:30, :111-118), and parks the replaced blob's name in the MutationContext (:126) so OnMutatedAsync (:141) can schedule its deletion once the new URL is persisted. That deletion is not best effort: the handler enqueues a DeleteAvatarBlobInternalCommand through the framework IInternalCommandScheduler (:31, :156-160), a durable row the processor retries until storage answers (ADR-114). The upload runs inside the mutation, so it also covers the opposite orphan: when the save that should point the row at the new blob fails or throws, HandleAsync schedules that blob's deletion before passing the original outcome on (:71-89), from a fresh DI scope with no cancellation, because the request scope is the one whose save just failed and a cancelled request must not cancel the cleanup (:175-198). The random suffix means a replacement never reuses the old URL, so stale caches self-resolve (:17-18). The result travels back as a UserAvatarDTO built in BuildResult (:169). The image port is the module's own: IImageProcessor (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/IImageProcessor.cs:11) declares one operation, NormalizeToSquareJpegAsync (:18), which decodes (rejecting anything that is not an image), corrects EXIF orientation, center-crops to a square, strips every piece of metadata (EXIF GPS coordinates are PII), and re-encodes as JPEG, so only pixels survive a polyglot or malformed payload (:5-10). Its one implementation, SkiaSharpImageProcessor (MMCA.ADC.Identity.Infrastructure/Services/Users/SkiaSharpImageProcessor.cs:16), encodes the JPEG from a fresh pixel buffer that carries no color space and no metadata, so nothing from the original file can be written back out (:11-14, :103-105), at quality 85 (:46). It bounds the cost an upload can choose before paying it: the stream is buffered up to 32 MiB (:43, :65-72), and the dimensions are read from the codec header, which allocates no frame, and refused above 50 megapixels or 20,000 pixels on either edge (:27, :35, :81-90), because the 2 MB cap bounds only the compressed file and a decompression bomb satisfies it (:23-25). A downscale samples through linear mipmaps, so a large photo shrunk to 256 pixels does not alias (:51-56). Undecodable or oversize content comes back as a failed Result<T> rather than an exception, which MutateAsync passes on unchanged (SetUserAvatarHandler.cs:106-109). RemoveUserAvatarHandler (over RemoveUserAvatarCommand) and GetUserAvatarHandler (over GetUserAvatarQuery) are the siblings on the same resource, and the remove path schedules the same durable deletion (RemoveUserAvatarHandler.cs:20, :74-80). All three avatar paths (replace, remove, erase the account) therefore converge on DeleteAvatarBlobInternalCommandHandler, a subclass of the framework DeleteBlobInternalCommandHandlerBase<TCommand> (DeleteAvatarBlobInternalCommandHandler.cs:17-20) whose only own member names the blob kind for the log lines (:23): the base owns the idempotent delete, treating an already-missing blob as the state the command asks for and completing the row, and returning any other failure so the framework backoff retries it (:10-14). The command record itself implements the framework IDeleteBlobInternalCommand under the wire name Identity.DeleteAvatarBlob.v1 (DeleteAvatarBlobInternalCommand.cs:16-17); DeleteAvatarBlobInternalCommandValidator rejects an empty name before the row is executed, which guards a scheduling bug rather than a caller (DeleteAvatarBlobInternalCommandValidator.cs:12-14, :5-9).

Persistence and seeding

Identity declares no context class of its own: the host composes one sealed context per engine (the framework SQLServerDbContext) over the base ApplicationDbContext, which supplies audit stamping, soft-delete query filters, and outbox / domain-event dispatch, and this module contributes User to that model through its scanned configuration. Identity owns its own ADC_Identity database with its own outbox table, so it never races another service's outbox (MMCA.ADC/Source/Hosting/MMCA.ADC.AppHost/Program.cs:37, ADR-006). UserConfiguration (MMCA.ADC.Identity.Infrastructure/Persistence/EntityConfiguration/UserConfiguration.cs:12) extends EntityTypeConfigurationSQLServer<TEntity, TIdentifierType>, maps the Email value object through the shared EmailValueConverter (:20-24), mirrors the invariant length constants onto the columns, stores the names and the free-text device fields as nvarchar so a non-Latin name is kept as entered rather than corrupted to ? by a varchar code page (:26-27, :65-66), ignores the computed FullName, IsExternalLogin and IsLocked members (:114-117), and pins three indexes that encode business rules as schema ([Rubric §8, Data Architecture]): unique Email (:122), a filtered unique index on LinkedSpeakerId that enforces the 1:1 User-to-Speaker relationship of BR-208 (:124-126), and a filtered unique composite on (LoginProvider, ProviderKey) for external accounts (:128-130). None of them spells the soft-delete clause by hand: the framework's SoftDeleteUniqueIndexConvention appends AND [IsDeleted] = 0 at model finalization, and writing it here would double it (:119-121, ADR-095).

Seeding is gated, not ambient. IdentityModuleSeeder (MMCA.ADC.Identity.API/IdentityModuleSeeder.cs:15) returns immediately unless Seeding:IncludeSampleUsers is set (:28-30, defaulting to false so a production service that sets nothing seeds nothing), and only then runs IdentityModuleDbSeeder (MMCA.ADC.Identity.Infrastructure/Persistence/DbContexts/Seeding/IdentityModuleDbSeeder.cs:27), a subclass of IdentityModuleDbSeederBase<TUser> that contributes only the three-account list (:33-38), the existence predicate (:41) and ADC's User.Create parameter order (:51); the check-then-insert idiom in the base is what makes the seeder idempotent, and the deliberately weak development credentials are documented in its own remarks (:21-25). Note the base's ShouldSeed is deliberately not overridden, so the configuration gate has exactly one home (:17-19). The IdentityModule descriptor itself carries no disabled-module stub: its Register is the single AddIdentityModule() call (IdentityModule.cs:18-19). A peer host that needs Identity's contracts never loads the module at all; it names only its own module to ModuleLoader and registers the gRPC adapter instead, which is then the only implementation of the interface in that process (MMCA.ADC/Source/Services/MMCA.ADC.Identity.Contracts/DependencyInjection.cs:32-36).

Crossing the service boundary: gRPC and integration events

Identity talks to its peers two ways, and both live in Shared and Contracts so neither side reaches into the other's domain ([Rubric §7, Microservices Readiness]). Synchronously, the Notification service needs the attendee audience of a broadcast; it depends on the IAttendeeQueryService interface, which reads that audience as a keyset, one page at a time, so no caller ever loads it whole (MMCA.ADC.Identity.Shared/Users/IAttendeeQueryService.cs:10-15): GetAttendeeUserIdPageAsync returns the ascending ids after a cursor, exactly take of them unless the audience is exhausted, so a short page means the end (:22-38), take is bounded by MaxPageSize = 10_000 (:20), and CountAttendeesAsync counts with the same rule (:40-45). An attendee is an active user with the Attendee role that is neither a machine client's service account nor a synthetic load-test account (:12-14). The in-process implementation is AttendeeQueryService (MMCA.ADC.Identity.Application/Users/AttendeeQueryService.cs:21). Its SQL half is AttendeeKeysetSpecification (MMCA.ADC.Identity.Application/Users/Specifications/AttendeeKeysetSpecification.cs:13), one batch of Attendee-role, non-service accounts after the cursor, ascending by id and paged to the batch size (:18-26). The synthetic filter cannot join it, because Email is stored through a value converter and a domain-suffix test does not translate to SQL (:7-12), so the service projects each batch to the private AttendeeRow record struct of id and address (AttendeeQueryService.cs:102, projection at :88-100), drops the synthetic rows in memory, and keeps reading batches until the page is full or the store runs out (:38-65): the push-delivery walk reads a short page as the end of the audience, so a page thinned by the filter would silently skip every attendee after it (:14-20). The count walks the same batches in steps of CountBatchSize = 1_000 with the same filter, so the two cannot disagree (:24, :69-86). Once Identity runs as its own process, a consumer host registers AttendeeQueryServiceGrpcAdapter (MMCA.ADC/Source/Services/MMCA.ADC.Identity.Contracts/AttendeeQueryServiceGrpcAdapter.cs:14), which implements the same C# interface over the generated client, setting the cursor only when one is given (:23-27), and lets transport failures propagate to the caller by design (:6-13); AttendeesGrpcService (MMCA.ADC.Identity.Service/Grpc/AttendeesGrpcService.cs:34) serves the other end by delegating to the in-process implementation (:55-57, :74). It refuses a page size outside 1 to MaxPageSize with InvalidArgument (:47-52), and because the replies enumerate attendee accounts, not the caller's own, it admits a service caller or a user who holds NotificationPermissions.Manage and answers anyone else with PermissionDenied (:78-87, rationale at :23-30). The host maps it under the InternalCaller policy (MMCA.ADC/Source/Services/MMCA.ADC.Identity.Service/Program.cs:314), because Notification calls it from an internal command with no organizer bearer to forward and therefore presents its service token (:307-313). The registration itself is the Contracts-layer DependencyInjection.AddIdentityAttendeeClient (MMCA.ADC.Identity.Contracts/DependencyInjection.cs:41), which opts the typed client in to that service token (:43, rationale at :26-29) and uses Replace rather than TryAdd so the adapter wins over any registration already present (:46); the extracted Notification host never discovers the Identity module, so this call is the only IAttendeeQueryService registration there (:32-36). Consumer code never changes, only the registration does (ADR-007, ADR-008). The extracted host runs h2c-only for cross-service gRPC, with an optional HTTP/1.1-only health-probe listener (HealthProbe:Port), which is the composed service host's default rather than a call of its own: on a cleartext endpoint without TLS/ALPN, Http1AndHttp2 would fall back to HTTP/1.1 and Kestrel would reject the gRPC client's HTTP/2 frames (Program.cs:40-47, ADR-012), and it primes its own request pipeline at startup: SelfHttpWarmupTask (MMCA.ADC.Identity.Service/SelfHttpWarmupTask.cs:25), a SelfHttpWarmupTaskBase subclass registered at Program.cs:132, replays the organizer roster read, GET users/paged, against its own Kestrel endpoint (:34-37) and holds /health/ready not-ready until it has had its chance, deliberately accepting the expected 401 by turning RequireSuccessStatusCode off (:54) because the JIT cost lives in the traversal, not the response (ADR-025, [Rubric §12, Performance and Scalability]).

Asynchronously, the User-to-Speaker link is kept consistent by events, not by a cross-database foreign key. When a user registers, AuthenticationService raises UserRegistered (MMCA.ADC.Identity.Shared/Users/IntegrationEvents/UserRegistered.cs:38, a BaseIntegrationEvent named Identity.UserRegistered.v1 on the wire, :35) on the aggregate, and the outbox carries it to Conference, whose UserRegisteredHandler runs the speaker email-match auto-link (BR-207) only when the event says the provider verified the address, and otherwise leaves the match for an organizer to link by hand (AuthenticationService.cs:243-246, :475-476). Conference then publishes SpeakerLinkedToUser / SpeakerUnlinkedFromUser back, which SpeakerLinkedToUserHandler (MMCA.ADC.Identity.Application/Speakers/IntegrationEventHandlers/SpeakerLinkedToUserHandler.cs:43) and SpeakerUnlinkedFromUserHandler consume to set or clear User.LinkedSpeakerId (:54), so the speaker_id claim appears on the next token issued (eventual consistency, BR-209). Both extend ScopedIntegrationEventHandlerBase<TIntegrationEvent> (:30), which opens one DI scope per event so the singleton handler can reach the scoped unit of work and wraps the body in the log-and-propagate envelope (:19-23); the handlers themselves are idempotent, returning early when the link already matches (:48-52). Their error policy is worth copying: the base logs and re-throws, and the subclass overrides only the log line (LogHandlerFailure at :78-79). The remarks explain the bug that motivated it (:66-77): swallowing meant one transient database fault lost the BR-209 back-link permanently, because the delivery had already been acked. Letting the exception through hands the decision to the delivery mechanism, which leaves the inbox row unprocessed so the framework's broker receive pipeline retries it in process, each attempt in a fresh DI scope, then asks the transport for second-level redeliveries, and once those are spent dead-letters it with one Error log (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Messaging/Consumers/BrokerReceivePipeline.cs:16-19, :178-181). The host registers both as broker consumers through IdentityBrokerConsumers.Register (Program.cs:292, rationale at :272-285). This event-carried link is what lets the bidirectional User-to-Speaker relationship survive the service split ([Rubric §6, CQRS and Event-Driven], ADR-006 / ADR-008).

The UI edge

The Blazor surface is registered as an IdentityUIModule (MMCA.ADC.Identity.UI/IdentityUIModule.cs:19), an IUIModule descriptor that contributes three NavItems as resource keys, "My Profile" in the user section for every signed-in user, "Users" in the admin section for Organizers, and "Roles" in the admin section (:17-33, ADR-027). The third one is gated on the capability rather than on a role name (:26-32), and the comment above it says why: role administration is the one screen whose whole point is that the role-to-capability map is editable, so an entry naming a role would state the thing the screen exists to change (:22-25). The sidebar reads the permission claim the Identity host mints from its registry, which is why that host applies every module's grants. The routes come from the IdentityRoutePaths constants /users, /profile, /roles and /confirm-email (IdentityRoutePaths.cs:8-9, :12, :15) plus two builders, one per account (:22-23) and one per role, where the role name is the key because a role has no surrogate id anywhere in the system (:32-33); the UI-layer DependencyInjection wires the module descriptor, the framework user- and role-administration clients, and the user service (MMCA.ADC.Identity.UI/DependencyInjection.cs:24, :31, :36, :39). The anonymous /confirm-email landing page and its client are no longer Identity types: they are the framework ConfirmEmail page and IEmailConfirmationUIService, the latter registered by the Common UI layer (MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:203). The Profile page (MMCA.ADC.Identity.UI/Pages/Users/Profile/Profile.razor.cs:21) lets an authenticated user change their password, manage their avatar, and delete their account. It mirrors the server's 2 MB cap client-side before any upload starts (:38, :155, :176), validates the new password inline for length and confirmation match so the form error summary carries the message rather than a server round-trip (:43-52, [Rubric §24, Forms / Validation / UX Safety]), and accepts an image from either a browser file input (:168) or, on MAUI, the camera and gallery through IMediaPickerService (:25, :95, :100). It talks to the API through the IUserUIService abstraction (MMCA.ADC.Identity.UI/Services/IUserUIService.cs:17) implemented by UserService (MMCA.ADC.Identity.UI/Services/UserService.cs:22), an AuthenticatedServiceBase subclass that attaches the bearer token and calls the REST users resource (:25), reads answers back through ProblemDetailsResultReader and HttpResultExecutor so nothing throws for a server answer (:14-19), and which deliberately skips the retry policy on the avatar upload because a picker stream is single-shot and cannot rewind (:82, against the RetryPolicy.ExecuteAsync every other call uses, :38, :53, :104, :123). UserList (MMCA.ADC.Identity.UI/Pages/Users/UserList.razor.cs:28) is the Organizer-only management screen, and it is a thin shell over the framework's shared UserAdminList<TUser> component, which renders the roster, the mobile cards and the lock / unlock / change-role actions against the Admin/Users endpoints (:14-17); ADC supplies the assignable roles from the shared vocabulary (:34-35) and the roster read, which goes through the standard entity-service client for UserListDTO (:39) so every column operator, the search box's Email / Email~search keys, the sort and the paging reach GET Users/paged unchanged (:62-82). That client is UserListService (MMCA.ADC.Identity.UI/Services/UserListService.cs:20), a one-line EntityServiceBase<UserListDTO, UserIdentifierType> over the users resource (:21) that the Identity UI module scan picks up as the IEntityService<,> for the roster (:8-12); only the paged read is served, and delete keeps going through IUserUIService (:14-16). The page adds a Signed in column for the live session count, whose two-value filter travels as ActiveSessionCount with > 0 or = 0, from the column filter and from the phone's card list alike (UserList.razor.cs:22-26, :114-131, :139-145).

Three administration pages sit beside the profile page, all of them thin shells over framework components. UserDetail (MMCA.ADC.Identity.UI/Pages/Users/UserDetail/UserDetail.razor.cs:30) shows read-only account facts plus the two administrative changes, lock or unlock and the single role the account holds, both going through the users:manage-gated Admin/Users endpoints (:15-17), and below them a view-only Signed-in devices section that lists the account live sessions from Admin/Users/{id}/sessions in the framework UserSessionsTable (:17-19); the assignable roles come from RoleNames least to most privileged (:28-32), and the actions are hidden on the signed-in operator own account, because locking or demoting yourself removes the capability needed to undo it and the API has no notion of "the caller" (:21-25). RoleList (MMCA.ADC.Identity.UI/Pages/Roles/RoleList.razor.cs:29) carries no members at all: the shared RoleAdminList owns the load, the empty state and the inline failure, and the class exists only because IStringLocalizer<RoleList> resolves by type full name, so the page needs a type of its own for its .resx pair to attach to (:12-18). RoleEdit (MMCA.ADC.Identity.UI/Pages/Roles/RoleEdit.razor.cs:16) adds one route parameter, the role name (:19-20), over the shared RoleAdminEdit, which renders the host whole permission catalog grouped by area, ticks and locks what compiled code already grants, and saves only the stored set (:6-14). Both keep their page authorization as a role while the sidebar entry that links there states the capability, and that split is deliberate: the route gate is what IdentityRouteAuthorizationTests pins so an organizer-only surface cannot silently regress to a bare [Authorize], while the endpoints behind the page are gated on the capability by the controller base, which is the check that actually decides (RoleList.razor.cs:19-25). The UI targets WCAG 2.1 AA; the login and register flows are scanned by the shared MMCA.Common.Testing.E2E workflow bases and the profile page has its own axe-core scan in ADC's suite (MMCA.ADC/Tests/E2E/MMCA.ADC.E2E.Tests/Workflows/AccessibilityTests.cs:509, with the rationale for not inheriting the Common profile base at :368-369), all of it running in the deploy-gating chromium E2E leg ([Rubric §21, Accessibility], [Rubric §22, Responsive and Cross-Browser]).

End-to-end: one registration

To see the chapter cooperate, follow a new attendee signing up. AuthController receives the register POST, captures the client IP for BR-213 rate limiting and the user-agent for the session about to be opened (AuthController.cs:56-59), and calls RegisterAsync on AuthenticationService, which opens one transaction (AuthenticationService.cs:88-90) and hands off to the shared G08 engine. The request shape was already checked by the framework RegisterRequestValidator (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Validation/RegisterRequestValidator.cs:7-20), so the engine only has to confirm the email is not taken (AuthenticationService.cs:198-199), call User.Create(...) with the Attendee role (:209-217), hash the password through the shared IPasswordHasher (ADR-032), add the aggregate, and save. Only after that first save, when the EF identity id exists, does OnUserRegisteredAsync raise UserRegistered and save again (:249-255); both saves sit inside the one transaction, so the user row and its outbox row commit atomically (ADR-003). One step follows the commit: AuthController schedules a SendEmailConfirmationCommand as a durable internal-command row rather than sending the confirmation inline, and a scheduling failure is logged rather than failing the 201, because the account exists and the user can ask for a link from the confirmation page (AuthController.cs:73-93). The refresh half of the token pair is a row in the shared RefreshSessions store, not a column on the aggregate (User.cs:15-18). The first access token returned does not yet carry speaker_id. Because the address was typed into a form, the event says EmailVerified: false, so Conference does not auto-link on the email match; it logs the matching speaker for an organizer to link by hand (AuthenticationService.cs:243-246). Once that link is made, Conference publishes SpeakerLinkedToUser; SpeakerLinkedToUserHandler sets User.LinkedSpeakerId (SpeakerLinkedToUserHandler.cs:54), and the attendee's next token carries the claim (AuthenticationService.cs:565-566). No password left the domain in plaintext, no cross-database foreign key was written, no event was hand-dispatched, and the same code path behaves identically whether Identity runs inside the monolith or as its own service, which is exactly the property the framework groups (G01 through G15) exist to provide. For the why behind each choice, ADR-003 (outbox), ADR-004 (JWKS), ADR-005 (soft-delete versus erasure), ADR-006 / ADR-007 / ADR-008 (database-per-service, gRPC extraction, service topology), ADR-012 (mixed Kestrel endpoint profile), ADR-020 (permission registry), ADR-025 (startup warm-up and readiness), ADR-027 / ADR-028 (culture and theme), ADR-029 (login protection), ADR-032 (password hashing), ADR-036 (external OAuth login), ADR-045 (file storage and avatars), ADR-047 (soft-deleted session revocation), ADR-050 (refresh rotation and reuse detection), ADR-091 (cache-backed password reset), ADR-095 (soft-delete unique indexes), ADR-096 (best-effort side effects), and ADR-097 (multi-device refresh sessions) are the primary references; the email-confirmation and user / role administration surface is recorded in ADR-116, and the durable internal-command queue behind the scheduled sends and blob deletions in ADR-114.

AssemblyReference, ClassReference

MMCA.ADC.Identity.API + MMCA.ADC.Identity.Application · MMCA.ADC.Identity.API / MMCA.ADC.Identity.Application · MMCA.ADC.Identity.API/AssemblyReference.cs:5 · Level 0 · class (static) + class

  • What it is: the assembly-marker pair, shipped once per project, that gives typeof()-based assembly scanning a stable handle on the Identity module's assemblies. Four members in this unit: an AssemblyReference and a ClassReference in the API project and the same pair in the Application project. No behavior, no state beyond the reflection handle.
Type File:Line Notes (what differs)
AssemblyReference (API) MMCA.ADC.Identity.API/AssemblyReference.cs:5 static class exposing Assembly (typeof(AssemblyReference).Assembly, line 7) and AssemblyName (line 8, Assembly.GetName().Name ?? string.Empty)
ClassReference (API) MMCA.ADC.Identity.API/AssemblyReference.cs:11 a one-line empty public class ClassReference { }, a handle for APIs that want a type rather than an Assembly
AssemblyReference (Application) MMCA.ADC.Identity.Application/AssemblyReference.cs:5 byte-for-byte the same shape as the API one, differing only in the enclosing namespace (:3) and therefore in which assembly typeof(...) resolves to
ClassReference (Application) MMCA.ADC.Identity.Application/AssemblyReference.cs:11 same empty class; this is the one the module actually passes as a generic argument
  • Depends on: nothing first-party; only System.Reflection (AssemblyReference.cs:1 in both files).
  • Concept introduced, the assembly-marker pattern. [Rubric §2, Design Patterns] (assesses whether the patterns in use are idiomatic and solve a real problem): instead of hard-coding an assembly-name string, a scanner takes a typeof(...) from a type it knows lives in the target assembly, so renaming the assembly cannot silently break discovery. [Rubric §15, Best Practices & Code Quality]: every layer of every ADC module ships this same pair, so registration and discovery code reads identically in every project; Identity's other three layers carry it too (MMCA.ADC.Identity.Domain/AssemblyReference.cs:5,11 and MMCA.ADC.Identity.Infrastructure/AssemblyReference.cs:5,11).
  • Walkthrough: AssemblyReference.Assembly (:7) is a public static readonly Assembly; AssemblyName (:8) is its short name, falling back to string.Empty when reflection returns null. ClassReference (:11) has no members at all. Both files are eleven lines long and identical apart from their namespace declaration.
  • Why it's built this way: a typeof() handle is refactor-safe where a magic string is not, and a non-static ClassReference is needed because a C# static type is not a legal generic type argument. The scanning helper is generic: ScanModuleApplicationServices<TAssemblyMarker>() immediately reduces to the assembly overload via typeof(TAssemblyMarker).Assembly (MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.ModuleScanning.cs:29-31), so the marker's only job is to name an assembly at compile time.
  • Where it's used: the Application ClassReference is the live one: DependencyInjection for the Application layer passes it to services.ScanModuleApplicationServices<ClassReference>() (MMCA.ADC.Identity.Application/DependencyInjection.cs:72), which is what discovers the module's domain event handlers, DTO/request mappers, command/query handlers, and validators by convention rather than by an explicit registration line each. The architecture fitness suite uses the same marker fully qualified to rebuild the pipeline under test (MMCA.ADC/Tests/Architecture/MMCA.ADC.Architecture.Tests/Cqrs/DecoratorPipelineOrderTests.cs:54). The API pair has no call site in MMCA.ADC/Source today; it exists so the layer-parallel convention holds across all five layers of the module.
  • Caveats / not-in-source: nothing in these files enforces the convention. Whether an architecture rule requires one pair per project is not visible here, and neither AssemblyReference nor ClassReference of the API project is referenced by name anywhere in the repo's source.

IdentityModule

MMCA.ADC.Identity.API · MMCA.ADC.Identity.API · MMCA.ADC.Identity.API/IdentityModule.cs:12 · Level 2 · class (sealed)

  • What it is: the Identity module's entry point, the concrete IModule that the ModuleLoader discovers by reflection and registers. Identity is a leaf in the module dependency graph: it declares no prerequisites (doc comment IdentityModule.cs:8-11).
  • Depends on: IModule; ApplicationSettings (in the signature only); its own DependencyInjection's AddIdentityModule; Microsoft.Extensions.Configuration and Microsoft.Extensions.DependencyInjection (IdentityModule.cs:1-4).
  • Concept introduced, the minimal leaf module. The module contract itself is taught in G14; the Identity-specific lesson is how little a leaf module has to say. [Rubric §7, Microservices Readiness] (assesses whether modules compose and deploy independently): the class overrides only Name and Register, so every other IModule member keeps its interface default. That includes RegisterDisabledStubs, whose default is an empty body (MMCA.Common/Source/Core/MMCA.Common.Application/Modules/IModule.cs:34): when the ModuleLoader finds a module disabled it calls that method instead of Register (MMCA.Common/Source/Core/MMCA.Common.Application/Modules/ModuleLoader.cs:119), and for Identity the call registers nothing. Identity's two cross-module services, IAttendeeQueryService and IVerifiedUserLookupService, therefore reach a peer host only through the gRPC client registrations: AddIdentityAttendeeClient adds AttendeeQueryServiceGrpcAdapter (MMCA.ADC/Source/Services/MMCA.ADC.Identity.Contracts/DependencyInjection.cs:46, with the comment at :45 recording why Replace and not TryAdd: the adapter wins over any registration made before the call) and AddIdentityVerifiedUserLookupClient adds VerifiedUserLookupServiceGrpcAdapter (:73).
  • Walkthrough: two members. Name => "Identity" (:15) is the topological-sort key and the value the loader logs. Register(IServiceCollection, IConfigurationBuilder, ApplicationSettings) (:18-19) delegates straight to the parameterless services.AddIdentityModule(); both the IConfigurationBuilder and the ApplicationSettings parameters are accepted and unused, because Identity contributes no configuration sources of its own and its registration reads no application settings. No dependency-declaration members are overridden, so the interface defaults apply (a leaf). There is deliberately no seeding here: that is a separate IModuleSeeder, IdentityModuleSeeder.
  • Why it's built this way: the module boundary is what makes each module extractable into its own service host without a rewrite (ADR-007, ADR-008). In the extracted MMCA.ADC.Identity.Service only this module is enabled; the other service hosts name only their own module assembly to the loader, so the Identity module is never discovered there and the gRPC client registration is the only registration of the interface (MMCA.ADC/Source/Services/MMCA.ADC.Identity.Contracts/DependencyInjection.cs:34-36). Application code never learns which transport it got.
  • Where it's used: discovered and registered in Kahn-topological order by the ModuleLoader at host startup in MMCA.ADC.Identity.Service. MMCA.ADC.Notification.Service is the counter-example: it names only the Notification assembly, so Identity is never registered there, and its pipeline calls AddIdentityAttendeeClient() to add the gRPC adapter (MMCA.ADC/Source/Services/MMCA.ADC.Notification.Service/Program.cs:119, with the rationale at :104-108).

DependencyInjection

MMCA.ADC.Identity.API · MMCA.ADC.Identity.API · MMCA.ADC.Identity.API/DependencyInjection.cs:13 · Level 4 · class (static)

  • What it is: the API-layer composition root for the Identity module. It exposes AddIdentityModule(), the single call that registers every layer of the module, plus AddModuleIdentityAPI(), which applies the module's role-to-permission grants.
  • Depends on: IServiceCollection (Microsoft.Extensions.DependencyInjection); the Application-layer AddModuleIdentityApplication (see DependencyInjection for the Application layer) and the Infrastructure-layer AddModuleIdentityInfrastructure; AddPermissions from MMCA.Common.API.Authorization and IdentityPermissionGrants.Apply from the module's Shared project (DependencyInjection.cs:1-5).
  • Concept introduced, the layered DI fan-out via extension(IServiceCollection). [Rubric §3, Clean Architecture] (assesses inward-pointing dependencies and a single composition point per module): the API layer is the only layer that can see all the others, so it owns the aggregate registration. The method hangs off IServiceCollection through the C# extension(IServiceCollection services) block (DependencyInjection.cs:15), the workspace idiom for DI registration (see primer §4). [Rubric §15, Best Practices & Code Quality]: the three-call body mirrors the layering, so registration order matches dependency order and there is exactly one place to look when wiring changes.
  • Walkthrough
    • AddIdentityModule() (:21-28) takes no parameters. It calls AddModuleIdentityApplication() (:23), AddModuleIdentityInfrastructure() (:24), and AddModuleIdentityAPI() (:25), then returns services for chaining (:27).
    • AddModuleIdentityAPI() (:42-47) does one thing: it calls services.AddPermissions(IdentityPermissionGrants.Apply) (:44), handing the whole grant map to the framework's AddPermissions helper rather than building .Grant(...) calls inline. Those grants back the module's [HasPermission(...)]-gated endpoints: organizers read the full user list and administer accounts and roles (doc comment :30-35, ADR-020).
    • Controllers are not registered here; ASP.NET Core's controller convention discovers them (doc comment :33-34).
  • Why it's built this way: one entry point per module is what IdentityModule calls, so module wiring stays discoverable. The grant map itself lives in IdentityPermissionGrants in the module's Shared project, because the token-minting host applies the same map: a token must carry the permission claims of every module, not only of the module the minting host boots (remarks :36-40), so the map has to be reachable from outside the API project too.
  • Where it's used: AddIdentityModule is invoked by IdentityModule's Register (MMCA.ADC.Identity.API/IdentityModule.cs:18-19) during topological module registration by the ModuleLoader.

IdentityModuleSeeder

MMCA.ADC.Identity.API · MMCA.ADC.Identity.API · MMCA.ADC.Identity.API/IdentityModuleSeeder.cs:15 · Level 16 · class (sealed)

  • What it is: the Identity module's startup data seeder. It is a thin IModuleSeeder that checks a configuration gate, resolves its dependencies from the host service provider, and delegates the actual inserts (default Organizer and Attendee accounts) to the Infrastructure-level IdentityModuleDbSeeder.
  • Depends on: IModuleSeeder; IConfiguration and IServiceProvider (Microsoft.Extensions); IUnitOfWork; IPasswordHasher; IdentityModuleDbSeeder.
  • Concept introduced, the config-gated seeder bridge. [Rubric §8, Data Architecture] (assesses deterministic, repeatable startup state), [Rubric §11, Security], and [Rubric §3, Clean Architecture] (the API layer orchestrates, Infrastructure persists). Two design points matter here. First, the gate: the seeded accounts carry deliberately weak, well-known credentials (three accounts, admin@adc.com with Admin123! among them, at MMCA.ADC.Identity.Infrastructure/Persistence/DbContexts/Seeding/IdentityModuleDbSeeder.cs:33-38, with an explicit security notice at :21-25), so seeding is opt-in via Seeding:IncludeSampleUsers (IdentityModuleSeeder.cs:29) and the method returns immediately when it is false (:30-31). GetValue<bool> defaults to false when the key is absent, so a production service that configures nothing seeds no accounts at all, exactly the same shape as the conference sample-data gate (comment :25-28). The DB seeder deliberately does not override its base's ShouldSeed (its own remark at :17-19), so this class stays the single home of the gate. Second, the bridge: this class resolves services from the provider instead of taking them in a constructor, then constructs the DB seeder by hand (:35).
  • Walkthrough (:15-38): ModuleName => "Identity" (:18) identifies the seeder to the loader. SeedAsync(IServiceProvider, CancellationToken) (:21-37) is a plain Task-returning method, not async: it resolves IConfiguration (:23), evaluates the gate (:29-31, returning Task.CompletedTask when seeding is off), then resolves IUnitOfWork (:33) and IPasswordHasher (:34) with GetRequiredService (a missing registration fails loudly at startup rather than silently skipping the seed), constructs new IdentityModuleDbSeeder(unitOfWork, passwordHasher) (:35), and returns its SeedAsync task directly (:36) rather than awaiting it, since nothing follows the call. IPasswordHasher is required because the seed data holds plaintext passwords that must be hashed before they touch the database (doc comment :10-14, ADR-032).
  • Why it's built this way: IModuleSeeder.SeedAsync runs inside a scope the loader creates after the host is fully built, so constructor-injecting scoped services would tie the seeder's own lifetime to that scope. Resolving at the boundary keeps the object simple and scope-agnostic. Keeping the EF insert logic in the Infrastructure *DbSeeder keeps the API assembly free of persistence detail and leaves the insert logic independently testable.
  • Where it's used: discovered through the IModuleSeeder interface and invoked at host startup after the database initialization strategy has created or migrated the schema.
  • Caveats / not-in-source: which hosts actually set Seeding:IncludeSampleUsers is configuration, not source; the code only records the intent (local AppHost and E2E CI) in its comment at :25-28.

IdentityErrorResources

MMCA.ADC.Identity.API · MMCA.ADC.Identity.API.Resources · MMCA.ADC.Identity.API/Resources/IdentityErrorResources.cs:11 · Level 0 · class (sealed)

  • What it is: an empty "resource anchor" type for the Identity module's localized error messages. It has no members; its only job is to be a typeof(...) handle that the localization layer uses to find the co-located .resx files (ADR-027).
  • Depends on: nothing first-party. At runtime its .resx siblings are loaded through IStringLocalizerFactory (ASP.NET Core localization).
  • Concept introduced, edge error-message localization keyed by error Code. [Rubric §27, Internationalization] (assesses whether user-facing strings, error text included, are translated rather than English-only). ADR-027 localizes failures at the API edge: a domain Error's Code (for example "User.Email.Empty") is the resource key, and the shared IErrorLocalizer looks that key up across every registered resource source before the failure is written into the ProblemDetails response. Each module contributes translations additively by registering its own anchor type, so Identity's strings live in IdentityErrorResources.resx and IdentityErrorResources.es.resx rather than in one central framework file that every module would have to edit.
  • Walkthrough: the class body is empty (IdentityErrorResources.cs:11-13); everything worth knowing is in the doc comment (:3-10), which records two design points. Keys are the domain error Code. And runtime-variable messages (those that interpolate a user-supplied value) are deliberately omitted from the .resx so they degrade to their English message with the value intact instead of showing a broken or value-less translation.
  • Why it's built this way: AddErrorResources<TResource>() (MMCA.Common/Source/Presentation/MMCA.Common.API/DependencyInjection.cs:144-149) resolves IStringLocalizerFactory, calls Create(typeof(TResource)), and registers the result as one more ErrorResourceSource singleton (:124-125); the convention "a .resx named after the type, sitting beside it" is what binds the strings, so an empty marker class is exactly enough. The framework registers its own ErrorResources through that very same helper inside AddErrorLocalization() (:107-113, the call at :111), which is what makes the mechanism additive rather than replace-only: each source is a plain AddSingleton, so registrations accumulate into the enumerable the localizer reads instead of overwriting one another.
  • Where it's used: registered at startup by the extracted Identity host, services.AddErrorResources<IdentityErrorResources>() (MMCA.ADC/Source/Services/MMCA.ADC.Identity.Service/Program.cs:282).

UserSearchFilter

MMCA.ADC.Identity.API · MMCA.ADC.Identity.API.Controllers · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/Controllers/UsersController.cs:27 · Level 0 · record (sealed)

  • What it is: one roster filter in a POST /Users/search body: an Operator (for example contains, equals, is empty) and the Value it compares against (UsersController.cs:30, :33). Both are nullable strings.
  • Depends on: nothing first-party; it is a plain JSON-bound record declared beside the controller that consumes it.
  • Concept reinforced, a body contract that mirrors the query-string bag. [Rubric §9, API & Contract Design]. The record is the body-shaped twin of one filters[P].operator / filters[P].value pair that QueryFilterModelBinder reads from the query string, so the search endpoint accepts exactly what the paged endpoint accepts, only in a different place in the request.
  • Walkthrough: two init-only properties. Value is documented as absent for a value-less operator (:32); the record itself validates nothing, and the decision to keep or drop an entry belongs to UserSearchRequest.ToQueryFilters().
  • Why it's built this way: keeping both members nullable lets the client send is empty without a value and lets the conversion step, not model binding, decide what an incomplete entry means (it is dropped rather than rejected).
  • Where it's used: the value type of UserSearchRequest.Filters (UsersController.cs:44); exercised by MMCA.ADC/Tests/Modules/Identity/MMCA.ADC.Identity.API.Tests/Controllers/UsersControllerTests.cs.

UserSearchRequest

MMCA.ADC.Identity.API · MMCA.ADC.Identity.API.Controllers · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/Controllers/UsersController.cs:41 · Level 1 · record (sealed)

  • What it is: the body of POST /Users/search: the roster filters keyed by UserListDTO property name, the sort, and the page, plus one conversion method that turns the filters into the shape the entity query service takes.
  • Depends on: UserSearchFilter, QueryFilterModelBinder (for its MaxFilters cap and as the rule set the conversion copies); externals: System.ComponentModel.DataAnnotations ([Range]).
  • Concept introduced, moving a search term out of the URL. [Rubric §30, Compliance, Privacy & Data Governance], [Rubric §11, Security], [Rubric §9, API & Contract Design]. The organizer's search term is often an attendee's email address; in a query string it lands in request telemetry and ingress logs. Carrying the same filters, sort and paging in a body keeps it out of both, while the conversion reproduces the query-string binder's rules exactly so the two endpoints cannot disagree on what a filter means.
  • Walkthrough
    • Filters (UsersController.cs:44), SortColumn (:47), SortDirection (:50), all nullable.
    • PageNumber defaults to 1 and PageSize to 10, each [Range(1, int.MaxValue)] (:53-54, :57-58), so a zero is a model-validation 400, as on the query-string endpoint. The 500-row cap is not applied here: the doc says "capped at 500" (:56) because UsersController applies MaxRosterPageSize when it forwards the request.
    • ToQueryFilters() (:67-87): returns null when no filters were sent (:69-70); otherwise builds a dictionary with StringComparer.OrdinalIgnoreCase keys (:72), stops at QueryFilterModelBinder.MaxFilters entries (:75-76), drops an entry with no operator, or with no value unless the operator is value-less (:80-81), and stores the (Operator, Value) tuple (:83). The doc comment names this as the binder's rule set (:60-64).
    • IsValueLessOperator (:89-94): a trimmed, case-insensitive match on IS EMPTY and IS NOT EMPTY.
  • Why it's built this way: converting to the binder's exact tuple shape lets SearchAsync delegate to the existing GetPagedAsync action unchanged, so the query service, the page-size cap and the pagination header have one implementation behind both routes.
  • Where it's used: bound [FromBody] by UsersController.SearchAsync (UsersController.cs:266-278); the Engagement UI's attendee lookup posts its body to the same endpoint (MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.UI/Services/Lookups/AttendeeLookupService.cs:24), building its own body in this shape rather than referencing the type.

UserClaimsController

MMCA.ADC.Identity.API · MMCA.ADC.Identity.API.Controllers · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/Controllers/UserClaimsController.cs:16 · Level 5 · class (sealed)

  • What it is: a single read-only endpoint that echoes the authenticated caller's JWT claims back as a JSON object (UC-10). It is the "who does the server think I am" diagnostic.
  • Depends on: ApiControllerBase; externals: ASP.NET Core MVC ([ApiController], [Authorize], HttpContext.User), Asp.Versioning.
  • Concept reinforced, the thin diagnostic controller. [Rubric §13, Observability & Operability] assesses whether an operator can inspect live state without attaching a debugger, and [Rubric §11, Security] covers what such a surface is allowed to reveal. The security property to notice is that the endpoint reflects only HttpContext.User (UserClaimsController.cs:28), the principal the authentication middleware already built from the presented token. It reads nothing from the database and accepts no id, so the worst a caller can learn is what they already hold. [Authorize] (UserClaimsController.cs:15) makes an anonymous call a 401 rather than an empty object.
  • Walkthrough: one action, GetClaims() (UserClaimsController.cs:26-39). It groups the principal's claims by type (UserClaimsController.cs:28-29) and projects each group into a dictionary entry whose value is either the single string or the list of strings (UserClaimsController.cs:34-35). That collapse is what makes the JSON pleasant: single-valued claims such as the identifier or email serialize as scalars, while a genuinely repeated claim stays an array instead of being silently truncated. The doc comment (UserClaimsController.cs:18-22) names the expected set and one non-obvious detail: the user identifier rides the token's sub, which the bearer handler surfaces as nameidentifier.
  • Why it's built this way: routing is [Route("[controller]")] (UserClaimsController.cs:13), so the resource is /userclaims, and [ApiVersion("1.0")] (UserClaimsController.cs:14) puts it under the same header-based versioning as every other ADC endpoint (ADR-046). Returning ActionResult with an anonymous dictionary rather than a named DTO is a deliberate exception to the module's DTO discipline: the payload is by definition whatever claims the token happens to carry, so there is no stable shape to name. The two ProducesResponseType entries (UserClaimsController.cs:24-25) therefore declare status codes only.
  • Where it's used: reachable through the Gateway alongside the other Identity endpoints; it is a support and debugging surface rather than something the ADC UI calls in a normal flow.

EmailConfirmationController

MMCA.ADC.Identity.API · MMCA.ADC.Identity.API.Controllers · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/Controllers/EmailConfirmationController.cs:29 · Level 6 · class (sealed)

  • What it is: the two-action email-confirmation surface, POST send-email-confirmation (schedules a confirmation link) and POST confirm-email (redeems it). It is now a body-light subclass: both actions are inherited from EmailConfirmationControllerBase<TSendCommand, TConfirmCommand> (EmailConfirmationController.cs:29-33), and this class supplies only the two command factories.
  • Depends on: EmailConfirmationControllerBase<TSendCommand, TConfirmCommand> (base, MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/EmailConfirmationControllerBase.cs:43), ICommandHandler<in TCommand, TResult> closed over SendEmailConfirmationCommand and ConfirmEmailCommand; externals: Asp.Versioning, ASP.NET Core MVC.
  • Concept reinforced, the derived controller supplies command factories to a shared base. [Rubric §11, Security], [Rubric §30, Compliance, Privacy & Data Governance], [Rubric §15, Best Practices & Code Quality]. The enumeration-safe posture is unchanged but now lives in the base: SendEmailConfirmationAsync always answers 202 Accepted on a well-formed request, whether or not the address holds an account and whether or not it is already confirmed (EmailConfirmationControllerBase.cs:71-96, Accepted() at :95), so a caller cannot enumerate registered addresses, the same posture PasswordResetController takes on forgot-password. Both base actions carry [AllowAnonymous], [Idempotent], and [EnableRateLimiting(WebApplicationBuilderExtensions.RateLimitPolicyAuthIp)] (:79-81, :107-109), the same "auth-ip" fixed window that guards login, register, and password reset (ADR-019). The commands stay app-side, as in the password-recovery base, and the base reads them back only through ICommandWithRequest<TRequest> (:46-47).
  • Walkthrough
    • The primary constructor (EmailConfirmationController.cs:29-33) takes the two closed command handlers and forwards them to the base. Route Auth and version 1.0 stay on this class, repeated because the base leaves them to the derived controller (base remarks, EmailConfirmationControllerBase.cs:38).
    • CreateSendCommand (:37) and CreateConfirmCommand (:40): one-line => new(request) factories building SendEmailConfirmationCommand and ConfirmEmailCommand, the abstract members the base declares (EmailConfirmationControllerBase.cs:61, :69).
    • The inherited ConfirmEmailAsync (EmailConfirmationControllerBase.cs:114) dispatches the confirm command and answers 204 on success ([ProducesResponseType(StatusCodes.Status204NoContent)], :110). Its doc comment states the transport reason the link works the way it does (:99-101): the address and the token travel in the URI fragment, so the confirmation page reads them client-side and posts them here, and neither ever reaches a server log or a Referer header.
  • Why it's built this way: the actions were previously written in this file; once the framework shipped a controller base for the pair, ADC kept only what is app-specific (the command records), the same split PasswordResetController uses. Both inherited actions end in the same result.IsFailure ? HandleFailure(result.Errors) : ... tail every controller in the module uses, so a validation or not-found failure becomes the shared ProblemDetails shape.
  • Where it's used: registration schedules a SendEmailConfirmationCommand from AuthController after a successful POST register (ADR-116); the confirmation page then calls confirm-email with the token from the emailed link. The architecture suite's anonymous-endpoint test enumerates both actions explicitly.

OAuthController

MMCA.ADC.Identity.API · MMCA.ADC.Identity.API.Controllers · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/Controllers/OAuthController.cs:21 · Level 7 · class (sealed)

  • What it is: ADC's external social-login endpoint surface (the class doc names Google, GitHub, and Apple). It is a body-less class: every action is inherited from the shared OAuthControllerBase, and this file exists to supply the route, the version, and the concrete dependencies.
  • Depends on: OAuthControllerBase, IAuthenticationService (aliased at OAuthController.cs:6 to disambiguate from the ASP.NET Core type of the same name), ICacheService, IConfiguration, IDistributedLock (ADR-108).
  • Concept introduced, the derived-controller-as-configuration pattern. [Rubric §15, Best Practices & Code Quality] assesses whether a shared workflow is inherited rather than copied, and [Rubric §9, API & Contract Design] covers the route surface. The whole class is a primary constructor forwarding four dependencies to a base (OAuthController.cs:21-25), terminated with a semicolon: there is no body at all. The base owns the four-step flow, which the class doc states in order (OAuthController.cs:10-17): challenge, provider callback, complete, then a single-use-code exchange, with tokens never riding the redirect URL (ADR-036). That last step is the security-relevant one, because a token in a redirect URL lands in browser history and referrer headers ([Rubric §26, Front-End Security], [Rubric §11, Security]).
  • Walkthrough: three attributes and four constructor parameters.
    • [ApiController], [Route("auth/oauth")], [ApiVersion("1.0")] (OAuthController.cs:18-20). The class doc records the non-obvious reason these are repeated here rather than inherited (OAuthController.cs:14-15): routing and versioning attributes are not reliably inherited from the base, so omitting them would leave the endpoints unroutable.
    • IAuthenticationService (OAuthController.cs:22) resolves to Identity's own AuthenticationService, which is what makes the base's provider-agnostic flow create or link an ADC User. ICacheService (:23) backs the single-use exchange code. IConfiguration (:24) supplies the provider and redirect settings.
    • IDistributedLock (:25) is passed to the base's four-argument primary constructor (OAuthControllerBase.cs:52-56). ExchangeAsync then reads and burns the single-use code inside TryAcquireAsync on lock:{cacheKey} (OAuthControllerBase.cs:343-354), so two replicas redeeming the same code at the same instant cannot both mint the token pair; a contended redeem is answered as an invalid code, never a second success (:250-252). That primary constructor is the base's only constructor, so every subclass must supply the lock; the base's doc states the subclass passes it and that the code is burned inside it (OAuthControllerBase.cs:42-45). The class doc records the same intent (OAuthController.cs:16).
  • Why it's built this way: external OAuth is an ADC-only feature (Store is local-credential only), but the protocol is app-agnostic, so the flow was hoisted into MMCA.Common.API and each app contributes only its route prefix and its authentication service. Pairing this controller with AddExternalAuthProviders in the service host is what completes the wiring, and the class doc says so (OAuthController.cs:13-14).
  • Where it's used: mounted by the Identity service host and fronted by the Gateway; the browser and MAUI clients drive it, and the email-verified guard on the linking step reads the provider's email_verified claim, extracted by the framework's OAuthControllerBase (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/OAuthControllerBase.cs:413-415) and enforced in AuthenticationService (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/AuthenticationService.cs:530).
  • Caveats / not-in-source: the provider registrations, the scopes, and the Google email_verified claim mapping live in the Identity service host's Program.cs, not in this file, so which of the three named providers a given environment actually offers is not determinable from here.

AdminViewAsGrantsController

MMCA.ADC.Identity.API · MMCA.ADC.Identity.API.Controllers · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/Controllers/AdminViewAsGrantsController.cs:20 · Level 7 · class (sealed)

  • What it is: the support access log (ADR-137): one paged, newest-first list of every read-only view-as grant, who viewed whom, why, when and how it ended (class doc, AdminViewAsGrantsController.cs:7-11). The class is one declaration with no body and no constructor.
  • Depends on: ViewAsGrantsAdminControllerBase (base, MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Administration/ViewAsGrantsAdminControllerBase.cs:40), which resolves IViewAsGrantStore per action; externals: Asp.Versioning, ASP.NET Core MVC.
  • Concept reinforced, the derived-controller-as-configuration pattern, with the route as the only app input. [Rubric §15, Best Practices & Code Quality], [Rubric §13, Observability & Operability], [Rubric §11, Security]. The base owns the action, its [HasPermission(AdministrationPermissions.ManageUsers)] gate (ViewAsGrantsAdminControllerBase.cs:39) and its host check: on a host with ViewAs:Enabled false, or one that does not hold the grant store, the list answers 404 (:70-73). The remarks here (AdminViewAsGrantsController.cs:12-16) record that this is the same users:manage capability the UsersAdminController actions require, granted to Organizer and never to ContentEditor.
  • Walkthrough: [ApiController], [Route("Admin/ViewAsGrants")], [ApiVersion("1.0")] (AdminViewAsGrantsController.cs:17-19), then public sealed class AdminViewAsGrantsController : ViewAsGrantsAdminControllerBase; (:20). The base takes no constructor dependencies: the inherited ListAsync (ViewAsGrantsAdminControllerBase.cs:53-63) receives the settings, the store and the clock through [FromServices] parameters.
  • Why it's built this way: the route lives on the subclass because the app owns its URL space (base remarks, ViewAsGrantsAdminControllerBase.cs:28-31), and the class sits on the Identity service because that is the one service holding the grant store (AdminViewAsGrantsController.cs:10).
  • Where it's used: called by the framework's UI client at Admin/ViewAsGrants through the Gateway; covered by MMCA.ADC/Tests/Modules/Identity/MMCA.ADC.Identity.API.Tests/Controllers/AdminViewAsGrantsControllerTests.cs.

SignInLinkController

MMCA.ADC.Identity.API · MMCA.ADC.Identity.API.Controllers · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/Controllers/SignInLinkController.cs:29 · Level 7 · class (sealed)

  • What it is: the anonymous sign-in-link pair, POST /Auth/sign-in-link and POST /Auth/sign-in-link/redeem (UC-54, BR-271, BR-275; class doc, SignInLinkController.cs:13-19). Both actions are inherited; this class supplies the route, the version and the two ADC command factories.
  • Depends on: SignInLinkControllerBase<TSendCommand, TRedeemCommand> (base, MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/SignInLinks/SignInLinkControllerBase.cs:35), ICommandHandler<in TCommand, TResult> closed over SendSignInLinkCommand and RedeemSignInLinkCommand, SendSignInLinkRequest, RedeemSignInLinkRequest, AuthenticationResponse; externals: Asp.Versioning, ASP.NET Core MVC.
  • Concept reinforced, a sibling controller on the /Auth prefix with the posture in the base. [Rubric §11, Security], [Rubric §9, API & Contract Design], [Rubric §15, Best Practices & Code Quality]. The remarks (SignInLinkController.cs:20-25) give the same reason as EmailConfirmationController: AuthController already occupies the single inheritance chain, and a literal [Route("Auth")] rides the existing Gateway route with no gateway change. The anonymous posture lives in the base: both actions are [AllowAnonymous] under the "auth-ip" fixed window (SignInLinkControllerBase.cs:82-83, :110-111, ADR-019); the send is [Idempotent] and answers 202 Accepted (:81, :97), while the redeem is [NonIdempotent] because a replayed response would hand a retrying client tokens minted for an earlier call (:109). The redeem reads the address and token from the URI fragment client-side, so neither reaches a server log or a Referer header (:100-103).
  • Walkthrough
    • [ApiController], [Route("Auth")], [ApiVersion("1.0")] (SignInLinkController.cs:26-28).
    • The primary constructor (:29-34) forwards the two closed handlers to the base.
    • CreateSendCommand(request) => new(request) (:37) and CreateRedeemCommand(request, ipAddress, userAgent) => new(request, ipAddress, userAgent) (:40-41), the two abstract factories (SignInLinkControllerBase.cs:61, :71). The redeem factory receives the client IP and user agent, which the base computes from HttpContext (:51) and passes in (:121).
  • Why it's built this way: the workflow is framework policy, while the command records are ADC's own, the same split PasswordResetController uses. The class doc notes that nothing is sent or redeemed unless Authentication:SignInLinks:Enabled is set (SignInLinkController.cs:17-18).
  • Where it's used: handled by SendSignInLinkHandler and RedeemSignInLinkHandler; driven by unauthenticated browser and MAUI clients through the Gateway's /Auth route; covered by MMCA.ADC/Tests/Modules/Identity/MMCA.ADC.Identity.API.Tests/Controllers/SignInLinkControllerTests.cs.
  • Caveats / not-in-source: whether Authentication:SignInLinks:Enabled is on in a given environment is host configuration, not determinable from this file.

UsersAdminController

MMCA.ADC.Identity.API · MMCA.ADC.Identity.API.Controllers · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/Controllers/UsersAdminController.cs:27 · Level 9 · class (sealed)

  • What it is: ADC's Admin/Users endpoint surface: one account, its signed-in devices, lock and unlock, and the role it holds (class doc, UsersAdminController.cs:9-15). It declares nothing beyond the route and the service binding: every action is inherited from UsersAdminControllerBase<TUserDto>. The paged roster is not here; it is GET /Users/paged on UsersController (:13-14).
  • Depends on: UsersAdminControllerBase<TUserDto> (base, closed over UserAdminDTO), IUserAdministrationService<TUserDto>.
  • Concept reinforced, the derived-controller-as-configuration pattern applied to administration. [Rubric §15, Best Practices & Code Quality], [Rubric §11, Security]. Like OAuthController and AdminRolesController, the class is a primary constructor forwarding one dependency to the base and ending in a semicolon (UsersAdminController.cs:27-28), binding the shared surface to UserAdministrationService. The remarks (:16-22) record where the policy lives: the base gates every action on the users:manage capability (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Administration/UsersAdminControllerBase.cs:67), which ADC grants to Organizer through IdentityPermissionGrants and not to ContentEditor; the base declares the idempotency intent of every action (lock and unlock carry [NonIdempotent] at UsersAdminControllerBase.cs:225, :247) and refuses the caller's own account on lock, unlock and role change with the UserAdministration.Self error (:322-325), "so nothing is overridden here" (UsersAdminController.cs:21).
  • Walkthrough: [ApiController], [Route("Admin/Users")], [ApiVersion("1.0")] (UsersAdminController.cs:24-26), then the one-line declaration (:27-28). The route makes the base's fixed action templates serve /Admin/Users/{userId}, /Admin/Users/{userId}/sessions, /Admin/Users/{userId}/lock and the rest (:11-13).
  • Why it's built this way: once the base carried the idempotency declarations and the self-administration refusal, the app had nothing left to add, so the class is pure configuration: the app owns its URL space and its service, the framework owns the workflow and its rules.
  • Where it's used: mounted by the Identity service host, routed through the Gateway under Admin/Users; driven by UserDetail and UserList through the framework's IUserAdminUIService<TUserDto> client. AdminRolesController is the equivalent surface for roles, and AdminViewAsGrantsController shares its users:manage gate.

UsersController

MMCA.ADC.Identity.API · MMCA.ADC.Identity.API.Controllers · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/Controllers/UsersController.cs:105 · Level 9 · class (sealed)

  • What it is: the /users REST surface: the organizer user roster (GET paged, and its body-carried twin POST search), account delete, and the three avatar endpoints for the signed-in user. Six actions: four are thin adapters over one handler each, the roster is an adapter over the generic entity query service, and the search delegates to the roster action.
  • Depends on: ApiControllerBase, IEntityQueryService<User, UserListDTO, UserIdentifierType> (the roster read, served by UserListEntityQueryService; UsersController.cs:106), ICommandHandler<in TCommand, TResult> and IQueryHandler<in TQuery, TResult> closed over the four remaining use cases (:107-110), ICurrentUserService (:111), HasPermissionAttribute, IdentityPermissions, IdempotentAttribute, NonIdempotentAttribute, FormFileUploadExtensions, QueryFilterModelBinder, UserSearchRequest, UserListDTO, UserAvatarDTO, PagedCollectionResult<T>; externals: ASP.NET Core MVC (IFormFile, [RequestSizeLimit], [Range]).
  • Concept introduced, the controller as a translator between HTTP and the handler pipeline, and the two shapes of authorization. [Rubric §9, API & Contract Design], [Rubric §11, Security], [Rubric §5, Vertical Slice] (assesses whether each endpoint routes to its own use case rather than into a shared service). Every handler-backed action follows the same four lines: read the caller from ICurrentUserService, build the command or query record, await handler.HandleAsync(...), then result.IsFailure ? HandleFailure(result.Errors) : Ok(...); the roster action swaps the handler for the entity query service and unwraps its result with TryGetValue (UsersController.cs:243), but still ends in the same HandleFailure(result.Errors) tail. The controller holds no business logic, which is why the decorator pipeline (logging, caching, validation, transaction) applies uniformly to the handlers. The authorization split is the interesting part:
    • Declarative, for a capability-shaped rule: the GET paged endpoint carries [HasPermission(IdentityPermissions.UsersRead)] (UsersController.cs:224; POST search repeats it at :262; the constant is "identity:users:read" at MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Shared/Authorization/IdentityPermissions.cs:13), the permission-based check of ADR-020. A caller without that capability never reaches the handler.
    • In-handler, for an ownership-shaped rule: delete passes the caller's id and role into the command (UsersController.cs:295) so DeleteUserHandler can apply owner-or-Organizer and, importantly, return 404 rather than 403 for a stranger's id, which avoids leaking whether that account exists (ADR-033).
  • Walkthrough: class-level [Authorize] (UsersController.cs:104) makes every action authenticated by default, and each me/... action re-checks currentUserService.UserId is null and returns Unauthorized() for the "authenticated but no usable id" case.
    • Three size constants, and the reason there are two avatar ones. MaxAvatarBytes = 2 * 1024 * 1024 (:114) is the BR-116a image ceiling; MaxAvatarRequestBytes = MaxAvatarBytes + 64 * 1024 (:123) is the transport-level cap for the whole multipart body. The doc explains the trap (:116-122): without headroom for the boundary lines and part headers, a file at exactly the image limit is rejected by Kestrel with a bare 413 before the friendly Avatar.InvalidUpload check can run. [Rubric §24, Forms, Validation & UX Safety]: the difference between a helpful error and a raw protocol failure is 64 KB of slack. The third constant, MaxRosterPageSize = 500 (:126, BR-11), caps the roster page size.
    • GET me/avatar (:129-144), resolving the subject from the token rather than from a route parameter.
    • POST me/avatar (:157-188) is the richest action, and it carries three attributes worth reading together. [Idempotent] (:158) routes the request through the framework's Idempotency-Key filter (ADR-017); the action doc explains the judgement call (:151-154), which is that the upload replaces the caller's avatar rather than appending one, so replaying the stored URL for a repeated key is both safe and useful (it skips a second re-encode of identical bytes and stops a flaky mobile upload from looking like a failure the user has to redo). [RequestSizeLimit(MaxAvatarRequestBytes)] (:159) rejects an oversized body at the pipeline before any of it is buffered, and the action declares that 413 in its ProducesResponseType set (:162). The file is then read through the framework's file.ReadBoundedAsync(MaxAvatarBytes, Error.Validation("Avatar.InvalidUpload", ...)) extension (:171-177, FormFileUploadExtensions), which returns a Result; a missing, empty or over-limit file comes back as that validation error and the action returns HandleFailure(upload.Errors) (:178-179), so the limit is enforced twice for two different failure modes. On success the bytes (avatar.Content) are handed to SetUserAvatarCommand (:181-183). The action doc also records what the handler then does (:147-149): sniff the real format (jpeg/png/webp), re-encode to 256x256 JPEG, return the public URL. Trusting a declared content type here would be an upload vulnerability.
    • DELETE me/avatar (:190-206), documented idempotent, returning 204.
    • GET paged (:208-250, route attribute :223): the roster action, the generic paged entity contract and the route the framework's entity-service client calls (doc, :208-222). Five parameters (:228-233): sortColumn, sortDirection, [Range(1, int.MaxValue)] pageNumber and pageSize (so a pageNumber=0 is a model-binding 400 rather than a handler concern), and a filters dictionary bound by QueryFilterModelBinder from the standard filters[P].operator / filters[P].value bag on UserListDTO property names. It calls usersQuery.GetAllAsync(...) with pageSize: Math.Min(pageSize, MaxRosterPageSize) and asTracking: false (:235-242), unwraps the result with if (!result.TryGetValue(out var page)) return HandleFailure(result.Errors); (:243-244), so the success path holds a non-null page without a null-forgiving result.Value!, then writes the pagination header with Response.AppendPaginationHeader(page.PaginationMetadata) (:248), the same header the framework's paged entity endpoint writes and the entity-service client reads back, before returning Ok(page) (:249).
    • POST search (:252-279, route attribute :261): the same roster read with the filters, sort and paging carried in a UserSearchRequest body, so the organizer's search term (often an attendee's email address) stays out of request telemetry and ingress logs (doc, :253-256; [Rubric §30, Compliance, Privacy & Data Governance]). It is [NonIdempotent] (:263) because a read-only search is already safe to retry and caching its page in the replay cache would keep attendee personal data there for nothing. The body is a guard plus one delegation: ArgumentNullException.ThrowIfNull(request) (:270), then return GetPagedAsync(...) with request.ToQueryFilters() (:272-278), so the page-size cap and the pagination header have one implementation.
    • DELETE {userId} (:281-301), the ownership-checked action, declaring 403 and 404 in its ProducesResponseType set (:284-285).
  • Why it's built this way: injecting four separate closed handler interfaces plus the generic entity query service rather than one "user service" is what keeps each endpoint on its own vertical slice and makes the decorator pipeline the single place where cross-cutting behavior lives (ADR-014). The consistent HandleFailure(result.Errors) tail means every failure becomes a ProblemDetails with the same shape, mapped once in ApiControllerBase. The GDPR export, which used to be a sixth action here, now lives on UsersDataExportController and still serves the same /Users/{userId}/export path.
  • Where it's used: mounted by the Identity service host and routed through the Gateway; consumed by UserService on the client side (and therefore by UserList and Profile), and warmed at startup by SelfHttpWarmupTask, which replays users/paged?pageNumber=1&pageSize=10 against this host's own Kestrel endpoint (MMCA.ADC/Source/Services/MMCA.ADC.Identity.Service/SelfHttpWarmupTask.cs:37; the path must name a routed action, :11-12) and treats the resulting 401 as the expected outcome (:50), because an unauthenticated self-request hits this class's [Authorize] plus [HasPermission] pair.

AdminRolesController

MMCA.ADC.Identity.API · MMCA.ADC.Identity.API.Controllers · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/Controllers/AdminRolesController.cs:36 · Level 11 · class (sealed)

  • What it is: ADC's role-administration endpoint surface. Like OAuthController, it is a body-less class: every action comes from RolesAdminControllerBase, and this file exists only to supply the concrete dependencies.
  • Depends on: RolesAdminControllerBase (base), IRoleAdministrationService, ICurrentUserService.
  • Concept reinforced, the derived-controller-as-configuration pattern. [Rubric §15, Best Practices & Code Quality]. The whole class is a primary constructor forwarding two dependencies to the base, terminated with a semicolon (AdminRolesController.cs:36-37): no route, no version attribute, no action body, the same shape OAuthController and UsersDataExportController use for a workflow that is app-agnostic once the app's own service is supplied.
  • Walkthrough: one line, public sealed class AdminRolesController(IRoleAdministrationService administration, ICurrentUserService currentUser) : RolesAdminControllerBase(administration, currentUser); (:36-37).
  • Why it's built this way: role administration (list roles, view members, grant/revoke) is identical in every app that shares the framework's role vocabulary, so the base owns the whole surface and each app contributes only the service that reads and writes its own User rows.
  • Where it's used: mounted by the Identity service host's Program.cs and routed through the Gateway; UsersAdminController is the equivalent surface for individual accounts rather than roles.

LegalAcceptanceController

MMCA.ADC.Identity.API · MMCA.ADC.Identity.API.Controllers · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/Controllers/LegalAcceptanceController.cs:24 · Level 11 · class (sealed)

  • What it is: the signed-in user's Terms of Service acceptance endpoint, GET and POST /Users/me/legal-acceptance. Like OAuthController it is body-less: the actions, their authorization and the version rules all come from LegalAcceptanceControllerBase, and this subclass supplies only the route (LegalAcceptanceController.cs:10-15).
  • Depends on: LegalAcceptanceControllerBase (base, MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Legal/LegalAcceptanceControllerBase.cs:45), ILegalAcceptanceService, ICurrentUserService, LegalAcceptanceOptions via IOptions, and the LegalAcceptanceDTO it returns.
  • Concept reinforced, the derived-controller-as-configuration pattern, with the policy in the base. [Rubric §15, Best Practices & Code Quality], [Rubric §9, API & Contract Design]. The primary constructor forwards three dependencies and ends in a semicolon (LegalAcceptanceController.cs:24-28). What matters is where the rules live: the base, not ADC's service. An acceptance is refused unless it names the configured current version (LegalAcceptancePolicy.EnsureAcceptsCurrentVersion, LegalAcceptanceControllerBase.cs:110-115), the stored value is the configured one and never the client's string (:117-120), and every answer is re-derived against that version (LegalAcceptancePolicy.Normalize, :83, :125). With no version configured, GET answers IsCurrent = true without calling the service (:65-69), so a client never blocks a user on a host that has not opted in. The base is [Authorize] (:44) and the POST is [Idempotent] (:94).
  • Walkthrough: three class attributes and one constructor.
    • [ApiController], [Route("Users")], [ApiVersion("1.0")] (LegalAcceptanceController.cs:21-23). The route is the literal Users, not [controller], because the base fixes the action template to me/legal-acceptance and the published path must stay /Users/me/legal-acceptance, which the Gateway already forwards under its /Users/** route (:16-19). Same trick as UsersDataExportController and PasswordResetController.
    • The three constructor parameters (:25-27) are passed straight to the base. The acceptance store itself is ADC's LegalAcceptanceService.
  • Why it's built this way: the version rules are framework policy shared by every consumer, so keeping them in the base means a consumer's service only stores and reads acceptance rows (opt-in under ADR-116).
  • Where it's used: called by the framework's ILegalAcceptanceUIService, which LegalAndDataCard reads to render the accepted-terms line; backed by LegalAcceptanceService.

UsersDataExportController

MMCA.ADC.Identity.API · MMCA.ADC.Identity.API.Controllers · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/Controllers/UsersDataExportController.cs:26 · Level 11 · class (sealed)

  • What it is: the data-subject access and portability endpoint, GET /Users/{userId}/export. Like OAuthController it declares no action of its own: the action, its authorization, its feature gate, and the file-download response all come from DataExportControllerBase<TQuery>, and this class supplies the route and one query factory.
  • Depends on: DataExportControllerBase<TQuery> (base), IQueryHandler<in TQuery, TResult> closed over ExportUserDataQuery, UserDataExportDTO, ICurrentUserService, Result, and PrivacyFeatures.
  • Concept introduced, the abstract base with an app-owned query factory. [Rubric §30, Compliance, Privacy & Data Governance] assesses whether the subject-rights obligations are implemented rather than described, and [Rubric §15, Best Practices & Code Quality] covers the factoring. The export workflow is identical in every app, but the query record is not: each app's ExportUserDataQuery lives in its own Application assembly, so a concrete shared controller could not construct a type it cannot see. The base's remarks state that reasoning explicitly (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Privacy/DataExportControllerBase.cs:45-50), and the resolution is an abstract CreateQuery (:119-122) implemented here as a one-liner (UsersDataExportController.cs:32-35).
  • Concept introduced (2), defence in depth on a privacy endpoint. [Rubric §11, Security]. Three independent gates sit in front of one document. The base carries [Authorize] (DataExportControllerBase.cs:59), so an anonymous caller never arrives; it carries [FeatureGate(PrivacyFeatures.DataExport)] (:58), so the whole surface stays absent until a host turns the flag on (ADR-031); and the handler independently enforces owner-or-Organizer, which is why the class doc here can say "the handler enforces it" (UsersDataExportController.cs:16-17) and the base can say the endpoint cannot leak another subject's data even if it were mounted without an [Authorize] of its own (DataExportControllerBase.cs:51-56). The ADC privilege predicate is one line in ExportUserDataHandler (.../UseCases/ExportUserData/ExportUserDataHandler.cs:38).
  • Walkthrough: three attributes and two members.
    • [ApiController], [Route("Users")], [ApiVersion("1.0")] (UsersDataExportController.cs:23-25). The route is the literal Users, not [controller], and the <remarks> say why (:19-22): the base fixes the action template to {userId}/export (DataExportControllerBase.cs:79), so a subclass routed at Users keeps serving the published /Users/{userId}/export path even though the class is named UsersDataExportController. This is the same trick PasswordResetController uses on /Auth.
    • The primary constructor (:26-29) takes the closed export handler and ICurrentUserService and forwards both to the base.
    • CreateQuery(userId, currentUserId, currentUserRole) (:32-35): builds ADC's ExportUserDataQuery from the route id and the authenticated caller. The base's constraint where TQuery : IUserOwnedRequest (DataExportControllerBase.cs:64) is what lets the shared pipeline reason about ownership on an app-owned record.
    • The inherited action, ExportAsync (DataExportControllerBase.cs:84-112): reject an unusable caller id with Privacy.Unauthorized (:86-90), build the query and dispatch (:92-94), then serialize the package with JsonSerializer.SerializeToUtf8Bytes(export, JsonSerializerOptions.Web) and return File(...) (:107-109). The comment explains the choice (:103-106): Ok(export) would content-negotiate and render inline, and the point of this endpoint is a document the subject saves and keeps. The download name is built from the package's own GeneratedOn under InvariantCulture (:133-134), so the file name and the document always agree and a saved file sorts the same in every locale.
  • Why it's built this way: ADR-076 is the decision this implements, and the split (route and query here, everything else in the base) follows the AuthControllerBase precedent the base cites (DataExportControllerBase.cs:40-44): the app owns its URL space, the framework owns the workflow.
  • Where it's used: handled by ExportUserDataHandler; called by an authenticated subject exporting their own data, or by an Organizer acting on a request, through the Gateway's existing /Users route.
  • Caveats / not-in-source: whether the endpoint is reachable in a given environment depends on the PrivacyFeatures.DataExport flag value, which lives in host configuration and not in this file.

PasswordResetController

MMCA.ADC.Identity.API · MMCA.ADC.Identity.API.Controllers · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/Controllers/PasswordResetController.cs:28 · Level 16 · class (sealed)

  • What it is: the anonymous password-recovery surface, POST /Auth/forgot-password and POST /Auth/reset-password. Like OAuthController it declares no actions of its own: the two endpoints are inherited, and this class supplies the route, the version, and two one-line command factories.
  • Depends on: PasswordResetAuthControllerBase<TForgotPasswordCommand, TResetPasswordCommand> (base, at MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/PasswordResetAuthControllerBase.cs:43), ICommandHandler<in TCommand, TResult> closed over ForgotPasswordCommand and ResetPasswordCommand, Result, and the shared ForgotPasswordRequest / ResetPasswordRequest contracts; externals: Asp.Versioning, ASP.NET Core MVC.
  • Concept introduced (1), the sibling controller as a way around single inheritance. [Rubric §9, API & Contract Design] assesses whether the URL surface stays coherent as capabilities are added, and [Rubric §15, Best Practices & Code Quality] covers the cost of getting there. AuthController already spends its one base class on the shared account controller, so recovery could not be more actions on that type. The resolution is a second controller with [Route("Auth")] written as a literal rather than [controller] (PasswordResetController.cs:26), which lands both endpoints on the same /Auth prefix the Gateway already fronts. The <remarks> state that motivation directly (:19-24): both endpoints ride the existing gateway route with no gateway change. Contrast this with UserClaimsController's [Route("[controller]")], where the class name is the resource.
  • Concept introduced (2), anonymous by necessity, and the response posture that follows. [Rubric §11, Security] and [Rubric §30, Compliance, Privacy & Data Governance]. A user who has lost a credential cannot present one, so requiring authentication here would be circular; the base marks both actions [AllowAnonymous] (PasswordResetAuthControllerBase.cs:77, :101) and the framework's anonymous-endpoint architecture test lists them explicitly rather than letting them slip through unnoticed. Because the endpoints are open, the response shapes are chosen to reveal nothing: forgot-password always answers 202 Accepted (:79, :92) whether or not the address holds an account, so a caller cannot enumerate registered addresses, and every reset rejection collapses into one 401 (:105) so an invalid token and an unknown address are indistinguishable. Both carry [EnableRateLimiting(WebApplicationBuilderExtensions.RateLimitPolicyAuthIp)] (:78, :102), the same "auth-ip" fixed window that guards login and register (ADR-019), and both carry [Idempotent] (:76, :100) so a retried mobile submit does not send a second reset email or burn a second token (ADR-017).
  • Walkthrough: three class attributes and four members.
    • [ApiController], [Route("Auth")], [ApiVersion("1.0")] (PasswordResetController.cs:25-27), the same routing-and-versioning triple every ADC controller repeats because those attributes are not reliably inherited.
    • The primary constructor (:28-33) takes the two closed command handlers and forwards them to the base, which exposes them as ForgotPasswordHandler and ResetPasswordHandler (PasswordResetAuthControllerBase.cs:50, :53).
    • CreateForgotPasswordCommand(ForgotPasswordRequest request) => new(request) (PasswordResetController.cs:36) and CreateResetPasswordCommand(ResetPasswordRequest request) => new(request) (:39), the two abstract factories the base declares (PasswordResetAuthControllerBase.cs:61, :69). This is the same split AuthController uses for change-password: the workflow is shared, the command records are not: each app declares its own ResetPasswordCommand record in its own Application namespace, and ADC's is a plain ICommandWithRequest<ResetPasswordRequest> with no cache-invalidation marker (ResetPasswordCommand.cs:10-11).
    • The inherited actions themselves: ForgotPasswordAsync (PasswordResetAuthControllerBase.cs:82-93) dispatches the app command and returns Accepted(); ResetPasswordAsync (:107-118) dispatches and returns NoContent(). Both end in the same result.IsFailure ? HandleFailure(result.Errors) : ... tail as every other controller in the module.
  • Why it's built this way: the reset credential is a cache record keyed by the address rather than columns on the user row, which is the decision ADR-091 records: it costs no migration in any consumer, adds nothing to the hottest entity in the system, needs no sweeper because the cache enforces expiry itself, and reuses the substrate ADR-029 already chose for login lockout. That choice is invisible from this file, which is the point: the controller only names the two commands.
  • Where it's used: handled by ForgotPasswordHandler and ResetPasswordHandler; driven by unauthenticated browser and MAUI clients through the Gateway's existing /Auth route.
  • Caveats / not-in-source: nothing about token generation, its TTL, the attempt cap, or the email send is visible here; all of it lives in the two handlers and the cache-backed store behind them.

AuthController

MMCA.ADC.Identity.API · MMCA.ADC.Identity.API.Controllers · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/Controllers/AuthController.cs:34 · Level 14 · class (sealed, partial)

  • What it is: the /auth endpoint surface: login, register, refresh, revoke, change password, and get/set the stored culture and theme preferences. Most of it is inherited; this class overrides two actions and supplies the two command factories.
  • Depends on: UserAccountAuthControllerBase<TChangePasswordCommand, TChangePreferencesCommand> (which itself extends AuthControllerBase), IAuthenticationService, ICurrentUserService, ChangePasswordCommand, ChangePreferencesCommand, GetUserPreferencesQuery, AuthenticationResponse, RegisterRequest, LoginRequest, UserPreferencesResponse, IInternalCommandScheduler, SendEmailConfirmationCommand; externals: ASP.NET Core rate limiting ([EnableRateLimiting]).
  • Concept introduced, the generic controller base parameterized by the app's command types. [Rubric §15, Best Practices & Code Quality], [Rubric §1, SOLID], [Rubric §11, Security]. The base owns the four token actions plus PUT password (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/UserAccountAuthControllerBase.cs:87), PUT preferences (:112), and GET preferences (:138). It cannot own the command records, because ADC marks its change-password command ICacheInvalidating with a cache prefix built from ADC's own User type while Store does not; the shared handler base's remarks record that reason (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/ChangePassword/ChangePasswordHandlerBase.cs:18-37). The resolution is two abstract factory methods (UserAccountAuthControllerBase.cs:67, :77), which this class implements as one-liners (AuthController.cs:132-140): the shared workflow stays shared, and each app keeps its own command semantics. PasswordResetController is the same pattern applied to the recovery pair.
  • Concept introduced (2), scheduling a side effect after commit instead of sending it inline (ADR-116). [Rubric §6, CQRS & Event-Driven], [Rubric §29, Resilience & Business Continuity]. Once the registration itself succeeds, RegisterAsync schedules a SendEmailConfirmationCommand through IInternalCommandScheduler (AuthController.cs:99-103), except for synthetic load-test accounts (below). The comment above the call (:88-98) states the reasoning in full: the registration transaction has already committed by that point, so the row is written and signalled immediately and the internal-command processor picks it up on its next tick; a mail outage or a crash in between defers the send rather than losing it. It also names why the trigger lives in the controller rather than in a domain event: ADC raises no UserRegistered domain event (only the cross-service integration event UserRegistered), and AuthenticationService already sits at the dependency ceiling, so the controller is the one place that both knows a registration just succeeded and is free to take a new dependency. A scheduling failure never fails the registration: the account exists and the user can request a fresh link from the confirmation page; the failure is logged at Error through LogConfirmationScheduleFailed (:105-108, declared :113-114) because a recurring one means nobody is being asked to confirm anything. The synthetic-account skip (:81-86): when SyntheticAccounts.IsSynthetic(request.Email) is true, RegisterAsync answers immediately and schedules nothing, because the conference-day load test's accounts sit under an undeliverable reserved domain and a confirmation email to each would only spend the SMTP relay's daily quota and reputation (comment at :81-82).
  • Walkthrough: primary constructor forwarding five of its seven dependencies to the base and keeping IInternalCommandScheduler and ILogger<AuthController> for itself (AuthController.cs:34-48), then four members.
    • RegisterAsync (AuthController.cs:53-111) is a genuine override rather than a pass-through. It passes the base's ClientIpAddress and ClientUserAgent into AuthenticationService.RegisterAsync (:66-68; the two properties are computed from HttpContext on the base). Every success, on both the synthetic path (:85) and the normal path (:110), answers through the framework's RegistrationResult(result, request.Email): 201 Created with the token pair, or 202 Accepted with RegistrationPendingResponse when the sign-in gate would refuse the new account, both declared in the ProducesResponseType set (:56-57). The comment (:75-79) explains why ADC answers 201 in practice: with RequireConfirmedEmail off, ADC's gate refuses only an unconfirmed Organizer, ContentEditor or speaker-linked account, and a registrant is always a plain attendee with no speaker link.
    • LoginAsync (AuthController.cs:127-130) overrides only to re-declare attributes, then returns base.LoginAsync(request, cancellationToken) directly as an expression-bodied, non-async override (:130), so no extra state machine or ConfigureAwait wraps the base's task. The reason is the attribute set: [EnableRateLimiting(WebApplicationBuilderExtensions.RateLimitPolicyAuthIp)] (:123) and the documented 429 (:126). The doc comment (:116-120) states the threat model precisely: the per-email lockout of BR-212 cannot stop one source spraying a single common password across many different emails, so a per-IP fixed window sits on top of it (ADR-019, ADR-029). Both anonymous endpoints, register and login, carry the same policy.
    • CreateChangePasswordCommand and CreateChangePreferencesCommand (AuthController.cs:132-140), the two factory implementations that bind ADC's command records to the base's workflow.
  • Why it's built this way: [Route("[controller]")] makes the prefix /auth, which is what the Gateway's route map fronts, and [ApiVersion("1.0")] keeps it on the header-based versioning scheme (ADR-046). The class is partial (:34) because the [LoggerMessage] source generator needs a partial method declaration for LogConfirmationScheduleFailed (:113-114). Both anonymous actions are marked [AllowAnonymous] with the fully qualified attribute name because the file's using set does not import the authorization namespace.
  • Where it's used: the entry point for every authenticated ADC client. The Blazor and MAUI clients call login/register/refresh through the Gateway; the Profile page uses the inherited PUT auth/password and the preferences pair; ChangePasswordRequestValidator guards the password action through the Validating decorator; a successful register schedules the confirmation link handled by EmailConfirmationController. Its anonymous siblings on the same /Auth prefix are PasswordResetController and SignInLinkController.

AttendeeRow

MMCA.ADC.Identity.Application · MMCA.ADC.Identity.Application.Users · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/AttendeeQueryService.cs:102 · Level 0 · record struct (private readonly, nested)

  • What it is: the two-field row the keyset reader inside AttendeeQueryService hands to both of that service's walks: one attendee's id and its address as a plain string. It is declared privately inside the service and never leaves it. (Not to be confused with the Engagement UI's AttendeeRow, an unrelated wire shape that shares the name.)
  • Depends on: the UserIdentifierType alias (solution-wide global using, see primer §2). Nothing else.
  • Concept introduced, unwrap the value object once, at the read. [Rubric §15, Best Practices & Code Quality] (assesses whether a conversion happens in one place). The repository projection reads { u.Id, u.Email }, where Email is the Email value object stored through a value converter; the private ReadBatchAsync turns each projected row into new AttendeeRow(r.Id, r.Email.Value) (AttendeeQueryService.cs:99), so the page walk and the count both test SyntheticAccounts.IsSynthetic(row.Email) against a string (:44, :77) without touching the value object again. [Rubric §12, Performance & Scalability]: a readonly record struct is a value type, so a batch list holds its rows inline rather than one heap object per row.
  • Walkthrough (AttendeeQueryService.cs:102): one line, private readonly record struct AttendeeRow(UserIdentifierType Id, string Email);. It is built only at :99; GetAttendeeUserIdPageAsync reads row.Email for the synthetic test (:44), row.Id for the page (:49) and batch[^1].Id to advance the keyset cursor (:64), and CountAttendeesAsync reads the same two members (:77, :84).
  • Why it's built this way: private keeps the row from becoming part of any contract. The cross-module answer stays IReadOnlyList<UserIdentifierType>, so the address used for the in-memory filter never crosses the module boundary.
  • Where it's used: only inside AttendeeQueryService, by ReadBatchAsync (returned as IReadOnlyList<AttendeeRow>, :88) and its two callers.

GetUserAvatarQuery

MMCA.ADC.Identity.Application · MMCA.ADC.Identity.Application.Users.UseCases.GetUserAvatar · MMCA.ADC.Identity.Application/Users/UseCases/GetUserAvatar/GetUserAvatarQuery.cs:5 · Level 0 · record (sealed)

  • What it is: the smallest query in the module, a single-field request for the current user's avatar state (BR-116a).
  • Depends on: the UserIdentifierType alias (ADR-048, see primer §2). Nothing else.
  • Concept introduced, the "identity is stamped, never asked for" query. The CQRS query record itself is taught at IQueryHandler<in TQuery, TResult>; the detail worth naming here is stated by the parameter doc (GetUserAvatarQuery.cs:4): UserId is "stamped by the controller, never client-supplied". [Rubric §11, Security] (assesses whether authorization is structural rather than a check that could be forgotten): the endpoint is me/avatar and the id comes from ICurrentUserService (MMCA.ADC.Identity.API/Controllers/UsersController.cs:133-135), so there is no request shape in which one user can ask for another user's avatar. Contrast the organizer roster read, UserListEntityQueryService, whose filter, sort and page inputs are client-supplied and are therefore checked against the roster's own field contract (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UserListEntityQueryService.cs:61-63).
  • Walkthrough: one line (:5), public sealed record GetUserAvatarQuery(UserIdentifierType UserId);. No validator, because there is no client-supplied field left to validate.
  • Why it's built this way: giving even a one-field read its own named query type keeps every use case discoverable in the same place and lets the CQRS decorator pipeline address it by type like any other (ADR-014).
  • Where it's used: constructed by UsersController's GetAvatarAsync (MMCA.ADC.Identity.API/Controllers/UsersController.cs:137-139), handled by GetUserAvatarHandler.

RemoveUserAvatarCommand

MMCA.ADC.Identity.Application · MMCA.ADC.Identity.Application.Users.UseCases.RemoveUserAvatar · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/RemoveUserAvatar/RemoveUserAvatarCommand.cs:8 · Level 0 · record (sealed)

  • What it is: the CQRS command that removes the signed-in user's avatar photo (BR-116a): it clears the stored URL and deletes the blob. It carries only the owning UserId.
  • Depends on: UserIdentifierType, the Identity module's identifier alias (see identifier aliases). The file has no using directives at all.
  • Concept: the avatar slice as a whole is a three-operation feature (get, set, remove) taught in depth at SetUserAvatarHandler; this record is its delete request. The doc comment (RemoveUserAvatarCommand.cs:3-6) records the load-bearing contract: the operation is idempotent, and removing a non-existent avatar succeeds rather than erroring. [Rubric §9, API and Contract Design] assesses predictable, repeat-safe mutation semantics: a delete that is safe to replay lets a client (or a retrying proxy) call it again without special-casing "already gone".
  • Walkthrough: a one-line positional record, RemoveUserAvatarCommand(UserIdentifierType UserId) (RemoveUserAvatarCommand.cs:8). No body. The parameter doc (:7) states that UserId is stamped by the controller from the authenticated principal and is never client-supplied, which is what makes this a self-service-only operation rather than an ownership check the handler has to perform.
  • Why it's built this way: a bare command record keeps the delete inside the command decorator pipeline like every other mutation, and the controller-stamped owner id turns ownership into a property of routing rather than an argument the client controls.
  • Where it's used: constructed by UsersController.RemoveAvatarAsync (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/Controllers/UsersController.cs:200), the [HttpDelete("me/avatar")] endpoint (:119) which returns 204 No Content on success (:120, :133). Handled by RemoveUserAvatarHandler, which returns a bare Result with no payload.
  • Caveats / not-in-source: unlike its sibling, this command has no FluentValidation validator, and that absence is deliberate and frozen: it is listed under "identifier-only commands" in CommandValidatorCoverageTests (MMCA.ADC/Tests/Architecture/MMCA.ADC.Architecture.Tests/Cqrs/CommandValidatorCoverageTests.cs:61), the fitness gate that otherwise fails a new data-carrying command that ships without one. Its whole payload is a server-supplied id, so there is no field a validator could reject.

IImageProcessor

MMCA.ADC.Identity.Application · MMCA.ADC.Identity.Application.Users · MMCA.ADC.Identity.Application/Users/IImageProcessor.cs:11 · Level 3 · interface

  • What it is: the Identity module's port for normalizing an untrusted uploaded avatar image: decode it (rejecting non-images), correct EXIF orientation, center-crop to a square of the requested size, strip all metadata, and re-encode as JPEG (type doc comment, IImageProcessor.cs:5-10). It lives in the ADC Identity Application layer, not in the framework: the avatar pipeline is the only consumer.
  • Depends on: Result (via MMCA.Common.Shared.Abstractions, IImageProcessor.cs:1); BCL Stream.
  • Concept introduced, re-encoding as an image trust boundary. [Rubric §11, Security] (assesses whether untrusted binary input is neutralized rather than merely inspected) and [Rubric §30, Compliance / Privacy / Data Governance] (assesses PII handling). EXIF GPS coordinates are PII that a naive avatar pipeline would publish to a public blob URL, and a crafted file can be a valid image and something else at once. The doc comment makes both points (ADR-045): metadata removal deletes the location data, and re-encoding is the defense against polyglot or malformed payloads because only pixels survive the decode and re-encode round trip (IImageProcessor.cs:8-9). This is the second gate of the upload: the framework's ImageContentSniffer checks the magic bytes first, then this processor rebuilds the image from pixels.
  • Walkthrough: one method, NormalizeToSquareJpegAsync(Stream content, int size, CancellationToken cancellationToken = default) (IImageProcessor.cs:18), returning Task<Result<byte[]>>: the normalized JPEG bytes, or a validation failure for undecodable content (:17). content is read from its current position (:14), and size is the output square edge length in pixels (:15), so the caller, not the processor, owns the avatar dimension.
  • Why it's built this way: returning bytes rather than writing to storage keeps the processor a pure transform, so the handler can sniff, then normalize, then hand the result to IFileStorageService; a Result failure on undecodable input stops a bad upload before it reaches storage. Declaring the port in Application and implementing it in Infrastructure keeps the native imaging library out of the Application assembly ([Rubric §3, Clean Architecture]).
  • Where it's used: injected into SetUserAvatarHandler (MMCA.ADC.Identity.Application/Users/UseCases/SetUserAvatar/SetUserAvatarHandler.cs:29), which calls it after the ImageContentSniffer.IsAllowedImage gate (:63) with AvatarSize (:37, 256) at :103, then uploads the result (:117). Implemented by SkiaSharpImageProcessor (MMCA.ADC.Identity.Infrastructure/Services/Users/SkiaSharpImageProcessor.cs:16), registered with TryAddSingleton<IImageProcessor, SkiaSharpImageProcessor>() by the Infrastructure-layer AddModuleIdentityInfrastructure (MMCA.ADC.Identity.Infrastructure/DependencyInjection.cs:25), whose doc comment records that the processor is stateless, so one instance serves every request (:17-19). The other usage site is SetUserAvatarHandlerTests.

AttendeeQueryService

MMCA.ADC.Identity.Application · MMCA.ADC.Identity.Application.Users · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/AttendeeQueryService.cs:21 · Level 9 · class (internal sealed)

  • What it is: Identity's in-process implementation of the cross-module IAttendeeQueryService contract. It answers two questions about one audience, "which user ids hold the Attendee role", one keyset page at a time, and "how many of them are there", in both cases leaving out the conference-day load test's synthetic accounts and every machine-client service account (type doc comment, AttendeeQueryService.cs:8-13). It is the only way another module gets either answer without touching the Identity domain.
  • Depends on: IAttendeeQueryService (the Shared-layer contract, whose MaxPageSize is 10_000, MMCA.ADC.Identity.Shared/Users/IAttendeeQueryService.cs:20); IUnitOfWork and IReadRepository<TEntity, TIdentifierType>; AttendeeKeysetSpecification (the read's criteria, order and size); User and SyntheticAccounts (Domain); the private AttendeeRow; the UserIdentifierType alias.
  • Concept introduced, serving data across a module boundary through a Shared-layer contract. [Rubric §7, Microservices Readiness] (assesses whether cross-module needs are met by explicit contracts rather than direct type references) and [Rubric §3, Clean Architecture]. Notification must fan a broadcast out to every attendee, but it must never reference MMCA.ADC.Identity.Domain. The interface therefore lives in MMCA.ADC.Identity.Shared, the implementation here in Application, and Notification sees only the interface. That indirection is exactly what later allows the same call to be satisfied over gRPC with no change at the call site (ADR-007). [Rubric §12, Performance & Scalability]: the read projects to an (Id, Email) pair in the database rather than materializing whole User rows, and it pages by keyset (Id greater than the last id read, ascending), so neither a page nor the count ever holds the whole audience in memory.
  • Concept introduced (2), a page an in-memory filter must not thin. The synthetic-account test cannot run in SQL: Email is stored through a value converter, so a domain-suffix test does not translate (remarks, :15-16). Filtering one database page in memory would hand back a short page, and the push-delivery walk reads a short page as the end of the audience, so every attendee after it would be skipped silently (:16-18). The service therefore keeps reading batches until the page is full or the store is exhausted, and the count walks the same batches with the same filter, "so the two can never disagree about who is an attendee" (:18-19).
  • Walkthrough (primary-constructor injection of IUnitOfWork, :21; the class is internal sealed, so nothing outside the Application assembly can bind to the concrete type)
    1. CountBatchSize (:24), an internal const int of 1_000: the batch the count walks in, bounding the rows held at once (:23).
    2. GetAttendeeUserIdPageAsync(afterUserId, take) (:27-66). It first throws on a take that is zero or negative or above IAttendeeQueryService.MaxPageSize (:32-33), a caller bug rather than a Result. It then loops: read a batch of take rows after the cursor (:40), skip each synthetic row (:44-47), add the id (:49) and return as soon as the page is full (:50-55); the comment there records that rows left in the batch are not lost, because the next page starts after the last id returned. A batch shorter than take means the store is exhausted, so the page, short or not, is "the honest end of the audience" (:58-62). Otherwise the cursor moves to the batch's last id (:64) and the loop reads again.
    3. CountAttendeesAsync (:69-86): starting from a null cursor, it reads batches of CountBatchSize (:76), adds the non-synthetic rows (:77), and returns once a batch comes back short (:79-82), otherwise advancing the cursor (:84).
    4. ReadBatchAsync (:88-100), the one read both walks share: unitOfWork.GetReadRepository<User, UserIdentifierType>() (:93), the read-only facade, then ListAsync(new AttendeeKeysetSpecification(afterUserId, take), u => new { u.Id, u.Email }, cancellationToken) (:94-97), mapped to AttendeeRow values (:99). The specification's criteria are u.Role == UserRole.Attendee.Value && !u.IsServiceAccount, plus u.Id > after once a cursor exists (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/Specifications/AttendeeKeysetSpecification.cs:20-22), ordered by Id (:24) and limited to take rows (doc comment, :9). The !u.IsServiceAccount clause drops every service account behind a machine client (ADR-140), which is never an attendee whatever its role; unlike the synthetic test it is an ordinary column, so it runs in SQL. Note the .Value: User stores its role as a plain string (MMCA.ADC.Identity.Domain/Users/User.cs:77) and UserRole is a value object, so the comparison unwraps it to the string the column holds (MMCA.ADC.Identity.Domain/Users/UserRole.cs:24). No explicit IsDeleted test appears, so the global soft-delete query filter is what keeps erased accounts out (the "active users" of the doc comment, :10). SyntheticAccounts.IsSynthetic (MMCA.ADC.Identity.Domain/Users/SyntheticAccounts.cs:30) is a trimmed, case-insensitive EndsWith of @loadtest.adc.invalid (:23), so an organizer broadcast is neither fanned out to the load test's accounts nor counted as reaching them.
  • Why it's built this way: pushing the role and service-account predicates, the keyset bound and the two-column projection into the database keeps each batch an ordered, bounded read, with only the cheap suffix test left in memory; refilling a page across batches keeps the "short page means done" signal true despite that in-memory test; and relying on the global query filter for soft-delete means this service can never diverge from the rest of the system's definition of "deleted" (ADR-005).
  • Where it's used: registered as the IAttendeeQueryService implementation by the Application-layer DependencyInjection (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/DependencyInjection.cs:38); consumed by the Notification module's push-delivery walk. In the extracted topology the registration is replaced by AttendeeQueryServiceGrpcAdapter with Replace (MMCA.ADC/Source/Services/MMCA.ADC.Identity.Contracts/DependencyInjection.cs:46), and this class becomes the code behind AttendeesGrpcService on the Identity side.

LegalAcceptanceService

MMCA.ADC.Identity.Application · MMCA.ADC.Identity.Application.Users · MMCA.ADC.Identity.Application/Users/LegalAcceptanceService.cs:21 · Level 8 · class (sealed)

  • What it is: Identity's implementation of the framework's ILegalAcceptanceService: it reads and records the signed-in user's Terms of Service acceptance, and is the service behind the framework's Users/me/legal-acceptance endpoints.
  • Depends on: ILegalAcceptanceService (the contract); IUnitOfWork; TimeProvider; User (AcceptTerms, AcceptedTermsVersion, TermsAcceptedOn); LegalAcceptanceDTO; Result and Error; the UserIdentifierType alias.
  • Concept introduced, a thin application service that leaves the rule in the aggregate. [Rubric §3, Clean Architecture] (assesses whether business rules live in the domain, not the orchestration layer) and [Rubric §30, Compliance / Privacy / Data Governance] (a recorded, versioned consent). The service only loads the user, calls the aggregate and saves; the version validation lives in User.AcceptTerms (MMCA.ADC.Identity.Domain/Users/User.cs:418), which checks the version with UserInvariants.EnsureTermsVersionIsValid before stamping it. The standing shown to the client is derived by the shared LegalAcceptanceDTO.Evaluate (MMCA.Common.Shared/Legal/LegalAcceptanceDTO.cs:42), so IsCurrent is computed the same way on every path: true when no version is configured or the accepted version equals the current one by ordinal comparison.
  • Walkthrough (primary-constructor injection of IUnitOfWork and TimeProvider, :21-23)
    1. GetForCurrentUserAsync (:26-40), a read: GetReadRepository<User, UserIdentifierType>().GetByIdAsync(currentUserId, ...) (:31-34); a missing user returns Error.NotFound with source and target set (:37-38); otherwise it returns LegalAcceptanceDTO.Evaluate(currentVersion, user.AcceptedTermsVersion, user.TermsAcceptedOn) (:39).
    2. AcceptForCurrentUserAsync (:43-67), a write: it loads the user through the mutable GetRepository<User, UserIdentifierType>() (:48-51), returns NotFound when absent (:52-56), then calls user.AcceptTerms(version, timeProvider.GetUtcNow().UtcDateTime) (:58). A failed acceptance (an invalid version) is returned as Result.Failure<LegalAcceptanceDTO>(acceptResult.Errors) before anything is saved (:59-62); on success it calls unitOfWork.SaveChangesAsync (:64) and returns the re-evaluated standing (:66).
  • Why it's built this way: injecting TimeProvider rather than reading DateTime.UtcNow keeps the stamped instant testable. New local sign-ups are stamped at registration by AuthenticationService's CreateUser, while external-login accounts are created unstamped, so this service is the path by which the UI acceptance gate records their acceptance later.
  • Where it's used: registered with TryAddScoped<ILegalAcceptanceService, LegalAcceptanceService>() by the Application-layer DependencyInjection (MMCA.ADC.Identity.Application/DependencyInjection.cs:60), explicitly because the convention scan only finds handlers, mappers and validators; the other usage site is LegalAcceptanceServiceTests. The HTTP surface is LegalAcceptanceController.

GetUserAvatarHandler

MMCA.ADC.Identity.Application · MMCA.ADC.Identity.Application.Users.UseCases.GetUserAvatar · MMCA.ADC.Identity.Application/Users/UseCases/GetUserAvatar/GetUserAvatarHandler.cs:10 · Level 8 · class (sealed)

  • What it is: the read side of the avatar feature (BR-116a). It returns the current user's avatar URL, or null inside a successful result when none is set.
  • Depends on: IQueryHandler<in TQuery, TResult>; GetUserAvatarQuery; IUnitOfWork; User; UserAvatarDTO; Result and Error.
  • Concept introduced, "absent value" is a success, "absent row" is a failure. [Rubric §9, API & Contract Design] (assesses whether responses distinguish states unambiguously). The two outcomes look similar from the outside but mean different things, and the handler keeps them apart: a user with no avatar yields Result.Success(new UserAvatarDTO(user.AvatarUrl)) with a null URL inside (:23, the property is string? at MMCA.ADC.Identity.Domain/Users/User.cs:118), which the controller returns as HTTP 200 with a JSON body; a user id that resolves to no row yields Error.NotFound (:22), which the shared failure mapping turns into a 404. The UI can therefore render the "no photo yet" placeholder without treating it as an error. Everything else here is standard CQRS read shape, taught in G05.
  • Walkthrough (primary constructor :10-11, single method :14-24): resolve the read-only repository and load in one expression, unitOfWork.GetReadRepository<User, UserIdentifierType>().GetByIdAsync(query.UserId, cancellationToken) (:18-19); then a ternary (:21-23) mapping null to Result.Failure<UserAvatarDTO>(Error.NotFound.WithSource(nameof(GetUserAvatarHandler)).WithTarget(nameof(User))) and a found user to Result.Success(new UserAvatarDTO(user.AvatarUrl)). Eleven lines of body, no branching beyond that.
  • Why it's built this way: GetReadRepository states the intent in the type, and the fluent WithSource / WithTarget error builders mean the edge can report what was missing without a bespoke error type per use case (ADR-013). Returning a DTO rather than the raw string leaves room to add avatar metadata later without changing the endpoint's shape (ADR-045).
  • Where it's used: injected into UsersController as IQueryHandler<GetUserAvatarQuery, Result<UserAvatarDTO>> (MMCA.ADC.Identity.API/Controllers/UsersController.cs:110) and invoked by GetAvatarAsync for GET /Users/me/avatar (:51-61); its write-side counterparts are the SetUserAvatarCommand and RemoveUserAvatarCommand handlers injected alongside it (:33-34).

VerifiedUserLookupService

MMCA.ADC.Identity.Application · MMCA.ADC.Identity.Application.Users · MMCA.ADC.Identity.Application/Users/VerifiedUserLookupService.cs:19 · Level 8 · class (internal sealed)

  • What it is: Identity's in-process implementation of the cross-module IVerifiedUserLookupService contract (BR-277): given a batch of addresses the caller already holds, it returns the active accounts whose confirmed address is one of them (type doc comment, VerifiedUserLookupService.cs:8-18). Engagement uses the answer to link an event's roster tickets to accounts that existed before the roster was uploaded.
  • Depends on: IVerifiedUserLookupService (the Shared-layer contract, with its MaxEmailsPerCall bound of 500, MMCA.ADC.Identity.Shared/Users/IVerifiedUserLookupService.cs:22); IUnitOfWork and IReadRepository<TEntity, TIdentifierType>; User; the Email value object; VerifiedUserDTO; the UserIdentifierType alias.
  • Concept reinforced, a cross-module read that cannot be used to enumerate users. The Shared-contract-plus-Application-implementation shape is taught at AttendeeQueryService; what this sibling adds is narrowness as a security property. [Rubric §11, Security] (assesses whether a data-access surface exposes only what its caller is entitled to): the contract answers only addresses the caller already supplies, only for confirmed addresses, and never for an erased account, so it cannot list users (IVerifiedUserLookupService.cs:11-12). [Rubric §12, Performance & Scalability] (assesses whether work stays bounded under load): one call carries at most MaxEmailsPerCall addresses, so the SQL IN list and the wire payload stay bounded, and the match runs in the database over a four-column projection.
  • Walkthrough (primary-constructor injection of IUnitOfWork, :19; one method, GetVerifiedUsersByEmailAsync(IReadOnlyCollection<string> emails, CancellationToken), :22-24)
    1. Guard the input (:26-27): ArgumentNullException.ThrowIfNull(emails) and ArgumentOutOfRangeException.ThrowIfGreaterThan(emails.Count, IVerifiedUserLookupService.MaxEmailsPerCall). An oversized batch is a caller bug, so it throws rather than returning a Result; the contract documents that exception (IVerifiedUserLookupService.cs:32).
    2. Normalize through the value object (:29-36): each address (a null entry becomes string.Empty) goes through Email.Create, failures are dropped with .Where(created => created.IsSuccess), and the survivors are de-duplicated with .Distinct(). The doc comment (:12-14) gives the reason: Email.Create trims and lowercases, the form User.Email is stored in, so the comparison is case-insensitive and the IN list compares the converted column directly. A malformed address simply matches nothing. When nothing survives, the method returns an empty list without touching the database (:37-38).
    3. Projected query (:40-44): GetReadRepository<User, UserIdentifierType>(), then GetProjectedAsync selecting { u.Id, u.Email, u.FirstName, u.LastName } where !u.IsDeleted && u.IsEmailConfirmed && wanted.Contains(u.Email). The explicit !u.IsDeleted test sits beside the confirmed-address test because erasure soft-deletes the row, overwrites the address with a placeholder and clears IsEmailConfirmed (:14-16), and the predicate checks both.
    4. Shape the answer (:46): one VerifiedUserDTO(u.Email.Value, u.Id, u.FirstName, u.LastName) per matching account; addresses with no such account are absent from the result rather than reported as misses.
  • Why it's built this way: the roster link needs to find pre-existing accounts, but an open "find user by email" query would be an enumeration oracle. Requiring a confirmed address keeps a typed-in, unproven registration from being attached to someone else's ticket, and filtering in SQL over a normalized IN list keeps a 500-address batch to one round trip.
  • Where it's used: registered with TryAddScoped<IVerifiedUserLookupService, VerifiedUserLookupService>() by the Application-layer DependencyInjection (MMCA.ADC.Identity.Application/DependencyInjection.cs:39); called from Engagement by ExistingAccountLinker, which splits addresses into batches of MaxEmailsPerCall (MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.Application/Tickets/Services/ExistingAccountLinker.cs:114), and injected into LinkExistingAccountsHandler and ProcessTicketRosterImportHandler. In the extracted topology the Contracts-layer DependencyInjection swaps the registration for VerifiedUserLookupServiceGrpcAdapter with Replace (MMCA.ADC/Source/Services/MMCA.ADC.Identity.Contracts/DependencyInjection.cs:73), and this class backs VerifiedUserLookupGrpcService on the Identity side. No disabled-module stub stands in for it: IdentityModule's Register does nothing but call AddIdentityModule (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/IdentityModule.cs:18-19).

UserListEntityQueryService

MMCA.ADC.Identity.Application · MMCA.ADC.Identity.Application.Users · MMCA.ADC.Identity.Application/Users/UserListEntityQueryService.cs:44 · Level 9 · class (sealed)

  • What it is: the organizer roster's query service (BR-51), serving GET Users/paged on the framework's generic paged entity path. It is a subclass of the framework's EntityQueryService<TEntity, TEntityDTO, TIdentifierType> that wraps the generic query with two things the generic path cannot do on its own: a signed-in filter and a per-page live session count.
  • Depends on: EntityQueryService<TEntity, TEntityDTO, TIdentifierType> (base, constructed with unitOfWork, navigationMetadataProvider, queryPipeline, dtoMapper and navigationPopulator, :44-52); IUnitOfWork, INavigationMetadataProvider, IEntityQueryPipeline, UserListDTOMapper, INavigationPopulator<in TEntity> over User; IUserSessionsAdministrationService (the extra parameter, :50, exposed as the private UserSessions property, :66); UserListDTO; QueryFieldContract; ISpecification<TEntity, TIdentifierType> and InlineSpecification<TEntity, TIdentifierType>; PagedCollectionResult<T>; Result and Error.
  • Concept introduced, a query column that is not an entity column. [Rubric §9, API & Contract Design] (assesses whether a list endpoint's filter and sort surface is explicit and validated) and [Rubric §12, Performance & Scalability]. UserListDTO.ActiveSessionCount is not stored on User: it is the number of live refresh sessions, which another service owns. So the service handles it on both sides of the generic query:
    • Contract. RosterContract (:61-63) is QueryFieldContract.ForNames over QueryFieldContract.For<UserListDTO>().Names minus ActiveSessionCount (case-insensitive compare against SignedInKey, :55), returned from the FieldContract override (:69). The generic filter and sort machinery therefore never sees the post-query field as an ordinary key.
    • Before the query (GetAllAsync, :72-132). It looks for the signed-in key in filters (:85-86). The filter accepts only > 0 ("signed in") or = 0 ("not signed in") with value 0: ParseSignedInFilter (:138-151) returns true, false or null, and null becomes Error.Validation("User.InvalidSignedInFilter", ...) (:96-100) instead of silently matching nothing. A valid filter is turned into a specification by BuildSignedInSpecificationAsync (:160-173): it asks the framework for the predicate itself, UserSessions.GetSignedInFilterAsync<User>(signedIn, cancellationToken) (:164-165), and wraps it in an InlineSpecification (:171-172), so "signed in" and "not signed in" are both decided on the framework side rather than by negating a spec here. The doc comment (:153-159) gives the shape of that predicate: User and RefreshSession share this host's one database, so the predicate carries the session query and runs as a single subquery, and the framework's bounded id-list fallback (with its validation failure) applies only when the two resolve to different data sources. A failed lookup is unwrapped with TryGetValue and its errors returned as-is (:166-169, and again at :105-108 in the caller). The new specification is And-ed with any caller-supplied one (:110-112), and the key is removed from a copy of the filter dictionary (:114-115) before the base GetAllAsync runs (:118-129); only a successful page goes on to the count fill (:131).
    • After the query (FillActiveSessionCountsAsync, :180-201). The page's ids go to ONE batch call, UserSessions.CountLiveSessionsAsync(pageIds) (:190), not one call per row; a failed count surfaces its errors (:191-194), an id the answer omits reads 0, and each UserListDTO is copied with the count via a with expression (:196-198) before the page itself is copied with the new items (:200). A row shaped into a field subset is not a UserListDTO and passes through unchanged (:175-179 doc comment), and an empty page short-circuits (:185-188).
  • Why it's built this way: the roster needs "who is signed in right now" and a count per row, but sessions live behind a separate administration service, so the query service composes around the generic path rather than adding a column or a join the Identity entity does not own. Using a specification keeps the signed-in filter on the same read-specification contract as every other list (ADR-055), taking the predicate from the framework keeps the same-database subquery and the cross-source fallback in one place, and the single batch count per page keeps the cost at one extra call regardless of page size.
  • Where it's used: registered with TryAddScoped<IEntityQueryService<User, UserListDTO, UserIdentifierType>, UserListEntityQueryService>() by the Application-layer DependencyInjection (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/DependencyInjection.cs:56); the module registers no INavigationPopulator<User>, so the constructor receives the framework's open-generic NullNavigationPopulator<User> default. UserListDTOMapper is the mapper it is constructed with, and the other usage site is UserListEntityQueryServiceTests.
  • Caveats / not-in-source: what GetSignedInFilterAsync and CountLiveSessionsAsync read, how the framework decides that User and RefreshSession share a data source, and how fresh the answer is, belong to IUserSessionsAdministrationService's implementation and are not visible here.

AuthenticationService

MMCA.ADC.Identity.Application · MMCA.ADC.Identity.Application.Users · MMCA.ADC.Identity.Application/Users/AuthenticationService.cs:52 · Level 11 · class (sealed)

  • What it is: ADC's authentication service. The generic login, registration, refresh, and revocation workflow is inherited from AuthenticationServiceBase<TUser>; this subclass supplies the ADC-specific pieces: the Attendee default role, the speaker_id and email_verified claims, the confirmed-email rule for privileged accounts, the outbox-atomic UserRegistered integration event, and the entire external OAuth login flow.

  • Depends on: AuthenticationServiceBase<TUser> and IAuthenticationService; IUnitOfWork, IPasswordHasher, ILoginProtectionService (:53-55), AuthenticationValidators and IAuthSessionIssuer (:56-57), plus IOptions<EmailConfirmationSettings> (:58), IInternalCommandScheduler (:59, used only to schedule a new unverified external account's confirmation email) and an optional TimeProvider? timeProvider = null (:60, used only to stamp the terms acceptance instant, falling back to TimeProvider.System), the base-relevant ones passed straight through to the base constructor (:61-68, with twoFactor: null); User, UserRole, UserRegistered, SendEmailConfirmationCommand, EmailConfirmationErrors, ClaimNames, Email, Result and Error; AuthenticationResponse and RegisterRequest; System.Security.Claims.

  • Concept introduced (1), the template-method base with app-specific hooks. [Rubric §2, Design Patterns] (assesses whether recurring shapes use a named, understood pattern) and [Rubric §15, Best Practices & Code Quality]. The base owns the security-critical sequence: validate first, ADR-029 lockout and registration rate limits, the ADR-004 dual-fetch pattern, and BR-205/206 refresh-session rotation with reuse detection (ADR-050). What varies per application is expressed as hooks, and this class overrides exactly those:

    • ValidateLoginCandidateAsync (:100-101), added for ADR-116: it delegates to the private CheckNotLocked (:165-171), which refuses Error.Unauthorized("Auth.AccountLocked", ...) when user.IsLocked. The base runs the login check after the password check, so reaching the distinct "locked" message already proves the caller owns the account, which is what makes the message safe to show (it is not an oracle for sweeping addresses).
    • ValidateRefreshCandidateAsync (:115-123), which runs the same lock check first (the backstop for a session opened the same instant an admin locks the account, since locking revokes the live sessions) and, when that passes, the privileged-account email rule below, so an unconfirmed account that has since become able to change conference content cannot keep a session it opened as an attendee (doc comment, :103-111).
    • CheckEmailConfirmed (:135-144), which keeps the base's own check and then adds the privileged-account rule. Both this hook and the refresh hook go through the private CheckPrivilegedAccountConfirmed (:154-157): it refuses with EmailConfirmationErrors.EmailNotConfirmed(source) when !user.IsEmailConfirmed and CanChangeConferenceContent(user) (:160-163), which is true for an Organizer, a ContentEditor (case-insensitive role compare) or any account with a LinkedSpeakerId. The doc comment (:125-132) records the owner decision of 2026-11-22: such an account needs a confirmed email to sign in whatever RequireConfirmedEmail says, while an attendee still signs in unconfirmed so a registration on the conference floor works before the inbox is reached. Because the base runs it after the password check, the distinct "confirm your address" answer reaches only the account's owner.
    • HasExternalLoginAsync (:182-186), which answers user.IsExternalLogin: an account linked to an external provider can sign in through it, so the framework counts the link as a sign-in method besides passkeys and does not refuse removing the account's last passkey (doc comment, :173-178).
    • EmailExistsAsync (:198-199), the registration uniqueness probe, run with ignoreQueryFilters: true.
    • CreateUser (:209-229), which fixes ADC's default role as UserRole.Attendee.Value (BR-45) and, when a Terms of Service version is configured (Legal:CurrentTermsVersion, read through the base's CurrentTermsVersion), stamps the new account with it: once User.Create succeeds (unwrapped with TryGetValue, which also returns a failed create untouched, :220-223) it calls user.AcceptTerms(termsVersion, (timeProvider ?? TimeProvider.System).GetUtcNow().UtcDateTime) (:225-228; User.AcceptTerms is at MMCA.ADC.Identity.Domain/Users/User.cs:418) and surfaces any failure as Result.Failure<User>. By the time this hook runs the base has already refused a request that did not tick the acceptance box. With no version configured the user is returned unstamped. The external-login path creates accounts outside this method, so those users stay unstamped and are asked by the UI acceptance gate on first sign-in; the later read and accept calls are served by LegalAcceptanceService.
    • CreateAccessToken (:232-233), which passes the private AdditionalClaims list (:562-572) to the token service: a speaker_id claim when LinkedSpeakerId has a value (BR-209, :565-566) and email_verified=false when the address is not confirmed, which the UI's reminder reads (:568-569). With neither present the helper returns null (:571), so a confirmed account without a speaker carries no extra claims rather than an empty set.
    • OnUserRegisteredAsync (:249-255), the post-save hook, below.
    • ExternalLoginAsync (:290-300), an override of the framework base's external-login member, below.

    The class does not override FindUntrackedByEmailAsync: the untracked by-email read the login path uses is the base's own.

  • Concept introduced (2), bypassing the query filter for a uniqueness probe, and what that actually protects. [Rubric §8, Data Architecture] and [Rubric §30, Compliance / Privacy / Data Governance]. Erasure in ADC always pairs Delete with Anonymize, which rewrites the stored address to a placeholder, so an erased account's real email is re-registrable by design, which is exactly what a right-to-erasure promise requires (ADR-005). And the unique Email index is filtered on [IsDeleted] = 0, because the framework's SoftDeleteUniqueIndexConvention appends that clause, so a soft-deleted row does not block the insert at the database level either. What the ignoreQueryFilters: true bypass buys is diagnosis rather than enforcement: the pre-insert check keeps seeing past the filter so it can report a live conflict as a clean domain error, instead of letting a legacy or placeholder row surface later as a save-time surprise.

  • Concept introduced (3), the outbox-atomic registration event, and what its EmailVerified flag settles. [Rubric §6, CQRS & Event-Driven], [Rubric §8, Data Architecture], [Rubric §29, Resilience & Business Continuity]. User.Id is a database-generated identity column, so at the moment the aggregate is created the id is still 0. The outbox serializes an event's payload at capture time, so raising UserRegistered before the insert would persist UserId = 0, and the cross-service Conference consumer, which has no access to the Identity database to re-match by email, could never resolve it. The fix is visible in two places:

    • RegisterAsync (:83-90) re-implements the interface member with new and wraps the base implementation in UnitOfWork.ExecuteInTransactionAsync(token => base.RegisterAsync(request, ipAddress, userAgent, token), cancellationToken). The interface is re-listed on the class declaration specifically so this override wins for callers holding an IAuthenticationService, since the base method is not virtual.
    • OnUserRegisteredAsync (:249-255) runs after the base's first save, when the identity value exists: it calls user.AddDomainEvent(new UserRegistered(user.Id, user.Email.Value, user.FirstName, user.LastName, user.Role, EmailVerified: false)), saves a second time so the outbox row is captured, and returns the user. Local registration always passes EmailVerified: false, because the address was typed into the form and nothing proves the caller owns it: Conference logs any speaker whose email matches for an organizer to link by hand (BR-209) rather than auto-linking. Both saves sit inside the one transaction opened by RegisterAsync, so a crash before commit rolls back user and event together, and after commit the OutboxProcessor guarantees delivery.
  • Concept introduced (4), the three-way external-login resolution, with its link and existing-account gates in their own helpers. [Rubric §11, Security]. ExternalLoginAsync (:290-300) overrides the framework base's member and is a transaction wrapper around ExternalLoginCoreAsync (:303-407). Its bool emailVerified parameter (:296) is the provider's assertion, which the framework's OAuth controller reads from the external-login principal and passes in, failing closed (absent or unparseable is false); the framework does not apply the verified-email rule itself, so this override does: without the assertion a new account never starts confirmed and an existing account is never linked by an email match (doc comment, :274-280). The core resolves the caller into exactly one of three paths:

    1. Known external identity (:313-316), a tracked lookup by LoginProvider and ProviderKey. Found means log in, subject only to the existing-account gates below.
    2. Email matches an existing local account (:341-355). The raw claim is parsed through the value object first, Email.Create(email) (:332), and unwrapped with TryGetValue, failing closed with Error.Validation("Auth.ExternalEmailInvalid", ...) (:333-339) rather than reading .Value directly: Result<T>.Value is null on failure and does not throw, so an unparseable provider claim would otherwise turn the lookup into "find the users whose email IS NULL". When a match is found, the linking decision itself is delegated to TryLinkProviderToExistingAccount(existingUser, loginProvider, providerKey, emailVerified) (:348), a private static helper (:505-555) that holds three refusals, checked in order: a one-link-per-account check, Error.Conflict("Auth.ExternalProviderAlreadyLinked", ...) (:517-523), which refuses whenever existingUser.IsExternalLogin (IsExternalLogin is LoginProvider is not null), whatever the provider asserts. The aggregate stores a single (LoginProvider, ProviderKey) pair, so linking a second provider would strand the original login; and the inline comment (:511-516, L229) extends the same refusal to the same provider under a different key: the helper is reached only after the provider-plus-key lookup missed, so the key differs, and a different key is a different account at the provider, which re-keying would hand this account to. Then the provider-side takeover guard, refusing Error.Unauthorized("Auth.ExternalEmailNotVerified", ...) (:530-536) when emailVerified is false; and the pre-registration takeover guard (SEC-ADC-01), Error.Conflict("Auth.ExternalLinkRequiresLocalSignIn", ...) (:545-551) whenever existingUser.HasLocalPassword. The assertion proves only the provider side of the address, and nothing proves the local row's address was ever confirmed, so linking an account that already signs in with a password could hand whoever typed that address into the registration form the provider owner's identity, with their own password still in place. Only an account with no local credentials is claimable by an email match, and only then does existingUser.LinkExternalProvider(loginProvider, providerKey) (:553) run. Every refusal message points the caller somewhere (the already-linked text names the linked provider "under a different account" and says to sign in with that account or use Forgot password, :521; sign in with email and password or use Forgot password for the unverified case, :534), so none is a dead end. The pre-registration refusal is the exception that closes a door rather than offering a link step: its text (:549) says to sign in with email and password and that the provider's sign-in "is not available for this account".
    3. Brand new user (:356-376). Unlike the link path, account creation is not gated on the verified-email assertion: emailVerified is passed straight into User.CreateExternal(email, firstName, lastName, loginProvider, providerKey, emailVerified) (:366-367) rather than used to refuse; a failed create is unwrapped with TryGetValue and returned as a failure before anything is added (:368-371). Refusing creation would close sign-up entirely for a provider that asserts nothing (GitHub carries no email_verified claim, :358-361); instead the flag rides along on downstream decisions: ADR-116 uses it to decide whether the new account starts already confirmed (a verified assertion) or unconfirmed (:362-365), and it is carried on the UserRegistered event so Conference only auto-links a speaker profile when the address was actually proven.

    Before anything is saved, both existing-account paths (matched by provider key, or linked by email) pass CheckExistingExternalAccount(user, email, emailVerified) (:383-390, private static helper at :423-443), so an administrator lock and the privileged-account email rule bind every sign-in path; a brand-new account cannot be locked, is an attendee, and skips it. The helper runs CheckNotLocked first and returns at once on a lock or an already-confirmed account (:428-432). For an unconfirmed account it treats the provider's assertion as the proof the rule asks for, but only when emailVerified is set and the asserted address parses and equals the account's own address (:436-438); then it calls user.ConfirmEmail() (:441; MMCA.ADC.Identity.Domain/Users/User.cs:398), which the doc comment (:414-415) says announces UserEmailVerified in the same save. Otherwise CheckPrivilegedAccountConfirmed decides (:442): an account that can change conference content is refused, an attendee signs in unconfirmed. Both helpers are pure functions of the loaded aggregate and the passed flag, with no I/O. All surviving paths then converge: save (:392), then RecordNewAccountAsync (:394-399, helper at :464-493), a no-op for an existing account (:470-473). For a new account it raises UserRegistered with the emailVerified flag (:475-476), the same post-identity pattern as local registration, and, when the provider did not vouch for the address, schedules a SendEmailConfirmationCommand through IInternalCommandScheduler (:478-489) so the account is asked to confirm exactly as a local registration is; a scheduling failure is returned and rolls the sign-up back. One second save (:491) writes the outbox row and the confirmation row together, so both commit with the account or not at all (doc comment, :452-457). Finally the flow hands off to the base's IssueTokensAsync(user, cancellationToken: cancellationToken) (:406), which opens a refresh session through the shared workflow (hash at rest, per-user cap, rotation chain) rather than stamping a plaintext token on the aggregate. The OAuth callback arrives through the framework's OAuthControllerBase, which does not surface the caller's IP or user-agent, so the session records neither; both fields are informational and nothing validates against them (:401-405).

  • Why it's built this way: the base class keeps every application on one audited auth workflow, so a fix to lockout or refresh-session reuse detection lands once in MMCA.Common rather than per app; the hooks keep ADC's divergences (role, claims, event, lock check, privileged-account email rule) small and named. Session issuance (access-token minting, refresh-session rotation and the per-user session cap) sits behind the framework's IAuthSessionIssuer, which AddInfrastructure registers, so the token lifetimes and the cap are configuration (the Jwt and RefreshSessions sections) rather than constructor arguments of this service (class doc comment, :46-49). The constructor takes 8 parameters (:52-60). That count is exactly the architecture suite's constructor-dependency ceiling, MaxConstructorDependencies => 8 (MMCA.ADC/Tests/Architecture/MMCA.ADC.Architecture.Tests/Cqrs/ConstructorDependencyCountTests.cs:38), whose doc comment names this class as the high-water mark at 8 (:6). Its history comment records why the scheduler is a collaborator rather than an artificial bundle (:31-35): only this facade knows both that an external account is new and that its address is unproven, so it alone can schedule the ADR-116 confirmation email on the same unit of work as the account insert; and why no verifier collaborator remains (:36-37): the framework's ExternalLoginAsync receives the provider's email_verified answer directly. The shared base fails when the ceiling is left above the observed mark (:29-30), so the gate carries no spare headroom. The UserRegistered integration event, rather than an in-process domain event, is a deliberate divergence from MMCA.Store, because Conference runs in a separate process with its own database and can only learn about a registration asynchronously (ADR-003 outbox, ADR-006 database-per-service). The EmailVerified flag is what lets Conference tell a typed-in address from a provider-proven one without re-implementing the OAuth trust decision on its own side of the boundary. The eventual-consistency cost stays the same either way: the first token issued does not yet carry speaker_id, and the claim appears on the next refresh once Conference has published SpeakerLinkedToUser back.

  • Where it's used: registered as the IAuthenticationService implementation by the Application-layer DependencyInjection (MMCA.ADC.Identity.Application/DependencyInjection.cs:35); driven by AuthController for local credentials and OAuthController for the social paths.

  • Caveats / not-in-source: whether email_verified is actually mapped for a given provider is host configuration, not visible here. The Identity service host's comment records that AddExternalAuthProviders maps Google's and Apple's email-verification assertion onto one email_verified claim, which the framework's OAuth controller passes to ExternalLoginAsync as emailVerified (fail closed), and that GitHub's payload asserts nothing, so GitHub logins read as unverified (MMCA.ADC/Source/Services/MMCA.ADC.Identity.Service/Program.cs:152-156). How the framework controller parses the claim lives in MMCA.Common and is not visible in this class.


DependencyInjection

MMCA.ADC.Identity.Application · MMCA.ADC.Identity.Application · MMCA.ADC.Identity.Application/DependencyInjection.cs:24 · Level 12 · class (static)

  • What it is: the Application-layer registration for Identity. It explicitly binds ten services that convention scanning cannot infer, contributes the module's three data-subject export sections, then runs the framework's own assembly scanning to auto-register every handler, mapper, validator, and domain-event handler in the assembly.
  • Depends on: IServiceCollection, TryAddScoped; IAuthenticationService with AuthenticationService, AuthenticationValidators, ISoftDeletedUserValidator with the framework's generic SoftDeletedUserValidator<TUser> closed over User, IAttendeeQueryService with AttendeeQueryService, IVerifiedUserLookupService with VerifiedUserLookupService, IUserAdministrationService<UserAdminDTO> with UserAdministrationService, IViewAsSubjectResolver with ViewAsSubjectResolver, IServiceAccountProvisioner with ServiceAccountProvisioner, IEntityQueryService<TEntity, TEntityDTO, TIdentifierType> with UserListEntityQueryService, and ILegalAcceptanceService with LegalAcceptanceService; the IUserDataExportSection contributors EngagementUserDataExportSection, NotificationUserDataExportSection and ConferenceUserDataExportSection; the AddUserDataExportSection<TSection> and ScanModuleApplicationServices<TAssemblyMarker> helpers from MMCA.Common.Application; ClassReference.
  • Concept introduced (1), explicit registration for the ambiguous, convention scanning for the rest. [Rubric §2, Design Patterns] and [Rubric §15, Best Practices & Code Quality]. Handlers, mappers, and validators follow a one-interface-one-implementation convention, so the framework's scanner (AddAssignableTypes calls inside ScanModuleApplicationServices, MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.ModuleScanning.cs:47) can find them: services.ScanModuleApplicationServices<ClassReference>() means adding a new use-case slice, GetUserAvatarHandler for instance, needs no DI edit at all. The services that are not convention-discoverable, because their interfaces live in other assemblies, have more than one plausible implementation, or (for IUserAdministrationService<UserAdminDTO>) are neither a handler, a mapper, nor a validator so the scan would never find them, are registered by hand. TryAddScoped rather than AddScoped is the load-bearing detail: a host that has already registered an override keeps it, and the module does not clobber it. (The gRPC swaps for IAttendeeQueryService and IVerifiedUserLookupService go further and use Replace, precisely because they must win over whatever is already there: MMCA.ADC/Source/Services/MMCA.ADC.Identity.Contracts/DependencyInjection.cs:46 and :73.)
  • Concept introduced (2), closing a framework generic over the app's own entity. [Rubric §1, SOLID] and [Rubric §11, Security]. ISoftDeletedUserValidator is a framework contract used by the shared SoftDeletedUserMiddleware to reject an access token that outlived its account (ADR-047). Identity satisfies it not with a hand-written class but by closing the framework's generic SoftDeletedUserValidator<TUser> over its own User type. The revocation check therefore has exactly one implementation across the whole workspace, and each app contributes only its entity type.
  • Concept introduced (3), the export section as an additive, ordered contribution. [Rubric §30, Compliance / Privacy / Data Governance] and [Rubric §7, Microservices Readiness]. The data-subject export (PRIVACY.md section 12, per the registration comment) has to include data Identity does not own, so the framework models each contributor as an IUserDataExportSection and the export handler fans out over the whole IEnumerable<>. Here Identity registers the three peer sections in order (:66-68), EngagementUserDataExportSection, NotificationUserDataExportSection, then ConferenceUserDataExportSection (the feedback answers the user authored, per the registration comment at :62-65), which records two consequences: registration order is the section order in the exported document, and the export handler itself needs no registration because the scan below picks it up as an ordinary IQueryHandler. On the framework side, AddUserDataExportSection<TSection> registers the concrete type with TryAddScoped and appends the interface mapping with TryAddEnumerable, so the same section registered twice is added once; the scoped lifetime is deliberate so a section may take repositories or gRPC clients.
  • Walkthrough: AddModuleIdentityApplication() (:33), which takes no parameters, lives inside an extension(IServiceCollection services) block (:26) of the static class (:24). Body order (:35-74): IAuthenticationService to AuthenticationService (:35), the AuthenticationValidators parameter object (:36), ISoftDeletedUserValidator to SoftDeletedUserValidator<User> (:37), IAttendeeQueryService to AttendeeQueryService (:38), IVerifiedUserLookupService to VerifiedUserLookupService (:39), IUserAdministrationService<UserAdminDTO> to UserAdministrationService (:43), the framework's opt-in Admin/Users endpoint backing (ADR-116); IViewAsSubjectResolver to ViewAsSubjectResolver (:47), the account reader read-only view-as mints its token from (ADR-137), which the framework calls only when ViewAs:Enabled is set on the Identity service; IServiceAccountProvisioner to ServiceAccountProvisioner (:51), the service accounts machine clients sign as (ADR-140), whose registration the Identity service's settings validator requires when MachineClients:Enabled is set (comment, :49-50); IEntityQueryService<User, UserListDTO, UserIdentifierType> to UserListEntityQueryService (:56), which serves GET Users/paged (BR-51) and, being a dedicated subclass, is neither a handler nor a mapper the scan would find; and ILegalAcceptanceService to LegalAcceptanceService (:60), which backs the framework's Users/me/legal-acceptance endpoints (Terms of Service acceptance) and, like the administration service, is neither a handler, a mapper nor a validator so the scan would not find it; then the three export sections (:66-68), the convention scan (:72), and return services (:74). The module registers no INavigationPopulator<User>: User has no cross-source navigation to batch-load, so the roster's query service resolves the framework's open-generic default, NullNavigationPopulator<TEntity>, which MMCA.Common.Application registers for every entity (MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.cs:58). AuthenticationService takes its IOptions<EmailConfirmationSettings> directly, and DI resolves it with no module-side registration, since IOptions<T> is satisfied by the options infrastructure itself.
  • Why it's built this way: mixing explicit and convention registration keeps the common case zero-ceremony while retaining precise control over the handful of services that need a specific lifetime or an override point. Registering the cross-boundary implementations (ISoftDeletedUserValidator, IAttendeeQueryService, IVerifiedUserLookupService) here is what closes the inversion those contracts set up: the framework, the Notification module and the Engagement module declare the need, Identity satisfies it. The view-as and machine-client registrations are unconditional, while the features they back stay off until their configuration switch turns them on, so enabling either is a settings change rather than a DI edit.
  • Where it's used: called by the API-layer DependencyInjection's AddIdentityModule, as a parameterless services.AddModuleIdentityApplication() (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/DependencyInjection.cs:23), which IdentityModule calls in turn (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/IdentityModule.cs:18-19).

RemoveUserAvatarHandler

MMCA.ADC.Identity.Application · MMCA.ADC.Identity.Application.Users.UseCases.RemoveUserAvatar · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/RemoveUserAvatar/RemoveUserAvatarHandler.cs:18 · Level 13 · class (sealed, partial)

  • What it is: the command handler that removes the signed-in user's avatar (BR-116a). It clears the stored URL on the User aggregate first (the user-visible state), then schedules the blob's deletion on the durable internal-command queue (ADR-114). It is idempotent: when no avatar is set it succeeds without writing, without logging and without touching storage.
  • Depends on: MutateEntityHandlerBase<TCommand, TEntity, TIdentifierType> (base class, which supplies ICommandHandler<RemoveUserAvatarCommand, Result>); MutationContext; IUnitOfWork; IInternalCommandScheduler (the framework's durable internal-command queue); DeleteAvatarBlobInternalCommand (the scheduled command this handler enqueues, handled by DeleteAvatarBlobInternalCommandHandler); SetUserAvatarHandler (it calls that class's internal static TryGetBlobName, imported at RemoveUserAvatarHandler.cs:3, which is why it sits one level higher than its sibling); User; Result; Microsoft.Extensions.Logging with [LoggerMessage] source generation.
  • Concept reinforced, the idempotent delete expressed as a workflow short-circuit. The mutation base offers context.SkipSave() for exactly this case: the command is already satisfied, so nothing is written, and the base skips the save, the LogMutated call and the post-commit hook while still answering success (MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Crud/MutationContext.cs:44-49 and the check at MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Crud/MutateEntityHandlerBase.cs:316-319). [Rubric §9, API and Contract Design]: the operation is safe to repeat, and the no-op path is an explicit success rather than an error (see RemoveUserAvatarCommand). [Rubric §12, Performance and Scalability]: the already-satisfied path costs one read and nothing else, no transaction and no storage round trip. [Rubric §13, Observability and Operability]: the removal is recorded through a source-generated [LoggerMessage] method (:84-85), so the class is partial, and the skip path deliberately logs nothing, so a repeated delete does not inflate the "avatar removed" signal.
  • Concept introduced, the blob delete is a durable internal command, not a best-effort inline call. Rather than calling IFileStorageService.DeleteAsync after the commit, this handler schedules a DeleteAvatarBlobInternalCommand through IInternalCommandScheduler instead (:74-76). [Rubric §6, CQRS & Event-Driven] and [Rubric §13, Observability and Operability]: ADR-114's internal-command table gives the delete retry semantics a bare try/await cannot, a transient storage outage defers the cleanup instead of losing it silently. The scheduling call can still fail (the row itself might not persist), and that failure is not escalated to the caller: it is logged at Warning through LogAvatarBlobScheduleFailed (:78-81, message declared at :87-88), whose text states the consequence in the log itself: the blob "is orphaned in storage and must be removed by hand."
  • Walkthrough
    • Primary-constructor injection of IUnitOfWork, an IInternalCommandScheduler and an ILogger<RemoveUserAvatarHandler> (RemoveUserAvatarHandler.cs:18-21), with the unit of work forwarded to MutateEntityHandlerBase<RemoveUserAvatarCommand, User, UserIdentifierType> (:22). Note the base without a payload type parameter: this command answers with a bare Result. One constant, private const string BlobNameKey = "Avatar.BlobName" (:25), the context key the orphaned blob's name travels under.
    • EntityId (:28) returns command.UserId, so the base loads that aggregate and answers Error.NotFound itself when the account does not exist.
    • The mutation (:31-50): it derives the blob name with SetUserAvatarHandler.TryGetBlobName(entity.AvatarUrl) (:37). When that is null (no avatar stored, or a URL with no usable final segment) it calls context.SkipSave() and returns Result.Success() (:42-43), with the comment at :40-41 naming the intent: "an already-satisfied command, not a refused one. No save, no log, no storage call." Otherwise it stashes the name under BlobNameKey (:46) and calls entity.SetAvatarUrl(null) (:47, domain setter at MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Domain/Users/User.cs:554).
    • LogMutated (:53-54) fires the source-generated LogAvatarRemoved at Information level with the message "User {UserId} avatar removed" (:84-85).
    • OnMutatedAsync (:62-82), post-commit: reads context.GetOrDefault<string>(BlobNameKey) (:68) and returns immediately when absent (:69-72). Otherwise it schedules new DeleteAvatarBlobInternalCommand(blobName) through internalCommandScheduler.ScheduleAsync (:74-76), and logs LogAvatarBlobScheduleFailed when scheduling itself fails (:78-81). The doc above the method (:56-60) states the ordering rationale: the row is already committed without the URL, and the blob delete becomes an internal-command row the framework retries, so a storage outage defers it instead of leaving an orphan nothing knows about.
  • Why it's built this way: clearing the URL before scheduling the blob delete makes the persisted "no avatar" state authoritative, so a later storage failure leaves an orphaned file rather than a dangling reference to a blob that no longer exists. That ordering is the same ADR-096 discipline as SetUserAvatarHandler, and reusing that handler's TryGetBlobName keeps the URL-to-blob-name parsing in exactly one place, so the two operations can never disagree about which blob a stored URL names. Routing the delete itself through the internal-command queue (ADR-114) rather than an inline await fileStorage.DeleteAsync trades an immediate best-effort attempt for a durable, retried one.
  • Where it's used: dispatched by UsersController.RemoveAvatarAsync (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/Controllers/UsersController.cs:199-201, injected as ICommandHandler<RemoveUserAvatarCommand, Result> at :109), whose 204 No Content response (:192) tells the client the avatar is gone (or was already absent). Unit-tested by MMCA.ADC/Tests/Modules/Identity/MMCA.ADC.Identity.Application.Tests/Users/UseCases/RemoveUserAvatar/RemoveUserAvatarHandlerTests.cs.
  • Caveats / not-in-source: the internal-command row's own retry and eventual-failure handling live in the internal-command processing pipeline, not in this handler; whether a command that keeps failing is ever surfaced anywhere beyond the Warning log is Not determinable from source within this unit.

InviteEmailSettings

MMCA.ADC.Identity.Application · MMCA.ADC.Identity.Application.Users.UseCases.SendSignInLink · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/SendSignInLink/InviteEmailSettings.cs:8 · Level 0 · class (sealed)

  • What it is: the options class behind the app-store links the ticket-holder invitation email lists (BR-271, InviteEmailSettings.cs:3-7). Two members, AppStoreUrl (:14) and GooglePlayUrl (:17), both Uri? with init setters, bound from the configuration section named by SectionName = "Invites" (:11).
  • Depends on: nothing first-party; BCL Uri only.
  • Concept reinforced, the optional options class. ADR-070 makes a misconfigured section stop the host at startup, and [Rubric §13, Observability & Operability] assesses whether configuration faults surface early. This class is the deliberate exception, and the registration says why (MMCA.ADC/Source/Services/MMCA.ADC.Identity.Service/Program.cs:185-188): it binds without ValidateOnStart, because an unset link is simply left out of the email, which is a working value rather than a misconfiguration.
  • Walkthrough: SectionName (:11) is the one constant the binding reads. The two Uri? properties (:14, :17) are the iPhone/iPad and Android listings. There is no web-app property: the summary (:5-6) explains that the web link is the origin of Authentication:SignInLinks:SignInUrl, which is already set per environment, and SendSignInLinkInternalCommandHandler derives it from there.
  • Where it's used: bound in the Identity service host (Program.cs:187-188); injected as IOptions<InviteEmailSettings> into SendSignInLinkInternalCommandHandler (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/SendSignInLink/SendSignInLinkInternalCommandHandler.cs:46), which passes it to InviteEmail.HtmlBody (InviteEmail.cs:33), where AppLinks reads both URLs (InviteEmail.cs:60-67).
  • Caveats / not-in-source: whether the Invites section is populated in any environment's configuration is Not determinable from source within this unit (no appsettings file was read).

ServiceAccounts

MMCA.ADC.Identity.Domain · MMCA.ADC.Identity.Domain.Users · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Domain/Users/ServiceAccounts.cs:13 · Level 0 · class (static)

  • What it is: the reserved address space of the service accounts that machine clients sign in as (ADR-140, ServiceAccounts.cs:3-8). A service account is an ordinary User row, so it needs a unique email like any other; this class generates one under a single reserved domain, EmailDomain = "clients.adc.invalid" (:16).
  • Depends on: nothing first-party; BCL Guid and string only.
  • Concept reinforced, the reserved-domain marker. SyntheticAccounts introduced the pattern for load-test accounts; this is its second use. [Rubric §11, Security] cares that a machine identity can never be confused with a person: the domain sits under .invalid (RFC 2606, :9-11), which can never be deliverable, so the confirmation and sign-in-link emails a person's account receives can never reach a service account. Unlike the load-test accounts, the address is not the marker code reads: the summary (:3-8) says the address is how a person reading the Users roster tells a service account apart, while code tells one apart by the aggregate's IsServiceAccount flag (User.cs:150), never by the address.
  • Walkthrough
    • EmailDomain (:16) and LastName = "Service account" (:19), the last name every service account carries so the Users roster reads "{client name} Service account".
    • The private EmailSuffix (:21), "@" + EmailDomain, which NewEmail appends.
    • NewEmail() (:25) returns svc-{guid:N}@clients.adc.invalid, a fresh GUID per call, so the unique-email invariant (BR-200) holds across any number of clients.
  • Where it's used: User.CreateServiceAccount generates the address with NewEmail() and sets the last name from LastName (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Domain/Users/User.cs:365, :376); that factory is called by ServiceAccountProvisioner (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/Administration/ServiceAccountProvisioner.cs:30). Unit-tested by ServiceAccountsTests and UserServiceAccountTests under MMCA.ADC/Tests/Modules/Identity/MMCA.ADC.Identity.Domain.Tests/Users/.
  • Caveats / not-in-source: the class only generates addresses; it has no predicate that classifies an existing address as a service account's. The reserved domain is therefore something a person sees on the roster, not a rule any code checks: service accounts are recognised at run time through User.IsServiceAccount alone (:7).

SyntheticAccounts

MMCA.ADC.Identity.Domain · MMCA.ADC.Identity.Domain.Users · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Domain/Users/SyntheticAccounts.cs:20 · Level 0 · class (static)

  • What it is: the rule that recognises the accounts the conference-day load test registers in production (SyntheticAccounts.cs:3-19). They are ordinary Attendee accounts to every request path, but they live under one reserved email domain, EmailDomain = "loadtest.adc.invalid" (:23), and two side effects that would leak outside the test skip them.
  • Depends on: nothing first-party; BCL string and StringComparison only.
  • Concept introduced, a reserved-domain marker instead of a flag column. [Rubric §13, Observability & Operability] assesses whether synthetic traffic can be told apart from real use without polluting it: the test accounts need no extra column or role, because the address itself is the marker, so the real login and bookmark paths are measured unchanged. The domain sits under .invalid (RFC 2606), which can never be deliverable, so no real attendee can be swept up by the rule (:14-17).
  • Walkthrough: IsSynthetic(string? email) (:30-31) is an expression-bodied predicate: true when the address is non-null and, after Trim(), ends with the private EmailSuffix ("@" + EmailDomain, :25) under StringComparison.OrdinalIgnoreCase. Case and surrounding whitespace never defeat it.
  • Why it is built this way: a pure static predicate in the Domain project keeps the rule in one place for both call sites below. The remarks note the k6 script spells the same domain, so the two must change together (:16-17); nothing in C# enforces that.
  • Where it's used: two skips. AuthController returns 201 Created straight after registration for a synthetic address, so no confirmation email is scheduled and the SMTP relay's daily quota and reputation are not spent (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/Controllers/AuthController.cs:83-86). AttendeeQueryService filters synthetic addresses out of the attendee id list, so an organizer broadcast never targets them (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/AttendeeQueryService.cs:44), and out of the attendee count (:77). Unit-tested by SyntheticAccountsTests under MMCA.ADC/Tests/Modules/Identity/MMCA.ADC.Identity.Domain.Tests/Users/.
  • Caveats / not-in-source: the k6 script (Tests/Load/k6/conference-day-attendee-load.js) is named in the doc comment but not read here, so whether its copy of the domain still matches is Not determinable from source within this unit.

UserRole

MMCA.ADC.Identity.Domain · MMCA.ADC.Identity.Domain.Users · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Domain/Users/UserRole.cs:18 · Level 4 · class (sealed)

  • What it is: the closed set of ADC roles as a value object: Organizer, Attendee, and ContentEditor, with case-insensitive parsing, validation, and equality.
  • Depends on: RoleValue (the shared base), RoleNames (the string constants), Result and Error; externals: System.Collections.Frozen.FrozenDictionary.
  • Concept introduced, the closed-set value object over a persisted string. [Rubric §4, DDD] assesses whether a concept with rules gets a type instead of a bare primitive, and [Rubric §2, Design Patterns] covers the shared-base factoring. The base RoleValue supplies case-insensitive value equality, hashing, and validation once for both apps; this type only fixes the ADC role set, and the class remarks say so (UserRole.cs:12-17). Note what it is not: an enum. The User aggregate stores Role as a string (User.cs:77) so EF maps a plain column and a JWT claim round-trips without conversion, while every place that reasons about roles goes through this type. That combination, primitive at rest and typed in the domain, is the pattern ADR-068 describes.
  • Walkthrough
    • The three static instances (UserRole.cs:21, :23, :30), each built from a RoleNames constant so the domain and the auth layer cannot drift apart. The ContentEditor doc (UserRole.cs:26-30) is worth reading: it defines the role as a strict capability subset of Organizer, able to curate sessions, speakers, and categories but not to change event structure, rooms, feedback questions, run session selection, or read the user list.
    • AllByValue (UserRole.cs:33-34), a FrozenDictionary<string, UserRole> built once by the base's BuildLookup (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/RoleValue.cs:76). Frozen dictionaries trade a slower build for faster reads, which is exactly right for a table populated at type-init and then read on every authorization check ([Rubric §12, Performance & Scalability]).
    • All (UserRole.cs:45) exposes the values; the private constructor (UserRole.cs:36-39) makes the three statics the only instances that can exist.
    • FromString(string role) (UserRole.cs:52-59) is the Result-returning parse: a hit returns Result.Success, a miss returns Error.Invariant with the code User.Role.Invalid. role ?? string.Empty (UserRole.cs:53) means a null argument is a clean validation failure, not a NullReferenceException.
    • IsValid(string role) (UserRole.cs:66) is the boolean form used by UserInvariants.EnsureRoleIsValid, with the same null-to-empty coalesce.
    • IsOrganizer(string? role) (UserRole.cs:76) compares with StringComparison.OrdinalIgnoreCase, and its doc explains the trap it exists to avoid (UserRole.cs:68-75): a raw claim string may carry any casing, and comparing against Organizer.Value directly would compare ordinally, quietly failing on "organizer". This is an authorization-relevant helper, so the subtlety is load-bearing ([Rubric §11, Security]).
    • The equality surface: the two operators (UserRole.cs:78-81) and the three overrides that forward to the base (UserRole.cs:84, :86, :89), plus ToString() returning the canonical string form (UserRole.cs:94).
  • Why it's built this way: a FromString returning Result<UserRole> instead of throwing keeps role parsing on the same error channel as every other validation in the codebase (ADR-013), and keeping the role set in the Domain assembly means the invariant "a user's role is one of these three" is enforced where the aggregate lives, not at the API edge.
  • Where it's used: by UserInvariants.EnsureRoleIsValid (UserInvariants.cs:68); by User's EF constructor default and by CreateExternal, both writing UserRole.Attendee.Value (User.cs:187, :218); by AuthenticationService for the BR-45 attendee default on registration (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/AuthenticationService.cs:217); by the seeder (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Infrastructure/Persistence/DbContexts/Seeding/IdentityModuleDbSeeder.cs:35-37); and by the two ownership-checked handlers whose privilege override is a one-liner, DeleteUserHandler (.../UseCases/DeleteUser/DeleteUserHandler.cs:42-43) and ExportUserDataHandler (.../UseCases/ExportUserData/ExportUserDataHandler.cs:38).
  • Caveats / not-in-source: there is no implicit string conversion on this type, so callers that need the persisted form write .Value explicitly (User.cs:187, AttendeeQueryService.cs:96). The role set here is three values, while the class remarks still describe the spec as defining two (UserRole.cs:12-14); the code is ground truth.

SendSignInLinkInternalCommand

MMCA.ADC.Identity.Application · MMCA.ADC.Identity.Application.Users.UseCases.SendSignInLink · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/SendSignInLink/SendSignInLinkInternalCommand.cs:34 · Level 4 · record (sealed)

  • What it is: the durable request to email one ticket holder a sign-in link that creates their account on first tap (BR-271, ADR-114, SendSignInLinkInternalCommand.cs:5-9), registered under the wire name Identity.SendSignInLink.v1 (:33).
  • Depends on: IInternalCommand, InternalCommandNameAttribute, SignInLinkPurpose; externals: BCL Guid and DateOnly.
  • Concept reinforced, the internal command as a durable row. [Rubric §13, Observability & Operability]: the remarks (:11-16) give the reason it is a row rather than an inline send, the same reason Identity.SendEmailConfirmation.v1 is one: a mail outage or a crash defers the invitation instead of losing it. Execution is at-least-once, so the handler is idempotent on InviteId, which the scheduler derives from the integration event's message id: a redelivered event schedules a row with the same id, and the second execution finds the invitation already sent.
  • Walkthrough: seven positional members (:34-41). InviteId is the idempotency key. Email, FirstName and LastName are the invitee and the name the account is created with. Purpose selects the link lifetime. EventName and EventStart feed the subject line and the body. Every member is a JSON primitive or an enum because the durable queue round-trips the payload through System.Text.Json (:17-22); Purpose is always SignInLinkPurpose.Invite today and is on the wire so a later sender of another purpose needs no v2 of the contract.
  • Where it's used: scheduled by TicketHolderInvitedHandler when Engagement publishes TicketHolderInvited, and by SendSignInLinkHandler when it re-issues an invitation (SendSignInLinkHandler.cs:69-90); checked by SendSignInLinkInternalCommandValidator; executed by SendSignInLinkInternalCommandHandler; rendered by InviteEmail.
  • Caveats / not-in-source: the re-issue path builds the command with Guid.NewGuid() (SendSignInLinkHandler.cs:74), not a message id, so each re-issue is a distinct invitation; repeats there are bounded by the token service's per-address throttle (SendSignInLinkHandler.cs:26-33), not by the sent marker.

SendSignInLinkCommand

MMCA.ADC.Identity.Application · MMCA.ADC.Identity.Application.Users.UseCases.SendSignInLink · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/SendSignInLink/SendSignInLinkCommand.cs:20 · Level 4 · record (sealed)

  • What it is: the command carrying the address an "Email me a sign-in link" request was made for (UC-54, BR-275, SendSignInLinkCommand.cs:7-11). Anonymous by design, and answered with success whether or not the address holds an account. It is also an internal command named Identity.RequestSignInLink.v1 (:19), so the same type is both the inline request and the durable row it becomes.
  • Depends on: ICommandWithRequest<out TRequest>, SendSignInLinkRequest, IInternalCommand, InternalCommandNameAttribute.
  • Concept reinforced, the command that wraps a framework request. [Rubric §2, Design Patterns]: the wire shape (SendSignInLinkRequest) is the framework's, shared with every consumer, while the command type is ADC's own, so the pipeline dispatches to ADC's handler without ADC redefining the request. The framework base requires both capabilities of TCommand, ICommandWithRequest<SendSignInLinkRequest> and IInternalCommand (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/SignInLinks/SendSignInLinkHandlerBase.cs:70), so dropping the second marker no longer compiles.
  • Walkthrough: one positional member, Request (:20-21), exposed through ICommandWithRequest<SendSignInLinkRequest>, plus the IInternalCommand marker (:21) and the [InternalCommandName("Identity.RequestSignInLink.v1")] attribute (:19) that gives the queued row a stable, versioned name.
  • Why it's built this way: the remarks (:12-17, ADR-114) state the two-phase shape. The endpoint dispatches the command inline, and the handler only schedules it; the account lookup, token issue and send run later, when the internal-command processor executes the row (the base branches on InternalCommandExecution.IsActive, SendSignInLinkHandlerBase.cs:89-91). The anonymous request therefore does the same work for every address, writing one queue row, and the anti-enumeration answer (:9-10) is the same whatever the row later finds. The name is deliberately distinct from Identity.SendSignInLink.v1, which is the ticket invitation (SendSignInLinkInternalCommand, :15-16). The command itself stays a bare carrier, so the same type serves an address with an account, one with a pending invitation, and one with neither.
  • Where it's used: dispatched by SignInLinkController, which builds it in CreateSendCommand (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/Controllers/SignInLinkController.cs:37); handled by SendSignInLinkHandler, which names it as the base class's TCommand (SendSignInLinkHandler.cs:52).

InviteEmail

MMCA.ADC.Identity.Application · MMCA.ADC.Identity.Application.Users.UseCases.SendSignInLink · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/SendSignInLink/InviteEmail.cs:15 · Level 5 · class (static, internal)

  • What it is: the ticket-holder invitation email (BR-271): the subject "Your {Event} account is ready", one button, and a list of where the app runs (InviteEmail.cs:6-14).
  • Depends on: SendSignInLinkInternalCommand, InviteEmailSettings; externals: System.Net.WebUtility, System.Globalization.CultureInfo.
  • Concept introduced, roster data is untrusted markup. [Rubric §11, Security]: the name and event name were typed into a third-party ticketing system, so every roster value that reaches the HTML is encoded with WebUtility.HtmlEncode (:40-41), and so are the link (:43) and each store URL (:74). The remarks (:10-13) also explain why the email is English only: the recipient may have no account yet, so there is no stored culture preference to render it in.
  • Walkthrough
    • Subject(string eventName) (:20) returns Your {eventName} account is ready.
    • HtmlBody(...) (:29-58) guards its three reference arguments (:36-38), encodes the roster values, formats the event date as dddd, MMMM d, yyyy under CultureInfo.InvariantCulture (:42), and concatenates the paragraphs: the greeting, the "Open my account" button with inline styles (:50-51), a note that the same account works on every device, the app list, the single-use and expiry sentence that points at "Email me a sign-in link" for a new one (:55-56), and an ignore-if-not-you line (:57).
    • AppLinks (:60-67) lists up to three items (iPhone and iPad, Android, Web) and returns an empty string when none is set, so no empty <ul> is emitted.
    • AddItem (:69-75) skips a null URL, which is how an unset InviteEmailSettings link is left out.
    • Describe(TimeSpan) (:77-87) renders the lifetime as whole days when it is at least one day, otherwise as minutes with a floor of one, with singular forms for 1.
  • Why it's built this way: pure static functions over their inputs, so the email is testable without a mail sender, and the expiry sentence is computed from the same lifetime the handler gives the sent marker (SendSignInLinkInternalCommandHandler.cs:104, :110), so the email states the window the link was issued for.
  • Where it's used: only by SendSignInLinkInternalCommandHandler (SendSignInLinkInternalCommandHandler.cs:109-110).
  • Caveats / not-in-source: Describe truncates, so a 36-hour lifetime reads "1 day". Subject does not encode the event name, which is correct for a plain-text header but means the subject is the one place a roster value appears unencoded.

SendSignInLinkInternalCommandHandler

MMCA.ADC.Identity.Application · MMCA.ADC.Identity.Application.Users.UseCases.SendSignInLink · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/SendSignInLink/SendSignInLinkInternalCommandHandler.cs:41 · Level 6 · class (sealed, partial)

  • What it is: the executor of Identity.SendSignInLink.v1: it issues an invitation token carrying the attendee's name, composes the link, and emails it (SendSignInLinkInternalCommandHandler.cs:12-16).
  • Depends on: ICommandHandler<in TCommand, TResult>, SendSignInLinkInternalCommand, ISignInLinkTokenService, SignInLinkSettings, SignInLinkProfile, IEmailSender, ICacheService, InviteEmailSettings, InviteEmail, Email, Result; externals: ILogger, IOptions.
  • Concept introduced, send then mark. [Rubric §13, Observability & Operability]: an at-least-once handler whose side effect cannot join a transaction must choose which failure it prefers. The remarks (:18-26) choose a duplicate over a loss: a marker keyed by InviteId is written to the shared cache only after the email is handed to the relay, so a crash between the two re-sends rather than loses the invitation, and the second email's link replaces the first one's, which still leaves the attendee one working link. A second execution that finds the marker completes without sending, because issuing again would replace the token the first email carries.
  • Walkthrough
    • SentMarkerValue (:50) and SentMarkerKey (:121-122, signinlink:invite-sent:{inviteId:N}).
    • WebAppUrl (:56-59) reduces the configured sign-in page URL to its origin with GetLeftPart(UriPartial.Authority), which is why InviteEmailSettings needs no web link.
    • HandleAsync (:62) completes with Result.Success() and a log line for every outcome a retry cannot fix: sign-in links disabled or no SignInUrl (:67-71), an address the Email value object refuses (:73-77), a marker already present (:79-87), and a refused token issue, which is the per-address throttle (:89-100). Otherwise it composes the link and looks up the purpose's lifetime (:103-104), sends the HTML email (:106-113), writes the marker for that same lifetime (:115), and logs the send (:117). A mail relay exception is not caught, so the framework retries the row with backoff (:27-33).
    • Three source-generated log methods (:124-132). None takes the address, and InvitationThrottled logs at Warning because a throttled invitation is dropped for good (:130); the address-free lines are what [Rubric §30, Compliance, Privacy & Data Governance] looks for.
  • Where it's used: runs for rows scheduled by TicketHolderInvitedHandler and by SendSignInLinkHandler's re-issue path; covered by SendSignInLinkInternalCommandHandlerTests under MMCA.ADC/Tests/Modules/Identity/MMCA.ADC.Identity.Application.Tests/Users/UseCases/SendSignInLink/.
  • Caveats / not-in-source: the marker expires with the link (:115), so a redelivery that arrives after the link lifetime would send again; whether the internal-command processor can redeliver that late is Not determinable from source within this unit.

UserInvariants

MMCA.ADC.Identity.Domain · MMCA.ADC.Identity.Domain.Users · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Domain/Users/UserInvariants.cs:9 · Level 6 · class (static)

  • What it is: the rule book for the User aggregate: the field length constants plus one Ensure... method per invariant, each returning a Result.
  • Depends on: CommonInvariants (the shared primitive checks), Result / Error, UserRole; externals: BCL only.
  • Concept reinforced, the static invariants class. [Rubric §4, DDD] assesses whether invariants live with the aggregate that owns them, and [Rubric §1, SOLID] covers the single-responsibility split. The framework convention, introduced in group-02, is that an aggregate's factory does not contain its rules: the rules live in a static sibling class as independent, individually testable functions, and the factory composes them with Result.Combine so the caller gets every violation at once instead of the first one. User.Create is the worked example, combining the email parse with six checks from this class in a single call (User.cs:233-241).
  • Walkthrough
    • Four public constants (UserInvariants.cs:12-21): FirstNameMaxLength and LastNameMaxLength at 100, EmailMaxLength at 100, and TermsVersionMaxLength at 32 (:21). They are public const for a reason: SendSignInLinkInternalCommandValidator reuses them (SendSignInLinkInternalCommandValidator.cs:22, :31, :35), and the EF configuration sizes its columns from them (UserConfiguration at MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Infrastructure/Persistence/EntityConfiguration/UserConfiguration.cs:23, :29, :33, and the accepted terms version column at :87), so the domain rule, that validator, and the schema cannot disagree. Registration is validated by the framework's RegisterRequestValidator, which does not reference this class: it declares its own EmailMaxLength and NameMaxLength, both 100 (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Validation/RegisterRequestValidator.cs:23, :26), equal to these values by number only.
    • EnsureTermsVersionIsValid (UserInvariants.cs:30-33) validates the Terms of Service version being recorded as accepted: it Result.Combines a non-empty check (User.TermsVersion.Empty) with a max-length check against TermsVersionMaxLength (User.TermsVersion.TooLong), so the value fits its column. User.AcceptTerms is its only caller (User.cs:420).
    • EnsureEmailFitsColumn (UserInvariants.cs:45-46) is a single length check, User.Email.TooLong, measured on the trimmed address. Its doc (:35-44) states the division of labour: presence and format are the Email value object's job, but that object allows 256 characters, so every factory that takes a caller-supplied address pairs it with this narrower check. The case it exists for is an OAuth provider's email, which reaches the domain with no request validator in front of it. The trim matches what Email.Create stores.
    • EnsureFirstNameIsValid / EnsureLastNameIsValid (UserInvariants.cs:48-56) each Result.Combine a non-empty check with a max-length check, so both problems surface together.
    • EnsurePasswordHashIsValid / EnsurePasswordSaltIsValid (UserInvariants.cs:58-62) delegate to CommonInvariants.EnsureBytesAreNotEmpty. They assert presence only: strength is a request-level concern (ChangePasswordRequestValidator) and the hash itself is opaque to the domain.
    • EnsureRoleIsValid (UserInvariants.cs:67-74) defers to UserRole.IsValid and returns User.Role.Invalid on a miss.
    • EnsurePreferredCultureIsValid and EnsurePreferredThemeIsValid (UserInvariants.cs:79-96) forward to the shared CommonInvariants equivalents, passing ADC's own error codes and messages. The allowlist of SupportedCultures (ADR-027) and the light/dark theme set (ADR-028) live in the framework; only the wording is app-specific.
  • Why it's built this way: every method takes a source string that becomes the error's source field, so a failure reports which operation raised it (nameof(Create), nameof(CreateFromInvitation), nameof(ChangePassword), nameof(UpdatePreferences)). That is why the same invariant can be shared by the create and change paths without losing diagnostic context ([Rubric §13, Observability & Operability]).
  • Where it's used: by User.Create (User.cs:235-240), User.CreateExternal (User.cs:286-288), User.CreateFromInvitation (User.cs:329-331), User.CreateServiceAccount (User.cs:368-369), User.UpdatePreferences (User.cs:535-536), User.ChangePassword (User.cs:566-567), User.RehashPassword (User.cs:591-592), User.ChangeRole (User.cs:646), and User.AcceptTerms (User.cs:420); the length constants are reused by SendSignInLinkInternalCommandValidator and UserConfiguration.
  • Caveats / not-in-source: CreateServiceAccount does not call EnsureEmailFitsColumn (User.cs:366-370); its address is generated by ServiceAccounts.NewEmail and is well under the limit, so the omission is safe by construction rather than by check.

SendSignInLinkInternalCommandValidator

MMCA.ADC.Identity.Application · MMCA.ADC.Identity.Application.Users.UseCases.SendSignInLink · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/SendSignInLink/SendSignInLinkInternalCommandValidator.cs:13 · Level 7 · class (sealed)

  • What it is: the FluentValidation rules that reject an invitation row which could never produce a usable link, before it is executed (SendSignInLinkInternalCommandValidator.cs:7-12).
  • Depends on: SendSignInLinkInternalCommand, UserInvariants, SignInLinkPurpose; externals: FluentValidation AbstractValidator<T>.
  • Concept reinforced, validating a published payload. [Rubric §4, DDD]: this payload is composed from a published event rather than typed by a caller, so the validator guards a publishing bug rather than user input. The doc names the failure it prevents: a name the User aggregate would refuse would otherwise mint a link whose redemption fails after the token is spent. Reusing the UserInvariants length constants is what keeps this check and the aggregate's in step.
  • Walkthrough: InviteId not empty (:17-18); Email not empty, at most UserInvariants.EmailMaxLength, and a valid address (:20-23); Purpose equal to SignInLinkPurpose.Invite (:25-27), because only invitations are scheduled and a link the account owner asks for is sent inline; FirstName and LastName not empty and within their maxima (:29-35); EventName not empty (:37-38).
  • Where it's used: covered by SendSignInLinkInternalCommandValidatorTests under MMCA.ADC/Tests/Modules/Identity/MMCA.ADC.Identity.Application.Tests/Users/UseCases/SendSignInLink/.
  • Caveats / not-in-source: EventStart carries no rule, so a default DateOnly passes and would render as a year-1 date in InviteEmail. The Email length rule measures the raw string while UserInvariants.EnsureEmailFitsColumn measures it trimmed. Where the internal-command path invokes this validator is Not determinable from source within this unit.

User

MMCA.ADC.Identity.Domain · MMCA.ADC.Identity.Domain.Users · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Domain/Users/User.cs:37 · Level 7 · class (sealed)

  • What it is: the Identity aggregate root. One row per account, holding credentials, role, profile fields, external-login identifiers, UI preferences, the avatar URL, email-confirmation and account-lock state, Terms of Service acceptance, the service-account flag, and the scalar link to a Conference Speaker with the stamp that orders its changes.
  • Depends on: AuditableAggregateRootEntity<TIdentifierType>, IPasswordChangeableUser, IPasswordRehashableUser, IPasswordClearableUser, IUserPreferences, IErasableUser (which extends IAnonymizable), IEmailConfirmableUser, ILegalAcceptingUser, IEmailIdentifiedUser, IAuditedEntity, Email, UserRole, UserInvariants, ServiceAccounts, UserEmailVerified, PiiAttribute, SensitiveAttribute, IdValueGeneratedAttribute, Result; externals: BCL only.
  • Concept introduced, the interface list as a workflow contract. [Rubric §4, DDD] assesses whether the aggregate is the consistency boundary and enforces its own invariants, and [Rubric §1, SOLID] assesses interface segregation: eight narrow capability interfaces (IPasswordChangeableUser, IPasswordRehashableUser, IPasswordClearableUser, IUserPreferences, IErasableUser, IEmailConfirmableUser, ILegalAcceptingUser, IEmailIdentifiedUser) plus the IAuditedEntity marker instead of one fat base (User.cs:38-39). The class remarks (User.cs:20-35) state what the list is for: it binds this aggregate to the shared Users use-case workflows. ChangePasswordHandlerBase<TUser, TCommand> constrains on IPasswordChangeableUser (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/ChangePassword/ChangePasswordHandlerBase.cs:62), the erasure workflow constrains on IErasableUser, and SendEmailConfirmationHandlerBase<TUser, TCommand> constrains on IEmailConfirmableUser (added for ADR-116). ILegalAcceptingUser (MMCA.Common/Source/Core/MMCA.Common.Domain/Auth/ILegalAcceptingUser.cs:21) is the Terms of Service capability: read-only AcceptedTermsVersion and TermsAcceptedOn plus an idempotent accept operation that User.AcceptTerms implements. IEmailIdentifiedUser (MMCA.Common/Source/Core/MMCA.Common.Domain/Auth/Credentials/IEmailIdentifiedUser.cs:18) exposes only the sign-in address, and User satisfies it implicitly with its own mapped Email property (User.cs:56): password sign-in, forgot password, the email-confirmation send and both sign-in-link workflows find the account through the framework's UserEmailLookup (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UserEmailLookup.cs:38-43), and their bases constrain TUser on this interface (for example MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/SignInLinks/SendSignInLinkHandlerBase.cs:69), so ADC writes no by-address lookup of its own. Two capabilities are opt-in by type test rather than by generic constraint. The shared sign-in flow checks user is not IPasswordRehashableUser rehashable (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/AuthenticationServiceBase.cs:1008) and only then calls RehashPassword (:1024), so declaring it here is what lets ADC accounts with an outdated hash be upgraded on their next successful sign-in (ADR-133). The sign-in link redemption checks user is not IPasswordClearableUser clearable (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/SignInLinks/RedeemSignInLinkHandlerBase.cs:308) and then calls ClearPassword (:322); the interface itself is MMCA.Common/Source/Core/MMCA.Common.Domain/Auth/Credentials/IPasswordClearableUser.cs:24 (extends IAuthUser). Remove either from the declaration list and the code still compiles while the framework quietly skips that step.
    • The soft-delete is the inherited one and raises no domain event (User.cs:26-28): the erasure is announced by the UserDeleted integration event that DeleteUserHandler adds to this aggregate (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/DeleteUser/DeleteUserHandler.cs:71).
    • IAuditedEntity (User.cs:39) is the one non-behavioural marker in the list, and the remarks justify it (User.cs:30-33): it opts the aggregate into a change history rather than just the last-writer audit fields. [Rubric §30, Compliance, Privacy & Data Governance]: account records are where a support or compliance question actually gets asked (who changed this attendee's email, when was this account raised to Organizer, who anonymized it), and LastModifiedOn/By alone answers only "who touched it last".
    • [IdValueGenerated] (User.cs:36) tells the persistence layer the id is database-generated. That single attribute is the root cause of the UserRegistered two-save dance: the id does not exist until after the insert, which the Create remarks state outright (User.cs:209-216): the registration flows (AuthenticationService, RedeemSignInLinkHandler) raise UserRegistered on the aggregate after the first SaveChangesAsync, inside the registration transaction, so subscribers receive the real id.
  • Walkthrough
    • State (User.cs:52-150). IsEmailConfirmed (User.cs:52) records whether the address has been proven reachable, either by redeeming a confirmation link or by an external provider asserting it (ADR-116). Email is an Email value object, not a string, and is marked [Pii] along with FirstName, LastName, AvatarUrl, LoginProvider, ProviderKey, and the computed FullName (User.cs:178, personal data because both parts are); the [Pii] marks are what let the privacy tooling find personal columns (ADR-005). PasswordHash and PasswordSalt are byte[] mapped to varbinary(max), inside a scoped CA1819 suppression that names EF mapping as the reason, and each carries [Sensitive] (User.cs:68, :72). That marker is deliberately not a personal-data mark: it makes the audit trail record a redaction placeholder instead of the old and new values, without feeding the [Pii] mechanisms (MMCA.Common/Source/Core/MMCA.Common.Domain/Attributes/SensitiveAttribute.cs:4-12). The framework already treats the hash and salt of an IAuthUser this way without a marker (SensitiveAttribute.cs:15-16), so here it states the intent on the property rather than changing behavior. Role (User.cs:77) is a string for EF and JWT round-tripping while UserRole owns the rules. LinkedSpeakerId (User.cs:87) is a nullable SpeakerIdentifierType scalar, the 1:1 bidirectional counterpart of Speaker.LinkedUserId (BR-208); it is also [Pii] (User.cs:86), because it points the account at a named, public speaker profile, so Anonymize clears it and the audit trail stores it redacted (User.cs:82-84). SpeakerLinkChangedOn (User.cs:95) is the DateOccurred of the newest link or unlink event applied (O-66). LockedOn (User.cs:125) records when an administrator locked the account, or null while usable; a locked account keeps every row it owns (bookmarks, feedback, points) and can be unlocked, which separates it from the irreversible Anonymize. AcceptedTermsVersion (User.cs:136) and TermsAcceptedOn (User.cs:142) hold the Terms of Service version this user last accepted and when, both null for an account created before the terms existed or through external sign-in (the UI acceptance gate asks on first sign-in). They are consent evidence rather than personal data, so Anonymize keeps them. IsServiceAccount (User.cs:150) marks the account behind a machine client (ADR-140); it is set only by CreateServiceAccount, the framework refuses such an account on every interactive sign-in path and as a view-as target, and the attendee broadcast skips it (User.cs:144-149). Every setter is private: state changes only through the methods below.
    • What is deliberately absent: refresh tokens and device metadata. The class summary states it (User.cs:15-18): sessions are per-device rows in the framework's RefreshSessions table (BR-205/206), hashed at rest, and the MAUI device metadata travels with those rows rather than with the account. [Rubric §8, Data Architecture]: a per-device session list cannot be modelled as one nullable token column on the account row, and moving it out is what lets a user revoke one device without touching the others.
    • Computed members: IsExternalLogin => LoginProvider is not null (User.cs:153); IsLocked => LockedOn is not null (User.cs:164), computed from LockedOn rather than stored so the state and the instant it began cannot disagree (the login and refresh paths refuse a locked account, and locking also revokes the account's live refresh sessions, so the lock takes effect within one access-token lifetime rather than at the next sign-in); HasLocalPassword => PasswordHash.Length > 0 (User.cs:174), which the external-login flow reads to decide whether an OAuth identity may be attached by email match alone (an account whose password someone already holds must be claimed by signing in with that password first); and FullName (User.cs:178). All are derived rather than stored so they cannot go stale.
    • Constructors (User.cs:180-204): a private parameterless one for EF that initializes the non-nullable members to safe defaults, including Role = UserRole.Attendee.Value (:187), and a private full one used by the factories.
    • Create (User.cs:224-255): parses the email, then Result.Combines the email result with six UserInvariants checks, including EnsureEmailFitsColumn (:235), returns Result.Failure<User>(result.Errors) on any failure, and otherwise constructs with Id = default. It stores the role's canonical spelling via UserRole.FromString(role).Value!.Value (User.cs:249), the same as ChangeRole (User.cs:652), because the role column is compared ordinally elsewhere and a validated "organizer" stored verbatim would match nothing.
    • CreateExternal (User.cs:275-304): the OAuth path. It validates the email (including EnsureEmailFitsColumn, :286) and names only, sets PasswordHash/PasswordSalt to empty arrays and forces UserRole.Attendee.Value, and records LoginProvider/ProviderKey. The emailVerified parameter (default false, :281) sets IsEmailConfirmed from it (:300): a provider assertion is exactly the proof the confirmation email exists to collect, so an account created from one starts confirmed and is never asked to prove it again; GitHub's OAuth flow asserts nothing, so those accounts start unconfirmed like a local registration. The password invariants are deliberately skipped because an external account has no local password.
    • CreateFromInvitation (User.cs:324-345): the Attendee account an invitation link provisions on its first redemption (BR-271, ADR-116). Same validation as CreateExternal (:327-332), no local password, and IsEmailConfirmed = true (:341), because the link that creates it was delivered to that mailbox. It raises no event: like Create, the UserRegistered integration event is raised by the provisioning workflow once the save has assigned the id (User.cs:313-319).
    • CreateServiceAccount (User.cs:362-384): the account a machine client signs as. It trims the client name into FirstName, generates the address with ServiceAccounts.NewEmail (:365), validates the first name and role (:366-370), and constructs with ServiceAccounts.LastName, no password, the canonical role, IsServiceAccount = true and IsEmailConfirmed = false (:376-381). No event is raised and no confirmation is sent, because a service account is not a registration; which roles may back a client is the framework's decision (User.cs:353-357).
    • ConfirmEmail (User.cs:398-408): returns success at once when the address is already confirmed (:400-403), which at-least-once delivery of the confirmation link requires; otherwise sets IsEmailConfirmed = true and raises UserEmailVerified (:405-406, BR-272), so the outbox captures the event in the same save as the flag.
    • RaiseEmailVerified (User.cs:464-472): the private helper both confirmation paths use. It skips an account whose Id is still default, because an unsaved account has no id to announce and its creation is announced by UserRegistered instead.
    • AcceptTerms(string version, DateTime acceptedOn) (User.cs:418-434): validates the version through UserInvariants.EnsureTermsVersionIsValid (:420) and returns the failure unchanged when it is empty or over 32 characters (UserInvariants.cs:21). Idempotent for the version already on record: an ordinal match returns success without touching either field (:426-429), so the stored instant still says when consent was first given. Otherwise it sets AcceptedTermsVersion and TermsAcceptedOn (:431-432). Called by LegalAcceptanceService (LegalAcceptanceService.cs:58), which reads both fields back at :39 and :66.
    • LinkExternalProvider (User.cs:451-457): attaches a provider to an existing local account, sets IsEmailConfirmed = true (:455), and raises UserEmailVerified on every link (:456), even for an address already confirmed: tickets imported since the earlier proof still need linking, and the consumer is idempotent (:446-448). The link is only ever made after the provider asserted the address as verified (the caller enforces that; it is the account-takeover guard).
    • LinkSpeaker / UnlinkSpeaker (User.cs:483-493, :505-522): apply Conference's SpeakerLinkedToUser / SpeakerUnlinkedFromUser events (BR-207, BR-209, BR-70), which reach Identity in no particular order. Each takes the event's occurredOn and returns bool (whether the user changed). LinkSpeaker drops an event at or before SpeakerLinkChangedOn (:485-488), so a late link never resurrects a link a newer unlink removed. UnlinkSpeaker ignores an unlink of a speaker the user is no longer linked to (:507-510) and a stale one (:513-517); a tie goes to the unlink, and an unlink that arrives before its own older link still records its stamp, so that link is dropped when it lands.
    • SetAvatarUrl (User.cs:554) records or clears the avatar URL and nothing else, with the doc drawing the boundary explicitly: size, format sniffing, and re-encoding belong to the upload use case, and the domain only stores the resulting public URL.
    • Lock(DateTime utcNow) / Unlock() (User.cs:626, :631): Lock is idempotent via LockedOn ??= utcNow, so locking an already-locked account keeps the original instant rather than resetting it, preserving the audit trail's "when the lock began". Unlock sets LockedOn = null and is a no-op on an account that is not locked.
    • ChangeRole(string role) (User.cs:644-654, BR-41, BR-45): validates through UserInvariants.EnsureRoleIsValid, then assigns the role's canonical spelling via UserRole.FromString(role).Value!.Value rather than the caller's casing, since the role column is compared and filtered ordinally elsewhere (the user list's role filter, the JWT role claim). Re-submitting the role the account already holds assigns the same value, so nothing is written.
    • UpdatePreferences (User.cs:532-545): combines the culture and theme invariants and assigns only after both pass, so a rejected theme cannot leave a half-applied culture.
    • ChangePassword (User.cs:563-578): validates the new hash and salt and assigns them (:574-575). It raises no domain event: the handlers that change or reset a password revoke the account's live sessions themselves (User.cs:556-559).
    • RehashPassword (User.cs:588-603): the IPasswordRehashableUser member. It runs the same hash and salt invariants as ChangePassword and assigns both, and also raises no event. The difference is in what its caller does: the sign-in flow calls it to re-derive the same password when the stored hash predates the hasher's current format or work factor, so, unlike after ChangePassword, no session is revoked (User.cs:580-584).
    • ClearPassword (User.cs:613-619): the IPasswordClearableUser member. It empties the hash and salt, leaving the state CreateExternal produces, so password sign-in is no longer a path for the account until its owner sets one through forgot password. The sign-in link workflow calls it when it confirms an address that already carried a password set before the address was proven; it raises no event, because no new password was set.
    • Anonymize (User.cs:667-707): the erasure half. It builds the placeholder address deleted-{Id}@anonymized.invalid with CultureInfo.InvariantCulture (:672), and the id embedded in the address is what keeps the unique-email invariant (BR-200) satisfiable across many erased accounts. It is idempotent by construction: if the current email already equals the placeholder there is nothing left to erase and it returns success (:679-682). Otherwise it overwrites the email, names, credentials, both external-login fields, and the avatar URL (:684-691), clears LinkedSpeakerId (User.cs:697) because the speaker's name and biography stay public and the link would make the row re-identifiable (the SpeakerUnlinkedFromUser Conference raises on UserDeleted no longer finds the soft-deleted user, so the erasure clears this half itself, User.cs:693-696), and resets IsEmailConfirmed = false (User.cs:701): the placeholder address is not reachable and was never proven, so the flag cannot keep asserting that it was. AcceptedTermsVersion and TermsAcceptedOn are deliberately kept (User.cs:703-705): they evidence which terms governed the account while it was live and identify no one once the other fields are overwritten.
  • Why it's built this way: soft-delete and Anonymize are separate operations, and the doc on Anonymize says exactly why (User.cs:656-665): the row survives so cross-context scalar references (bookmarks, notifications) and the audit trail do not break, which is the anonymize-in-place policy of ADR-005. It is also why a re-registration with an erased account's original email succeeds by design. The avatar comment draws the matching line for storage: the domain nulls the URL, and the use case, which knows the blob boundary, deletes the file (ADR-045). IsEmailConfirmed, the invitation factory, ClearPassword and the lock/role additions exist because ADC opted into the framework's optional Identity completions (ADR-116): ADC sends the confirmation but does not gate sign-in on it (Authentication:EmailConfirmation:RequireConfirmedEmail is false, User.cs:45-51), because an attendee who registers on the conference floor must be able to use the app immediately; the flag is what an organizer reads before trusting an address, and what a later decision to gate would key off without a second migration.
  • Where it's used: persisted by UserConfiguration, projected by UserListDTOMapper, driven by AuthenticationService and the Users use cases (ChangePasswordHandler, ChangePreferencesHandler, DeleteUserHandler, ExportUserDataHandler, SetUserAvatarHandler, RemoveUserAvatarHandler, SendEmailConfirmationHandler, SendSignInLinkHandler, and the reset-password path behind PasswordResetController); created from an invitation by RedeemSignInLinkHandler (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/RedeemSignInLink/RedeemSignInLinkHandler.cs:71) and as a service account by ServiceAccountProvisioner (ServiceAccountProvisioner.cs:30); mutated on the cross-context link by SpeakerLinkedToUserHandler and SpeakerUnlinkedFromUserHandler.
  • Caveats / not-in-source: Anonymize leaves Role, PreferredCulture, PreferredTheme, SpeakerLinkChangedOn and IsServiceAccount untouched, so an erased account keeps its role and its UI preferences. Two of these carry a stated reason: IsServiceAccount (User.cs:149, "the flag identifies no one") and SpeakerLinkChangedOn, kept so a late link event still drops (User.cs:696); for the role and preferences nothing in this file states the judgement, so it is a behavior to notice rather than a documented decision. The ChangeRole doc calls a repeated role a no-op, but the method has no equality check: the no-op is the unchanged value, not a guard.

SendSignInLinkHandler

MMCA.ADC.Identity.Application · MMCA.ADC.Identity.Application.Users.UseCases.SendSignInLink · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/SendSignInLink/SendSignInLinkHandler.cs:44 · Level 9 · class (sealed)

  • What it is: ADC's handler for "Email me a sign-in link" (UC-54, BR-275): it emails a single-use sign-in link to an existing account, answers success for every outcome so the response cannot enumerate registered addresses, and never creates an account itself (SendSignInLinkHandler.cs:14-18).
  • Depends on: SendSignInLinkHandlerBase<TUser, TCommand>, User, SendSignInLinkCommand, IUnitOfWork, ISignInLinkTokenService, IEmailSender, SignInLinkSettings, IPendingTicketInvitationService, IInternalCommandScheduler, SendSignInLinkInternalCommand, SignInLinkPurpose, Email; externals: ILogger, IOptions.
  • Concept reinforced, the framework workflow with app hooks. [Rubric §2, Design Patterns]: the workflow and the localized email live in the framework base (:21-24); ADC supplies only the one step that needs its own types, handling an address with no account. The base also resolves the account by address (:21-24), through the framework's UserEmailLookup over IEmailIdentifiedUser, which User implements (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/SignInLinks/SendSignInLinkHandlerBase.cs:117-119), so this class carries no lookup of its own. [Rubric §11, Security]: the anti-enumeration answer is the base's, so this class cannot leak it.
  • Walkthrough
    • The primary constructor forwards six dependencies to the base, the scheduler among them (:52-53), and keeps pendingInvitations for itself. The base uses the scheduler to queue the sign-in request (the SendSignInLinkCommand row, MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/SignInLinks/SendSignInLinkHandlerBase.cs:95-105), and this class keeps its own copy in _scheduler (:55-57) to queue the re-issued invitation, as the comment there says.
    • OnNoAccountAsync (:65-91) is the invitation re-issue (BR-271, :27-34). It asks Engagement whether an invitation still stands for the address (:69) and returns when none does (:70-71). Otherwise it builds a SendSignInLinkInternalCommand with a fresh Guid, SignInLinkPurpose.Invite and the invitation's names and event (:73-80), and schedules it through _scheduler (:85), so the re-issued link goes out through the same durable row and the same email as the original. A failed schedule throws InvalidOperationException naming the invite id and the error codes, never the address (:86-90).
  • Why it's built this way: nothing is sent inline from the anonymous request. The base's HandleAsync only schedules the command when called from the endpoint and runs the lookup and send when the internal-command processor executes the row (SendSignInLinkHandlerBase.cs:89-91), so the base's lookup and the hook here both run on the processor, not on the request. The comment (:82-84) and the remarks (:60-64) explain that a throwing lookup or a failed schedule of the re-issue propagates to the base, which logs it without the address and still answers success, so neither a peer outage nor a scheduling fault changes the outcome. Repeat requests are bounded by the token service's per-address throttle (:32-33).
  • Where it's used: dispatched for SendSignInLinkCommand by SignInLinkController; covered by SendSignInLinkHandlerTests under MMCA.ADC/Tests/Modules/Identity/MMCA.ADC.Identity.Application.Tests/Users/UseCases/SendSignInLink/ and, for the base, by SignInLinkHandlerBaseTests in MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Users/.
  • Caveats / not-in-source: the summary says the link lasts 15 minutes (:15); the actual lifetime comes from SignInLinkSettings configuration, which is Not determinable from source within this unit.

AssemblyReference

MMCA.ADC.Identity.Domain + MMCA.ADC.Identity.Infrastructure · MMCA.ADC.Identity.{Domain,Infrastructure} · Level 0 · class (static) · two layer copies (table below)

  • What it is: the static assembly marker each Identity layer ships so that scanning code can say "this assembly" without a string literal and without naming a real business type. Each copy exposes a handle onto its own assembly (Assembly) plus that assembly's simple name (AssemblyName).
  • Depends on: System.Reflection.Assembly (BCL) only, imported at line 1 of each file. No first-party dependencies, which is why both sit at Level 0.
Type (assembly) File:Line Notes (what differs)
AssemblyReference (Identity.Domain) MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Domain/AssemblyReference.cs:5 Domain-layer copy; namespace MMCA.ADC.Identity.Domain (:3). No call site in ADC today (see Caveats).
AssemblyReference (Identity.Infrastructure) MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Infrastructure/AssemblyReference.cs:5 Infrastructure-layer copy; byte-identical body, namespace MMCA.ADC.Identity.Infrastructure (:3). This is the one the Identity migrations host scans.
  • Concept: the assembly-marker idiom is taught once at AssemblyReference in the module-system chapter; these are the Identity Domain and Infrastructure instances of the same shape, and the API, Application, Shared and UI layers ship their own copies (covered in the sibling parts of this chapter). [Rubric §5, Vertical Slice] assesses convention-driven wiring and feature cohesion: a marker lets a scanner target an assembly through typeof(AssemblyReference).Assembly rather than a brittle string or a concrete type name, so adding an entity configuration or a handler to a slice needs no registration edit. [Rubric §1, SOLID] (Dependency Inversion): registration code binds to a deliberate, behavior-free token instead of typeof(UserConfiguration).Assembly, so renaming or moving a real type never silently breaks the scan.
  • Walkthrough: two public static readonly fields, resolved once at type initialization. Assembly = typeof(AssemblyReference).Assembly (line 7 of each file) is the self-referential handle; AssemblyName = Assembly.GetName().Name ?? string.Empty (line 8) is the simple name, with the ?? string.Empty fallback so the field is never null even if the runtime reports no simple name. No constructor, no methods.
  • Why it's built this way: every module layer ships the identical marker so generic scanning code can be told which assembly to scan while the layer identity travels purely in the type argument. That keeps Clean Architecture layering intact: the scanner never needs a type reference that would create an upward dependency.
  • Where it's used: the Infrastructure copy is what the Identity migrations host hands to AddConfigurationAssembly(...): MMCA.ADC/Source/Hosting/MMCA.ADC.Migrations.SqlServer.Identity/DesignTimeSQLServerDbContextFactory.cs:59, right after the same factory registers the "Identity" data source (:47-50). That is how UserConfiguration is discovered without the migrations host referencing it directly, and the Conference and Engagement migrations hosts do the identical thing with their own Infrastructure markers (.../MMCA.ADC.Migrations.SqlServer.Conference/DesignTimeSQLServerDbContextFactory.cs:43, .../MMCA.ADC.Migrations.SqlServer.Engagement/DesignTimeSQLServerDbContextFactory.cs:45). The general registration machinery lives in G14, Module System and Composition.
  • Caveats / not-in-source: the Domain copy has no call site in MMCA.ADC/Source or MMCA.ADC/Tests today: a repository-wide search for the name returns only its own declaration and the other layers' copies. It exists for structural symmetry across layers. Whether a Domain-assembly scan is intended is Not determinable from source.

ClassReference

MMCA.ADC.Identity.Domain + MMCA.ADC.Identity.Infrastructure · MMCA.ADC.Identity.{Domain,Infrastructure} · Level 0 · class · two layer copies (table below)

  • What it is: the empty, non-static companion to AssemblyReference, declared in the same file. It exists so a scanning API that needs an instantiable generic type argument has one available from this assembly, since a C# static class cannot be used as a generic type argument.
  • Depends on: nothing first-party, and nothing from the BCL beyond object.
Type (assembly) File:Line Notes (what differs)
ClassReference (Identity.Domain) MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Domain/AssemblyReference.cs:11 Empty marker, same file as the Domain AssemblyReference.
ClassReference (Identity.Infrastructure) MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Infrastructure/AssemblyReference.cs:11 Empty marker, same file as the Infrastructure AssemblyReference. Identical body.
  • Concept: cross-reference the marker idiom taught under AssemblyReference and first introduced in G14. The companion is needed because the framework's scan helper constrains its type parameter to a reference type: ScanModuleApplicationServices<TAssemblyMarker>() where TAssemblyMarker : class (MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.ModuleScanning.cs:29-31), a constraint a static class cannot satisfy. Its own doc names the expected argument outright, "a type in the module's Application assembly (typically ClassReference)" (DependencyInjection.ModuleScanning.cs:23). [Rubric §33, Developer Experience] assesses how much ceremony the inner loop demands: one conventional token per layer is the entire registration ritual for a new slice.
  • Walkthrough: public class ClassReference { } (line 11 of each file), no members. Its only meaningful property is the assembly it belongs to, read by a scanner through typeof(ClassReference).Assembly (the assembly-typed overload the generic one delegates to is at MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.ModuleScanning.cs:47).
  • Why it's built this way: keeping the instantiable anchor separate sidesteps the static-class generic-argument restriction while leaving AssemblyReference impossible to instantiate by accident. Each layer declares its own copy so it can be scanned by passing its local token.
  • Where it's used: neither of these two copies is passed as a type argument anywhere in ADC today. The Identity module's generic scan uses the Application-layer copy (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/DependencyInjection.cs:72, services.ScanModuleApplicationServices<ClassReference>(), which the comment above it describes as picking up "domain event handlers, DTO/request mappers, command/query handlers, and validators", :45-46). Two test suites pass that same Application copy explicitly: MMCA.ADC/Tests/Architecture/MMCA.ADC.Architecture.Tests/Cqrs/DecoratorPipelineOrderTests.cs:54 and MMCA.ADC/Tests/Modules/Identity/MMCA.ADC.Identity.Application.Tests/Users/UseCases/ExportUserData/ExportUserDataRegistrationTests.cs:26.
  • Caveats / not-in-source: the Domain and Infrastructure copies are declared and unreferenced; they are present for symmetry. Whether a layer-specific scan is planned for either is Not determinable from source.

AssemblyReference

MMCA.ADC.Identity.{API,Application} · MMCA.ADC.Identity.{API,Application} · MMCA.ADC.Identity.API/AssemblyReference.cs:5 · Level 0 · class (static)

  • What it is: the per-layer assembly marker, one static class holding the layer's own Assembly and its AssemblyName string. It carries no behavior; it exists so reflection-driven code can name an assembly without a magic string. This unit covers the API and Application copies (the Domain, Infrastructure, Shared and UI copies are byte-identical and belong to their own layers).
Type File:Line Notes (what differs)
AssemblyReference (API) MMCA.ADC.Identity.API/AssemblyReference.cs:5 resolves to MMCA.ADC.Identity.API
AssemblyReference (Application) MMCA.ADC.Identity.Application/AssemblyReference.cs:5 resolves to MMCA.ADC.Identity.Application
  • Depends on: System.Reflection only (BCL, imported at AssemblyReference.cs:1). No first-party types.
  • Concept introduced, the assembly marker. The pattern is taught for the framework's own layers in G14; this is its Identity realization. Assembly is initialized from typeof(AssemblyReference).Assembly (AssemblyReference.cs:7), so it always resolves to the assembly that declares the marker: that is why the type is duplicated per layer instead of shared, and why the two copies differ only in their namespace line (:3). [Rubric §15, Best Practices & Code Quality] (assesses idiomatic, low-ceremony conventions): a typeof handle survives a project rename, an Assembly.Load("MMCA.ADC.Identity.Application") string does not.
  • Walkthrough: two public static readonly fields, Assembly (:7) and AssemblyName = Assembly.GetName().Name ?? string.Empty (:8). The null-coalescing guard is there because AssemblyName.Name is declared nullable in the BCL, and the repo compiles with warnings as errors, so the nullable flow has to be closed rather than suppressed.
  • Why it's built this way: static readonly fields are computed once at type initialization, so the reflection cost is paid a single time per process rather than at every scan site.
  • Where it's used: as the stable handle for assembly-scanning code (Scrutor convention registration, EF configuration discovery, architecture fitness tests). The scanning call itself takes the sibling ClassReference as its generic argument.

ClassReference

MMCA.ADC.Identity.{API,Application} · MMCA.ADC.Identity.{API,Application} · MMCA.ADC.Identity.API/AssemblyReference.cs:11 · Level 0 · class

  • What it is: an empty, member-less class that exists purely to be a type argument. Generic scanning APIs of the shape DoSomething<T>() derive the target assembly from typeof(T).Assembly, so each layer ships its own ClassReference to point such a call at itself.
Type File:Line Notes (what differs)
ClassReference (API) MMCA.ADC.Identity.API/AssemblyReference.cs:11 declared but not referenced by the API layer's own registration
ClassReference (Application) MMCA.ADC.Identity.Application/AssemblyReference.cs:11 the T in ScanModuleApplicationServices<ClassReference>()
  • Depends on: nothing. public class ClassReference { }, no base type beyond object, no members.
  • Concept introduced: cross-reference AssemblyReference above. The two solve the same problem from opposite directions: AssemblyReference hands out an Assembly value, ClassReference hands out a type that a generic method can turn into one without the caller ever mentioning System.Reflection.
  • Walkthrough: the whole declaration is one line (AssemblyReference.cs:11), sharing the file with its AssemblyReference sibling. It is deliberately neither static nor sealed: a static class cannot be used as a generic type argument at all, and sealing would buy nothing for a type that is never instantiated.
  • Why it's built this way: ScanModuleApplicationServices<T>() reads better and refactors more safely than passing an Assembly argument, and a dedicated empty type avoids accidentally anchoring the scan to some real class that might later move to another project.
  • Where it's used: the Application copy is the type argument at MMCA.ADC.Identity.Application/DependencyInjection.cs:72, which resolves to ScanModuleApplicationServices<TAssemblyMarker> in MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.ModuleScanning.cs:29-31, a one-line generic wrapper that forwards typeof(TAssemblyMarker).Assembly to the Assembly-typed overload declared at :46. See DependencyInjection for the Application layer.
  • Caveats / not-in-source: whether the API-layer copy has an active consumer is Not determinable from source within this unit; the API registration (MMCA.ADC.Identity.API/DependencyInjection.cs:42-47) does not reference it.

ClaimNames

MMCA.ADC.Identity.Shared · MMCA.ADC.Identity.Shared.Authorization · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Shared/Authorization/ClaimNames.cs:19 · Level 0 · class (static)

  • What it is: ADC's application-specific JWT claim names: two string constants, SpeakerId and EmailVerified (ClaimNames.cs:19-34), used instead of literals when Identity mints a claim and when any module reads one back.
  • Depends on: nothing first-party.
  • Concept, one spelling for a claim across the minting site and every reader. The sibling of RoleNames, and the class remarks (ClaimNames.cs:7-18) say so: the vocabulary lives beside RoleNames because Identity mints the tokens and every other module reads the claims through this Shared project, the one cross-module reference the architecture rules allow. [Rubric §11, Security] assesses authorization correctness: a claim name is compared ordinally, so a misspelled literal does not fail the build, it silently fails the lookup and a speaker is denied their own data (:14-16). [Rubric §15, Best Practices & Code Quality] assesses single points of change: one constant keeps the writer and the readers on one spelling.
  • Walkthrough: two public const string fields. SpeakerId = "speaker_id" (ClaimNames.cs:25) carries the linked speaker id (User.LinkedSpeakerId) and is present only when the account is linked to a speaker profile (:21-24). EmailVerified = "email_verified" (:33) is the OpenID Connect claim, issued only as "false" on an account whose address is not yet confirmed (an attendee, since a privileged account cannot sign in unconfirmed); a confirmed account carries no such claim, and the UI reads it to show the confirm-your-address reminder (:27-32).
  • Why it's built this way: const so the values can sit in attribute and record initializers that need compile-time constants (the nav-item RequiredClaim: argument below is one). Emitting email_verified only in the negative keeps every confirmed token unchanged and makes the reminder a presence check.
  • Where it's used: minted in AuthenticationService (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/AuthenticationService.cs:566 for SpeakerId, :570 for EmailVerified with ClaimValueTypes.Boolean). SpeakerId is read back for speaker self-access checks in Conference and Engagement controllers, for example SpeakersController (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.API/Controllers/Speakers/SpeakersController.cs:277, :368) and SessionQuestionsController, which reads it through the Engagement API's LiveCallerRights.SpeakerId (MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.API/Authorization/LiveCallerRights.cs:29, called at MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.API/Controllers/SessionQuestionsController.cs:254), and gates the speaker nav entries (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.UI/ConferenceUIModule.cs:74-75). EmailVerified is read by EmailConfirmationReminder (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.UI/Components/EmailConfirmationReminder.razor.cs:28).

RoleNames

MMCA.ADC.Identity.Shared · MMCA.ADC.Identity.Shared.Authorization · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Shared/Authorization/RoleNames.cs:20 · Level 0 · class (static)

  • What it is: the canonical role-name string constants for the ADC Identity module: three roles, Organizer, Attendee, and ContentEditor (RoleNames.cs:20-34), referenced instead of magic strings.
  • Depends on: nothing first-party.
  • Concept, centralized constants over magic strings. [Rubric §11, Security] assesses authorization correctness and [Rubric §15, Best Practices & Code Quality] assesses duplication and single points of change. Roles are stored as plain strings and emitted as claims, so a typo in a literal does not fail to compile: it silently fails to authorize, or worse, silently authorizes nobody while looking correct. Referencing RoleNames.Organizer instead of "Organizer" moves that class of bug to compile time. ContentEditor is documented as a strict subset of the Organizer's capabilities (RoleNames.cs:28-32): it curates the session catalog without rights over event structure, rooms, questions, session selection, speaker-account linking, or user administration. That subset is precisely the case ADR-020 uses to justify the permission layer, and you can see the payoff in ADC's Conference grants, where Organizer receives the module's whole permission set (plus the framework's feature-management capability) while ContentEditor receives only the content-management slice, one extra line rather than an edit to every attribute (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Shared/Authorization/ConferencePermissionGrants.cs:53-54). The class remarks (RoleNames.cs:7-19) add why the vocabulary lives in Identity: the framework declares no role names of its own, and every other module reaches these through this Shared project; role comparisons are case-insensitive.
  • Walkthrough: three public const string fields. Organizer = "Organizer" (RoleNames.cs:23) is documented as managing conference master data (:22); Attendee = "Attendee" (:26) is the default for new registrations (:25); ContentEditor = "ContentEditor" (:33) curates the session catalog (sessions, speakers, categories, sponsors, partners, activities, session assets) without full organizer rights, and its doc comment (:28-32) spells out exactly which rights it lacks.
  • Why it's built this way: const rather than static readonly so the values can appear in attribute and option initializers that require compile-time constants.
  • Where it's used: the per-app role type (UserRole; MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Domain/Users/UserRole.cs:21,24,31), each module's permission grants (ConferencePermissionGrants, MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Shared/Authorization/ConferencePermissionGrants.cs:53-54; EngagementPermissionGrants, MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.Shared/Authorization/EngagementPermissionGrants.cs:42; NotificationPermissionGrants, MMCA.ADC/Source/Modules/Notification/MMCA.ADC.Notification.Shared/Authorization/NotificationPermissionGrants.cs:38; IdentityPermissionGrants.Apply, MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Shared/Authorization/IdentityPermissionGrants.cs:43), and the ownership-filter bypass role in ADC's Engagement module (MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.API/DependencyInjection.cs:53).

IAttendeeQueryService

MMCA.ADC.Identity.Shared · MMCA.ADC.Identity.Shared.Users · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Shared/Users/IAttendeeQueryService.cs:17 · Level 0 · interface

  • What it is: the attendee-audience read contract Identity publishes. It answers two questions, "which user ids are attendees, one keyset page at a time?" and "how many attendees are there?", so the Notification module can fan a broadcast out to every attendee without knowing anything about the User aggregate and without ever loading the whole audience at once.
  • Depends on: MMCA.Common.Shared.Abstractions for the ServiceContractAttribute marker (IAttendeeQueryService.cs:1), the UserIdentifierType alias, and BCL (Task, IReadOnlyList<T>, CancellationToken). Note what is not imported: no Identity Domain, Application, or Infrastructure namespace appears anywhere in the file.
  • Concept introduced, the cross-module contract in the Shared assembly. [Rubric §7, Microservices Readiness] (assesses whether modules talk through narrow, transport-agnostic interfaces that survive extraction into separate processes) and [Rubric §3, Clean Architecture] (assesses dependency direction: the consumer depends on an abstraction, not on the producer's internals). The doc comment (IAttendeeQueryService.cs:5-9) states the rule outright: the contract lives in Shared so the Notification module can call it without depending on the Identity implementation, preserving module boundary isolation. That one placement decision is what makes two wirings interchangeable behind the same interface: the in-process AttendeeQueryService where the Identity module is loaded, and the AttendeeQueryServiceGrpcAdapter in the extracted Notification host, which names only its own module to ModuleLoader, so the adapter is the only IAttendeeQueryService registration there (MMCA.ADC/Source/Services/MMCA.ADC.Identity.Contracts/DependencyInjection.cs:32-36, :46). No consumer code changes between the two.
  • Concept introduced, the keyset page over a bounded audience. [Rubric §8, Data Architecture] (assesses whether reads stay bounded as data grows) and [Rubric §12, Performance & Scalability]. The remarks (IAttendeeQueryService.cs:10-15) state that the audience is read as a keyset, one page at a time, so no caller ever loads it whole, and they pin down who counts as an attendee: an active (non-deleted) user with the Attendee role that is neither a service account behind a machine client nor a synthetic load-test account, with the page and the count applying the same rule.
  • Concept reinforced, the [ServiceContract] marker as a machine-checked boundary. The attribute at IAttendeeQueryService.cs:16 is not decoration and it is not System.ServiceModel: it is the framework's own marker introduced in G13, whose doc records that a dedicated ServiceContractPurityTestsBase fitness rule scans every mapped assembly for types carrying it and fails the build if such a type depends on the producing service's Domain, Application, or Infrastructure layers (MMCA.Common/Source/Core/MMCA.Common.Shared/Abstractions/ServiceContractAttribute.cs:3-21). Marking this interface therefore converts "we intend to keep this extractable" from a comment into a test ([Rubric §14, Testability], [Rubric §34, Architecture Governance and Documentation]). The attribute carries no properties and no version: its only constructor is parameterless (ServiceContractAttribute.cs:28), so marking this interface states membership in the wire surface and nothing more.
  • Walkthrough: an interface constant and two members. const int MaxPageSize = 10_000 (IAttendeeQueryService.cs:20) is the largest page the contract serves. GetAttendeeUserIdPageAsync(UserIdentifierType? afterUserId, int take, CancellationToken cancellationToken = default) (:35-38) returns Task<IReadOnlyList<UserIdentifierType>>: distinct attendee ids in ascending order greater than afterUserId (from the start when it is null), with take between 1 and MaxPageSize (:22-34). The page holds exactly take ids unless the audience is exhausted, so a shorter page is the end signal; rows the attendee rule leaves out are read past rather than returned as a thinned page (:26-30). CountAttendeesAsync(CancellationToken cancellationToken = default) (:45) returns Task<int>, counting with the same rule as the page (:40-44). The page carries ids only, not user records: the caller needs recipients, not personal data, so the contract carries the minimum ([Rubric §30, Compliance, Privacy and Data Governance], data minimization across a module boundary).
  • Why it's built this way: coarse, id-only, async, cancellable methods map cleanly onto gRPC unary calls, which is exactly the extraction path ADR-007 describes, and the [ServiceContract] marker names them as such. Anything richer (a filtered query object, an IQueryable) would leak Identity's persistence model across the boundary and would not survive the process split. Putting MaxPageSize on the contract lets the in-process implementation and the gRPC server enforce the same bound: AttendeeQueryService guards with ArgumentOutOfRangeException.ThrowIfGreaterThan(take, IAttendeeQueryService.MaxPageSize) (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/AttendeeQueryService.cs:33), and AttendeesGrpcService documents refusing a larger request (MMCA.ADC/Source/Services/MMCA.ADC.Identity.Service/Grpc/AttendeesGrpcService.cs:28).
  • Where it's used: consumed by Notification's AttendeeNotificationRecipientProvider (which bridges it to INotificationRecipientProvider, forwarding the page call and the count at MMCA.ADC/Source/Modules/Notification/MMCA.ADC.Notification.Application/AttendeeNotificationRecipientProvider.cs:23, :27); implemented in-process by AttendeeQueryService (AttendeeQueryService.cs:27, :69), served over the wire by AttendeesGrpcService, and satisfied remotely by AttendeeQueryServiceGrpcAdapter (MMCA.ADC/Source/Services/MMCA.ADC.Identity.Contracts/AttendeeQueryServiceGrpcAdapter.cs:18, :37), which AddIdentityAttendeeClient installs with services.Replace(...) (MMCA.ADC/Source/Services/MMCA.ADC.Identity.Contracts/DependencyInjection.cs:46).

UserAvatarDTO

MMCA.ADC.Identity.Shared · MMCA.ADC.Identity.Shared.Users · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Shared/Users/UserAvatarDTO.cs:6 · Level 0 · record (sealed)

  • What it is: the one-field response body every avatar endpoint returns: the current public avatar URL, or null when the user has none (BR-116a).
  • Depends on: nothing first-party; one BCL attribute (System.Diagnostics.CodeAnalysis.SuppressMessage).
  • Concept reinforced, the response DTO as a stable wire shape. [Rubric §9, API and Contract Design] (assesses whether endpoints return a named, versionable shape rather than a bare primitive). Returning { "avatarUrl": ... } instead of a raw string means a later addition (a thumbnail URL, an upload timestamp) is an additive change, not a breaking one. The CA1054 suppression (UserAvatarDTO.cs:5) carries its own justification in source: this is a serialized DTO field, so the URL stays a string on the wire rather than becoming a Uri.
  • Walkthrough: a single positional record, public sealed record UserAvatarDTO(string? AvatarUrl) (UserAvatarDTO.cs:6), with the parameter documented at UserAvatarDTO.cs:4. The nullable parameter is the whole contract: "no avatar" is a first-class, non-exceptional state.
  • Why it's built this way: avatars are managed file storage (ADR-045), so the only thing a client ever needs back from an upload is the new public URL. Handing it back in a named record keeps the read endpoint, the write endpoint, and the client projection on one type.
  • Where it's used: produced by the avatar read and write use cases (GetUserAvatarHandler, SetUserAvatarHandler) and returned by UsersController's me/avatar endpoints (GET at MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/Controllers/UsersController.cs:129 returning Ok(result.Value) at :65, POST at :79 returning at :115). The delete endpoint (:119) returns a bare ActionResult with a 204 (:133), because there is no avatar state left to report. Client-side it is deserialized by UserService in GetMyAvatarUrlAsync (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.UI/Services/UserService.cs:56-59) and UploadMyAvatarAsync (:139-142), both of which immediately flatten it with dto.Map(value => value.AvatarUrl ?? string.Empty) so the page never handles the envelope, only a Result<string>. The Profile page stores that string in its _avatarUrl field (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.UI/Pages/Users/Profile/Profile.razor.cs:71, :173).

VerifiedUserDTO

MMCA.ADC.Identity.Shared · MMCA.ADC.Identity.Shared.Users · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Shared/Users/VerifiedUserDTO.cs:12 · Level 0 · record (sealed)

  • What it is: one account whose address is confirmed, as IVerifiedUserLookupService answers it (BR-277): the normalized (lowercase) address, the account id, and the first and last name (VerifiedUserDTO.cs:3-11).
  • Depends on: the UserIdentifierType alias only.
  • Concept, the minimum a cross-module answer needs. [Rubric §30, Compliance, Privacy and Data Governance] assesses data minimization across boundaries: the record carries exactly what the roster import needs to link a ticket to an existing account, the id to link and the name that the roster's name match (BR-272) compares against a ticket's attendee name (VerifiedUserDTO.cs:5-6), and nothing about role, device or lock state. [Rubric §9, API and Contract Design]: a named, sealed positional record is the wire shape the gRPC adapter maps to and from.
  • Walkthrough: public sealed record VerifiedUserDTO(string Email, UserIdentifierType UserId, string FirstName, string LastName) (VerifiedUserDTO.cs:12), each parameter documented at :8-11. Email is documented as already normalized to lowercase, so callers compare it without re-casing.
  • Why it's built this way: it lives in Shared beside its contract so Engagement and the gRPC adapter can name it without referencing Identity's Application or Domain assemblies.
  • Where it's used: produced by VerifiedUserLookupService in process and by VerifiedUserLookupServiceGrpcAdapter across the service boundary, and consumed by ExistingAccountLinker in Engagement (MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.Application/Tickets/Services/ExistingAccountLinker.cs).

IdentityPermissions

MMCA.ADC.Identity.Shared · MMCA.ADC.Identity.Shared.Authorization · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Shared/Authorization/IdentityPermissions.cs:10 · Level 1 · class (static)

  • What it is: the capability-permission catalog for the Identity module: string constants that endpoints demand through [HasPermission(...)] instead of naming roles inline. It holds one ADC-defined capability, reading the user list; the four administration capabilities (users, roles, view-as, machine clients) are the framework's own constants, aliased here and granted separately.
  • Depends on: AdministrationPermissions (the framework's shared administration capability names, aliased here rather than re-coined). BCL IReadOnlyList<string> plus a collection expression.
  • Concept, permission-based authorization over role-based. An endpoint declares the capability it needs (identity:users:read), and the role-to-permission grants are declared once, in IdentityPermissionGrants (IdentityPermissions.cs:5-9), so adding a role or re-mapping a capability never touches an endpoint attribute. [Rubric §11, Security] assesses authorization design and least privilege: naming the capability at the endpoint and centralizing the grants makes the authorization surface auditable in one place rather than scattered across [Authorize(Roles = ...)] strings. [Rubric §7, Microservices Readiness] assesses whether a boundary survives extraction: the catalog lives in the module's Shared project, so the in-process host and the standalone Identity service consume the exact same constants with no duplication.
  • Walkthrough: public const string UsersRead = "identity:users:read" (IdentityPermissions.cs:13), documented as "list or read all user accounts (organizer user-management screens)" (:12). public const string UsersManage = AdministrationPermissions.ManageUsers (:26) administers user accounts (lock, unlock, change role); its doc and remarks (:15-25) note it aliases the framework's AdministrationPermissions.ManageUsers because UsersAdminControllerBase gates its actions on that exact capability string, that it stays OUT of All because All is the list of capabilities ADC itself defines, that IdentityPermissionGrants grants it to Organizer by name instead, and that ContentEditor holds none of these, which is the strict-subset property that role is defined by. public const string RolesManage = AdministrationPermissions.ManageRoles (:41) administers roles (list them, edit the stored permission grants attached to each); its doc and remarks (:28-40) note that RolesAdminControllerBase gates on that exact string, add the same "stays out of All, granted by name" note, and state it is granted in compiled code and never from a stored row, because it is the only protection on the screen that edits stored rows, so the framework refuses to store it and a deleted row could otherwise lock every operator out of the surface that would restore it. public const string UsersViewAs = AdministrationPermissions.ViewAsUsers (:52) lets an account view the app read-only as another account for at most 15 minutes (ADR-137, :43-45); its remarks (:46-51) note that UsersAdminControllerBase gates its view-as action on it, that ADC has no Admin role so Organizer holds it, and that an account holding it can never be viewed, so organizers cannot view each other. public const string ClientsManage = AdministrationPermissions.ManageClients (:64) administers machine clients, creating, rotating, promoting and revoking the OAuth client credentials a program signs in with (ADR-140, :54-57); its remarks (:58-63) note that MachineClientsControllerBase gates every action on it and that the framework never lets a role holding it back a client, so no machine client can create another. public static IReadOnlyList<string> All { get; } (:73) is a collection expression holding only UsersRead (:74-76), documented (:66-72) as every Identity capability ADC itself defines, with the four framework administration capabilities deliberately excluded because they are the framework's constants and are granted by name in IdentityPermissionGrants instead.
  • Why it's built this way: a namespace:resource:action string convention keeps permissions self-describing and greppable. Splitting All (ADC's own capabilities) from the four aliased framework constants keeps the catalog honest about provenance: a reader scanning All sees only what this module coined, while the grant that actually assigns roles is the single place that decides which framework capabilities Organizer also needs. Aliasing the AdministrationPermissions constants rather than coining Identity-specific names keeps the framework controller gates and the compiled role grant agreeing on one string per capability.
  • Where it's used: UsersRead is demanded by two endpoints on UsersController: GET Users/paged (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/Controllers/UsersController.cs:223-224) and POST Users/search (:261-262). The four aliases are consumed by the framework controller bases that UsersAdminController, AdminRolesController and AdminMachineClientsController close. All five constants are granted to Organizer in IdentityPermissionGrants.Apply (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Shared/Authorization/IdentityPermissionGrants.cs:42-51).

IVerifiedUserLookupService

MMCA.ADC.Identity.Shared · MMCA.ADC.Identity.Shared.Users · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Shared/Users/IVerifiedUserLookupService.cs:16 · Level 1 · interface

  • What it is: the second cross-module read contract Identity publishes, beside IAttendeeQueryService. Given addresses the caller already holds, it returns the active accounts whose confirmed address matches, so Engagement can link an event's roster tickets to accounts that existed before the roster was uploaded (BR-277, UC-55; IVerifiedUserLookupService.cs:5-9).
  • Depends on: ServiceContractAttribute (MMCA.Common.Shared.Abstractions, imported at IVerifiedUserLookupService.cs:1); VerifiedUserDTO; BCL (Task, IReadOnlyList<T>, IReadOnlyCollection<T>, CancellationToken).
  • Concept, a narrow contract that cannot enumerate users. The Shared-layer contract and the [ServiceContract] purity marker are taught under IAttendeeQueryService; this interface adds a privacy constraint on top. [Rubric §30, Compliance, Privacy and Data Governance] and [Rubric §11, Security]: the doc (IVerifiedUserLookupService.cs:10-13) states it answers only addresses the caller already holds, only for confirmed addresses, and never for a deleted (erased) account, so it cannot be used to list who has an account. [Rubric §7, Microservices Readiness]: across the service boundary it is answered over gRPC (ADR-007), and the batch cap below keeps one call bounded.
  • Walkthrough: the attribute [ServiceContract] (:15) and two members. const int MaxEmailsPerCall = 500 (:22) is an interface constant: a caller with more addresses splits them into batches of at most this many, so a request stays bounded on the wire and in the SQL IN list (:18-21). GetVerifiedUsersByEmailAsync(IReadOnlyCollection<string> emails, CancellationToken cancellationToken = default) (:33-35) returns Task<IReadOnlyList<VerifiedUserDTO>>: matches are case-insensitive, an address with no account is simply absent, a malformed address matches nothing, and passing more than MaxEmailsPerCall addresses throws ArgumentOutOfRangeException (:24-32).
  • Why it's built this way: putting the cap on the contract lets the caller, the in-process implementation, the gRPC adapter and the gRPC server all reference the same number: ExistingAccountLinker chunks by it (MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.Application/Tickets/Services/ExistingAccountLinker.cs:114), and both implementations guard with ArgumentOutOfRangeException.ThrowIfGreaterThan(emails.Count, IVerifiedUserLookupService.MaxEmailsPerCall) (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/VerifiedUserLookupService.cs:27, MMCA.ADC/Source/Services/MMCA.ADC.Identity.Contracts/VerifiedUserLookupServiceGrpcAdapter.cs:22).
  • Where it's used: implemented in process by VerifiedUserLookupService (registered with TryAddScoped at MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/DependencyInjection.cs:39), served by VerifiedUserLookupGrpcService (MMCA.ADC/Source/Services/MMCA.ADC.Identity.Service/Grpc/VerifiedUserLookupGrpcService.cs:33), and satisfied remotely by VerifiedUserLookupServiceGrpcAdapter, which AddIdentityVerifiedUserLookupClient installs with services.Replace(...) (MMCA.ADC/Source/Services/MMCA.ADC.Identity.Contracts/DependencyInjection.cs:73). Consumed by ExistingAccountLinker, whose callers are LinkExistingAccountsHandler and ProcessTicketRosterImportHandler.

UserAdminDTO

MMCA.ADC.Identity.Shared · MMCA.ADC.Identity.Shared.Users · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Shared/Users/UserAdminDTO.cs:25 · Level 1 · record (sealed)

  • What it is: the administration-facing view of a user account, served behind the users:manage capability: id, email, name, role, creation date, lock state, and the two account-nature flags an operator needs to act on the account: whether it signs in externally and whether the email is confirmed.
  • Depends on: the UserIdentifierType alias; BCL (DateTime).
  • Concept introduced, the permission-scoped sibling DTO. [Rubric §8, Data Architecture] (assesses whether reads project only the columns a screen needs) and [Rubric §11, Security] (assesses that secrets never reach a serialization boundary). The type's remarks (UserAdminDTO.cs:10-15) states directly why this is not more fields bolted onto UserListDTO: the two DTOs are reached through different permissions, identity:users:read serves the organizer's roster, users:manage serves the administration screens. Device metadata stays out of both (attendee device privacy), and no credential material is ever projected here either, the same restraint UserDataExportSubjectDTO documents for the export path.
  • Walkthrough: nine positional parameters (UserAdminDTO.cs:23-32), each documented at :14-22: Id (renamed from UserId so the record satisfies IBaseDTO<UserIdentifierType>, declared on the record at UserAdminDTO.cs:34), Email, FirstName, LastName, Role, CreatedOn, a nullable LockedOn, IsExternalLogin, and IsEmailConfirmed (ADR-116). Two computed members read off those without adding wire fields: IsLocked => LockedOn is not null (:35) and FullName => $"{FirstName} {LastName}" (:38).
  • Why it's built this way: this is the app-owned TUserDto closing the framework's generic administration slice. UserAdministrationService implements IUserAdministrationService<UserAdminDTO> (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/Administration/UserAdministrationService.cs:39) and projects it directly inside the paged EF query, .Select(u => new UserAdminDTO(...)) after OrderBy/Skip/Take (UserAdministrationService.cs:72-86), so the excluded columns never leave the database: the same projection-as-privacy-boundary pattern UserListDTO uses for its own row. UsersAdminController closes the framework's generic controller over it, UsersAdminControllerBase<UserAdminDTO> (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/Controllers/UsersAdminController.cs:26-27), and both DI registrations name the closed type explicitly: services.TryAddScoped<IUserAdministrationService<UserAdminDTO>, UserAdministrationService>() on the Application side (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/DependencyInjection.cs:43) and services.AddUserAdministrationUI<UserAdminDTO>() on the UI side (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.UI/DependencyInjection.cs:31).
  • Where it's used: produced by UserAdministrationService.MapToDto (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/Administration/UserAdministrationService.cs:46-55), the one mapping hook over the framework's UserAdministrationServiceBase<User, UserAdminDTO> workflow (:43; the roster itself is the generic GET Users/paged endpoint, :13-15), and served through UsersAdminController's Admin/Users endpoints; consumed client-side as IUserAdminUIService<UserAdminDTO> on the UserDetail page (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.UI/Pages/Users/UserDetail/UserDetail.razor.cs:38, :42), and covered by unit and controller tests (MMCA.ADC/Tests/Modules/Identity/MMCA.ADC.Identity.UI.Tests/Pages/Users/UserDetail/UserDetailTests.cs, MMCA.ADC/Tests/Modules/Identity/MMCA.ADC.Identity.Application.Tests/Users/Administration/UserAdministrationServiceTests.cs, MMCA.ADC/Tests/Modules/Identity/MMCA.ADC.Identity.API.Tests/Controllers/UsersAdminControllerTests.cs).

UserListDTO

MMCA.ADC.Identity.Shared · MMCA.ADC.Identity.Shared.Users · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Shared/Users/UserListDTO.cs:16 · Level 2 · record (sealed)

  • What it is: the row shape for the organizer user list (BR-51): id, email, first/last name, role, creation date, and lock state, and nothing else.
  • Depends on: the UserIdentifierType alias; IUserAdminDTO (MMCA.Common.Shared.Auth.Administration, imported at UserListDTO.cs:1); BCL (DateTime).
  • Concept introduced, the list projection DTO as a privacy boundary, and now also the framework's shared roster row. [Rubric §8, Data Architecture] and [Rubric §30, Compliance, Privacy and Data Governance] for the projection; [Rubric §7, Microservices Readiness] and [Rubric §2, Design Patterns] for the interface. The type's doc comment is explicit that device-specific fields are excluded to protect attendee device privacy: the User aggregate carries DeviceId, DeviceModel, DeviceManufacturer and friends, but an organizer browsing the user grid has no business seeing them. Its remarks (ADR-116) add a second fact on top: this is also the row the framework's shared user-administration list renders, so the type answers IUserAdminDTO by reusing Id, Email, and Role as-is, without renaming the wire contract, and maps the lock state explicitly off LockedOn (UserListDTO.cs:16). The remarks now also name it as the row the generic paged entity endpoint serves (GET Users/paged), and through IUserAdminDTO it answers IBaseDTO, which is why the identifier property is Id rather than the earlier UserId. The row is built by UserListDTOMapper, which copies only the roster columns off each User on the page (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/DTOs/UserListDTOMapper.cs:17-31), after UserListEntityQueryService has filtered, sorted and paged the entities on the generic path (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UserListEntityQueryService.cs:44-52, with the mapping step at MMCA.Common/Source/Core/MMCA.Common.Application/Services/Query/EntityQueryService.cs:406-414), so the excluded columns are loaded into the entity but never leave the API, and the roster's field contract keeps them out of reach as filter or sort keys (UserListEntityQueryService.cs:16-19, :60-62).
  • Walkthrough: eight members (UserListDTO.cs:16-52). Id (:20), Email (:23), FirstName (:26), LastName (:29), and Role (:32) are required init; CreatedOn is a plain init DateTime (:35). Role is a string, not the UserRole value object: the wire format stays primitive, and the closed-set type is a domain concern. The nullable LockedOn (:42, documented :37-41) is new: when an administrator locked the account, or null while it is usable, carried on the roster so an operator can see which accounts are locked without opening each one; the lock itself is changed through the Admin/Users endpoints. int ActiveSessionCount (:50, documented :44-49) is the count of live refresh sessions (not revoked, not expired) shown as the roster's "Signed in" column; it is not a mapped column, it is filled per page after the query runs, so it is neither sortable nor filterable as an ordinary field, and the grid's signed-in filter reaches the server under that key where it is translated. bool IUserAdminDTO.IsLocked => LockedOn is not null; (:53) is an explicit interface implementation, so IsLocked is reachable only through an IUserAdminDTO-typed reference, leaving the record's own public surface unchanged for every existing consumer that names UserListDTO directly.
  • Why it's built this way: keeping the list DTO separate from UserAdminDTO lets the grid evolve (sortable columns, CreatedOn, now LockedOn) without touching the administration-facing account DTO, and it keeps the list endpoint's payload small enough to page cheaply. Filtering, sorting and paging run on the shared query pipeline and only the returned page is mapped (EntityQueryService.cs:367, :406-414), so the DTO is the only user shape the roster endpoint ever returns. Implementing IUserAdminDTO explicitly, rather than adding a second public lock-state property, lets UserListDTO also satisfy the framework's shared roster contract (ADR-116) without growing the type's own public surface: the interface exists so a framework-owned consumer can render either this DTO or UserAdminDTO (which the app-side Admin/Users screens use instead) through the same shape.
  • Where it's used: produced by UserListDTOMapper on UserListEntityQueryService's paged read (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UserListEntityQueryService.cs:48-52), returned inside a PagedCollectionResult<T> by UsersController's GET Users/paged endpoint (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/Controllers/UsersController.cs:223-227, the query service injected at :34), and consumed client-side through UserListService, the standard entity-service client for this DTO (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.UI/Services/UserListService.cs:21), which the UserList page injects as its IEntityService<UserListDTO, UserIdentifierType> (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.UI/Pages/Users/UserList.razor.cs:39). The grid's signed-in filter key is read back off the DTO with nameof(UserListDTO.ActiveSessionCount) (UserList.razor.cs:143), so a renamed property breaks at compile time rather than at runtime. Also referenced from UserAdminDTO's own doc comment (UserAdminDTO.cs:7) and consumed from SpeakerDetail/SpeakerUserSearch in the Conference module (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.UI/Pages/Speakers/SpeakerDetail.razor.cs, SpeakerUserSearch.cs).

IdentityPermissionGrants

MMCA.ADC.Identity.Shared · MMCA.ADC.Identity.Shared.Authorization · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Shared/Authorization/IdentityPermissionGrants.cs:17 · Level 3 · class (static)

  • What it is: the module's one role-to-permission grant: it hands every IdentityPermissions capability, plus the five framework administration capabilities the shipped controller bases gate on, to RoleNames.Organizer and to no other role.
  • Depends on: RoleNames; IdentityPermissions; AdministrationPermissions (for ViewAuditTrail) and PermissionRegistryBuilder (the framework's grant-accumulation type), both imported from MMCA.Common.Shared.Auth.Permissions (IdentityPermissionGrants.cs:1).
  • Concept: cross-reference IdentityPermissions for the permission-based authorization model this grant populates and for why the framework aliases are named here rather than folded into IdentityPermissions.All. [Rubric §11, Security] assesses least privilege: factoring the grant into its own static class keeps "who can administer users, roles, view-as, machine clients and the audit trail" answerable by reading one method rather than tracing every [HasPermission] attribute back to a role. [Rubric §7, Microservices Readiness]: the class remarks (IdentityPermissionGrants.cs:5-16) explain it lives in Shared because a grant map is a statement about the application's vocabulary, not one host's composition, which is what lets the map be applied by two hosts without being written twice.
  • Walkthrough: one method, public static void Apply(PermissionRegistryBuilder permissions) (IdentityPermissionGrants.cs:38), guarded by ArgumentNullException.ThrowIfNull(permissions) (:40). The doc comment (:19-24) states the policy: every Identity capability goes to Organizer, and content editors deliberately hold none, because their strict-subset property is defined by holding no user or role administration. The remarks (:25-36) add that UsersManage, RolesManage, UsersViewAs and ClientsManage are the framework's own constants (AdministrationPermissions), not ADC's, so All stays the list ADC itself defines; that view-as goes to Organizer because ADC has no Admin role, and the framework never lets an account holding it be viewed, so one organizer cannot view another (ADR-137); and that AdministrationPermissions.ViewAuditTrail (audit:view) gates the three services' audit-history endpoints and history panels, granted here once because the token-minting host reads this map, and to Organizer only. The body is one call, permissions.Grant(RoleNames.Organizer, [...]) (:42-51), whose list spreads IdentityPermissions.All and then names UsersManage, RolesManage, UsersViewAs, ClientsManage and AdministrationPermissions.ViewAuditTrail (:45-50).
  • Why it's built this way: a dedicated Apply method, rather than inline calls at the module's DependencyInjection, gives the grant a single, independently testable entry point that both the in-process API host and the token-minting Identity service call, whose TokenService turns the registry's grants into the permission claims a downstream service reads (:5-10).
  • Where it's used: passed to services.AddPermissions(IdentityPermissionGrants.Apply) in the API layer's registration (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/DependencyInjection.cs:44) and called as IdentityPermissionGrants.Apply(permissions) from the Identity service's TokenPermissionGrants (MMCA.ADC/Source/Services/MMCA.ADC.Identity.Service/Authorization/TokenPermissionGrants.cs:55), so the in-process host and the standalone service register the identical grant.

DependencyInjection

MMCA.ADC.Identity.Infrastructure · MMCA.ADC.Identity.Infrastructure · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Infrastructure/DependencyInjection.cs:13 · Level 5 · class (static)

  • What it is: the Infrastructure-layer DI entry point for the Identity module. It registers exactly one service: AddModuleIdentityInfrastructure() binds the avatar image processor, SkiaSharpImageProcessor, behind the Application-layer IImageProcessor port as a singleton, then returns the IServiceCollection (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Infrastructure/DependencyInjection.cs:23-27).
  • Depends on: Microsoft.Extensions.DependencyInjection.IServiceCollection and the TryAddSingleton extension from Microsoft.Extensions.DependencyInjection.Extensions (NuGet, imported at DependencyInjection.cs:1-2); first-party, IImageProcessor (MMCA.ADC.Identity.Application.Users, imported at DependencyInjection.cs:3) and SkiaSharpImageProcessor (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Infrastructure/Services/Users/SkiaSharpImageProcessor.cs:16, imported at DependencyInjection.cs:4).
  • Concept: the extension(IServiceCollection) registration idiom, taught once in the primer. C# preview extension members let each layer contribute an AddModule{Name}{Layer}() method that reads like a built-in IServiceCollection API. [Rubric §3, Clean Architecture] assesses layer discipline, and this class is the point where it pays off: the Application layer owns the IImageProcessor abstraction, the Infrastructure layer owns the SkiaSharp adapter and the binding between the two, and the API layer composes it without ever referencing SkiaSharp. [Rubric §15, Best Practices & Code Quality] assesses uniform, predictable structure: every module and layer exposes the same AddModule{Name}{Layer}() shape, so the composition root never special-cases Identity.
  • Walkthrough: a single extension(IServiceCollection services) block (DependencyInjection.cs:15) exposing public IServiceCollection AddModuleIdentityInfrastructure() (DependencyInjection.cs:23), whose body is services.TryAddSingleton<IImageProcessor, SkiaSharpImageProcessor>(); (:25) followed by return services; (:26) for chaining. The method's XML doc (DependencyInjection.cs:17-21) gives the reasons for both choices: the processor is stateless, so one instance serves every request, and its native library loads on the first upload, not at registration (BR-116a, ADR-045). The class-level doc (DependencyInjection.cs:8-12) records what is not registered here: the EF configurations are discovered by assembly scanning, and the seeder is constructed by the API layer's IdentityModuleSeeder. That matches the layer's contents: besides this file, the project holds the two markers above, IdentityModuleDbSeeder, UserConfiguration and SkiaSharpImageProcessor; it declares no DbContext of its own, since each engine has one sealed context over Common's ApplicationDbContext (ADR-006).
  • Why it's built this way: TryAdd rather than Add means the first registration wins, so a test host or another composition step that registered its own IImageProcessor earlier is not overridden. Keeping the SkiaSharp binding in Infrastructure is what lets the avatar use cases (SetUserAvatarHandler) depend only on the port (ADR-045).
  • Where it's used: invoked from the API layer's AddIdentityModule(...) at MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/DependencyInjection.cs:24, between AddModuleIdentityApplication(applicationSettings) (:28) and AddModuleIdentityAPI() (:30). That composite is called in turn by IdentityModule.Register (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/IdentityModule.cs:18-19), the IModule contract from G14 (IdentityModule.cs:12).
  • Caveats / not-in-source: the Identity module ships one DependencyInjection class per layer (this Infrastructure one plus the API, Application, Contracts and UI copies covered in sibling parts of this chapter). They all slug to the bare dependencyinjection anchor, which resolves to the first occurrence in the assembled chapter, so cross-references disambiguate by layer in prose.

IdentityRoutePaths

MMCA.ADC.Identity.UI · MMCA.ADC.Identity.UI · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.UI/IdentityRoutePaths.cs:6 · Level 0 · class (static)

  • What it is: the route strings and route-builder helpers the Identity UI module owns: /users, /profile, /roles, /users/support-access, /users/machine-clients, /confirm-email, plus two parameterized builders for a specific user's detail page and a specific role's edit page (ADR-116).
  • Depends on: UserIdentifierType (the Identity identifier alias, UserDetail's parameter); externals: BCL System.Globalization.CultureInfo (UserDetail's culture-invariant interpolation) and System.Uri (RoleEdit's Uri.EscapeDataString).
  • Concept reinforced, route constants as the module's public navigation surface. [Rubric §25, Navigation and Information Architecture] (assesses whether routes are declared in one place so menu entries, redirects, and tests cannot drift from the pages themselves) and [Rubric §15, Best Practices & Code Quality]. The nav items in IdentityUIModule reference IdentityRoutePaths.Profile, .Users, .Roles, .SupportAccess and .MachineClients (IdentityUIModule.cs:27-44) rather than repeating the strings, so renaming a route is a one-line change here.
  • Walkthrough: six public static readonly string fields on a public static class (IdentityRoutePaths.cs:6): Users = "/users" (:8), Profile = "/profile" (:9), Roles = "/roles" (:12, the ADR-116 role-administration roster), SupportAccess = "/users/support-access" (:15, the log of every read-only view-as grant, ADR-137), MachineClients = "/users/machine-clients" (:18, the credentials programs sign in with, ADR-140) and ConfirmEmail = "/confirm-email" (:21, the anonymous landing page for the emailed confirmation link). The two newer administration routes nest under /users rather than taking a top-level segment of their own. Two parameterized builders follow: UserDetail(UserIdentifierType userId) (:28-29), which culture-invariantly interpolates {Users}/{userId}, and RoleEdit(string role) (:38-39), which interpolates {Roles}/{Uri.EscapeDataString(role ?? string.Empty)}. The doc comment on RoleEdit (:31-37) explains why the role name IS the key: a role has no surrogate id anywhere in the system, so the registry, the grant table and the token all name it by its string, and the value is escaped because a role name can contain characters a raw URL segment cannot.
  • Caveats / not-in-source: the @page directives on UserList, Profile, RoleList and RoleEdit still spell their route literally, because a Razor @page directive requires a compile-time const, and these are static readonly fields, not const. So this type is the single source of truth for navigation and for building a link to a specific detail, not for the page routing attribute itself.
  • Where it's used: IdentityUIModule's NavItems, UserDetail's own page (UserDetail.razor.cs), and the UI tests (MMCA.ADC/Tests/Modules/Identity/MMCA.ADC.Identity.UI.Tests/IdentityUIModuleTests.cs, Pages/Roles/RoleListTests.cs, Pages/Roles/RoleEditTests.cs, Pages/Users/MachineClientsPageTests.cs).

UserDataExportBookmarkDTO

MMCA.ADC.Identity.Shared · MMCA.ADC.Identity.Shared.Users.DataExport · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Shared/Users/DataExport/UserDataExportBookmarkDTO.cs:7 · Level 0 · record (sealed)

  • What it is: one session-bookmark row inside the Engagement section of a data-subject export: which session the user bookmarked and when.
  • Depends on: the SessionIdentifierType alias; BCL (DateTime).
  • Concept introduced, the export row DTO (ids and dates only). [Rubric §30, Compliance, Privacy and Data Governance] (assesses whether a data-subject access or portability request returns the subject's own data, and only that). The doc comment (UserDataExportBookmarkDTO.cs:3-6) ties the shape directly to PRIVACY.md §7. Note what is not here: no session title, no speaker, no other user's activity. The export carries the personal fact ("you bookmarked session X at time T") rather than a denormalized copy of another context's catalog, which keeps the Identity service from becoming an accidental read model of Conference data.
  • Walkthrough: two required init members, SessionId (UserDataExportBookmarkDTO.cs:10) and CreatedOn, documented as UTC (:13). required means the producing section cannot forget a field, and init makes the row immutable once produced (the required/init immutability convention from the primer).
  • Where it's used: built by EngagementUserDataExportSection from the Engagement peer's response, in a [.. export.Bookmarks.Select(...)] spread (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/ExportUserData/EngagementUserDataExportSection.cs:37-41), and carried inside UserDataExportEngagementSectionDTO (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Shared/Users/DataExport/UserDataExportEngagementSectionDTO.cs:17). The source aggregate on the far side is UserSessionBookmark.

UserDataExportCheckInDTO

MMCA.ADC.Identity.Shared · MMCA.ADC.Identity.Shared.Users.DataExport · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Shared/Users/DataExport/UserDataExportCheckInDTO.cs:8 · Level 0 · record (sealed)

  • What it is: one attendance row in the Engagement section of a data-subject export: what the attendee was checked in to (a session, a sponsor booth, or the event itself) and when.
  • Depends on: the EventIdentifierType, SessionIdentifierType and SponsorIdentifierType aliases; BCL (DateTimeOffset).
  • Concept: the same export-row shape UserDataExportBookmarkDTO introduces, with one policy worth reading carefully. The doc comment (UserDataExportCheckInDTO.cs:3-7) records that check-ins are reported independently of the points ledger, "since a check-in that earned no points still leaves an attendance record". [Rubric §30, Compliance, Privacy and Data Governance] (assesses completeness of a subject access response): had the export derived attendance from UserDataExportPointsEntryDTO rows, a repeat scan or a scan outside the awarding window would be personal data the system holds and the export never mentions. Two independent lists is the honest answer.
  • Walkthrough: five members (UserDataExportCheckInDTO.cs:11-23). Scope (:11) is a required string, documented as the readable name of what the check-in attests to (for example "Session"); EventId (:14) is a required EventIdentifierType and documented as always set for every scope, which is what makes the row self-locating. SessionId (:17, SessionIdentifierType?) and SponsorId (:20, SponsorIdentifierType?) are nullable aliases, each set only for its own scope, so the row is a discriminated shape expressed with nullability rather than a type hierarchy. CheckedInOn (:23) is a required DateTimeOffset: unlike the sibling rows, which carry DateTime and depend on the producer to stamp UTC, this one carries its offset on the wire.
  • Why it's built this way: Scope is a string and not the CheckInScope enum, and the mapping site says why in a comment: "the export document is read by the data subject, so the scope travels as its readable name rather than a number" (EngagementUserDataExportSection.cs:60-61). A numeric enum value in a portable document is meaningless to the person it was produced for, and it silently re-numbers if the enum is ever reordered. The check-in and points data itself arrives via ADR-072.
  • Where it's used: projected by EngagementUserDataExportSection from UserEngagementCheckInExportDTO rows (EngagementUserDataExportSection.cs:58-67, which copies the three ids straight through at :63-65), into the CheckIns list of UserDataExportEngagementSectionDTO (UserDataExportEngagementSectionDTO.cs:29).

UserDataExportFeedbackAnswerDTO

MMCA.ADC.Identity.Shared · MMCA.ADC.Identity.Shared.Users.DataExport · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Shared/Users/DataExport/UserDataExportFeedbackAnswerDTO.cs:8 · Level 0 · record (sealed)

  • What it is: one feedback answer the user authored, as it appears in the Conference section of a data-subject export. A session answer carries a session id, an event answer carries an event id, and the other is null.
  • Depends on: the QuestionIdentifierType, SessionIdentifierType and EventIdentifierType aliases; BCL (DateTime).
  • Concept: a flat export row, the same shape UserDataExportBookmarkDTO and its siblings use for the Engagement section ([Rubric §30, Compliance, Privacy and Data Governance], assesses whether the right of access covers free-text content the user wrote). The type doc (UserDataExportFeedbackAnswerDTO.cs:3-7) says the answer value is the user's own text or rating, "so it travels in full".
  • Walkthrough: five members. QuestionId (:11) and AnswerValue (:20) and CreatedOn (:23, UTC) are required; SessionId (:14) and EventId (:17) are nullable and mutually exclusive by convention (the doc comments at :13 and :16 say "or null for an event answer" and "or null for a session answer"). Nothing in the type enforces the exclusivity: it is produced by ConferenceUserDataExportSection, which sets only SessionId on session rows and only EventId on event rows (ConferenceUserDataExportSection.cs:36-49).
  • Where it's used: the element type of both lists on UserDataExportConferenceSectionDTO (UserDataExportConferenceSectionDTO.cs:13, :16).

UserDataExportNotificationDTO

MMCA.ADC.Identity.Shared · MMCA.ADC.Identity.Shared.Users.DataExport · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Shared/Users/DataExport/UserDataExportNotificationDTO.cs:8 · Level 0 · record (sealed)

  • What it is: one notification-inbox row in the Notifications section of a data-subject export: the notification id, its title, the sent/read timestamps, and the scope the notification was sent under.
  • Depends on: the UserNotificationIdentifierType alias; BCL (DateTime).
  • Concept: the same export-row shape UserDataExportBookmarkDTO introduces ([Rubric §30, Compliance, Privacy and Data Governance]), with one extra nuance: it does include the Title text, because a notification's title is content that was addressed to this user, so it is part of their personal data rather than someone else's.
  • Walkthrough: six members (UserDataExportNotificationDTO.cs:11-30). NotificationId (:11), Title (:14), and SentOn (:17, documented UTC) are required init. The pair that describes read state is not: IsRead is a plain bool (:20) that defaults to false, and ReadOn is a nullable DateTime (:23) documented as null while unread. An unread row therefore simply carries the defaults, with no ceremony at the construction site. The last member, ScopeKey (:30), is a nullable string carrying the scope the notification was sent under (the doc gives event:1 as the example, :26-29), null for an unscoped notification; its doc states the reason it is exported at all, so the data subject can tell which conference a notification belonged to. That is a small but instructive privacy call: an inbox row without its scope is ambiguous to the reader of a multi-event export, and an ambiguous export is an incomplete one.
  • Where it's used: projected by NotificationUserDataExportSection from the Notification peer's rows (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/ExportUserData/NotificationUserDataExportSection.cs:35-43, with ScopeKey copied straight through at :42) into UserDataExportNotificationSectionDTO; the underlying entity is UserNotification.

UserDataExportPointsEntryDTO

MMCA.ADC.Identity.Shared · MMCA.ADC.Identity.Shared.Users.DataExport · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Shared/Users/DataExport/UserDataExportPointsEntryDTO.cs:7 · Level 0 · record (sealed)

  • What it is: one awarded-points row in the Engagement section of a data-subject export: what the attendee did, how many points it was worth, what it was scoped to, and when.
  • Depends on: nothing first-party; BCL (DateTime).
  • Concept: the same export-row shape as UserDataExportBookmarkDTO, applied to a gamification ledger. [Rubric §30, Compliance, Privacy and Data Governance]: a points ledger is derived data, not something the subject typed in, and it is still personal data the operator holds about them, so it is exported. The Points doc (UserDataExportPointsEntryDTO.cs:12) is precise about which number is reported: "as configured at award time", not recomputed from today's configuration, so the export reproduces what the ledger actually recorded rather than what the current rules would say.
  • Walkthrough: four required init members (UserDataExportPointsEntryDTO.cs:10-19). ActivityType (:10) is a string carrying the readable activity name (for example "SessionCheckIn"), Points (:13) the awarded amount, SubjectKey (:16) the subject the award was scoped to (documented as, for example, the session key), and CreatedOn (:19) the UTC timestamp.
  • Why it's built this way: same reason as UserDataExportCheckInDTO's Scope. The producing section maps p.ActivityType.ToString() off the PointsActivityType enum with the rationale in a comment: the document is read by the data subject, so the activity travels as its readable name "(the same choice the Role field makes) rather than a number" (EngagementUserDataExportSection.cs:51-53).
  • Where it's used: projected by EngagementUserDataExportSection from UserEngagementPointsEntryExportDTO rows (EngagementUserDataExportSection.cs:49-57) into the PointsEntries list of UserDataExportEngagementSectionDTO (UserDataExportEngagementSectionDTO.cs:23); the owning aggregate on the far side is PointsEntry.

UserDataExportPollVoteDTO

MMCA.ADC.Identity.Shared · MMCA.ADC.Identity.Shared.Users.DataExport · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Shared/Users/DataExport/UserDataExportPollVoteDTO.cs:7 · Level 0 · record (sealed)

  • What it is: one live-poll vote row in the Engagement section of a data-subject export: which poll the user voted in, which option they picked, and when.
  • Depends on: the LivePollIdentifierType and LivePollOptionIdentifierType aliases; BCL (DateTime).
  • Concept: the same export-row shape UserDataExportBookmarkDTO introduces ([Rubric §30, Compliance, Privacy and Data Governance]): ids and a date only. The row records the personal fact ("you chose option O in poll P at time T") and leaves the poll text and the tally on the Engagement side, so the export does not copy other people's data or the catalog.
  • Walkthrough: three required init members: LivePollId (UserDataExportPollVoteDTO.cs:10), OptionId (:13), and CreatedOn (:16, documented UTC).
  • Where it's used: projected by EngagementUserDataExportSection from the peer's PollVotes rows (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/ExportUserData/EngagementUserDataExportSection.cs:68-73) into the PollVotes list of UserDataExportEngagementSectionDTO (UserDataExportEngagementSectionDTO.cs:32).

UserDataExportQuestionUpvoteDTO

MMCA.ADC.Identity.Shared · MMCA.ADC.Identity.Shared.Users.DataExport · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Shared/Users/DataExport/UserDataExportQuestionUpvoteDTO.cs:7 · Level 0 · record (sealed)

  • What it is: one question-upvote row in the Engagement section of a data-subject export: which session question the user upvoted and when.
  • Depends on: the SessionQuestionIdentifierType alias; BCL (DateTime).
  • Concept: the same export-row shape as UserDataExportBookmarkDTO ([Rubric §30, Compliance, Privacy and Data Governance]). It is the upvote counterpart of UserDataExportSubmittedQuestionDTO: questions the user wrote and questions the user merely endorsed are both personal activity, so they travel as two separate lists.
  • Walkthrough: two required init members: QuestionId (UserDataExportQuestionUpvoteDTO.cs:10) and CreatedOn (:13, documented UTC).
  • Where it's used: projected by EngagementUserDataExportSection (EngagementUserDataExportSection.cs:74-78) into the QuestionUpvotes list of UserDataExportEngagementSectionDTO (UserDataExportEngagementSectionDTO.cs:35).

UserDataExportSubjectDTO

MMCA.ADC.Identity.Shared · MMCA.ADC.Identity.Shared.Users.DataExport · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Shared/Users/DataExport/UserDataExportSubjectDTO.cs:16 · Level 0 · record (sealed)

  • What it is: the Identity-owned half of a data-subject export: everything the Identity service holds about one account, from the login email and role to the terms-consent record, display preferences and lock state. It is the Subject slot of the framework's export envelope, not the whole document.
  • Depends on: the UserIdentifierType and SpeakerIdentifierType aliases; BCL (DateTime). Notably it depends on nothing from MMCA.Common: the envelope types it plugs into declare that slot as object.
  • Concept introduced, the app-owned subject snapshot inside a framework-owned envelope. [Rubric §30, Compliance, Privacy and Data Governance] (assesses whether the right of access and portability is implemented as a real, complete, machine-readable artifact) and [Rubric §11, Security] (assesses that secrets never reach a serialization boundary). The type doc (UserDataExportSubjectDTO.cs:3-8) names the exclusions and the reason: the password hash and salt, the refresh token, and the opaque external-provider key are secrets, not portable personal data, so exporting them would create a credential-leak channel out of a privacy feature. The remarks block (:9-15) records the split that ADR-076 introduced: this type is the Subject of UserDataExportDTO in MMCA.Common.Shared.Privacy, and the cross-service data travels beside it as section envelopes, each aggregated best-effort. The framework owns the envelope, each app owns which of its own fields are portable, which is exactly why the envelope's Subject property is typed object and serializes by runtime type (MMCA.Common/Source/Core/MMCA.Common.Shared/Privacy/UserDataExportDTO.cs:32-40).
  • Walkthrough
    • Identity account fields (UserDataExportSubjectDTO.cs:19-34): required UserId (:19), Email (:22), FirstName (:25), LastName (:28), FullName (:31), and Role (:34, documented as Attendee, Organizer or ContentEditor at :33).
    • External-login fields (:37, :40): IsExternalLogin and the provider name only; the doc on LoginProvider (:39) restates that the opaque provider key is intentionally omitted.
    • Cross-context link and profile (:43, :46): the nullable LinkedSpeakerId (the scalar link to a Conference speaker, never a cross-database FK) and AvatarUrl (BR-116a). The record carries no device metadata: nothing about the MAUI client's device appears in the subject snapshot.
    • Audit timestamps (:49, :52): CreatedOn and nullable LastModifiedOn, both documented UTC, the same audit fields the framework stamps in SaveChangesAsync. ExportUserDataHandler re-stamps their DateTimeKind on the way out (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/ExportUserData/ExportUserDataHandler.cs:67-70) because SQL Server hands them back as Kind=Unspecified, which would serialize without the trailing Z the doc promises; the comment at :62-64 is the record of that.
    • Consent, preferences and account state (:55-70), all optional (init, no required): the consent record AcceptedTermsVersion (:55, the Terms of Service version accepted, null when none) and TermsAcceptedOn (:58, UTC, null when never); the two display preferences PreferredCulture (:61) and PreferredTheme (:64, "light" or "dark", null to follow the OS); IsEmailConfirmed (:67, a plain bool); and LockedOn (:70, UTC, null when an organizer has not locked the account). The handler's comment (ExportUserDataHandler.cs:71-72, tagged M244) gives the reason they are in the export: these are personal data held on the account row too. The two timestamps get the same SpecifyKind treatment (:72-74, :78-80).
  • Why it's built this way: ADR-076 split the export handler in two, an orchestration that is identical in ADC and Store (authorize, load, fan out, degrade, envelope) and a projection that names app types and therefore cannot be shared. This record is that projection. Keeping it flat and required-heavy means the compiler catches a snapshot that forgets a field, and keeping it in Shared lets the API, the UI, and the tests name it without referencing the Domain assembly. Together with the erasure path on the User aggregate (ADR-005), it is the read half of the privacy pair: export what we hold, then anonymize it on request.
  • Where it's used: assembled by ExportUserDataHandler in one object initializer (ExportUserDataHandler.cs:52-83) and returned as the object? subject (:83); the shared base then stamps it into the envelope's Subject alongside a FormatVersion of "1.0" and the section list (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/ExportUserData/ExportUserDataHandlerBase.cs:74, :129-136). The whole envelope is served by UsersDataExportController, a subclass of the framework's DataExportControllerBase<TQuery> that supplies only the Users route and the ADC query factory (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/Controllers/UsersDataExportController.cs:26-35).
  • Caveats / not-in-source: the endpoint that serves this record is feature-gated, not always on. The base carries [Authorize] and [FeatureGate(PrivacyFeatures.DataExport)] at the class level (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Privacy/DataExportControllerBase.cs:59-60), so GET /Users/{userId}/export (:77) returns 404 in a host that has not enabled PrivacyFeatures.DataExport. Whether any given deployed environment has that flag on is configuration, not code: Not determinable from source which environments currently serve it.

UserDataExportSubmittedQuestionDTO

MMCA.ADC.Identity.Shared · MMCA.ADC.Identity.Shared.Users.DataExport · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Shared/Users/DataExport/UserDataExportSubmittedQuestionDTO.cs:7 · Level 0 · record (sealed)

  • What it is: one submitted session-question row in the Engagement section of a data-subject export: the question id, the session it was asked in, and when it was submitted.
  • Depends on: the SessionQuestionIdentifierType and SessionIdentifierType aliases; BCL (DateTime).
  • Concept: the same export-row shape as UserDataExportBookmarkDTO, and the sharpest illustration of its restraint. The doc comment (UserDataExportSubmittedQuestionDTO.cs:3-6) spells the rule out: ids plus submission date only, never other users' data. The question text and its upvote count are omitted, so an export cannot be turned into a scrape of the live question feed ([Rubric §30, Compliance, Privacy and Data Governance], [Rubric §11, Security]).
  • Walkthrough: three required init members, QuestionId (UserDataExportSubmittedQuestionDTO.cs:10), SessionId (:13), and CreatedOn in UTC (:16).
  • Where it's used: carried in UserDataExportEngagementSectionDTO's SubmittedQuestions (UserDataExportEngagementSectionDTO.cs:20), populated by EngagementUserDataExportSection (EngagementUserDataExportSection.cs:42-48); the source aggregate is SessionQuestion in the Engagement live layer.

UserDataExportTicketDTO

MMCA.ADC.Identity.Shared · MMCA.ADC.Identity.Shared.Users.DataExport.Tickets · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Shared/Users/DataExport/Tickets/UserDataExportTicketDTO.cs:8 · Level 0 · record (sealed)

  • What it is: one roster ticket linked to the user, as a row in the Engagement section of a data-subject export: the TicketLeap fields imported for the ticket and how it came to be linked to the account (BR-274).
  • Depends on: the EventIdentifierType alias; BCL (DateTimeOffset).
  • Concept: the same export-row shape as UserDataExportBookmarkDTO, applied to data the system did not collect from the user directly. The doc comment (UserDataExportTicketDTO.cs:3-7) scopes it to the ticket fields that were imported plus the link record. A roster import puts a third party's record of the person (the name and order email on a ticket) into the system, and a subject access response that omitted it would leave out personal data the system holds ([Rubric §30, Compliance, Privacy and Data Governance]).
  • Walkthrough: ten members (UserDataExportTicketDTO.cs:11-38). EventId (:11, required EventIdentifierType) locates the row. Four required string fields carry the TicketLeap identity of the ticket: SourceEventName (:14, the TicketLeap event it was sold under), ExternalTicketId (:17), and TicketTypeName (:20). The attendee name printed on the ticket follows as AttendeeFirstName (:23) and AttendeeLastName (:26), both required. Two members are optional: OrderEmail (:29, null when the order carried none) and InvitedOn (:32, DateTimeOffset?, null when no invite was sent). The link record closes the row: LinkMethod (:35, a required string holding the readable name, for example "Barcode") and LinkedOn (:38, required DateTimeOffset).
  • Why it's built this way: LinkMethod is a string and not the enum it comes from. The mapping site makes the same choice it makes for activity types, with the comment "the readable name, not a number" (EngagementUserDataExportSection.cs:90-91), because the document is read by the data subject and a numeric enum value means nothing to them. Both timestamps are DateTimeOffset, so the offset travels on the wire, as on UserDataExportCheckInDTO.
  • Where it's used: projected field by field by EngagementUserDataExportSection from the Engagement export's Tickets (EngagementUserDataExportSection.cs:79-93) into the Tickets list of UserDataExportEngagementSectionDTO (UserDataExportEngagementSectionDTO.cs:38).

UserDataExportConferenceSectionDTO

MMCA.ADC.Identity.Shared · MMCA.ADC.Identity.Shared.Users.DataExport · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Shared/Users/DataExport/UserDataExportConferenceSectionDTO.cs:10 · Level 1 · record (sealed)

  • What it is: the Conference-owned payload of a data-subject export: the session feedback answers and the event feedback answers the user authored.
  • Depends on: UserDataExportFeedbackAnswerDTO.
  • Concept: the same section payload UserDataExportEngagementSectionDTO introduces, applied to a third peer ([Rubric §29, Resilience and Business Continuity]). The type doc (UserDataExportConferenceSectionDTO.cs:3-9) repeats the contract: aggregation is best-effort, and when the Conference peer stays unreachable after the standard resilience pipeline the export still succeeds and the enclosing envelope reports Available = false, because "reachability lives on the envelope, never here".
  • Walkthrough: two members, both IReadOnlyList<UserDataExportFeedbackAnswerDTO> defaulting to []: SessionFeedbackAnswers (:13) and EventFeedbackAnswers (:16). Neither is required, so an empty list is a truthful "no answers" result.
  • Why it's built this way: the doc on ConferenceUserDataExportSection (ConferenceUserDataExportSection.cs:7-17, tagged M244) records the motive: without this section the export left the free-text feedback out silently. Transport failures are deliberately not caught in the section, so a peer failure degrades only this section to Available = false instead of failing the whole export.
  • Where it's used: constructed by ConferenceUserDataExportSection from the Conference peer's IUserConferenceExportService.GetUserConferenceExportAsync result (ConferenceUserDataExportSection.cs:30-50) and returned via UserDataExportSectionResult.Complete(SectionName, data) (:52). It is registered third, after the Engagement and Notification sections (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/DependencyInjection.cs:66-68).

UserDataExportEngagementSectionDTO

MMCA.ADC.Identity.Shared · MMCA.ADC.Identity.Shared.Users.DataExport · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Shared/Users/DataExport/UserDataExportEngagementSectionDTO.cs:14 · Level 1 · record (sealed)

  • What it is: the Engagement-owned payload of a data-subject export: the user's session bookmarks, submitted session questions, points ledger, check-in history, and leaderboard participation.
  • Depends on: UserDataExportBookmarkDTO, UserDataExportSubmittedQuestionDTO, UserDataExportPointsEntryDTO, UserDataExportCheckInDTO, UserDataExportPollVoteDTO, UserDataExportQuestionUpvoteDTO.
  • Concept introduced, the section payload with reachability held one level up. [Rubric §29, Resilience and Business Continuity] (assesses whether a request that fans out to peers degrades instead of failing when one peer is down) and [Rubric §7, Microservices Readiness] (assesses that a cross-service aggregate does not turn every peer into a hard dependency). The interesting move in the export is that "Engagement is unreachable" is modelled as data rather than as an exception, so a GDPR request that cannot reach one peer still succeeds. What is worth reading carefully here is where that flag lives: not on this type. The doc comment (UserDataExportEngagementSectionDTO.cs:5-13) is explicit, "reachability lives on the envelope, never here", because the framework's UserDataExportSectionDTO owns Available and UnavailableReason (MMCA.Common/Source/Core/MMCA.Common.Shared/Privacy/UserDataExportDTO.cs:72, :88). This type is only the payload the envelope carries in its object? Data slot (:80). That is the ADR-076 split again: degradation semantics belong to the framework, the field list belongs to the app.
  • Walkthrough: eight members, none of them required, all six collections defaulting to an empty collection expression []. Bookmarks (UserDataExportEngagementSectionDTO.cs:17), SubmittedQuestions (:17), PointsEntries (:20), CheckIns (:26, whose doc at :22-25 records that it is reported independently of the points ledger), and the two conference-day live-layer lists PollVotes (:29, UserDataExportPollVoteDTO) and QuestionUpvotes (:32, UserDataExportQuestionUpvoteDTO). IsOnLeaderboard (:35) is a plain bool and LeaderboardDisplayName (:38) a nullable string documented as null when the user never opted in, which is how the export reports a privacy choice the user made and not just the data it produced.
  • Why it's built this way: the empty-list defaults mean a section that legitimately holds nothing for the user is a truthful Complete result with an empty payload, which the framework contract distinguishes from an unknown one (IUserDataExportSection, MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/ExportUserData/IUserDataExportSection.cs:8-14). The reader of an export can therefore tell "you had no bookmarks" apart from "we could not check", and neither of those states is expressible as a null list.
  • Where it's used: constructed by EngagementUserDataExportSection from UserEngagementExportDTO (EngagementUserDataExportSection.cs:35-96) and handed to UserDataExportSectionResult.Complete(SectionName, data) (:81); ExportUserDataHandlerBase<TUser, TQuery> then wraps it into a section envelope in RunSectionAsync (ExportUserDataHandlerBase.cs:194-212) and, on a thrown call, replaces it with an Available = false envelope carrying a generic reason instead (:213-226).

UserDataExportNotificationSectionDTO

MMCA.ADC.Identity.Shared · MMCA.ADC.Identity.Shared.Users.DataExport · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Shared/Users/DataExport/UserDataExportNotificationSectionDTO.cs:10 · Level 1 · record (sealed)

  • What it is: the Notification-owned payload of a data-subject export: the user's inbox rows, newest first.
  • Depends on: UserDataExportNotificationDTO.
  • Concept: structurally the same section payload UserDataExportEngagementSectionDTO introduces, applied to a second peer ([Rubric §29, Resilience and Business Continuity]), and carrying the same "reachability lives on the envelope, never here" contract in its doc comment (UserDataExportNotificationSectionDTO.cs:3-9). Two peers means two independent envelopes: the Notification service can be down while Engagement answers, and the export still returns everything it managed to gather, because the shared base runs each registered section through its own try/catch in a sequential loop (ExportUserDataHandlerBase.cs:123-127, :201-226). The loop is sequential on purpose, and the comment says why: the sections share the scoped unit of work and its DbContext, which is not thread-safe, and registration order is the published order of the document (:121-122).
  • Walkthrough: one member. IReadOnlyList<UserDataExportNotificationDTO> Notifications { get; init; } = [] (UserDataExportNotificationSectionDTO.cs:13), documented as newest first. The ordering is part of the contract but is produced by the peer, not enforced here.
  • Where it's used: constructed by NotificationUserDataExportSection (NotificationUserDataExportSection.cs:33-44) and returned via UserDataExportSectionResult.Complete(SectionName, data) (:46). It is the second of the two sections ADC registers, and the registration order is the document order: AddUserDataExportSection<EngagementUserDataExportSection>() then AddUserDataExportSection<NotificationUserDataExportSection>() (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/DependencyInjection.cs:66-67, with the ordering rationale in the comment at :38-41).

IdentityUIModule

MMCA.ADC.Identity.UI · MMCA.ADC.Identity.UI · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.UI/IdentityUIModule.cs:19 · Level 7 · class (sealed)

  • What it is: the Identity module's UI descriptor. It tells the shared Blazor shell three things: which navigation entries this module contributes, which layout component to host (the terms-acceptance gate), and which assembly to scan for routable components.
  • Depends on: IUIModule (the contract, IdentityUIModule.cs:6, :13), NavItem and NavSection from MMCA.Common.UI.Common (:3), IdentityRoutePaths and RoleNames from MMCA.Common.Shared.Auth (:2); externals: MudBlazor Icons.Material.Filled (:5), BCL System.Reflection.Assembly (:1).
  • Concept reinforced, the pluggable UI module descriptor. [Rubric §18, UI Architecture] (assesses whether the shell discovers features rather than hard-coding them) and [Rubric §25, Navigation and Information Architecture] (assesses that menu structure, role gating, and routes are declared next to the feature that owns them). The IUIModule contract is introduced in G15: a host collects every registered implementation, merges their NavItems into the sidebar, and passes their Assembly to the router's additional assemblies so pages in a Razor Class Library are found (ADR-067). The effect is that adding the Identity module to a host adds its pages and its menu entries in one registration, with no edit to the shell. [Rubric §11, Security] and [Rubric §27, Internationalization] both show up in the declarations below.
  • Walkthrough: three members.
    • NavItems (IdentityUIModule.cs:24-45), a collection-expression-initialized IReadOnlyList<NavItem> with three entries. "My Profile" points at IdentityRoutePaths.Profile with a Person icon in NavSection.User and no required role, so every signed-in user sees it (:21). "Users" points at IdentityRoutePaths.Users with a SupervisedUserCircle icon, passes RoleNames.Organizer as the RequiredRole positional argument, and sits in NavSection.Admin (:22), so the link is only rendered for organizers (MMCA.Common/Source/Presentation/MMCA.Common.UI/Common/NavItem.cs:5, :16). Note that this hides the entry: the actual enforcement is server-side on UsersController, whose list endpoint demands IdentityPermissions.UsersRead (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/Controllers/UsersController.cs:224). Menu gating is UX, not authorization.
    • The third entry, "Roles" (:28), points at IdentityRoutePaths.Roles with an AdminPanelSettings icon, and is gated on RoleNames.Organizer as RequiredRole, exactly like "Users". The comment above it (:24-27) states the reason: it is gated on exactly what the page guards on. /roles (RoleList) authorizes the Organizer role, so an entry gated on the role-administration capability would show a link that a holder of that capability without the Organizer role cannot open. The comment also names the maintenance rule: when the page guard changes, this gate changes with it, and NavItemGuardContractTests is the test that keeps the two in step.
    • Every entry passes typeof(IdentityUIModule) as the TitleResource argument, which per the NavItem contract turns "Nav.MyProfile", "Nav.Users" and "Nav.Roles" into resource keys resolved against this type's resources at render time, per circuit, so the menu follows the active culture; a key the resource type does not declare renders as the raw string, which keeps a not-yet-translated entry legible instead of blank (NavItem.cs:13-18, ADR-027).
    • LayoutComponentTypes { get; } = [typeof(TermsAcceptanceGate)] (:33): contributes the invisible-until-needed TermsAcceptanceGate (from MMCA.Common.UI.Components.Legal) as a layout component, which asks a signed-in user to accept the current Terms of Service when their accepted version is behind. It overrides the contract's empty default (MMCA.Common/Source/Presentation/MMCA.Common.UI/Common/Interfaces/IUIModule.cs:42). The source comment (:31-32) explains the placement: both the Web and the MAUI heads load the Identity UI module, so one registration covers every client.
    • Assembly => typeof(IdentityUIModule).Assembly (:35): the self-referencing assembly handle used for Blazor route discovery.
  • Why it's built this way: a descriptor class is the smallest thing that can carry declarative metadata into DI. Because it is a plain sealed class with no dependencies, it registers as a singleton and costs nothing at runtime, while keeping the sidebar's Identity section owned by the Identity module rather than by the host. Gating the Roles entry on the same role the page authorizes means the menu never offers a link the page would refuse; the cost is that the entry follows the page guard, not the capability, which is why the contract test pins the pair (ADR-116).
  • Where it's used: passed as the type argument to the framework's AddUIModule<TModule>() inside DependencyInjection.AddIdentityUI (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.UI/DependencyInjection.cs:24). That one call does both jobs: its assembly is the scan root (AddAssignableTypes(typeof(TModule).Assembly, typeof(IEntityService<,>), ...) registers every entity service as scoped) and it is the descriptor registration (AddSingleton<IUIModule, TModule>), at MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:490-500.

DependencyInjection

MMCA.ADC.Identity.UI · MMCA.ADC.Identity.UI · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.UI/DependencyInjection.cs:12 · Level 9 · class (static)

  • What it is: the one-call registration entry point for the Identity UI layer. AddIdentityUI() wires the module's entity services, its user-administration and role-administration clients (ADR-116), the support access log client (ADR-137), the machine-client administration client (ADR-140), its bespoke user service, and its IdentityUIModule descriptor into any Blazor host.
  • Depends on: IdentityUIModule, IUserUIService / UserService from MMCA.ADC.Identity.UI.Services, UserAdminDTO (the DTO the user-administration client closes over), and the framework's AddUIModule<TModule>(), AddUserAdministrationUI<TUserAdminDTO>(), AddRoleAdministrationUI(), AddSupportAccessLogUI() and AddMachineClientAdministrationUI() extensions from MMCA.Common.UI; externals: Microsoft.Extensions.DependencyInjection.IServiceCollection (:1).
  • Concept reinforced, the extension(IServiceCollection) registration block. [Rubric §15, Best Practices and Code Quality] (assesses idiomatic, current-language composition) and [Rubric §3, Clean Architecture] (assesses that each layer owns its own wiring instead of the host reaching into it). This file is the UI-layer instance of the convention used across all four repos: instead of a classic public static IServiceCollection AddX(this IServiceCollection services), the method lives inside a C# preview extension(IServiceCollection services) block (DependencyInjection.cs:14) and the receiver is named once for the whole block, which the class doc calls out explicitly (:8-11). Callers see an ordinary services.AddIdentityUI().
  • Walkthrough: AddIdentityUI() (DependencyInjection.cs:20-52) makes six registration calls and returns services for chaining (:51).
    • services.AddUIModule<IdentityUIModule>() (:24), the shared two-step prologue every module's Add{Module}UI() opens with, with the intent restated in the comment above it (:22-23). Inside MMCA.Common.UI that single call runs the framework's own assembly scan (AddAssignableTypes, no third-party scanning library) over the descriptor's assembly, registering every IEntityService<TEntityDTO, TIdentifierType> implementation under its implemented interfaces (ScanRegistration.ImplementedInterfaces) with a scoped lifetime, then registers the descriptor with AddSingleton<IUIModule, TModule> (MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:490-499). Convention over configuration: a new standard CRUD-shaped UI service needs no registration edit here.
    • services.AddUserAdministrationUI<UserAdminDTO>() (:31), the framework's client for the shared Admin/Users endpoints, gated server-side on users:manage. The comment above it (:26-30) is explicit that this is closed over ADC's own UserAdminDTO, which the user detail page reads and the shared user-administration list acts through, and that it is a different resource under a different permission from the "Users" roster nav entry, not more methods on that roster's client.
    • services.AddRoleAdministrationUI() (:36), the framework's client for the Admin/Roles endpoints, gated server-side on roles:manage. The comment above it (:33-35) explains it is non-generic, unlike the user-administration client, because a role is a string and a permission is a string, so there is no ADC DTO to close over.
    • services.AddSupportAccessLogUI() (:41), the framework's client for the Admin/ViewAsGrants endpoint (users:manage, ADR-137) that the shared SupportAccessLog component reads through. The comment above it (:38-40) records why it sits in the module rather than in each head: the Web, WebAssembly and MAUI clients all get it from this one call. In Common it is a single TryAddScoped<IViewAsGrantsUIService, ViewAsGrantsService>() (MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:383-388).
    • services.AddMachineClientAdministrationUI() (:46), the framework's client for the Admin/MachineClients endpoints (clients:manage, ADR-140) that the shared MachineClientAdmin component reads through, registered here for the same every-client reason (:43-45). In Common it is a single TryAddScoped<IMachineClientAdminUIService, MachineClientAdminService>() (MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:365-370).
    • An explicit services.AddScoped<IUserUIService, UserService>() (:49). The comment above it (:48) explains why this one is hand-written: users are a custom contract, not an IEntityService, so the scan cannot pick it up (the same asymmetry IUserUIService documents, because the Users API returns UserListDTO rather than an IBaseDTO-shaped entity DTO and exposes only list plus delete).
  • Why it's built this way: one host-facing method per module keeps the three hosts symmetric: they each call AddIdentityUI() and nothing else. The mix of shared scan helpers and generic and non-generic administration clients is deliberate, and the framework doc for AddUIModule<TModule>() (MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:479-483) records the ordering rationale: module-specific services are registered by the caller after the prologue, so a module whose service must win over a shared default still controls its own registration order. The four administration clients are each opt-in in Common (their docs state that nothing else in the framework calls them, MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:361-362 and :387-388), so Identity UI is where ADC opts in, once for every head. The email-confirmation client is not registered here: Common's shared UI registration supplies it with TryAddScoped<IEmailConfirmationUIService, EmailConfirmationUIService>() (MMCA.Common/Source/Presentation/MMCA.Common.UI/DependencyInjection.cs:203).
  • Where it's used: called by all three UI hosts, MMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI.Web/Program.cs:86 (Blazor Server), MMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI.Web.Client/Program.cs:53 (the WebAssembly client), and MMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI/MauiProgram.cs:137 (MAUI), which is what lets the same Razor Class Library render on web and mobile.
  • Caveats / not-in-source: the Identity module ships one DependencyInjection class per layer (this UI one plus the API, Application, and Infrastructure copies covered in sibling parts of this chapter). They all slug to the bare dependencyinjection anchor, which resolves to the first occurrence in the assembled chapter, so cross-references disambiguate by layer in prose.

RoleEdit

MMCA.ADC.Identity.UI · MMCA.ADC.Identity.UI.Pages.Roles · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.UI/Pages/Roles/RoleEdit.razor.cs:16 · Level 0 · class (partial)

  • What it is: the code-behind for the role permission-editor page: one [Parameter], the role name bound from the route.
  • Depends on: nothing beyond ComponentBase and the [Parameter] attribute (ASP.NET Core Components).
  • Concept: a minimal route-bound component parameter, the same shape used across the UI layer wherever a page's identity comes entirely from its URL segment; see IdentityRoutePaths.RoleEdit(role), the builder that constructs the link this page receives Role from.
  • Walkthrough: public string Role { get; set; } = string.Empty (RoleEdit.razor.cs:19-20), the role being edited, defaulted to empty and overwritten by route binding before first render.
  • Why it's built this way: a role has no surrogate id, so the route parameter is the role's own name; the page's Razor markup (not shown here) renders the permission editor against that name.
  • Where it's used: reached from IdentityRoutePaths.RoleEdit(role), which RoleList links to per row. Exercised by MMCA.ADC/Tests/Modules/Identity/MMCA.ADC.Identity.UI.Tests/Pages/Roles/RoleEditTests.cs and cross-checked for authorization by MMCA.ADC/Tests/Modules/Identity/MMCA.ADC.Identity.UI.Tests/IdentityRouteAuthorizationTests.cs.

RoleList

MMCA.ADC.Identity.UI · MMCA.ADC.Identity.UI.Pages.Roles · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.UI/Pages/Roles/RoleList.razor.cs:29 · Level 0 · class (partial)

  • What it is: the code-behind for the role-administration roster page (ADR-116); the class declaration carries no members of its own (public partial class RoleList : ComponentBase;, :27), so all behavior lives in the paired Razor markup.
  • Depends on: ComponentBase (ASP.NET Core Components) only, at this span.
  • Concept: a bare partial declaration is the minimum a routable Razor component needs when the markup file owns all state and logic; contrast with RoleEdit, whose code-behind at least carries a route parameter.
  • Why it's built this way: the roster page has no route parameters of its own (unlike the per-role editor), so there is nothing for the code-behind to declare; it exists only to anchor the @page "/roles" directive and the partial split from the .razor markup.
  • Where it's used: reached via IdentityRoutePaths.Roles, linked from IdentityUIModule's "Roles" nav item. Exercised by MMCA.ADC/Tests/Modules/Identity/MMCA.ADC.Identity.UI.Tests/Pages/Roles/RoleListTests.cs and IdentityRouteAuthorizationTests.cs.

SetUserAvatarCommand

MMCA.ADC.Identity.Application · MMCA.ADC.Identity.Application.Users.UseCases.SetUserAvatar · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/SetUserAvatar/SetUserAvatarCommand.cs:12 · Level 1 · record (sealed)

  • What it is: the CQRS command that sets (uploads or replaces) the signed-in user's avatar photo (BR-116a, ADR-045). It carries the owning UserId plus the raw uploaded image bytes, and declares its own execution timeout.
  • Depends on: UserIdentifierType (the Identity identifier alias), IHasTimeout (the timeout-declaring marker interface), and BCL System.ReadOnlyMemory<byte> for the payload and System.TimeSpan for the budget.
  • Concept: the upload-security pipeline this command feeds is taught in full at SetUserAvatarHandler. What matters here is the shape of the payload: Content is a ReadOnlyMemory<byte> of raw bytes, and the doc comment (SetUserAvatarCommand.cs:5-9) is explicit that the handler validates the true format from those bytes (magic bytes), not the client-declared content type, before re-encoding to the canonical 256x256 JPEG. [Rubric §11, Security] assesses input trust boundaries: carrying an opaque byte buffer rather than a client-typed stream forces the trust decision into the handler, where the format is sniffed instead of believed. [Rubric §12, Performance and Scalability]: implementing IHasTimeout gives the pipeline an explicit per-command execution budget rather than a global default.
  • Walkthrough: a positional record SetUserAvatarCommand(UserIdentifierType UserId, ReadOnlyMemory<byte> Content) : IHasTimeout (SetUserAvatarCommand.cs:12). UserId is controller-stamped from the authenticated principal and never client-supplied; Content is the uploaded image. The body adds one member, public TimeSpan Timeout => TimeSpan.FromSeconds(60) (:19-20), whose doc comment (:13-18) states the budget covers the re-encode plus the blob PUT: the source bytes are capped by the upload limit and the stored image is a fixed 256x256 JPEG, so sixty seconds exists to bound a storage call that never returns rather than to pace legitimate work.
  • Why it's built this way: modeling the upload as an immutable command with a read-only memory buffer keeps it inside the command pipeline like any other mutation, and hands the handler a view of the bytes it can sniff and re-encode without owning a disposable stream. Declaring IHasTimeout directly on the command keeps the budget next to the payload it bounds, rather than in a configuration file the reader has to cross-reference.
  • Where it's used: constructed by UsersController.SetAvatarAsync (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/Controllers/UsersController.cs:116), the [HttpPost("me/avatar")] multipart endpoint (:79). Three boundary guards run before the command is built: [Idempotent] (:80), the request ceiling [RequestSizeLimit(MaxAvatarRequestBytes)] (:81), and an explicit reject of a missing, empty or oversized file with the Avatar.InvalidUpload validation error (:92-98). Note the two distinct limits: MaxAvatarBytes = 2 * 1024 * 1024 is the image budget (BR-116a, 2 MB, :39), while MaxAvatarRequestBytes = MaxAvatarBytes + 64 * 1024 (:48) is the Kestrel request ceiling, padded by 64 KB of multipart headroom precisely so that a file at exactly 2 MB is refused by the friendly Avatar.InvalidUpload check instead of by a bare Kestrel 413 (:42-47). The stream is then buffered into a byte[] (:100-107). Handled by SetUserAvatarHandler, which returns a UserAvatarDTO carrying the new URL, and pre-screened by SetUserAvatarCommandValidator.

ConfirmEmailCommand

MMCA.ADC.Identity.Application · MMCA.ADC.Identity.Application.Users.UseCases.ConfirmEmail · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/ConfirmEmail/ConfirmEmailCommand.cs:11 · Level 1 · record (sealed)

  • What it is: ADC's command wrapper for redeeming an email-confirmation link (ADR-116). A single-member positional record that carries the shared ConfirmEmailRequest wire payload.
  • Depends on: ConfirmEmailRequest (the shared request DTO), ICommandWithRequest<ConfirmEmailRequest> (the marker that routes it through the shared request-validator convention, the same mechanism ForgotPasswordCommand uses).
  • Concept: the same anonymous-command shape ForgotPasswordCommand teaches: the caller has no session yet (the link is followed from an email client), so the command carries only the request payload and no authenticated user id.
  • Walkthrough: public sealed record ConfirmEmailCommand(ConfirmEmailRequest Request) : ICommandWithRequest<ConfirmEmailRequest> (ConfirmEmailCommand.cs:11-12). No body; Request is the whole payload.
  • Why it's built this way: routing through ICommandWithRequest<TRequest> gets the command an auto-registered IValidator<ConfirmEmailCommand> for free via CommandRequestValidator<TCommand, TRequest>, the same convention ForgotPasswordCommand relies on, so ADC supplies no bespoke validator for this command.
  • Where it's used: constructed by EmailConfirmationController and handled by ConfirmEmailHandler. Covered by MMCA.ADC/Tests/Modules/Identity/MMCA.ADC.Identity.API.Tests/Controllers/EmailConfirmationControllerTests.cs and MMCA.ADC/Tests/Modules/Identity/MMCA.ADC.Identity.Application.Tests/Users/UseCases/ConfirmEmail/ConfirmEmailHandlerTests.cs, and pinned by CommandValidatorCoverageTests.

ResetPasswordCommand

MMCA.ADC.Identity.Application · MMCA.ADC.Identity.Application.Users.UseCases.ResetPassword · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/ResetPassword/ResetPasswordCommand.cs:10 · Level 1 · record (sealed)

  • What it is: the second half of the forgot-password vertical (ADR-091). It carries the address, the single-use token from the reset email, and the new password, and nothing else: its one marker is the automatic-validation opt-in.
  • Depends on: ResetPasswordRequest (from MMCA.Common.Shared.Auth); ICommandWithRequest<out TRequest>.
  • Concept reinforced, the marker that opts into validation. Put this record next to ChangePreferencesCommand below and the marker system explains itself: both are one-line records, and the difference is that this one does implement ICommandWithRequest<ResetPasswordRequest> (ResetPasswordCommand.cs:11), which opts it into automatic CommandRequestValidator<TCommand, TRequest> registration, so the validating decorator runs ResetPasswordRequestValidator against the embedded payload before the handler ever sees the command. [Rubric §11, Security]: that validator includes StrongPasswordRules<T> over NewPassword (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Validation/ResetPasswordRequestValidator.cs:23), with the stated reason that a reset must not become a way around the complexity policy that registration and change-password enforce (:8-10). [Rubric §6, CQRS & Event-Driven]: notice there is no UserId parameter. The caller is anonymous at this point, so the account is not named by the request at all: it is recovered from the redeemed token inside the handler, which is what stops the endpoint from being usable to set an arbitrary account's password.
  • Walkthrough: a single-parameter positional record (ResetPasswordRequest Request) (ResetPasswordCommand.cs:10) implementing the single marker (:11), with no body. It names no cache to evict: query caching is a host opt-in (AddQueryCaching(), ADR-026) that no ADC host takes, so a cache-invalidation marker here would be inert (MMCA.ADC/Tests/Architecture/MMCA.ADC.Architecture.Tests/Cqrs/DecoratorPipelineOrderTests.cs:28-30). The payload itself is a readonly record struct of three strings, Email, Token, NewPassword (MMCA.Common/Source/Core/MMCA.Common.Shared/Auth/Requests/ResetPasswordRequest.cs:9-12), whose doc comment marks NewPassword as transmitted over TLS and never logged (:8).
  • Why it's built this way: the record stays application-side while its workflow lives in the framework, for the reason the base states in its own <remarks>: the command record stays app-side, matching ChangePasswordHandlerBase, and the base reads it only through ICommandWithRequest<ResetPasswordRequest> (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/ResetPassword/ResetPasswordHandlerBase.cs:24-27). That is the same hoist boundary the change-password vertical uses (see ChangePasswordCommand), so each application keeps its own record and its own marker set.
  • Where it's used: built by PasswordResetController's CreateResetPasswordCommand override, a single expression-bodied new(request) (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/Controllers/PasswordResetController.cs:39), behind POST /Auth/reset-password; handled by ResetPasswordHandler.

SetUserAvatarCommandValidator

MMCA.ADC.Identity.Application · MMCA.ADC.Identity.Application.Users.UseCases.SetUserAvatar · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/SetUserAvatar/SetUserAvatarCommandValidator.cs:17 · Level 1 · class (sealed)

  • What it is: the FluentValidation rule set for SetUserAvatarCommand (BR-116a, ADR-045). Three rules on one property: the content must be non-empty, at most 2 MB, and must sniff as a JPEG, PNG or WebP image.
  • Depends on: SetUserAvatarCommand (the validated type); ImageContentSniffer from MMCA.Common.Application (imported at SetUserAvatarCommandValidator.cs:2); the FluentValidation AbstractValidator<T> base (NuGet, imported at :1).
  • Concept, the pipeline-stage validator as a defense-in-depth copy rather than a single gate. Validators are discovered by the module's assembly scan (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/DependencyInjection.cs:72) and run by ValidatingCommandDecorator<TCommand, TResult>, which resolves every IValidator<TCommand> registered for the command (MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Decorators/ValidatingCommandDecorator.cs:33), runs them sequentially because a validator may reach the database through a scoped repository and a DbContext is not thread-safe (:69-83), and converts every failure into a domain Error via ValidationFailureExtensions.ToErrors (:82, implementation at MMCA.Common/Source/Core/MMCA.Common.Application/Extensions/ValidationFailureExtensions.cs:62-63), which passes an explicitly set code through unchanged (:56) and so is what carries the WithErrorCode(...) strings below out to the client. The decorator sits in front of the transaction, so a rejected upload never opens one. [Rubric §6, CQRS and Event-Driven] assesses whether cross-cutting concerns live in the pipeline rather than in handlers: validation here is a decorator stage, not handler code. [Rubric §11, Security] assesses input trust boundaries: the same magic-byte gate exists in two places on purpose, and the class remarks (SetUserAvatarCommandValidator.cs:9-16) spell out why. [Rubric §34, Architecture Governance]: this validator is one of the entries that left the frozen-exception list in CommandValidatorCoverageTests, whose doc records that the "commands carrying real payload with no rule" group "is now empty: those were written rather than frozen, which is the only way an entry should ever leave this list" (MMCA.ADC/Tests/Architecture/MMCA.ADC.Architecture.Tests/Cqrs/CommandValidatorCoverageTests.cs:12-15).
  • Walkthrough
    • internal const int MaxAvatarBytes = 2 * 1024 * 1024 (:20), the 2 MB ceiling, documented as BR-116a (:19). It restates the constant of the same name on UsersController (.../UsersController.cs:39) rather than sharing it, because the two live in different layers.
    • Rule 1, presence (:24-27): RuleFor(x => x.Content).Must(content => !content.IsEmpty) with the message "An avatar image is required." and error code Avatar.Content.Required.
    • Rule 2, size (:29-32): content.Length <= MaxAvatarBytes, error code Avatar.Content.TooLarge, with the byte count interpolated into the message (:31).
    • Rule 3, format (:34-38): ImageContentSniffer.IsAllowedImage(content.Span), guarded by .When(x => !x.Content.IsEmpty) (:36) so an empty upload reports only the presence failure rather than both. Error code Avatar.UnsupportedFormat, the same code SetUserAvatarHandler emits from its own gate.
  • Why it's built this way: the remarks (:9-16) state the design explicitly. Both rules are "the pipeline-stage copy of limits the app already enforces, moved in front of the transaction rather than replacing anything". The size ceiling exists here because a command "can also arrive from a caller that never crossed that endpoint" (an in-process dispatch, a future gRPC or messaging entry point), so the HTTP-layer [RequestSizeLimit] is not the only defense. The format rule duplicates the handler's sniff because the handler "owns the Avatar.UnsupportedFormat contract and the re-encode that follows": the handler's check is what guarantees the invariant even if this validator were never registered, and this one just fails faster and cheaper.
  • Where it's used: never referenced by name. It is registered by the convention scan at MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/DependencyInjection.cs:72 and resolved by the validating decorator as an IValidator<SetUserAvatarCommand>. A repository-wide search for the type name returns only its own declaration (:17) and its constructor (:22).
  • Caveats / not-in-source: there is no dedicated unit-test class for this validator in MMCA.ADC/Tests; its rules are exercised only indirectly. Note also that the three error codes it produces (Avatar.Content.Required, Avatar.Content.TooLarge, Avatar.UnsupportedFormat) are not the code the controller's own pre-check emits (Avatar.InvalidUpload, .../UsersController.cs:95), so an oversized upload arriving over HTTP is reported with the controller's code, and these codes surface only for a caller that bypasses the endpoint.

ChangePasswordCommand

MMCA.ADC.Identity.Application · MMCA.ADC.Identity.Application.Users.UseCases.ChangePassword · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/ChangePassword/ChangePasswordCommand.cs:12 · Level 2 · record (sealed)

  • What it is: the command for a self-service password change. It pairs the target UserId with the ChangePasswordRequest body and opts into automatic request validation.
  • Depends on: ChangePasswordRequest; the UserIdentifierType alias; and two framework markers, ICommandWithRequest<out TRequest> and IUserScopedCommand<out TRequest>.
  • Concept introduced, markers that each buy exactly one behavior. [Rubric §6, CQRS & Event-Driven] (a command is a named intention carrying exactly what the write needs) and [Rubric §2, Design Patterns]. The record has no body at all; everything it does beyond carrying its two values is expressed by which interfaces it lists (ChangePasswordCommand.cs:13).
    • ICommandWithRequest<ChangePasswordRequest> opts the command into automatic validation: the framework registers a CommandRequestValidator<TCommand, TRequest> that delegates to the registered IValidator<ChangePasswordRequest> through FluentValidation's SetValidator, with TryAdd semantics so an explicit command-level validator still wins (MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Contracts/ICommandWithRequest.cs:5-11).
    • No cache-invalidation marker. The framework offers the entity-keyed ICacheInvalidating<TEntity> (the generic form of ICacheInvalidating, whose default interface member supplies "{typeof(TEntity).FullName}:", MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Markers/ICacheInvalidating.cs:39-43), but the eviction it triggers lives in the caching decorator, and that decorator is registered only by the host opt-in AddQueryCaching() (ADR-026), which no ADC host takes (MMCA.ADC/Tests/Architecture/MMCA.ADC.Architecture.Tests/Cqrs/DecoratorPipelineOrderTests.cs:28-30). The ADC records therefore carry no such marker; ResetPasswordCommand likewise lists only ICommandWithRequest<ResetPasswordRequest> (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/ResetPassword/ResetPasswordCommand.cs:10-11).
    • IUserScopedCommand<ChangePasswordRequest> is the view the shared handler base reads the command through, and it changes no pipeline behavior on its own. Its doc comment records why the two are separate rather than merged: the automatic-validation opt-in is a per-application decision, and ADC and Store agree on it for password change but disagree for preferences (MMCA.Common/Source/Core/MMCA.Common.Application/Users/IUserScopedCommand.cs:6-12).
  • Walkthrough: a two-parameter positional record (UserIdentifierType UserId, ChangePasswordRequest Request) (ChangePasswordCommand.cs:12) whose declaration ends at the marker list with a semicolon (:13): it has no members of its own. UserId comes from the authenticated principal, Request from the body.
  • Why it's built this way: splitting "who" (the token) from "what" (the body) makes it structurally impossible for a request to target another account, and the shared handler base stays generic in TCommand precisely so each application can keep its own marker set on the record while sharing one workflow.
  • Where it's used: constructed by AuthController's CreateChangePasswordCommand override (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/Controllers/AuthController.cs:133-135) and handled by ChangePasswordHandler.

ChangePreferencesCommand

MMCA.ADC.Identity.Application · MMCA.ADC.Identity.Application.Users.UseCases.ChangePreferences · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/ChangePreferences/ChangePreferencesCommand.cs:11 · Level 2 · record (sealed)

  • What it is: the command that persists one user's culture and theme preferences, the write side of ADR-027 / ADR-028. It pairs the target UserId with the partial ChangePreferencesRequest.
  • Depends on: ChangePreferencesRequest; the UserIdentifierType alias (= int in this module); IUserScopedCommand<out TRequest>.
  • Concept reinforced, marker-driven pipeline behavior (introduced at ChangePasswordCommand). [Rubric §6, CQRS & Event-Driven] assesses whether a command is a named intention carrying exactly what the write needs. The instructive detail is what this record does not implement: the declaration lists only IUserScopedCommand<ChangePreferencesRequest> (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/ChangePreferences/ChangePreferencesCommand.cs:12), with no ICommandWithRequest<out TRequest>, so the framework's reflection loop never registers a CommandRequestValidator<TCommand, TRequest> bridge for it (MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.ModuleScanning.cs:86-100). IUserScopedCommand<out TRequest>'s own <remarks> records why the two markers are separate rather than merged: the automatic-validation opt-in is a per-application decision, and ADC and Store agree on it for the password change but disagree for preferences (MMCA.Common/Source/Core/MMCA.Common.Application/Users/IUserScopedCommand.cs:6-12). Declining the bridge is not the same as declining validation: ADC hand-writes ChangePreferencesCommandValidator directly over this command type, which AddValidatorsFromAssembly(moduleAssembly) picks up (DependencyInjection.ModuleScanning.cs:82) and the validating decorator runs. The aggregate still owns the last word regardless, because User.UpdatePreferences re-checks both values through UserInvariants (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Domain/Users/User.cs:532-545).
  • Walkthrough: a two-parameter positional record (UserIdentifierType UserId, ChangePreferencesRequest Request) (ChangePreferencesCommand.cs:11) with no body (:12). It declares no cache eviction: query caching is a host opt-in (AddQueryCaching(), ADR-026) that no ADC host takes (MMCA.ADC/Tests/Architecture/MMCA.ADC.Architecture.Tests/Cqrs/DecoratorPipelineOrderTests.cs:28-30), so there is no cached read for a preference change to make stale.
  • Why it's built this way: the command record stays application-side rather than moving into the framework alongside its handler, so each application keeps its own marker set while the payload record (ChangePreferencesRequest) is shared. The base's <remarks> records that split: each app declares its own command record, the same type parameter flows through its auth controller base and command validator, and the base reads it only through IUserScopedCommand<ChangePreferencesRequest> while the payload record is shared (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/ChangePreferences/ChangePreferencesHandlerBase.cs:16-19). The ADC record carries no cache-eviction marker, so the difference between the two applications that matters here is the validation route described above, not eviction.
  • Where it's used: constructed by AuthController's CreateChangePreferencesCommand override (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/Controllers/AuthController.cs:138-140) for the profile page and the app-bar culture and theme switchers; handled by ChangePreferencesHandler.

DeleteUserCommand

MMCA.ADC.Identity.Application · MMCA.ADC.Identity.Application.Users.UseCases.DeleteUser · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/DeleteUser/DeleteUserCommand.cs:18 · Level 2 · record (sealed)

  • What it is: the command that soft-deletes and erases a user account (UC-21). It carries the account being deleted and the authenticated caller, because deletion is one of the few operations where the caller may legitimately not be the subject.
  • Depends on: the UserIdentifierType alias; ITransactional; IUserOwnedRequest.
  • Concept introduced, the owner-or-privileged-role request shape. [Rubric §11, Security] assesses whether authorization decisions are made from data the caller cannot forge, and [Rubric §1, SOLID] covers why this is an interface rather than a naming convention. IUserOwnedRequest extends IUserScopedRequest with CurrentUserId and a nullable CurrentUserRole (MMCA.Common/Source/Core/MMCA.Common.Application/Users/IUserOwnedRequest.cs:8-19), which is exactly the triple the shared UserOwnershipRule needs to answer "may this caller act on that account". Both extra values are filled from the token by the controller, never from the body, so a client cannot claim a role it was not issued. Only two ADC use cases wear this shape, deletion and data export, and they are precisely the two that must let an Organizer act on someone else's row.
  • Concept introduced, marking erasure as one atomic write. [Rubric §29, Resilience & Business Continuity] and [Rubric §30, Compliance, Privacy & Data Governance]. The record implements ITransactional (DeleteUserCommand.cs:21), and its <remarks> (:7-14) explains why: the soft-delete flag, the anonymized personal data, the UserDeleted outbox row, and the internal-command row that schedules the avatar blob delete (ADR-114) all need to commit together or not at all. DeleteUserHandler's tail enrolls that internal-command row before the save, and an enrolled row is exactly what a transaction makes atomic with the change it belongs to; without ITransactional the schedule could flush ahead of a half-finished erasure.
  • Walkthrough: a three-parameter positional record, UserId, CurrentUserId, CurrentUserRole (DeleteUserCommand.cs:18-21), with no body: the two markers ITransactional and IUserOwnedRequest close the declaration (:21), and no cache-invalidation marker is listed because no ADC host opts into query caching (MMCA.ADC/Tests/Architecture/MMCA.ADC.Architecture.Tests/Cqrs/DecoratorPipelineOrderTests.cs:28-30). CurrentUserRole is string? because a token may carry no role claim at all, and the null case must resolve to "no privilege" rather than to an exception.
  • Why it's built this way: modelling the caller as part of the command, rather than reaching for an ambient HttpContext inside the handler, is what keeps the handler testable without a web host and keeps the Application layer free of ASP.NET types ([Rubric §3, Clean Architecture], [Rubric §14, Testability]).
  • Where it's used: constructed by UsersController's DeleteAsync from currentUserService.UserId and currentUserService.Role (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/Controllers/UsersController.cs:286, construction at :295); handled by DeleteUserHandler.

ChangePreferencesCommandValidator

MMCA.ADC.Identity.Application · MMCA.ADC.Identity.Application.Users.UseCases.ChangePreferences · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/ChangePreferences/ChangePreferencesCommandValidator.cs:10 · Level 9 · class (sealed)

  • What it is: the FluentValidation validator for ChangePreferencesCommand, declared as a one-line sealed subclass of the framework's ChangePreferencesCommandValidatorBase<TCommand> closed over ADC's command record (ChangePreferencesCommandValidator.cs:10). It carries no rules of its own: the base rejects an unsupported culture or an unknown theme at the edge of the pipeline, before a transaction opens, while treating a null field as "leave this preference unchanged".
  • Depends on: ChangePreferencesCommandValidatorBase<TCommand> (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/ChangePreferences/ChangePreferencesCommandValidatorBase.cs:29-30, an AbstractValidator<TCommand> constrained to IUserScopedCommand<ChangePreferencesRequest>); ChangePreferencesCommand; through the base, SupportedCultures.IsSupported (MMCA.Common/Source/Core/MMCA.Common.Shared/Globalization/SupportedCultures.cs:35-37) and CommonInvariants.EnsurePreferredThemeIsValid (MMCA.Common/Source/Core/MMCA.Common.Domain/Invariants/CommonInvariants.cs:158-164).
  • Concept introduced, the shared rule set with an app-assembly subclass. [Rubric §6, CQRS & Event-Driven], [Rubric §15, Best Practices & Code Quality]. The base's summary records that the app Identity modules used to carry near-identical copies of this validator (ChangePreferencesCommandValidatorBase.cs:8-13); the rules now live once in Common. The base is abstract, and ADC still needs this subclass, because module scanning registers validators from the app assemblies only (ChangePreferencesCommandValidator.cs:5-9, ChangePreferencesCommandValidatorBase.cs:18-20): AddValidatorsFromAssembly(moduleAssembly) (MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.ModuleScanning.cs:82) finds this sealed type in the ADC Identity Application assembly and registers it as IValidator<ChangePreferencesCommand>. It is the same split the handler side uses (ChangePreferencesHandlerBase<TUser, TCommand>, named in the base's remarks at :21).
  • Concept introduced, validating a command directly instead of through the request bridge. [Rubric §6, CQRS & Event-Driven] assesses where input rejection belongs in a command pipeline, and [Rubric §24, Forms, Validation & UX Safety] covers partial updates. Most ADC commands get their validator for free: they implement ICommandWithRequest<out TRequest>, and the framework registers a CommandRequestValidator<TCommand, TRequest> bridge that forwards to the payload's validator (DependencyInjection.ModuleScanning.cs:84-100). ChangePreferencesCommand carries its payload through IUserScopedCommand<TRequest> instead, which does not opt it into that bridge, so an IValidator<ChangePreferencesRequest> would never run; the base is therefore written against the command type (ChangePreferencesCommandValidatorBase.cs:15-18). Both routes land in the same place: ValidatingCommandDecorator<TCommand, TResult> resolves IEnumerable<IValidator<TCommand>> and runs every one it finds, sequentially, short-circuiting into a failure result before the transactional decorator is reached (MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Decorators/ValidatingCommandDecorator.cs:31-33, :74-76). The framework's own architecture fitness rule counts either route as coverage and fails a data-carrying command that has neither (MMCA.Common/Source/Hosting/MMCA.Common.Testing.Architecture/Rules/Cqrs/ArchitectureRules.CommandValidators.cs:9-31).
  • Concept introduced, the two-layer guard and why it is not a duplicated rule. [Rubric §4, DDD] assesses whether the aggregate remains the authority on its own invariants. The base's <remarks> states that the accepted values come from the same definitions the aggregate enforces, so this moves the rejection in front of the handler without a second definition of what is valid (ChangePreferencesCommandValidatorBase.cs:21-26). The theme rule makes that literal: its predicate BeAKnownTheme calls CommonInvariants.EnsurePreferredThemeIsValid and reads IsSuccess (:67-69), the same invariant ADC's UserInvariants.EnsurePreferredThemeIsValid delegates to (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Domain/Users/UserInvariants.cs:90-91). The aggregate side is User.UpdatePreferences, which combines the culture and theme checks and refuses to mutate on failure (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Domain/Users/User.cs:532-536). Read together, the validator gives a caller a 400 with a field-level error code instead of an opaque handler failure, and the domain still cannot be talked into an invalid state by a code path that skips the decorator (a seeder, a test, another module).
  • Walkthrough (all in the base constructor, ChangePreferencesCommandValidatorBase.cs:42-61)
    • RuleFor(c => c.Request).NotNull() (:45-46), with message "Preferences are required." and error code User.Preferences.Required (:34). Every rule carries an explicit WithErrorCode from a private constant (:33-40), which is what lets the UI bind the failure to a specific control rather than showing a banner.
    • An outer When(c => c.Request is not null, ...) (:48) wraps the two field rules, so a null body yields only the required-request failure.
    • Culture (:50-54): Must(SupportedCultures.IsSupported) with code User.PreferredCulture.Invalid, gated by .When(c => c.Request.Culture is not null). That When clause is the partial-update contract in code: a request that omits the culture is not validated for culture at all, because omitting it means "keep what is stored". SupportedCultures.IsSupported matches case-insensitively against the framework allowlist All (SupportedCultures.cs:35-37), so adding a locale is a change there and no change here (ADR-027).
    • Theme (:56-60): the same When shape over BeAKnownTheme, with code User.PreferredTheme.Invalid and a message naming the two accepted values from CommonInvariants.LightTheme ("light") and CommonInvariants.DarkTheme ("dark") (CommonInvariants.cs:16, :19). The invariant compares OrdinalIgnoreCase (CommonInvariants.cs:161-162) (ADR-028): the theme value round-trips through a client-side toggle and a cookie, and casing is not part of the meaning.
  • Why it's built this way: [Rubric §12, Performance & Scalability] and [Rubric §15, Best Practices & Code Quality]. Rejecting bad input before the transactional decorator means an invalid preference costs no database transaction and no cache eviction. Keeping the rules in one Common base, and having the theme predicate call the domain invariant rather than re-type "light" and "dark", is what keeps this validator from becoming a second, drifting definition of what is valid; the guard is duplicated in placement, not in content.
  • Where it's used: never referenced by name. It is discovered by the module-registration scan (DependencyInjection.ModuleScanning.cs:82) and injected into ValidatingCommandDecorator<TCommand, TResult> as one element of IEnumerable<IValidator<ChangePreferencesCommand>> around ChangePreferencesHandler.
  • Caveats / not-in-source: the NotNull rule on Request and the outer When both test c.Request is not null, even though ChangePreferencesRequest arrives from a deserialized body where the framework's nullable annotations do not bind; the defensive shape is what makes the validator safe against a body of null.

ChangePasswordHandler

MMCA.ADC.Identity.Application · MMCA.ADC.Identity.Application.Users.UseCases.ChangePassword · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/ChangePassword/ChangePasswordHandler.cs:24 · Level 9 · class (sealed)

  • What it is: ADC's change-password handler. The class body is empty: the whole workflow lives in the framework base ChangePasswordHandlerBase<TUser, TCommand>, and this type exists to bind the generic parameters and to keep the name.
  • Depends on: ChangePasswordHandlerBase<TUser, TCommand> (base), IUnitOfWork, IPasswordHasher, ILogger<T>, IRefreshSessionStore, ILoginProtectionService, TimeProvider, User, and ChangePasswordCommand.
  • Concept introduced, the name-preserving thin subclass. [Rubric §15, Best Practices & Code Quality] assesses de-duplication across applications, and [Rubric §9, API & Contract Design] covers why the class name survives the move. ADC and Store carried line-identical copies of this handler, so the workflow was hoisted into MMCA.Common (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/ChangePassword/ChangePasswordHandlerBase.cs:14-17). What could not be hoisted is the error payload: every failure the framework returns carries a source, the base defaults it to GetType().Name through a virtual HandlerName (ChangePasswordHandlerBase.cs:70-75), and clients match on the string ChangePasswordHandler. Keeping an empty subclass under the original name makes the hoist invisible on the wire, and the <remarks> says so outright (ChangePasswordHandler.cs:14-23). It is a small pattern with a large consequence: a refactor that would otherwise be a breaking API change becomes a no-op for consumers. The same shape recurs at ChangePreferencesHandler, GetUserPreferencesHandler, and (for the controller layer) at PasswordResetController and UsersDataExportController.
  • Concept introduced, revoking live sessions on a credential change (SEC-Common-02). [Rubric §11, Security]. The constructor takes IRefreshSessionStore and a TimeProvider, forwarded straight to the base (ChangePasswordHandler.cs:24-39), so a successful change revokes every live refresh session on the account (ChangePasswordHandlerBase.cs:121-128), not only the credential the caller just replaced. Without them a stolen refresh chain would outlive the very password change meant to remediate it, which is the one recovery step a compromised account has. ResetPasswordHandler carries the identical addition for the same reason.
  • Concept introduced, throttling the current-password check (ADR-029). [Rubric §11, Security]. The constructor also takes ILoginProtectionService, forwarded to the base (ChangePasswordHandler.cs:29, :36). A wrong current password counts against the account through the same failed-attempt counter and exponential lockout that guard sign-in, so a caller holding a session cannot use the endpoint as an unthrottled password oracle (ChangePasswordHandlerBase.cs:47-53). The counter is keyed password-change:{userId} rather than by email, because the authenticated user exposes no address and a separate key keeps a change-password lockout from locking the owner out of sign-in (ChangePasswordHandlerBase.cs:50-52).
  • Walkthrough: a primary constructor taking IUnitOfWork, IPasswordHasher, ILogger<ChangePasswordHandler>, IRefreshSessionStore, ILoginProtectionService and TimeProvider, forwarding all six to the base (ChangePasswordHandler.cs:24-37), with an empty body (:38-39). The inherited workflow (ChangePasswordHandlerBase.cs:78-136) is: null-guard the command (:69); load the user through the mutating repository and return Error.NotFound tagged with HandlerName when absent (:71-76); reject an account with no stored hash or salt (an external-OAuth account) with the same Error.Unauthorized("Auth.InvalidCurrentPassword", ...) (:82-86); return the lockout failure if the password-change key is locked (:88-93); verify the supplied current password with passwordHasher.VerifyPassword(command.Request.CurrentPassword, user.PasswordHash, user.PasswordSalt) and, on a mismatch, increment the failed-attempt counter and return Error.Unauthorized("Auth.InvalidCurrentPassword", ...) (:95-100); reset the counter on a match (:102); hash the new password into a fresh hash and salt pair (:104); call user.ChangePassword(newHash, newSalt) and, only when that succeeds, save, revoke every refresh session and log (:105-117); return the aggregate's Result unchanged (:119).
  • Why it's built this way: [Rubric §11, Security]. Note the division of responsibility the base encodes. Proving knowledge of the current password is a cryptographic operation, so it happens where the stored hash and salt are in hand, not in a request validator (a validator can only check that a value is present). The domain then applies its own invariants on the new credential material, and nothing is persisted unless both gates pass. The generic constraint where TUser : AuditableAggregateRootEntity<UserIdentifierType>, IPasswordChangeableUser (ChangePasswordHandlerBase.cs:62) is what lets the base call ChangePassword on an application's aggregate without knowing the concrete type, and the hashing scheme itself is ADR-032.
  • Where it's used: resolved as ICommandHandler<ChangePasswordCommand, Result> and injected into AuthController (AuthController.cs:37), which exposes it through the base's PUT /auth/password action; the Profile page is the client.

ChangePreferencesHandler

MMCA.ADC.Identity.Application · MMCA.ADC.Identity.Application.Users.UseCases.ChangePreferences · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/ChangePreferences/ChangePreferencesHandler.cs:17 · Level 9 · class (sealed)

  • What it is: ADC's change-preferences handler, an empty subclass. The whole workflow lives in ChangePreferencesHandlerBase<TUser, TCommand>; this type exists to bind the generic parameters and to keep the name.
  • Depends on: ChangePreferencesHandlerBase<TUser, TCommand> (base), IUnitOfWork, ILogger<T>, User, and ChangePreferencesCommand.
  • Concept reinforced, the name-preserving thin subclass (introduced at ChangePasswordHandler); the <remarks> here carries the same rationale, that the class name is kept so the source reported on every error stays ChangePreferencesHandler, which clients match on (ChangePreferencesHandler.cs:12-16). The behavior worth learning is the null-coalescing merge inside the base. [Rubric §27, Internationalization] assesses whether a locale choice survives a session, and [Rubric §24, Forms, Validation & UX Safety] covers partial updates. The merge is one expression (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/ChangePreferences/ChangePreferencesHandlerBase.cs:53-55): user.UpdatePreferences(command.Request.Culture ?? user.PreferredCulture, command.Request.Theme ?? user.PreferredTheme). A request carrying only a culture re-supplies the stored theme, and the reverse, which is precisely why the app-bar language switcher cannot wipe the user's dark-mode choice. It is also the same "null means unchanged" contract ChangePreferencesCommandValidator encodes with its When clauses one stage earlier.
  • Walkthrough: a primary constructor taking IUnitOfWork and ILogger<ChangePreferencesHandler> and forwarding both to the base (ChangePreferencesHandler.cs:17-20), with an empty body (:21-22). The inherited workflow (ChangePreferencesHandlerBase.cs:40-63): a null guard on the command (:44); load through the mutating repository, unitOfWork.GetRepository<TUser, UserIdentifierType>(), returning Error.NotFound.WithSource(HandlerName).WithTarget(typeof(TUser).Name) when absent (:46-51); the merge above (:53-55); then, only when the returned Result is a success, SaveChangesAsync plus the handler's own source-generated PreferencesChanged log (:56-60, declared at :65-66); return the result unchanged (:62). Value checking is not the handler's job: User.UpdatePreferences combines the culture allowlist and the light/dark rule and hands back a failure the handler simply propagates.
  • Why it's built this way: guarding both the save and the log behind IsSuccess means a rejected culture or theme produces a clean failure (a 400 at the edge) with no write and, just as importantly, no misleading "preferences changed" log line for an operator to chase later. The HandlerName indirection (ChangePreferencesHandlerBase.cs:37, GetType().Name) is what makes the empty subclass sufficient: the base reports the runtime type name, so the hoist is invisible on the wire.
  • Where it's used: resolved as ICommandHandler<ChangePreferencesCommand, Result> and injected into AuthController (AuthController.cs:38) as PUT /Auth/preferences; wrapped by the decorator pipeline, whose caching decorator performs the eviction declared on ChangePreferencesCommand.
  • Caveats / not-in-source: UpdatePreferences raises no domain event (User.cs:532-545), so a preference change writes the row and publishes nothing to the outbox.

DeleteUserHandler

MMCA.ADC.Identity.Application · MMCA.ADC.Identity.Application.Users.UseCases.DeleteUser · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/DeleteUser/DeleteUserHandler.cs:37 · Level 9 · class (sealed)

  • What it is: ADC's account-deletion handler (UC-21). Unlike the thin siblings it is not empty: it inherits the shared erasure workflow from DeleteUserHandlerBase<TUser, TCommand> and supplies the pieces its <remarks> names as ADC-specific (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/DeleteUser/DeleteUserHandler.cs:24-28): the Organizer role that bypasses ownership, the cross-service UserDeleted integration event, and a durable internal command that deletes the avatar blob. The class name is kept so the source reported on every error stays DeleteUserHandler, which clients match on (:22-24).
  • Depends on: DeleteUserHandlerBase<TUser, TCommand> (base), IUnitOfWork, IInternalCommandScheduler, ISoftDeletedUserMarkerWriter (taken only to forward to the base), IRefreshSessionStore and IViewAsGrantStore (both required, forwarded to the base, DeleteUserHandler.cs:43-45), TimeProvider, ILogger<T>, UserRole, UserDeleted (the Identity.Shared integration event), SetUserAvatarHandler (for its TryGetBlobName helper), DeleteAvatarBlobInternalCommand, and Result.
  • Concept introduced (1), erasure as a fixed workflow with application-specific hooks. [Rubric §30, Compliance, Privacy & Data Governance] assesses whether a deletion request actually destroys personal data. The base's HandleAsync (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/DeleteUser/DeleteUserHandlerBase.cs:117-222) runs a fixed order: null-guard the command (:121); check ownership through UserOwnershipRule.CheckOwnership using the application's HasDeletePrivilege answer, failing with User.DeleteForbidden (:123-133); load the user through the mutating repository, Error.NotFound when absent (:135-140); soft-delete (:150-155); run the application's tail (:157-162); anonymize (:164-169); revoke and anonymize the account's refresh-session rows through RefreshSessionRevocation.RevokeAndAnonymizeAllAsync (:171-178); blank the erased account's email on the support access log's view-as grants through viewAsGrants.ForgetUserAsync (:180-184, ADR-137); schedule a DeleteUserPushInstallationsInternalCommand so the account's native-push installations are deleted, failing the erasure if that cannot be scheduled (:186-197); save (:199); write the shared soft-deleted marker (:201-212); then run whatever post-save actions the tail enqueued (:214-217) and log the erasure (:219). The two-step delete-then-anonymize is ADR-005's resolution of a real tension: the row must survive because other bounded contexts hold scalar UserId references and the audit trail depends on it, but the personal data must not survive, because the privacy promise is erasure. One detail in the base rewards a second read (:147-151): it dispatches through IErasableUser erasable = user; rather than calling user.Delete() directly, so interface dispatch runs whichever Delete() the application's type maps onto IErasableUser, and a User that forgets the interface fails the TUser constraint at compile time (:103). ADC's User keeps the inherited soft-delete, which raises no domain event (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Domain/Users/User.cs:26-28): the erasure's only announcement is the integration event this handler raises.
  • Concept introduced (2), raising a cross-service integration event from inside the erasure. [Rubric §6, CQRS & Event-Driven] and [Rubric §30]. Personal data this account published into another service has to travel: Engagement holds a DisplayName snapshot on the leaderboard opt-in, Engagement is its own process with its own database, and only an integration event through the outbox reaches it. So the override calls user.AddDomainEvent(new UserDeleted(command.UserId, timeProvider.GetUtcNow())) (DeleteUserHandler.cs:71) on the aggregate, before the save. The comment (:65-70) states the invariant this buys: the outbox row is written by the very SaveChangesAsync that commits the erasure, so the fact and its announcement cannot come apart, whereas publishing after the commit would leave a crash window in which the account is gone and the published name is not. The event's own doc lists who acts on it (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Shared/Users/IntegrationEvents/UserDeleted.cs:11-19): Engagement takes the account off the leaderboard and erases its display name, deletes its bookmarks, badge, live-poll votes and question upvotes, erases its session questions, and anonymizes and unlinks its roster tickets; Conference anonymizes and unlinks the linked speaker profile's email and erases the account's feedback answers. The payload is deliberately just the id and a timestamp, because carrying a name or email would publish the very data the erasure exists to remove onto a broker that persists messages (:21-25).
  • Concept introduced (3), scheduling the blob delete as a durable internal command instead of a post-commit action. [Rubric §29, Resilience & Business Continuity] and [Rubric §30, Compliance, Privacy & Data Governance]. The hook signature takes the base's ICollection<Func<CancellationToken, Task>> afterCommit parameter (DeleteUserHandler.cs:55-59) and leaves it empty. When there is a blob, the hook calls ScheduleAvatarBlobDeletionAsync (:80-83), which enrolls a DeleteAvatarBlobInternalCommand row through ScheduleAsync (:90-92). Because this hook runs inside the erasure transaction, before SaveChangesAsync (DeleteUserHandlerBase.cs:158, :199), the scheduled row commits with the anonymized aggregate or rolls back with it (ADR-114), which is exactly why DeleteUserCommand is marked ITransactional (DeleteUserCommand.cs:18-21). The comment (DeleteUserHandler.cs:73-79) states the trade: an erasure that persists can never lose the instruction to delete the photo, which a best-effort post-commit call would whenever storage was unreachable or the host died in that tail; the framework's internal-command processor picks the row up on its next poll and retries it until storage answers. If the scheduling call itself fails, ScheduleAvatarBlobDeletionAsync returns Result.Failure(scheduled.Errors) (:97) rather than success, which fails the whole erasure: a partial erasure the caller was told succeeded is worse than a retryable failure (:94-96). The base applies the identical shape to the account's push installations (DeleteUserHandlerBase.cs:186-197).
  • Walkthrough
    • Constructor (DeleteUserHandler.cs:37-45): seven dependencies. unitOfWork, markerWriter, logger, refreshSessions, viewAsGrants and internalCommandScheduler are forwarded to DeleteUserHandlerBase<User, DeleteUserCommand> (:45); the scheduler is also kept in a private field for this type's own scheduling (:47), and timeProvider stamps only the integration event. Both stores are non-optional, matching the base, which takes them as required parameters (DeleteUserHandlerBase.cs:99-100); the <remarks> gives the reason, that no erasure step can be skipped by a missing registration (DeleteUserHandler.cs:33-35). timeProvider is not forwarded, so the base's own optional clock (DeleteUserHandlerBase.cs:102) stays at its system-clock default for the revocation stamps (:94). There is no logger field and no [LoggerMessage] partial here: both log lines on this path belong to the base (DeleteUserHandlerBase.cs:255-259).
    • HasDeletePrivilege (DeleteUserHandler.cs:49-52): UserRole.IsOrganizer(currentUserRole), whose implementation is an OrdinalIgnoreCase comparison (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Domain/Users/UserRole.cs:76), with a <remarks> noting it is case-insensitive because a role claim may carry any casing (:50). The base's abstract hook uses an Admin-role check as its example (DeleteUserHandlerBase.cs:224-230); this one override is where an application states its own privileged role.
    • OnAfterSoftDeleteAsync (DeleteUserHandler.cs:54-86): it first captures the avatar blob name before anonymization clears the URL (:61-63), reusing SetUserAvatarHandler.TryGetBlobName (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/SetUserAvatar/SetUserAvatarHandler.cs:203). That ordering is the whole reason the hook runs where it does: the base invokes it after Delete() and before Anonymize(), the only point where an app can still read the personal data anonymization is about to erase (DeleteUserHandlerBase.cs:49-52). It then raises the integration event (DeleteUserHandler.cs:71) and, only when there was a blob, schedules its durable deletion (:80-83); with no blob it returns Task.FromResult(Result.Success()) (:85).
    • ScheduleAvatarBlobDeletionAsync (:88-98): awaits _internalCommandScheduler.ScheduleAsync(new DeleteAvatarBlobInternalCommand(avatarBlobName), ...) (:90-92) and translates a failed schedule into Result.Failure(scheduled.Errors) (:97), which propagates up through OnAfterSoftDeleteAsync and aborts the erasure before anything is persisted (DeleteUserHandlerBase.cs:159-162, the hook contract at :234).
    • Marker failure policy (DeleteUserHandlerBase.cs:205-212): the marker write is wrapped in a try/catch that swallows everything except OperationCanceledException and logs through the base's source-generated SoftDeletedMarkerFailed (:211, declared at :258-259). The reasoning is stated on the base (:33-37): the erasure is already saved by this point, and a cache fault must not turn a successful, irreversible deletion into a failure the caller would retry. A failed write leaves the Identity host still rejecting the token through its uncached validator query, while a host without that query accepts it until it expires. That is the shape ADR-096 generalized into a policy.
  • Why it's built this way: [Rubric §11, Security]. Access tokens are self-contained and valid until they expire, so deleting an account does not by itself stop a token already in the wild; the marker is what lets the shared SoftDeletedUserMiddleware reject those requests, and it lives in the base so every application gets the identical revocation window rather than each one re-implementing it in its own tail (DeleteUserHandlerBase.cs:29-32). It is written ahead of the post-save actions, so unbounded app work queued behind it cannot stretch the window in which the token still works (:40-43). Refresh sessions need no marker: the refresh flow's soft-delete filter already stops an erased account's sessions, and the revocation records why (:171-175). The base still revokes the un-revoked rows and anonymizes every row, revoked ones included, in the same save as the erasure, because the IP address and user agent captured at sign-in are personal data that must not outlive the account (:72-78). Treating the access-token marker as best-effort is the correct trade: erasure is the promise that must hold, and the token window is bounded anyway. [Rubric §30]: the avatar photo is personal data too (BR-116a), so its deletion is scheduled durably rather than merely being a best-effort call.
  • Where it's used: resolved as ICommandHandler<DeleteUserCommand, Result> and invoked by UsersController's DeleteAsync (UsersController.cs:286-300), which returns 204 on success (:300); the callers are the Profile page's self-service deletion and the organizer UserList. The UserDeleted integration event it raises is consumed downstream by Engagement's UserDeletedPointsHandler and Conference's UserDeletedSpeakerErasureHandler and UserDeletedFeedbackHandler. The scheduled DeleteAvatarBlobInternalCommand is drained later by DeleteAvatarBlobInternalCommandHandler. Covered by MMCA.ADC/Tests/Modules/Identity/MMCA.ADC.Identity.Application.Tests/Users/UseCases/DeleteUser/DeleteUserHandlerTests.cs and MMCA.ADC/Tests/Integration/MMCA.ADC.Identity.IntegrationTests/Compliance/ErasureAndPiiLoggingTests.cs.
  • Caveats / not-in-source: three things to watch. First, the avatar delete does not run inline during the request: ScheduleAvatarBlobDeletionAsync only enrolls the internal-command row (DeleteUserHandler.cs:88-98), and the blob is actually removed later, off the request, whenever the internal-command processor drains it; a caller who deletes the account cannot assume the photo is already gone at the moment the 204 comes back. Second, because DeleteUserCommand is ITransactional, the base's "after save" steps (the marker write and any afterCommit action) run before the transaction commits, which is why the base tells apps to enqueue only idempotent, retry-safe work there (DeleteUserHandlerBase.cs:22-25). Third, the base's own summary still words session revocation and grant blanking as conditional ("when the host registered a session store", "when the subclass forwards the grant store", DeleteUserHandlerBase.cs:16-18), while both stores are required constructor parameters (:99-100, documented as required at :76-77 and :83). Trust the signature.

ResetPasswordHandler

MMCA.ADC.Identity.Application · MMCA.ADC.Identity.Application.Users.UseCases.ResetPassword · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/ResetPassword/ResetPasswordHandler.cs:24 · Level 9 · class (sealed)

  • What it is: ADC's completion step for a forgotten password: redeem the single-use token, set the new credential, then clear the account's lockout. Like its change-preferences and get-preferences siblings it is an empty subclass; the workflow lives in ResetPasswordHandlerBase<TUser, TCommand>.
  • Depends on: ResetPasswordHandlerBase<TUser, TCommand> (base), IUnitOfWork, IPasswordHasher, IPasswordResetTokenService, ILoginProtectionService, ILogger<T>, IRefreshSessionStore, TimeProvider, User, and ResetPasswordCommand.
  • Concept introduced, revoking live sessions on a completed reset (SEC-Common-02). [Rubric §11, Security]. The constructor now also takes IRefreshSessionStore and a TimeProvider, forwarded straight to the base alongside the other five dependencies (ResetPasswordHandler.cs:24-39), so a completed reset revokes every live session on the account. A reset is the remediation for an account someone else is signed into, and without this addition it evicted nobody. ChangePasswordHandler carries the identical addition for the same reason.
  • Concept introduced, uniform failure as an anti-enumeration device. [Rubric §11, Security] assesses whether an anonymous endpoint leaks facts about accounts it will not authenticate. The base collapses every rejection to one error: Error.Unauthorized("Auth.InvalidResetToken", "The reset link is invalid or has expired. Please request a new one.", HandlerName) (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/ResetPassword/ResetPasswordHandlerBase.cs:126-130). An unknown token, an expired token, a token issued for a different address, a token past its validation-attempt cap and an account that has since vanished are all indistinguishable to the caller, which the <remarks> states as the point: the endpoint reveals nothing about which addresses hold accounts or which tokens exist (:18-22). The two failure branches differ only in the reason string handed to the log, "token rejected" (:81) and "account no longer resolvable" (:90), so an operator can still tell them apart while the client cannot. [Rubric §13, Observability & Operability]: both go through the handler's own source-generated [LoggerMessage] methods, PasswordResetRejected and PasswordResetCompleted (ResetPasswordHandlerBase.cs:132-138), and the success line records only the user id, never the address or the token.
  • Concept introduced, consume the token before the write. [Rubric §11, Security] again, and the ordering is the interesting part. The base redeems the token first (ResetPasswordHandlerBase.cs:77-79) and only then loads the user, hashes and saves. The comment states the trade explicitly (:58-60): leaving the token live until the write succeeds would open a replay window in which the same token redeems twice, so the token is burned up front, and the cost of a later invariant failure is that the user requests one more reset. Note also that the account is never named by the request: userId comes out of the redeemed token (:70), so the endpoint cannot be pointed at somebody else's account.
  • Walkthrough: a primary constructor taking the seven dependencies and forwarding all of them to the base (ResetPasswordHandler.cs:24-39), with an empty body (:40-41). The inherited HandleAsync (ResetPasswordHandlerBase.cs:66-124): null guard (:54); read the payload through the ICommandWithRequest<ResetPasswordRequest> constraint (:56), which is the whole reason the base never mentions ADC's command type; tokenService.ValidateAndConsumeAsync(request.Email, request.Token, ...) and the uniform failure on rejection (:61-68); load through the mutating repository by the id the token yielded, same uniform failure when the row is gone (:71-77); passwordHasher.HashPassword(request.NewPassword) and user.ChangePassword(newHash, newSalt) (:79-84), which returns the aggregate's own Result and is propagated untouched on failure; SaveChangesAsync (:86); then loginProtection.ResetFailedAttemptsAsync(request.Email, ...) (:89) with the one-line reason above it, that a user who reset the password because of a lockout must not stay locked out (:88); finally the success log and the result (:91-92).
  • Why it's built this way: the token material never touches the database. ADR-091 puts it in the cache, hashed at rest, with a per-email request throttle and a per-token validation-attempt cap owned by IPasswordResetTokenService (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/IPasswordResetTokenService.cs:5-9), so the reset vertical adds no schema and no migration. The clean split between "who owns the token" (the service) and "who owns the credential" (the aggregate, through User.ChangePassword at MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Domain/Users/User.cs:563) is what lets this handler be twelve lines of forwarding.
  • Where it's used: resolved as ICommandHandler<ResetPasswordCommand, Result> and injected into PasswordResetController (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/Controllers/PasswordResetController.cs:30), which exposes it as POST /Auth/reset-password with [Idempotent], [AllowAnonymous] and the shared auth-ip rate-limiting policy, all inherited from the framework base (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/PasswordResetAuthControllerBase.cs:99-102).
  • Caveats / not-in-source: User.ChangePassword raises no domain event (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Domain/Users/User.cs:556-558): the handlers that change or reset a password revoke the live sessions themselves, so the successful save writes the new credential and no outbox row. The lockout clear at ResetPasswordHandlerBase.cs:120 runs after the commit and is awaited without a try/catch, so a failure there surfaces to the caller even though the password has already changed.

ConfirmEmailHandler

MMCA.ADC.Identity.Application · MMCA.ADC.Identity.Application.Users.UseCases.ConfirmEmail · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/ConfirmEmail/ConfirmEmailHandler.cs:25 · Level 10 · class (sealed)

  • What it is: ADC's handler for ConfirmEmailCommand (ADR-116). Like ForgotPasswordHandler, it is a thin primary-constructor subclass with no body of its own: its <remarks> says nothing is overridden, and every step of the redeem workflow lives in the shared base (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/ConfirmEmail/ConfirmEmailHandler.cs:13-19).
  • Depends on: ConfirmEmailHandlerBase<TUser, TCommand> (base), User, ConfirmEmailCommand, IUnitOfWork, IEmailConfirmationTokenService, ICurrentUserService, IAccountClaimService; externals: Microsoft.Extensions.Logging.ILogger<T>.
  • Concept introduced, the link proves the mailbox, not the account. [Rubric §11, Security] assesses whether a credential flow can be completed by someone who does not own the account. Anyone can open an account under an address they do not read, so when the unconfirmed account holds a password credential the token alone confirms nothing (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/EmailConfirmation/ConfirmEmailHandlerBase.cs:26-43). The confirmation completes only when the caller also is signed in as that account, supplies the current password under the same lockout accounting a password sign-in uses, or supplies a new password that claims the account (every refresh session revoked, any enrolled second factor removed, the password replaced). Otherwise the answer is PasswordRequiredCode and nothing changes: the token stays redeemable so the page can ask for a password and post again. An account with no password credential (an external-login or link-only account) is confirmed by the token alone (:200-203). Those two extra proofs are why the subclass forwards ICurrentUserService (the signed-in check, :205-208) and IAccountClaimService (the password check and the claim, :58-61).
  • Concept reinforced, the template-method split ForgotPasswordHandler teaches: the framework owns the entire redeem sequence and ADC supplies nothing beyond the type arguments and constructor forwarding, because confirming an email needs no app-specific lookup step the way starting a reset does.
  • Walkthrough: public sealed class ConfirmEmailHandler(IUnitOfWork unitOfWork, IEmailConfirmationTokenService tokenService, ILogger<ConfirmEmailHandler> logger, ICurrentUserService currentUser, IAccountClaimService accountClaims) : ConfirmEmailHandlerBase<User, ConfirmEmailCommand>(unitOfWork, tokenService, logger, currentUser, accountClaims); (ConfirmEmailHandler.cs:25-31). Five constructor parameters, all forwarded to the base; no members, no overrides. The inherited HandleAsync (ConfirmEmailHandlerBase.cs:98-144) checks the token without spending it and answers any rejection with the uniform invalid-token error (:104-113); loads the account by the id the token yields, with the same error when it is gone (:115-122); treats an already-confirmed account as a success that spends the token and writes nothing (:124-138); otherwise proves the account and completes (:140-143). Completion (:155-186) spends the token before anything is saved (:162-166), applies the new-password claim or user.ConfirmEmail() (:168-174), saves (:176), and clears the lockout counter when a password was proved (:178-182).
  • Why it's built this way: the redeem workflow is identical across every app that uses email confirmation, so the base class carries it once and each app only fixes the TUser/TCommand type arguments. Two choices in the base are security trades: every token rejection collapses to one Authentication.InvalidConfirmationToken error, so the endpoint reveals nothing about which addresses hold accounts or which tokens exist (ConfirmEmailHandlerBase.cs:21-24); and the token is checked first but spent only once the request will complete, before the save, matching ResetPasswordHandlerBase, so the same token cannot redeem twice while a refused request still leaves it usable (:45-49).
  • Where it's used: registered as ICommandHandler<ConfirmEmailCommand, Result> by the module scan (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/DependencyInjection.cs:72), and injected into EmailConfirmationController. Covered by MMCA.ADC/Tests/Modules/Identity/MMCA.ADC.Identity.Application.Tests/Users/UseCases/ConfirmEmail/ConfirmEmailHandlerTests.cs and the framework's own MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Users/EmailConfirmationHandlerBaseTests.cs.
  • Caveats / not-in-source: the redeem logic itself lives entirely in ConfirmEmailHandlerBase in MMCA.Common and is not visible in this file. IAccountClaimService is registered by AddEmailConfirmation (ConfirmEmailHandlerBase.cs:58-61), so this handler resolves only on a host that made that call.

SetUserAvatarHandler

MMCA.ADC.Identity.Application · MMCA.ADC.Identity.Application.Users.UseCases.SetUserAvatar · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/SetUserAvatar/SetUserAvatarHandler.cs:27 · Level 12 · class (sealed, partial)

  • What it is: the command handler that uploads or replaces the signed-in user's avatar (BR-116a, ADR-045). It sniffs the true image format, re-encodes to a canonical 256x256 JPEG, stores the result under a fresh random blob name, persists the new URL on the User aggregate, then schedules the previous blob for deletion through the durable internal-command queue (ADR-114). It returns a UserAvatarDTO with the new URL.
  • Depends on: MutateEntityPayloadHandlerBase<TCommand, TEntity, TIdentifierType, TResultPayload> (base class, which supplies the ICommandHandler<in TCommand, TResult> implementation); MutationContext; IUnitOfWork; IImageProcessor; IFileStorageService; IInternalCommandScheduler; DeleteAvatarBlobInternalCommand; ImageContentSniffer; User; UserAvatarDTO; Result; Error; externals Microsoft.Extensions.Logging (ILogger plus [LoggerMessage] source generation), Microsoft.Extensions.DependencyInjection (IServiceScopeFactory, for the failure-path cleanup scope), System.Guid, System.IO.MemoryStream, System.Uri, System.Globalization.CultureInfo.
  • Concept introduced, safe handling of a user-supplied binary upload (ADR-045). This is the one place in the Identity module that accepts arbitrary bytes from an end user, and it treats them as hostile. [Rubric §11, Security] assesses input trust boundaries and defense against malicious uploads: the accepted format is decided by magic-byte sniffing (ImageContentSniffer.IsAllowedImage, called at SetUserAvatarHandler.cs:63, implemented at MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/Infrastructure/Storage/ImageContentSniffer.cs:14-15 as JPEG or PNG or WebP, each with its own byte-signature test at :21-36), never the client-declared content type, and the image is re-encoded rather than stored as received, which the class doc (:14-19, specifically :16) notes strips EXIF and kills polyglots (a payload that is a valid image and a valid script). [Rubric §30, Compliance, Privacy and Data Governance]: the same re-encode drops geolocation and camera EXIF a user did not intend to publish, and the stored URL lands on a [Pii]-tagged property (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Domain/Users/User.cs:116-118), so it participates in the erasure story of ADR-005.
  • Concept introduced (second), the templated mutation workflow with a side-data context. This handler writes almost no plumbing: the base MutateEntityHandlerCore<TCommand, TEntity, TIdentifierType> owns the load-mutate-save sequence in MutateCoreAsync (MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Crud/MutateEntityHandlerBase.cs:285-336): resolve the repository (:286), load the aggregate (:287), answer Error.NotFound stamped with the handler name when it is missing (:288-289), stamp the caller's rowversion when the endpoint is conditional (:297-302, ADR-035), run the subclass mutation (:304), skip the save on an idempotent no-op (:310-311), touch the root's concurrency token on a conditional write (:319-320), save (:322), then call LogMutated (:324) and the post-commit OnMutatedAsync (:325). Subclasses fill in hooks. The MutationContext is the mechanism that lets one hook hand a value to a later one: a Dictionary<string, object?> bag (MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Crud/MutationContext.cs:33) with Set<TValue> (:56), type-checked TryGet<TValue> (:69) and GetOrDefault<TValue> (:93). [Rubric §2, Design Patterns] assesses whether recurring shapes are factored into a named abstraction: this is Template Method with an explicit, typed side channel for the value that crosses the commit (the replaced blob's name). The one value the overridden HandleAsync must read after a failed run, the blob this request just uploaded, lives instead in a single private field, _uploadedBlobName (:42-47): set by the mutation, cleared by the post-commit hook, and (per its doc) still set when the save fails, which is how the handler knows the new blob has been orphaned. [Rubric §15, Best Practices & Code Quality]: the interesting lines of this handler are the image work and the orphan bookkeeping, not the repository and save ceremony. [Rubric §13, Observability and Operability]: the success path logs through a compile-time [LoggerMessage] source-generated method (:208-209), as do both scheduling-failure warnings (:211-212, :214-215), which is why the class is partial.
  • Walkthrough
    • Primary-constructor injection of IUnitOfWork, IImageProcessor, IFileStorageService, IInternalCommandScheduler, an IServiceScopeFactory and an ILogger<SetUserAvatarHandler> (SetUserAvatarHandler.cs:27-33), with the unit of work forwarded to the base MutateEntityPayloadHandlerBase<SetUserAvatarCommand, User, UserIdentifierType, UserAvatarDTO> (:34). Two constants: internal const int AvatarSize = 256, the canonical edge length (:37), and private const string PreviousBlobNameKey = "Avatar.PreviousBlobName", the context key the replaced blob's name travels under (:40). One field: private string? _uploadedBlobName (:47), the blob this request uploaded until the row pointing at it is committed.
    • EntityId (:50) tells the base which aggregate to load: command.UserId.
    • Format gate, before the aggregate is loaded (:57-69): the async HandleAsync override first runs ImageContentSniffer.IsAllowedImage(command.Content.Span) (:63) and returns Error.Validation with code "Avatar.UnsupportedFormat" and the source stamped as the handler name (:65-68) without touching the base. The doc (:52-55) gives the reason: an unsupported upload is answered with the format error whether or not the account exists, so the response cannot be used to probe for account existence.
    • Orphan guard around the base workflow (:71-89): the comment (:71-73) states the problem. The new blob is uploaded before the row is saved, so a save that throws, or a failure returned after the upload, leaves a blob no row points at. The override resets _uploadedBlobName (:74), awaits base.HandleAsync (:77), and when the result is a failure with the field still set it schedules that blob's cleanup before returning the original result unchanged (:78-83). A thrown exception is caught only when the field is set (exception filter at :85), the cleanup is scheduled, and the exception is rethrown (:87-88), so the caller sees exactly the outcome it would have seen without the guard.
    • The mutation (:93-130), which runs with the aggregate already loaded and tracked. The bytes are wrapped in a non-writable MemoryStream (:99) and handed to imageProcessor.NormalizeToSquareJpegAsync(content, AvatarSize, ...) inside an await using block (:101-104). The outcome is unwrapped with normalized.TryGetValue(out var jpegBytes) (:106, the Result<T>.TryGetValue accessor at MMCA.Common/Source/Core/MMCA.Common.Shared/Abstractions/Result.cs:206), and a failure re-returns its own errors (:106-109), so the failure detail from the image layer reaches the client unchanged and the save never happens (the base short-circuits at MutateEntityHandlerBase.cs:313-314). Nothing has been uploaded yet on this path, so the field stays null and no cleanup is scheduled.
    • Upload (:111-123): a fresh eight-hex-character suffix comes from Guid.NewGuid().ToString("N")[..8] (:111), and the blob name is built culture-invariantly with string.Create(CultureInfo.InvariantCulture, $"{command.UserId}-{suffix}.jpg") (:112). The unwrapped jpegBytes are wrapped in a second non-writable MemoryStream (:113) and streamed to fileStorage.UploadAsync(blobName, jpeg, "image/jpeg", ...) (:117); the returned Result<Uri> is unwrapped the same way with uploaded.TryGetValue(out var avatarUri) (:120), and a failed upload short-circuits identically (:120-123).
    • Record the new blob, hand the old one forward, then mutate (:125-127): _uploadedBlobName = blobName (:125) marks the fresh upload as an orphan candidate until commit; context.Set(PreviousBlobNameKey, TryGetBlobName(entity.AvatarUrl)) captures the blob this write is about to orphan before the property is overwritten (:126); then entity.SetAvatarUrl(avatarUri.AbsoluteUri) (:127, domain setter at MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Domain/Users/User.cs:554). The base commits.
    • LogMutated (:133-134) fires the source-generated LogAvatarSet at Information level with the message "User {UserId} avatar updated" (:208-209).
    • OnMutatedAsync (:141-166), the post-commit hook: it first clears _uploadedBlobName (:147-148), because the row now points at the new blob and it is no longer an orphan candidate. It then reads context.GetOrDefault<string>(PreviousBlobNameKey) (:150) and returns immediately when it is null (:151-154). Otherwise it schedules a DeleteAvatarBlobInternalCommand through internalCommandScheduler.ScheduleAsync(...) (:158-160) instead of deleting the blob inline; a scheduling failure is logged via LogAvatarBlobScheduleFailed at Warning (:162-165) rather than surfaced to the caller, since the mutation itself already committed. The comment above the call (:156-157) explains why: no transaction is active this late, so the row is already written and signalled immediately, and the internal-command processor picks the delete up on its next tick rather than waiting for the poll interval.
    • BuildResult (:169-173) shapes the handler's answer from the mutated aggregate: Result.Success(new UserAvatarDTO(entity.AvatarUrl)).
    • ScheduleUploadedBlobCleanupAsync (:180-200), the failure-path cleanup: it opens a fresh async DI scope (:184), resolves its own IInternalCommandScheduler from it (:185), and schedules a DeleteAvatarBlobInternalCommand for the orphaned new blob with CancellationToken.None (:186-188). The doc (:175-179) gives both reasons: the request scope's context is the one whose save just failed, and a cancelled request token must not cancel the cleanup. A failed Result logs LogAvatarBlobScheduleFailed (:189-192) and a thrown exception logs LogAvatarBlobScheduleThrew with the exception (:195-199); neither replaces the original outcome. The catch-all is the one analyzer suppression in the class: a CA1031 pragma pair (:194, :196) whose justification states that the cleanup is best-effort and the failed save's original outcome must reach the caller.
    • TryGetBlobName (:203-206): an internal static helper that parses the stored URL with Uri.TryCreate, requires more than one segment, and returns the unescaped final segment as the blob name (otherwise null). It is deliberately internal static because RemoveUserAvatarHandler reuses it.
  • Why it's built this way: the random blob-name suffix means a replacement never reuses the old URL, so browser and CDN caches self-resolve without an explicit purge (class doc, :17-18). Doing the blob work inside the mutation and deferring the cleanup to a durable queue is the ADR-096 shape combined with the ADR-114 durable-job pattern, as the class remarks (:20-26) state: an upload that fails stops the write before the row is touched, and the blob the write orphans is handed to the internal-command queue rather than deleted inline, so a storage outage or a crash in the post-commit tail defers the delete instead of leaking an image with nothing left that knows about it. The orphan guard in HandleAsync covers the other direction: a fresh upload whose save then fails or throws is queued for deletion through the same command, from a scope and a token that the failed request cannot affect. Sniffing plus mandatory re-encoding is the ADR-045 rule that an accepted upload is only ever stored in a shape the server itself produced.
  • Where it's used: dispatched by UsersController.SetAvatarAsync (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/Controllers/UsersController.cs:181-183, injected as ICommandHandler<SetUserAvatarCommand, Result<UserAvatarDTO>> at :33); the returned UserAvatarDTO carries the new URL back for immediate display. The type is also referenced from RemoveUserAvatarHandler, DeleteUserHandler and SetUserAvatarCommandValidator. Unit-tested by MMCA.ADC/Tests/Modules/Identity/MMCA.ADC.Identity.Application.Tests/Users/UseCases/SetUserAvatar/SetUserAvatarHandlerTests.cs.
  • Caveats / not-in-source: the concrete resize and crop strategy behind NormalizeToSquareJpegAsync, and the storage provider behind IFileStorageService, live in MMCA.Common and are not visible here: this handler only orchestrates them. The 2 MB per-upload size limit is enforced outside this file, at the API boundary (.../UsersController.cs:81, :92-98) and in SetUserAvatarCommandValidator (:29-32); the comment at :61-62 says the size limit stays app-side. The actual blob deletion never runs inside this handler: both the post-commit hook and the failure-path cleanup only schedule DeleteAvatarBlobInternalCommand; its processor and retry behavior live in the internal-command infrastructure, not here. A failed or thrown scheduling call is logged and otherwise swallowed, so a blob can still be left behind when the queue itself is unavailable (both warning messages say it "must be removed by hand", :211, :214). The _uploadedBlobName field makes the handler instance stateful for the duration of one call; that is safe only while each call gets its own handler instance, a lifetime set by DI registration outside this file.

SelfHttpWarmupTask

MMCA.ADC.Identity.Service · MMCA.ADC.Identity.Service · MMCA.ADC/Source/Services/MMCA.ADC.Identity.Service/SelfHttpWarmupTask.cs:25 · Level 2 · class (sealed, internal)

  • What it is: the Identity service's startup warm-up. Once Kestrel is listening, it replays the hot users read against the host's own cleartext endpoint so routing, authentication, and the middleware pipeline are JIT-compiled before the first real request arrives.
  • Depends on: SelfHttpWarmupTaskBase from MMCA.Common.Aspire.Warmup; externals: ASP.NET Core (IServer, IHostApplicationLifetime, IHostEnvironment), IConfiguration, ILogger<T>.
  • Concept reinforced, the cold-start warm-up task (ADR-025). [Rubric §12, Performance & Scalability] (assesses whether first-request latency after a scale-out or restart is managed rather than paid by a user) and [Rubric §13, Observability & Operability] (assesses that readiness reflects the instance's real ability to serve). The base class, taught in group-16, discovers the bound address, waits for the host lifetime, and issues the configured GETs; the runner registered by AddWarmupReadiness() keeps /health/ready not-ready until the task has had its chance, so the orchestrator does not route traffic into a cold instance. Failures are logged and fall back to lazy warm-up, so a warm-up problem degrades startup latency rather than blocking the service (SelfHttpWarmupTask.cs:15-18).
  • Walkthrough: a primary-constructor class that forwards all five dependencies to the base (SelfHttpWarmupTask.cs:25-31) and overrides four members.
    • Paths (SelfHttpWarmupTask.cs:35-38), one entry: users/paged?pageNumber=1&pageSize=10. The comment above it ties the string to reality (SelfHttpWarmupTask.cs:33-34): it is the shape the organizer list requests, GET users/paged, once the empty filter and sort values are dropped, leaving only the paging pair. The client that issues it is now the framework's entity-service client, UserListService, not UserService.
    • RequestedPaths (SelfHttpWarmupTask.cs:40-41), an internal static view of the same array, exposed so a test can pin each warm-up path to a routed GET action (MMCA.ADC/Tests/Services/MMCA.ADC.Services.Tests/Warmup/IdentitySelfHttpWarmupTaskTests.cs), which keeps the string from drifting away from the controller route.
    • Name => "SelfHttpWarmup" (SelfHttpWarmupTask.cs:44) and WarmupPaths => Paths (SelfHttpWarmupTask.cs:47), the base's two abstractions.
    • RequireSuccessStatusCode => false (SelfHttpWarmupTask.cs:54), the one genuinely interesting override. UsersController is [Authorize] plus [HasPermission], so an unauthenticated self-request is refused by design and returns 401. The comment (SelfHttpWarmupTask.cs:49-53) makes the argument: the refusal still traverses Kestrel, routing, authentication, and the whole middleware pipeline, which is exactly where the cold-start JIT cost lives, so a 401 is the correct outcome and treating it as a failure would log a spurious warning on every single startup.
  • Why it's built this way: the class doc (SelfHttpWarmupTask.cs:6-19) draws the contrast with Conference's task, which warms public read endpoints and therefore also populates the output cache. Identity has no anonymous read to warm, and its host sets a NoCache base output-cache policy anyway (MMCA.ADC/Source/Services/MMCA.ADC.Identity.Service/Program.cs:159), so this task buys pipeline JIT only and says so rather than pretending to prime a cache it cannot reach.
  • Where it's used: registered with services.AddWarmupTask<SelfHttpWarmupTask>() in the Identity service host (MMCA.ADC/Source/Services/MMCA.ADC.Identity.Service/Program.cs:165), where the surrounding comment block (Program.cs:161-164) repeats the rationale for an operator reading the host file.
  • Caveats / not-in-source: the base type decides how the bound address is discovered and whether the run is skipped under the Testing environment; this file only supplies the paths and the status-code policy.

IUserUIService

MMCA.ADC.Identity.UI · MMCA.ADC.Identity.UI.Services · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.UI/Services/IUserUIService.cs:17 · Level 3 · interface

  • What it is: the client-side contract the Identity Blazor pages call for the user operations outside the generic entity contract: account delete, the three avatar operations on the signed-in user, and the data-subject export download. The organizer roster read (BR-51) is not here: it goes through the standard entity-service client UserListService. Every member returns a Result.
  • Depends on: Result and ErrorType, the UserIdentifierType alias; BCL (Task, Stream, CancellationToken).
  • Concept introduced, the bespoke UI service contract (when the generic one does not fit). [Rubric §18, UI Architecture] (assesses whether components talk to a typed abstraction instead of raw HTTP) and [Rubric §9, API & Contract Design]. The framework's default for a UI-to-API contract is IEntityService<TEntityDTO, TIdentifierType>, which assumes a full CRUD resource whose DTO implements IBaseDTO<TIdentifierType>. The doc comment (IUserUIService.cs:6-10) draws the line: the operations that are not list-shaped (delete UC-21, the caller's own avatar BR-116a, the data-subject export) sit outside the generic entity contract, while the roster itself (BR-51) is read through the standard entity-service client for UserListDTO, GET users/paged. Those operations get a narrow interface of their own. The UI registration documents the consequence: the assembly scan behind AddUIModule<IdentityUIModule>() finds the IEntityService<,> implementations (that is how UserListService is picked up), so this contract is registered by hand (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.UI/DependencyInjection.cs:22-49).
  • Concept introduced, the Result-typed UI contract. [Rubric §24, Forms/Validation/UX Safety] (assesses whether a page can render a server-side failure as UI rather than as an unhandled exception). The second paragraph of the doc comment is the rule (IUserUIService.cs:11-15): every member returns a Result carrying the API's own errors with their ErrorType intact, so a page branches on the outcome instead of catching, and only the caller's own OperationCanceledException still escapes. That single sentence is what removes try/catch from the Identity pages.
  • Walkthrough: five members.
    • DeleteAsync(UserIdentifierType userId, ...) (IUserUIService.cs:22) returns a bare Result; the doc records that the server requires owner-or-Organizer (UC-21), so the client never has to reason about the rule.
    • GetMyAvatarUrlAsync (IUserUIService.cs:28), UploadMyAvatarAsync(Stream content, string fileName, string contentType, ...) (IUserUIService.cs:33), and RemoveMyAvatarAsync (IUserUIService.cs:36), the BR-116a trio. Note the "my" naming: none of them take a user id, because the server derives the subject from the token. A client that cannot name another user's avatar cannot accidentally ask for one. The avatar getter is documented as a success carrying an empty string when no avatar is set (IUserUIService.cs:25-26), which keeps "nothing set" out of the failure channel entirely.
    • ExportAsync(UserIdentifierType userId, ...) (IUserUIService.cs:38-46) downloads the data-subject export (GET Users/{userId}/export, PRIVACY.md section 12), the JSON document the API serves as a file. Unlike the avatar trio it does take a user id (the signed-in user on the profile page), and the doc records that the API enforces owner-or-Organizer. It returns Result<(byte[] Content, string? FileName)>: the raw bytes plus the server's suggested file name, null when the server sent none, so a page can hand both straight to a browser download. The export is produced server-side by ExportUserDataHandler and surfaced by LegalAndDataCard.
  • Why it's built this way: an interface here is what lets the Profile page (and the UserList page, which also injects it) be tested with a fake instead of a live HTTP stack ([Rubric §14, Testability]), and it is the boundary that keeps HttpClient, retries, and JSON shapes out of the components entirely.
  • Where it's used: implemented by UserService (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.UI/Services/UserService.cs:23); injected into UserList (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.UI/Pages/Users/UserList.razor.cs:37), Profile (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.UI/Pages/Users/Profile/Profile.razor.cs:23) and LegalAndDataCard, which issues the export download (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.UI/Pages/Users/Profile/LegalAndDataCard.razor.cs:42). UserListService only names it in a doc comment, to record that the roster delete still goes through IUserUIService.DeleteAsync (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.UI/Services/UserListService.cs:16). Registered scoped in AddIdentityUI (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.UI/DependencyInjection.cs:49).

UserService

MMCA.ADC.Identity.UI · MMCA.ADC.Identity.UI.Services · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.UI/Services/UserService.cs:22 · Level 5 · class (sealed)

  • What it is: the HTTP implementation of IUserUIService. It builds the request URLs, attaches the bearer token, applies the shared retry policy, and turns every response (success or failure) into a Result.
  • Depends on: IUserUIService, AuthenticatedServiceBase, ITokenStorageService, HttpResultExecutor, ProblemDetailsResultReader, UserAvatarDTO; externals: IHttpClientFactory, MultipartFormDataContent, HttpStatusCode.
  • Concept introduced, the two-halves rule for an honestly typed client. [Rubric §18, UI Architecture], [Rubric §26, Front-End Security] (assesses that tokens are attached by one audited helper rather than by each caller), and [Rubric §29, Resilience & Business Continuity]. Every method here is the same sandwich: HttpResultExecutor.ExecuteAsync on the outside, ProblemDetailsResultReader.ReadAsync on the inside. The reader converts a response into a Result, parsing the API's ProblemDetails and preserving the original ErrorType where the API emitted the MMCA error array (MMCA.Common/Source/Core/MMCA.Common.Shared/Http/ProblemDetailsResultReader.cs:50-56); the executor converts the absence of one, a refused connection, a DNS failure, a dropped socket, an HttpClient timeout (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Api/HttpResultExecutor.cs:13-17). Both halves are needed before a service method can honestly claim to return a Result. The one exception is deliberate and stated: when the caller's own token is why the operation stopped, the OperationCanceledException is rethrown, because a disposed component or a superseded grid fetch is not an error to render (HttpResultExecutor.cs:18-24, :100-103); a timeout raises the same exception type with the token not cancelled, and that one does become a failure (:104-107). The base class supplies CreateAuthenticatedClientAsync(), RetryPolicy and a ready-made SendRequestAsync that wraps the whole sandwich around one HTTP call (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Api/AuthenticatedServiceBase.cs:201-217), so the token never appears in this file, which is the point.
  • Walkthrough: five methods over a single Endpoint = "users" constant (UserService.cs:25). The methods are non-async and return a Task directly, since each body is a single call: the base's SendRequestAsync for the two body-less deletes, HttpResultExecutor.ExecuteAsync for the other three, each of which needs something that helper does not offer (a 404 special case, no retry, a non-JSON success body). The paged roster read is no longer here: UserListService serves it (GET users/paged), which is why SelfHttpWarmupTask warms users/paged?pageNumber=1&pageSize=10.
    • DeleteAsync (UserService.cs:28-37) builds users/{id} with CultureInfo.InvariantCulture (an id must never be culture-formatted) and hands the DELETE to SendRequestAsync (:34-36), which runs it through the executor and the retry policy and returns the reader's bare Result (AuthenticatedServiceBase.cs:209-216).
    • GetMyAvatarUrlAsync (UserService.cs:40-61) is the one method with a status-code special case: a 404 short-circuits to Result.Success(string.Empty) (:51-54), because "no avatar set" is not a failure and an empty URL renders as the profile's fallback icon (:49-50). Anything else goes through the reader and is mapped to AvatarUrl ?? string.Empty (:56-59).
    • UploadMyAvatarAsync (UserService.cs:64-88) posts a MultipartFormDataContent with one file part carrying the caller's content type (:75-78). It deliberately does not use the retry policy, and the comment says why (:74): the content stream is single-shot, since file-picker and file-input streams do not rewind, so a retry would post an empty body. This is the sharpest example in the module of a resilience policy being wrong for a specific call.
    • RemoveMyAvatarAsync (UserService.cs:91-94) sends DELETE users/me/avatar through SendRequestAsync exactly as DeleteAsync does and returns the reader's Result.
    • ExportAsync (UserService.cs:97-126) builds users/{id}/export with CultureInfo.InvariantCulture and retries like the other reads. It is the one method that does not run a success through the reader: the success body is the file itself, not a JSON DTO, so only a non-success response goes through ProblemDetailsResultReader.ReadAsync and is re-wrapped with Result.Failure<...>(failure.Errors) (:113-117). On success it reads the bytes and takes the file name from the Content-Disposition header, preferring FileNameStar over FileName and trimming quotes (:119-121), so the name is null when the server sent none.
  • Why it's built this way: hand-built URLs for the few non-CRUD operations keep the client honest about what the API actually accepts, while the list read rides the framework's generic client. Returning Result rather than throwing is what lets the pages branch: Profile uses TryGetValue on the avatar read (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.UI/Pages/Users/Profile/Profile.razor.cs:69), IsSuccess on the avatar removal (Profile.razor.cs:225), and IsFailure on the account delete (Profile.razor.cs:269); the removal and the delete sit in a try that catches only the OperationCanceledException of component disposal (Profile.razor.cs:235, Profile.razor.cs:290), so a failed call is a branch on the result, never a caught exception.
  • Where it's used: registered as IUserUIService in AddIdentityUI (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.UI/DependencyInjection.cs:49) and consumed through the interface by Profile (Profile.razor.cs:215) and LegalAndDataCard (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.UI/Pages/Users/Profile/LegalAndDataCard.razor.cs:42); UserList injects the interface too (UserList.razor.cs:37), so the same code runs on Blazor Server, WebAssembly, and MAUI.

UserListService

MMCA.ADC.Identity.UI · MMCA.ADC.Identity.UI.Services · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.UI/Services/UserListService.cs:20 · Level 5 · class (sealed)

  • What it is: the organizer-roster client (BR-51). It is a one-line class, EntityServiceBase<UserListDTO, UserIdentifierType>("users", ...) (UserListService.cs:20-21), whose GetPagedAsync calls GET users/paged with the generic filter, sort and paging contract (UserListService.cs:8-13).
  • Depends on: EntityServiceBase<TEntityDTO, TIdentifierType>, IEntityService<TEntityDTO, TIdentifierType>, UserListDTO, ITokenStorageService; externals: IHttpClientFactory.
  • Concept reinforced, the generic entity-service client (ADR-094). [Rubric §18, UI Architecture] (assesses whether components talk to a typed abstraction instead of raw HTTP). The framework base supplies the HTTP, token and retry plumbing, so the module contributes only the DTO type, the id alias and the route segment "users". The class remarks (UserListService.cs:14-17) are explicit about scope: only the paged read is served by the API, since the roster has no create or update endpoint, and delete stays on IUserUIService.DeleteAsync (UC-21).
  • Walkthrough: no members of its own. The Identity UI module scan registers it as IEntityService<UserListDTO, UserIdentifierType> (UserListService.cs:11-12), and the UserList page injects that interface (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.UI/Pages/Users/UserList.razor.cs:39) and calls Users.GetPagedAsync(filters, page, pageSize, sortColumn, sortDirection, ...) (UserList.razor.cs:82).
  • Why it's built this way: the roster is a plain list-of-DTOs read, so it fits the generic contract; routing it through the framework client removes the hand-built query-string code the bespoke UserService once carried, and lets the grid's operators reach the server verbatim. SelfHttpWarmupTask warms the matching users/paged route.
  • Where it's used: resolved by the Identity UI module scan and consumed by the UserList page; exercised in MMCA.ADC/Tests/Modules/Identity/MMCA.ADC.Identity.UI.Tests/Services/UserServiceTests.cs.

ExportUserDataQuery

MMCA.ADC.Identity.Application · MMCA.ADC.Identity.Application.Users.UseCases.ExportUserData · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/ExportUserData/ExportUserDataQuery.cs:12 · Level 2 · record (sealed)

  • What it is: the request for a data-subject export (PRIVACY.md §7): which account to export, plus who is asking and with what role.
  • Depends on: IUserOwnedRequest, the UserIdentifierType alias.
  • Concept introduced, carrying the caller inside the query. [Rubric §11, Security] (assesses whether authorization decisions are made on trusted, explicit inputs) and [Rubric §5, Vertical Slice] (assesses whether a use case owns its own request shape). Three positional members (ExportUserDataQuery.cs:12-15): UserId, CurrentUserId, and the nullable CurrentUserRole. The handler never reaches for HttpContext; the controller reads the claims once through ICurrentUserService and hands them to the query factory (UsersDataExportController, MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/Controllers/UsersDataExportController.cs:32-35). That is what makes the whole use case testable without a web host, and it is why the ownership rule can live in the shared base rather than in a controller filter. Implementing IUserOwnedRequest is the load-bearing part: the framework's generic constraint is where TQuery : IUserOwnedRequest (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/ExportUserData/ExportUserDataHandlerBase.cs:68), so the shared UserOwnershipRule can read UserId, CurrentUserId, and CurrentUserRole off any app's query record (ExportUserDataHandlerBase.cs:100-105).
  • Walkthrough: a positional record with an XML doc per parameter and nothing else (ExportUserDataQuery.cs:5-15). What it deliberately does not implement is as informative as what it does: it carries no IQueryCacheable, so the Caching decorator has nothing to act on. The base handler's remarks say why (ExportUserDataHandlerBase.cs:54-57): the document it produces is PII by design and must never be logged or cached.
  • Why it's built this way: the nullable CurrentUserRole mirrors reality at the edge, where a role claim may simply be absent. The privilege check is therefore written to accept null and answer false rather than to assume a role exists (ExportUserDataHandler.HasExportPrivilege, ExportUserDataHandler.cs:42).
  • Where it's used: constructed by UsersDataExportController for GET Users/{userId}/export (UsersDataExportController.cs:32-35) and handled by ExportUserDataHandler, which the controller receives as IQueryHandler<ExportUserDataQuery, Result<UserDataExportDTO>> (UsersDataExportController.cs:27).

RedeemSignInLinkCommand

MMCA.ADC.Identity.Application · MMCA.ADC.Identity.Application.Users.UseCases.RedeemSignInLink · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/RedeemSignInLink/RedeemSignInLinkCommand.cs:19 · Level 2 · record (sealed)

  • What it is: the command that redeems a sign-in link or a ticket-holder invitation (UC-54, BR-271, BR-275). It carries the shared request (address, single-use token, Terms acceptance flag) plus the two client details the new refresh session records (RedeemSignInLinkCommand.cs:7-9, :16-18).
  • Depends on: RedeemSignInLinkRequest (the shared wire payload), IRedeemSignInLinkCommand (the framework contract the shared controller and handler read it through), ITransactional (the marker that opens a transaction around the handler).
  • Concept reinforced, the anonymous command (taught at ForgotPasswordCommand), here with a transaction boundary. [Rubric §6, CQRS & Event-Driven] (assesses whether transactional scope is declared on the use case rather than coded in the handler) and [Rubric §11, Security]. The doc says it outright: anonymous by design, because the caller is signing in (RedeemSignInLinkCommand.cs:9), so no authenticated user id rides on it. What is new compared with the other anonymous commands is ITransactional, and the remarks give the reason (:11-15): redeeming an invitation for an address with no account inserts the account, then raises UserRegistered once the save has assigned its id, and that outbox row must commit with the account or not at all (ADR-107). It is the same reason registration runs in one transaction.
  • Walkthrough: a three-member positional record with no body (RedeemSignInLinkCommand.cs:19-23).
    • Request is the RedeemSignInLinkRequest from MMCA.Common.Shared.Auth.Requests (:3, :20).
    • IpAddress and UserAgent (:21-22) are nullable strings recorded on the refresh session the redemption opens; they are supplied by the controller from the HTTP connection, never by the request body.
    • The base list IRedeemSignInLinkCommand, ITransactional (:23) is the whole contract: the first lets the framework's controller base and handler base stay generic over each app's command, the second pulls the command into the transactional decorator.
  • Why it's built this way: the record stays app-side even though the redeem workflow is shared, the same split ForgotPasswordCommand uses, which leaves ADC free to attach the ITransactional marker its provisioning step needs.
  • Where it's used: built by SignInLinkController in its CreateRedeemCommand(RedeemSignInLinkRequest request, string? ipAddress, string? userAgent) override (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/Controllers/SignInLinkController.cs:40), which closes SignInLinkControllerBase<SendSignInLinkCommand, RedeemSignInLinkCommand> (:32) and receives RedeemSignInLinkHandler as ICommandHandler<RedeemSignInLinkCommand, Result<AuthenticationResponse>> (:31). Covered by MMCA.ADC/Tests/Modules/Identity/MMCA.ADC.Identity.API.Tests/Controllers/SignInLinkControllerTests.cs and MMCA.ADC/Tests/Modules/Identity/MMCA.ADC.Identity.Application.Tests/Users/UseCases/RedeemSignInLink/RedeemSignInLinkHandlerTests.cs.

NotificationUserDataExportSection

MMCA.ADC.Identity.Application · MMCA.ADC.Identity.Application.Users.UseCases.ExportUserData · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/ExportUserData/NotificationUserDataExportSection.cs:18 · Level 3 · class (sealed)

  • What it is: the Notifications contribution to a data-subject export: the user's notification inbox rows, fetched from the Notification service and projected into the export's own DTO shape.
  • Depends on: IUserDataExportSection (the contract), UserDataExportSectionResult, IUserNotificationExportService (the cross-service peer), UserDataExportNotificationSectionDTO, UserDataExportNotificationDTO.
  • Concept introduced, the export section as a pluggable contributor. [Rubric §30, Compliance, Privacy & Data Governance] (assesses whether a data-subject access request can actually be satisfied across every store that holds the subject's data) and [Rubric §7, Microservices Readiness] (assesses that a module reaches a peer through an interface it could satisfy in-process or over the wire). An access request is only as complete as the list of places that answer it, and in ADC those places are separate processes with separate databases. The framework's answer is a small interface, IUserDataExportSection (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/ExportUserData/IUserDataExportSection.cs:20), with a stable SectionName that appears verbatim in the document a subject reads (IUserDataExportSection.cs:27) and one ExportAsync per user (:38). Sections accumulate through AddUserDataExportSection<TSection>(), which registers them scoped and via TryAddEnumerable so a double registration adds one entry (MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.Extensibility.cs:41-43), and they are exported in registration order (IUserDataExportSection.cs:16-17).
  • Walkthrough: a primary-constructor class over one dependency (NotificationUserDataExportSection.cs:18-19).
    • SectionName => "Notifications" (NotificationUserDataExportSection.cs:22). Treat it as contract text, not a label: it is the key a subject (or a regulator) reads in the JSON.
    • ExportAsync (NotificationUserDataExportSection.cs:25-47) awaits GetUserNotificationExportAsync(userId, ...) on the peer (:29-31), then projects each row into a UserDataExportNotificationDTO with NotificationId, Title, SentOn, IsRead, ReadOn, and ScopeKey (:35-43), wrapped in a UserDataExportNotificationSectionDTO (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Shared/Users/DataExport/UserDataExportNotificationSectionDTO.cs:10). ScopeKey is the event-scoping key each notification carries (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Shared/Users/DataExport/UserDataExportNotificationDTO.cs:30), and exporting it is what lets a subject see which event a notification belonged to rather than an undifferentiated list. The re-projection is what keeps the exported wire shape owned by Identity.Shared rather than by whatever the peer happens to return today.
    • UserDataExportSectionResult.Complete(SectionName, data) (:46) closes it out. A user with an empty inbox produces an empty list and a Complete result, which is a truthful "nothing here" rather than the ambiguous "could not tell" an Unavailable would report (IUserDataExportSection.cs:9-13).
  • Why it's built this way: the class doc (NotificationUserDataExportSection.cs:11-15) makes the omission explicit: transport failures are not caught here. Catching them locally would mean every section reinventing the degrade policy; letting them propagate one frame lets the base of ExportUserDataHandler apply one policy to all sections ([Rubric §29, Resilience & Business Continuity]).
  • Where it's used: registered second, after Engagement, in AddModuleIdentityApplication (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/DependencyInjection.cs:67), which fixes its position in the document; the peer client is wired in the Identity service host with services.AddNotificationUserExportClient() inside the application-pipeline chain (MMCA.ADC/Source/Services/MMCA.ADC.Identity.Service/Program.cs:325), resolving to a gRPC adapter outside the Notification process. Covered by MMCA.ADC/Tests/Modules/Identity/MMCA.ADC.Identity.Application.Tests/Users/UseCases/NotificationUserDataExportSectionTests.cs.

ConferenceUserDataExportSection

MMCA.ADC.Identity.Application · MMCA.ADC.Identity.Application.Users.UseCases.ExportUserData · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/ExportUserData/ConferenceUserDataExportSection.cs:19 · Level 3 · class (sealed)

  • What it is: the Conference contribution to a data-subject export: the session and event feedback answers the user authored, read from the Conference service and projected into the export's own DTO shape. The class doc records why it exists (ConferenceUserDataExportSection.cs:7-11, M244): without it the export left the free-text feedback out silently.
  • Depends on: IUserDataExportSection (the contract), UserDataExportSectionResult, IUserConferenceExportService (the cross-service peer), UserDataExportConferenceSectionDTO, UserDataExportFeedbackAnswerDTO.
  • Concept reinforced, the export section (introduced at NotificationUserDataExportSection), here as the third contributor. [Rubric §30, Compliance, Privacy & Data Governance] and [Rubric §7, Microservices Readiness]. The structure is the sibling's: a primary constructor over one peer interface (ConferenceUserDataExportSection.cs:19), a constant SectionName, one ExportAsync, and no local try/catch. The peer is in-process inside the Conference service and a gRPC adapter everywhere else (ConferenceUserDataExportSection.cs:9-11), which is why the section depends on the interface and not on a client.
  • Walkthrough: ExportAsync (ConferenceUserDataExportSection.cs:26-53) makes one peer call, GetUserConferenceExportAsync(userId, ...) (:30-32), and assembles one UserDataExportConferenceSectionDTO (:34-50).
    • SectionName => "Conference" (:23). As with its siblings it is contract text: the key the subject reads in the JSON.
    • SessionFeedbackAnswers (:36-42) and EventFeedbackAnswers (:43-49) both project into the same UserDataExportFeedbackAnswerDTO row, carrying QuestionId, AnswerValue and CreatedOn. The only difference is the scope id: SessionId on the session rows, EventId on the event rows. The AnswerValue is the free text the user typed, so it is exported verbatim.
    • UserDataExportSectionResult.Complete(SectionName, data) (:52) closes it out. A user who answered nothing yields two empty lists and a Complete result, a truthful "nothing here".
  • Why it's built this way: transport failures are deliberately not caught (ConferenceUserDataExportSection.cs:13-16). The export handler wraps every section, so a peer still unreachable after the standard Polly resilience pipeline degrades this one section to Available = false instead of failing the whole export ([Rubric §29, Resilience & Business Continuity]). Re-projecting into Identity.Shared DTOs keeps the exported wire shape owned by Identity rather than by the peer's current return type.
  • Where it's used: registered third, after Engagement and Notification, in AddModuleIdentityApplication (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/DependencyInjection.cs:66-68), with the comment above the calls recording that registration order is document order (:59-62). The peer client is wired in the Identity service host with AddConferenceUserExportClient() (MMCA.ADC/Source/Services/MMCA.ADC.Identity.Service/Program.cs:326), which replaces the in-process service with a gRPC adapter (MMCA.ADC/Source/Services/MMCA.ADC.Conference.Contracts/DependencyInjection.cs:91-96). Covered by MMCA.ADC/Tests/Modules/Identity/MMCA.ADC.Identity.Application.Tests/Users/UseCases/ExportUserData/ConferenceUserDataExportSectionTests.cs and the registration pin in ExportUserDataRegistrationTests.cs.

EngagementUserDataExportSection

MMCA.ADC.Identity.Application · MMCA.ADC.Identity.Application.Users.UseCases.ExportUserData · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/ExportUserData/EngagementUserDataExportSection.cs:20 · Level 4 · class (sealed)

  • What it is: the Engagement contribution to a data-subject export: session bookmarks, submitted session questions, the points ledger, check-in history, live-poll votes, question upvotes, tickets, and leaderboard participation, read from the Engagement service and projected into the export's DTOs (class doc, EngagementUserDataExportSection.cs:8-12).
  • Depends on: IUserDataExportSection, UserDataExportSectionResult, IUserEngagementExportService, UserDataExportEngagementSectionDTO and its seven row types (UserDataExportBookmarkDTO, UserDataExportSubmittedQuestionDTO, UserDataExportPointsEntryDTO, UserDataExportCheckInDTO, UserDataExportPollVoteDTO, UserDataExportQuestionUpvoteDTO, UserDataExportTicketDTO).
  • Concept reinforced, the export section (introduced at NotificationUserDataExportSection), here at its widest. [Rubric §30, Compliance, Privacy & Data Governance] and [Rubric §9, API & Contract Design]. Everything structural is identical to its sibling: a primary constructor over one peer interface (EngagementUserDataExportSection.cs:20), a constant SectionName (:24), one ExportAsync, and no local try/catch (EngagementUserDataExportSection.cs:13-17). What differs is breadth, seven collections instead of one, which is what makes its three projection comments worth reading.
  • Walkthrough: ExportAsync (EngagementUserDataExportSection.cs:27-99) makes a single peer call (:31-33) and then assembles one section DTO (:35-96).
    • Bookmarks (:37-41) projects the scalar SessionId plus CreatedOn: no session title is pulled across, because Engagement stores the id and the export is truthful about what Engagement actually holds. SubmittedQuestions (:42-48) carries QuestionId and SessionId and, unlike the bookmark, the question's Text (:46): the subject authored that text, so it is their personal data and travels verbatim.
    • PointsEntries (:49-57) converts ActivityType with .ToString(), and the comment says why (:51-52): the export document is read by the data subject, so an activity travels as its readable name rather than an enum number. That is a real API-design decision, because it means renaming an enum member changes an externally visible document. The row also carries Points and SubjectKey (:54-55), the scalar ledger facts.
    • CheckIns (:58-67) applies the same rule to Scope (:60-62) and carries the nullable EventId, SessionId, and SponsorId alongside CheckedInOn, which is what makes the three check-in scopes distinguishable in the output.
    • PollVotes (:68-73) projects LivePollId, OptionId, and CreatedOn, and QuestionUpvotes (:74-78) projects QuestionId and CreatedOn. Both are id-only rows like the bookmarks, so the export states which poll option and which question the subject voted on without pulling any poll or question text the subject did not write.
    • Tickets (:79-93) is the widest row: the EventId, the SourceEventName and ExternalTicketId from the ticketing source, the TicketTypeName, the attendee's first and last name and OrderEmail as the roster recorded them, InvitedOn, and how and when the ticket was linked to the account. LinkMethod follows the readable-name rule a third time (:90-91), next to LinkedOn (:92).
    • IsOnLeaderboard and LeaderboardDisplayName (:94-95) close the section. Those are the same two facts Engagement's UserDeletedPointsHandler erases on account deletion, which is the neat symmetry of this module: access and erasure operate on the identical set of data.
    • UserDataExportSectionResult.Complete(SectionName, data) (:98).
  • Why it's built this way: registration order is document order, and Engagement is registered first of the three sections (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/DependencyInjection.cs:66-68), with the comment above the calls recording that this is deliberate rather than incidental (:70). Stable ordering means an exported document can be diffed across runs.
  • Where it's used: the peer client is wired in the Identity service host with AddEngagementUserExportClient() as one registration in the host's application-pipeline chain (MMCA.ADC/Source/Services/MMCA.ADC.Identity.Service/Program.cs:288), which resolves to a gRPC adapter outside the Engagement process. The host comment states the coupling explicitly (Program.cs:250-263): the export clients are best-effort consumers, so a peer that stays unreachable degrades one section instead of failing the export, and Identity never hard-depends on any peer. Covered by MMCA.ADC/Tests/Modules/Identity/MMCA.ADC.Identity.Application.Tests/Users/UseCases/ExportUserData/EngagementUserDataExportSectionTests.cs and the registration pin in ExportUserDataRegistrationTests.cs.

UserDeleted

MMCA.ADC.Identity.Shared · MMCA.ADC.Identity.Shared.Users.IntegrationEvents · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Shared/Users/IntegrationEvents/UserDeleted.cs:30 · Level 3 · record (sealed)

  • What it is: the cross-service announcement that an account has been erased (UC-21, BR-56). It is the only announcement of an erasure: the soft-delete on the User aggregate raises no domain event of its own (UserDeleted.cs:18-19, MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Domain/Users/User.cs:26-28).
  • Depends on: BaseIntegrationEvent, EventNameAttribute, the UserIdentifierType alias.
  • Concept introduced, the erasure announcement, and why its payload is nearly empty. [Rubric §30, Compliance, Privacy & Data Governance] (assesses whether an erasure reaches every store that holds the subject's personal data) and [Rubric §11, Security]. Two positional members only (UserDeleted.cs:30-33): UserId and DeletedOn. The doc comment gives the reason in one sentence (UserDeleted.cs:21-25): a downstream module reacting to an erasure already stores the scalar user id, and carrying a name or an email here would publish the very personal data the erasure exists to remove, onto a broker that persists messages. An erasure event that leaked PII would be self-defeating.
  • Concept introduced, the wire name is not the CLR name. [EventName("Identity.UserDeleted.v1")] (UserDeleted.cs:29) pins the string the broker and the outbox use, so a future namespace move or rename cannot break a running consumer. The version suffix is what makes an incompatible payload change expressible as a new name rather than as a silent break (ADR-010).
  • Walkthrough: the interesting mechanics are not in the record, they are at the raise site. DeleteUserHandler calls user.AddDomainEvent(new UserDeleted(command.UserId, timeProvider.GetUtcNow())) inside OnAfterSoftDeleteAsync, before the erasure is saved (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/DeleteUser/DeleteUserHandler.cs:55-71), and the record's own doc spells out what that buys (UserDeleted.cs:7-10): the outbox row is written by the very SaveChangesAsync that commits the soft-delete and the anonymization, so an account that is erased has always produced exactly one event, and an erasure that rolls back produces none. Publishing after the commit instead would leave a crash window in which the account is gone and the published name is not. The timestamp comes from the injected TimeProvider (DeleteUserHandler.cs:41), not DateTimeOffset.UtcNow, so the handler stays testable.
  • Why it's built this way: the subscribers are other processes. The doc comment (UserDeleted.cs:11-19) lists them: Engagement's points, bookmark, badge, live-poll, question and roster handlers, and Conference's UserDeletedSpeakerErasureHandler and UserDeletedFeedbackHandler. Each runs in its own host with its own database and never sees an Identity in-process dispatch, so the fact is modelled once, as a BaseIntegrationEvent, and the base type alone sends the same AddDomainEvent call down the outbox path to the broker rather than the in-process one (ADR-003).
  • Where it's used: consumed by Engagement's UserDeletedPointsHandler (MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.Application/Points/IntegrationEventHandlers/UserDeletedPointsHandler.cs:38-45), which takes the account off the public leaderboard and overwrites the LeaderboardOptIn display name the attendee had published there, the one place Engagement holds a name rather than a scalar id (UserDeletedPointsHandler.cs:13-20). The subscription is wired in the Engagement service host by .RegisterIntegrationEventConsumer<UserDeleted>() inside EngagementBrokerConsumers.Register, the consumer list that host hands to AddBrokerMessaging (MMCA.ADC/Source/Services/MMCA.ADC.Engagement.Service/EngagementBrokerConsumers.cs:29). That handler is idempotent in both directions and deliberately does not swallow exceptions, so a failed erasure is retried by the outbox and the broker instead of being acked away with a log line (UserDeletedPointsHandler.cs:23-28).

UserRegistered

MMCA.ADC.Identity.Shared · MMCA.ADC.Identity.Shared.Users.IntegrationEvents · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Shared/Users/IntegrationEvents/UserRegistered.cs:38 · Level 3 · record (sealed)

  • What it is: the cross-service announcement that a new account exists. It carries the database-generated user id plus the identity fields another context needs to match on, and it is the event that drives the BR-207 speaker auto-link.
  • Depends on: BaseIntegrationEvent, EventNameAttribute, the UserIdentifierType alias.
  • Concept introduced, the integration event as a published contract. [Rubric §6, CQRS & Event-Driven] (assesses whether contexts collaborate through facts rather than commands), [Rubric §7, Microservices Readiness] (assesses that the producer does not know its consumers), and [Rubric §9, API & Contract Design]. Four properties of this record make it a contract rather than an internal message. It lives in Shared, the assembly a consumer may reference without touching Identity's Domain or Application. It carries denormalized primitives (string Email, string FirstName, string LastName, string Role) rather than the Email value object or UserRole, so a subscriber needs no Identity types to deserialize it. It is a record with positional members, so adding an optional member later is an additive change consumers can ignore, which is exactly how EmailVerified arrived. And it declares its wire name explicitly, [EventName("Identity.UserRegistered.v1")] (UserRegistered.cs:37), so the published contract survives any CLR-side rename (ADR-010).
  • Concept introduced, an additive member that gates a downstream side effect. [Rubric §9, API & Contract Design], [Rubric §11, Security]. The sixth positional member, bool EmailVerified = false (UserRegistered.cs:38-45), is what makes the BR-207 speaker auto-link safe rather than merely convenient: the type's own doc comment says nothing proves ownership of an address typed into the registration form, so a speaker profile may only be handed out when an external provider asserted the address as verified. Because the member is additive with a false default, an outbox row written before it existed, or one still in flight across a deploy, deserializes to the value that links nothing, so the rollout cannot silently grant auto-links it should not.
  • Walkthrough: six positional members (UserRegistered.cs:38-45): UserId, Email, FirstName, LastName, Role, EmailVerified. Email is the field the auto-link actually matches on; the two name fields exist so a subscriber can report candidates without a call back into Identity; EmailVerified is always false for a local password registration, whose address is unproven, and reflects the external provider's own assertion for an OAuth registration.
  • Why it's built this way: the ordering problem is the whole story. The id is a database-generated identity column, so the event cannot be raised inside User.Create (the factory remarks say so outright, MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Domain/Users/User.cs:209-216): the id is still default at that point, and the outbox serializes the payload at capture time, so it would persist UserId = 0, which the cross-service Conference consumer cannot resolve (AuthenticationService.cs:35-42). Instead AuthenticationService wraps the base registration workflow in a single UnitOfWork.ExecuteInTransactionAsync (AuthenticationService.cs:83-90), then in OnUserRegisteredAsync raises the event on the already-persisted aggregate and saves a second time (AuthenticationService.cs:249-254). The first save populates the real id; the second save writes the outbox row; both are inside one transaction, so the user and the event commit atomically. The remarks on that override (AuthenticationService.cs:166-191) name the consequence honestly: this is eventual consistency, and the token handed back to the just-registered user does not yet carry the speaker_id claim. The same raise happens for brand-new external OAuth users, guarded by an isNewUser flag (AuthenticationService.cs:327-337), and it is that path that can populate EmailVerified = true.
  • Where it's used: consumed by Conference's UserRegisteredHandler, which runs the email-match speaker auto-link and publishes SpeakerLinkedToUser back so Identity can set User.LinkedSpeakerId; Identity registers the consumers for that return event in its own host, in IdentityBrokerConsumers.Register (MMCA.ADC/Source/Services/MMCA.ADC.Identity.Service/IdentityBrokerConsumers.cs:25-26).
  • Caveats / not-in-source: the type's own doc comment says the event is "Published by AuthenticationService AFTER the unit-of-work commit" (UserRegistered.cs:7-9), and the User.Create remarks repeat the phrasing (User.cs:210-215); neither still describes the mechanism. Current source raises it via AddDomainEvent on the aggregate after the first save, inside the transaction, so the outbox row commits with the insert (AuthenticationService.cs:196-197). The code is ground truth here; both doc comments predate the atomicity fix described at AuthenticationService.cs:31-41. Whether UserRegisteredHandler currently reads EmailVerified to gate the auto-link, or the flag is carried on the wire ahead of that consumer-side change, is not determinable from this unit's source.

TicketHolderInvited

MMCA.ADC.Identity.Shared · MMCA.ADC.Identity.Shared.Users.IntegrationEvents · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Shared/Users/IntegrationEvents/TicketHolderInvited.cs:32 · Level 3 · record (sealed)

  • What it is: the integration event in which Engagement asks Identity to email a ticket holder a one-tap invitation (BR-270, BR-271). Identity owns the contract but is not the publisher: Engagement raises it, Identity consumes it.
  • Depends on: BaseIntegrationEvent, EventNameAttribute, the EventIdentifierType alias; BCL DateOnly.
  • Concept introduced, the contract lives in the leaf module, not the publisher. [Rubric §7, Microservices Readiness] (assesses whether contexts can be deployed and versioned apart) and [Rubric §10, Messaging & Integration]. The remarks give the dependency argument (TicketHolderInvited.cs:13-17): Identity's Shared project references no other module's project, while Engagement already references it for UserRegistered, so putting the record here keeps the leaf project free of module references and adds no new edge. The wire name is pinned with [EventName("Identity.TicketHolderInvited.v1")] (TicketHolderInvited.cs:31), so the consumer side owns the name as well (ADR-010).
  • Concept reinforced, personal data on a persistent broker. [Rubric §30, Compliance, Privacy & Data Governance]. Unlike the id-only UserDeleted, this payload carries an address and two names, and the remarks justify each (TicketHolderInvited.cs:20-23): an invitation may create the account, and the account needs a name. They are the minimum the invite needs, matching the field set of UserRegistered.
  • Walkthrough: six positional members (TicketHolderInvited.cs:32-39): EventId, Email (the order email, normalized by the publisher), FirstName and LastName (the attendee's, or the buyer's when the ticket names no attendee), EventName for the subject line, and EventStart for the body (TicketHolderInvited.cs:25-30).
  • Why it's built this way: the event is raised by Ticket.AnnounceInvitation before the save, so the outbox captures it in the same transaction that stamps InvitedOn and a re-run never emails the same order twice (MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.Domain/Tickets/Ticket.cs:227-263, ADR-003). That method refuses a ticket with no order email or no invitation stamp, refuses a blank event name, and substitutes fallback names for blank ones because Identity refuses an invitation with a blank name (Ticket.cs:239-261). One ticket per order email announces, which the publisher picks (Ticket.cs:229-230).
  • Where it's used: raised from Engagement's SendTicketInvitesHandler through Ticket.AnnounceInvitation; consumed by TicketHolderInvitedHandler, which schedules the Identity.SendSignInLink.v1 internal command SendSignInLinkInternalCommand with the event's MessageId as the invite id, so a redelivery is harmless (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/IntegrationEventHandlers/TicketHolderInvitedHandler.cs:24-28, :49-56). The Identity host subscribes to it in IdentityBrokerConsumers (MMCA.ADC/Source/Services/MMCA.ADC.Identity.Service/IdentityBrokerConsumers.cs:30).

UserEmailVerified

MMCA.ADC.Identity.Shared · MMCA.ADC.Identity.Shared.Users.IntegrationEvents · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Shared/Users/IntegrationEvents/UserEmailVerified.cs:31 · Level 3 · record (sealed)

  • What it is: the cross-service announcement that an account's owner has proven control of its address (BR-272). Engagement subscribes to it to link the address's roster tickets to the account.
  • Depends on: BaseIntegrationEvent, EventNameAttribute, the UserIdentifierType alias.
  • Concept reinforced, the integration event as a published contract. Taught on UserRegistered; the same shape applies: denormalized primitives in Shared, and a pinned wire name, [EventName("Identity.UserEmailVerified.v1")] (UserEmailVerified.cs:30, ADR-010). [Rubric §11, Security] (assesses whether a privileged side effect rests on proven facts): linking tickets on an email match is only safe once ownership of the address is proven, which is exactly the fact this event names.
  • Walkthrough: two positional members (UserEmailVerified.cs:31-34): UserId and Email, the normalized proven address the consumer matches on (UserEmailVerified.cs:28-29).
  • Why it's built this way: the doc comment lists the three raise sites, each through the outbox in the same save as the state it announces (UserEmailVerified.cs:10-20):
    • the User aggregate's ConfirmEmail, on the transition from unconfirmed to confirmed (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Domain/Users/User.cs:392);
    • User.LinkExternalProvider, which the caller reaches only after the provider asserted the address as verified (User.cs:442-451; AuthenticationService fails the link when the provider's emailVerified assertion is false, MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/AuthenticationService.cs:530-533); the aggregate raises the event from one announcing helper (User.cs:460-471);
    • RedeemSignInLinkHandler, for any redemption the aggregate transition did not already announce, since redeeming a link is itself a fresh proof that may cover tickets imported since (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/RedeemSignInLink/RedeemSignInLinkHandler.cs:117). The doc also sets the consumer obligation (UserEmailVerified.cs:21-26): an account created by an invitation additionally raises UserRegistered with EmailVerified true, and an account created from a verified external login raises only UserRegistered, so a consumer that links on proven ownership handles both events, idempotently, because proof of the same address can be announced more than once (ADR-021).
  • Where it's used: consumed by Engagement's UserEmailVerifiedTicketLinkHandler (MMCA.ADC/Source/Modules/Engagement/MMCA.ADC.Engagement.Application/Tickets/IntegrationEventHandlers/UserEmailVerifiedTicketLinkHandler.cs:22-25), alongside its UserRegistered sibling UserRegisteredTicketLinkHandler; subscribed in EngagementBrokerConsumers (MMCA.ADC/Source/Services/MMCA.ADC.Engagement.Service/EngagementBrokerConsumers.cs:31).

IdentityBrokerConsumers

MMCA.ADC.Identity.Service · MMCA.ADC.Identity.Service · MMCA.ADC/Source/Services/MMCA.ADC.Identity.Service/IdentityBrokerConsumers.cs:16 · Level 4 · class (internal static)

  • What it is: the single list of integration events the Identity service host subscribes to on the broker, passed to AddBrokerMessaging as its consumer callback.
  • Depends on: IBrokerConsumerBuilder, SpeakerLinkedToUser, SpeakerUnlinkedFromUser, TicketHolderInvited.
  • Concept reinforced, the subscription list as a testable artifact. [Rubric §10, Messaging & Integration] (assesses whether every message a service relies on is actually routed to it) and [Rubric §14, Testability]. Against a real broker a handler whose event is not registered here never runs, and nothing fails loudly. The class doc states why the list lives outside Program.cs (IdentityBrokerConsumers.cs:7-11): the subscriptions can be asserted without booting the host, following the ConferenceBrokerConsumers precedent, and MMCA.ADC/Tests/Services/MMCA.ADC.Services.Tests/Messaging/BrokerConsumersTests.cs does exactly that, with BrokerTopologyBicepTests.cs beside it checking the matching Bicep entities. The remarks add the routing fact (IdentityBrokerConsumers.cs:12-15): every subscription lands on this host's one queue (MessageBus:QueueName), and no other ADC service consumes these events.
  • Walkthrough: one expression-bodied method, Register(IBrokerConsumerBuilder consumers) (IdentityBrokerConsumers.cs:20-30), chaining three RegisterIntegrationEventConsumer<T>() calls:
    • SpeakerLinkedToUser and SpeakerUnlinkedFromUser (:25-26), published by Conference.Service after speaker link and unlink operations (BR-207); SpeakerLinkedToUserHandler and SpeakerUnlinkedFromUserHandler set and clear User.LinkedSpeakerId (:22-24).
    • TicketHolderInvited (:30), published by Engagement.Service when an organizer sends ticket invites (BR-271); TicketHolderInvitedHandler schedules the invitation email (:28-29).
  • Where it's used: passed as a method group in the Identity host, s.AddBrokerMessaging(builder.Configuration, IdentityBrokerConsumers.Register) (MMCA.ADC/Source/Services/MMCA.ADC.Identity.Service/Program.cs:292), with the comment above it pointing at the same test (Program.cs:278). Its siblings are ConferenceBrokerConsumers and EngagementBrokerConsumers.

ExportUserDataHandler

MMCA.ADC.Identity.Application · MMCA.ADC.Identity.Application.Users.UseCases.ExportUserData · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/ExportUserData/ExportUserDataHandler.cs:33 · Level 9 · class (sealed)

  • What it is: ADC's data-subject export handler. It is a thin subclass of the framework's export workflow that answers exactly two app-specific questions: which role may export somebody else's account, and which of the account's own fields count as portable personal data.
  • Depends on: ExportUserDataHandlerBase<TUser, TQuery>, User, ExportUserDataQuery, UserRole, UserDataExportSubjectDTO, IUnitOfWork, IUserDataExportSection, IAuditTrailWriter; externals: TimeProvider, ILogger<T>.
  • Concept introduced, the template-method handler where the app supplies only its vocabulary. [Rubric §30, Compliance, Privacy & Data Governance] (assesses whether access and portability are implemented once and identically everywhere), [Rubric §2, Design Patterns] (template method), and [Rubric §1, SOLID] (the base is closed for modification and open through three protected hooks). The base (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/ExportUserData/ExportUserDataHandlerBase.cs:61) owns the whole workflow: the owner-or-privileged-role check via UserOwnershipRule.CheckOwnership, returning a User.ExportForbidden error (ExportUserDataHandlerBase.cs:100-109), a no-tracking load through GetReadRepository with Error.NotFound when the account is gone (:111-117), the subject snapshot, the section fan-out (:123-127), and the envelope stamped with CurrentFormatVersion "1.0" and a GeneratedOn from TimeProvider (:74, :129-136). Two of those choices carry real weight. The fan-out is sequential on purpose, because sections share the scoped unit of work and its DbContext, which is not thread-safe, and because registration order is the published order of the document (:121-122). And each section runs inside its own try/catch (:201-226) that degrades a failing section to Available = false with a deliberately generic reason, sending the exception detail to the log and never to the subject (:213-225); OperationCanceledException is explicitly excluded, because a cancelled request is not a degraded one.
  • Walkthrough: a primary constructor forwarding five dependencies to the base, the audit-trail writer among them (ExportUserDataHandler.cs:33-39), and two overrides.
    • HasExportPrivilege(string? currentUserRole) => UserRole.IsOrganizer(currentUserRole) (ExportUserDataHandler.cs:42). One line, and the case-insensitive comparison lives inside UserRole.IsOrganizer rather than here, so a claim with unexpected casing cannot silently deny an organizer (a test pins the lowercase "organizer" case, MMCA.ADC/Tests/Modules/Identity/MMCA.ADC.Identity.Application.Tests/Users/UseCases/ExportUserData/ExportUserDataHandlerTests.cs:138).
    • BuildSubjectSnapshotAsync (ExportUserDataHandler.cs:45-86) guards its argument (:50) and projects the aggregate into a UserDataExportSubjectDTO: identity and profile fields, IsExternalLogin and LoginProvider, LinkedSpeakerId, AvatarUrl, the two audit timestamps (:54-70), and, added under M244 (:71-82), the consent record (AcceptedTermsVersion, TermsAcceptedOn), the preferences (PreferredCulture, PreferredTheme) and the account state (IsEmailConfirmed, LockedOn), because those are personal data held on the account row too. No device fields appear: the User aggregate carries none, so the snapshot has nothing device-shaped to project. What is absent is the point: no PasswordHash, no PasswordSalt, no refresh token, no external ProviderKey. The class doc states the principle (ExportUserDataHandler.cs:17-20): credentials are secrets, not portable personal data, and a portability right is not a right to a copy of your own password hash.
    • The timestamp handling is the subtle bit (ExportUserDataHandler.cs:64-70). SQL Server hands audit timestamps back as Kind=Unspecified, and the DTO documents them as UTC but serializes them without a Z marker in that state, so DateTime.SpecifyKind(..., DateTimeKind.Utc) only restores the marker on a value that was already UTC. LastModifiedOn is null-checked first, since a never-updated account has none. The M244 additions follow the same rule for the two nullable stored-UTC timestamps, TermsAcceptedOn and LockedOn (:74-76, :80-82).
    • The method returns Task.FromResult<object?>(subject) (:85): the hook is asynchronous because some apps read a second aggregate for the snapshot, and ADC does not need to.
  • Why it's built this way: the handler needs no DI registration of its own. ScanModuleApplicationServices<ClassReference>() finds it through the base class's IQueryHandler<TQuery, Result<UserDataExportDTO>> implementation, which both the Identity module scan (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/DependencyInjection.cs:72) and the framework's own registration remarks record (MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.Extensibility.cs:32-35), and a dedicated test pins it (MMCA.ADC/Tests/Modules/Identity/MMCA.ADC.Identity.Application.Tests/Users/UseCases/ExportUserData/ExportUserDataRegistrationTests.cs:29). Best-effort section aggregation is the same posture the module takes for the best-effort live-channel publish (ExportUserDataHandler.cs:26-31): one peer outage costs the subject one section, never the whole document ([Rubric §29, Resilience & Business Continuity]).
  • Where it's used: injected into UsersDataExportController as IQueryHandler<ExportUserDataQuery, Result<UserDataExportDTO>> (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/Controllers/UsersDataExportController.cs:27) and invoked from the inherited GET Users/{userId}/export action, which the framework's DataExportControllerBase<TQuery> declares [Authorize] and feature-gates on PrivacyFeatures.DataExport (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Privacy/DataExportControllerBase.cs:59-60, action at :77-82), returning the document as a file download (:109). Covered by MMCA.ADC/Tests/Modules/Identity/MMCA.ADC.Identity.Application.Tests/Users/UseCases/ExportUserData/ExportUserDataHandlerTests.cs and, at the controller edge, MMCA.ADC/Tests/Modules/Identity/MMCA.ADC.Identity.API.Tests/Controllers/UsersDataExportControllerTests.cs.
  • Caveats / not-in-source: every completed export leaves an access record, and that behavior lives entirely in the base. ADC pins MMCA.Common.Application 1.333.0 (MMCA.ADC/Directory.Packages.props:148) and forwards the IAuditTrailWriter it is given (ExportUserDataHandler.cs:36, :39); once the package is assembled the base writes one Exported row (ExportedAuditOperation, ExportUserDataHandlerBase.cs:80) carrying the account's type and id and the caller, never the exported content, before it returns the package, and a failure to write it fails the export (:33-39, :138-144). The record is inert in a host whose trail is off; the Identity host registers it with AddAuditTrail (MMCA.ADC/Source/Services/MMCA.ADC.Identity.Service/Program.cs:203) and ships AuditTrail:Enabled true (MMCA.ADC/Source/Services/MMCA.ADC.Identity.Service/appsettings.json:69-70). OnExportCompletedAsync (ExportUserDataHandlerBase.cs:187) runs after that record (:146); ADC does not override it.

RedeemSignInLinkHandler

MMCA.ADC.Identity.Application · MMCA.ADC.Identity.Application.Users.UseCases.RedeemSignInLink · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/RedeemSignInLink/RedeemSignInLinkHandler.cs:46 · Level 11 · class (sealed)

  • What it is: ADC's handler for RedeemSignInLinkCommand (UC-54, BR-271, BR-275). The redeem workflow itself (spend the token first, resolve the account, confirm the address, open a session) lives in the framework base; this subclass supplies the account an invitation creates and the two integration events. The class summary still lists "the ADC account lookup" among its contributions (RedeemSignInLinkHandler.cs:16-21), but the lookup now runs in the base, through the framework's shared untracked email lookup (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/SignInLinks/RedeemSignInLinkHandlerBase.cs:185-189, MMCA.Common/Source/Core/MMCA.Common.Application/Users/UserEmailLookup.cs:38).
  • Depends on: RedeemSignInLinkHandlerBase<TUser, TCommand>, User, RedeemSignInLinkCommand, IUnitOfWork, ISignInLinkTokenService, IAuthenticationService, SignInLinkSettings, LegalAcceptanceOptions, LegalAcceptancePolicy, SignInLinkProfile, SignInLinkGrant, RedeemSignInLinkRequest, UserRegistered, UserEmailVerified, Email; externals: IOptions<T>, TimeProvider, ILogger<T>.
  • Concept introduced, provisioning on redemption with exactly-once event semantics. [Rubric §2, Design Patterns] (template method; ADC overrides three of the base's protected hooks), [Rubric §6, CQRS & Event-Driven] (assesses whether each state change announces itself exactly once through the outbox) and [Rubric §30, Compliance, Privacy & Data Governance] (Terms consent is recorded, never assumed). The class remarks state the two rules the hooks enforce (RedeemSignInLinkHandler.cs:22-38). Provisioning (BR-271): an invitation for an address with no account creates an Attendee with the address already confirmed and no local password, records Terms acceptance as registration does, and raises UserRegistered with EmailVerified true, which also drives the BR-207 speaker auto-link (:24-29). Proven ownership (BR-272): every redemption proves the caller reads the mailbox, so each one announces exactly one UserEmailVerified, either from the aggregate's own ConfirmEmail transition or from this handler, so tickets imported after an earlier proof are still linked (:32-36).
  • Walkthrough: a primary constructor over seven dependencies (RedeemSignInLinkHandler.cs:46-53), five of them forwarded to the base (:54-55); legalAcceptance and timeProvider are kept for the Terms stamp. No fields and three overrides; the account lookup by Email is the base's, not an override.
    • ProvisionUser(Email, SignInLinkProfile, RedeemSignInLinkRequest) (:66-83) guards its arguments (:68-69), creates the account with User.CreateFromInvitation(email.Value, profile.FirstName, profile.LastName) (:71), and resolves the configured Terms version through LegalAcceptancePolicy.ResolveCurrentVersion (:73). When the factory failed, no version is configured, or the visitor did not tick the acceptance, it returns the factory result unchanged (:74-77); otherwise it calls user.AcceptTerms(termsVersion, timeProvider.GetUtcNow().UtcDateTime) and surfaces that failure if there is one (:79-82). The remarks give the deliberate asymmetry with registration (:58-65): a missing acceptance does not refuse, because the token is already spent and a refusal would burn the invitation with no account to send another link to, so the account is created unstamped and the UI's acceptance gate asks on first sign-in.
    • OnUserProvisionedAsync (:92-99) runs after the base has saved the new account, so its database-generated id is populated: it adds a UserRegistered(user.Id, user.Email.Value, user.FirstName, user.LastName, user.Role, EmailVerified: true) domain event (:96-97) and saves again (:98), which captures the outbox row inside the command's transaction (remarks :86-91).
    • OnEmailOwnershipProvedAsync(User, SignInLinkGrant, bool confirmedByThisRedemption, CancellationToken) (:107-119) returns early when confirmedByThisRedemption is true (:112-115); otherwise it adds UserEmailVerified(user.Id, user.Email.Value) and saves (:117-118). The base computes that flag and passes it in: true when this redemption moved an IEmailConfirmableUser from unconfirmed to confirmed, so the aggregate's own ConfirmEmail transition has already raised the event (RedeemSignInLinkHandlerBase.cs:164-176, remarks RedeemSignInLinkHandler.cs:102-106). That is what keeps the announcement at exactly one per redemption.
  • Why it's built this way: the account insert and its UserRegistered outbox row can only commit together because RedeemSignInLinkCommand is ITransactional; the second save in OnUserProvisionedAsync mirrors AuthenticationService.OnUserRegisteredAsync (remarks :86-91), so an invitation-created account looks to every consumer exactly like a registered one. The Identity host comment names this handler beside AuthenticationService.RegisterAsync and ExternalLoginAsync as a raiser of UserRegistered (MMCA.ADC/Source/Services/MMCA.ADC.Identity.Service/Program.cs:280).
  • Where it's used: injected into SignInLinkController as ICommandHandler<RedeemSignInLinkCommand, Result<AuthenticationResponse>> (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/Controllers/SignInLinkController.cs:31) and registered by the module scan (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/DependencyInjection.cs:72). Covered by MMCA.ADC/Tests/Modules/Identity/MMCA.ADC.Identity.Application.Tests/Users/UseCases/RedeemSignInLink/RedeemSignInLinkHandlerTests.cs and the framework's MMCA.Common/Tests/Core/MMCA.Common.Application.Tests/Users/SignInLinkHandlerBaseTests.cs.
  • Caveats / not-in-source: the token validation and spend, the session issue and the account lookup, the confirmation check and the order in which the base calls the three hooks live in RedeemSignInLinkHandlerBase in MMCA.Common and are not visible in this file. Because the confirmation state now arrives as a hook argument rather than in a field, the handler holds no per-call state.

TokenPermissionGrants

MMCA.ADC.Identity.Service · MMCA.ADC.Identity.Service.Authorization · MMCA.ADC/Source/Services/MMCA.ADC.Identity.Service/Authorization/TokenPermissionGrants.cs:34 · Level 4 · class (static)

  • What it is: the composition point that applies every module's permission-grant map to one host's shared PermissionRegistryBuilder, used by the Identity Service host that issues tokens for all four modules.
  • Depends on: PermissionRegistryBuilder, IdentityPermissionGrants, ConferencePermissionGrants, EngagementPermissionGrants, NotificationPermissionGrants; externals: Microsoft.Extensions.DependencyInjection.IServiceCollection.
  • Concept reinforced, an extension block as a DI registration surface. The workspace-wide convention of C# extension types for DI (CLAUDE.md) shows up here as extension(IServiceCollection services) (TokenPermissionGrants.cs:36) exposing AddTokenPermissionGrants().
  • Walkthrough: AddTokenPermissionGrants() (TokenPermissionGrants.cs:44-45) calls services.AddPermissions(ApplyAll). ApplyAll(PermissionRegistryBuilder permissions) (TokenPermissionGrants.cs:53-59) calls each module's own Apply(permissions) in turn: Identity, Conference, Engagement, Notification. Its doc (TokenPermissionGrants.cs:48-51) notes it is exposed separately so a test can build the same registry without booting a web host.
  • Why it's built this way: a token-issuing service needs to know every module's permission set, not just its own, so the token it mints carries claims another module's API can authorize against; the grant maps accumulate and union, so calling this alongside the Identity module's own registration is additive and order-independent (TokenPermissionGrants.cs:38-42).
  • Where it's used: registered by the Identity Service host's composition root.

ForgotPasswordCommand

MMCA.ADC.Identity.Application · MMCA.ADC.Identity.Application.Users.UseCases.ForgotPassword · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/ForgotPassword/ForgotPasswordCommand.cs:20 · Level 4 · record (sealed)

  • What it is: the command that starts a password reset. It wraps the address the reset was requested for, and nothing else, and it is also a durable internal command: the endpoint dispatches it inline, the handler only queues it, and the real work runs when the internal-command processor executes the row.
  • Depends on: ForgotPasswordRequest (the shared wire payload), ICommandWithRequest<out TRequest>, IInternalCommand, InternalCommandNameAttribute.
  • Concept introduced, the command with no caller identity. [Rubric §11, Security] (assesses whether an anonymous surface leaks information through its shape) and [Rubric §5, Vertical Slice] (assesses whether a use case owns its own request shape). Every other user command in this module carries the caller: ChangePasswordCommand is (UserIdentifierType UserId, ChangePasswordRequest Request) and additionally marks itself IUserScopedCommand<ChangePasswordRequest> (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/ChangePassword/ChangePasswordCommand.cs:12-13). This one carries none of that, and the record's own doc comment says why (ForgotPasswordCommand.cs:8-10): the caller has lost the credential, so there is no authenticated user id to scope it to, and the handler answers success whether or not the address holds an account. A caller-scoped marker would be a lie here, and an authorization-flavored failure would be the enumeration oracle the workflow exists to close.
  • Walkthrough: a two-line positional record with a single member, Request, implementing two markers (ForgotPasswordCommand.cs:20-21), under one attribute (:19).
    • [InternalCommandName("Identity.ForgotPassword.v1")] (ForgotPasswordCommand.cs:19) gives the queued row a stable, versioned name, and IInternalCommand (:21) is what lets the handler schedule the command at all: the shared base constrains TCommand to ICommandWithRequest<ForgotPasswordRequest>, IInternalCommand (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/ForgotPassword/ForgotPasswordHandlerBase.cs:71 on Common main, v1.327.0; ADC pins v1.326.0 at MMCA.ADC/Directory.Packages.props:147). The remarks give the reason (ForgotPasswordCommand.cs:12-17, ADR-114): the lookup, token issue and send run when the processor executes the row, so a mail outage defers the email instead of losing it, and the payload is one string, so it round-trips through JSON as the durable queue requires.
    • Request is the whole payload, so the marker interfaces are the load-bearing part of the declaration. Because the record implements ICommandWithRequest<ForgotPasswordRequest>, the module scan auto-registers IValidator<ForgotPasswordCommand> as a CommandRequestValidator<TCommand, TRequest> that delegates to whatever IValidator<ForgotPasswordRequest> is registered (MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.ModuleScanning.cs:86-99).
    • That request validator is ForgotPasswordRequestValidator, and it lives in the framework rather than in ADC (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Validation/ForgotPasswordRequestValidator.cs:11), registered by AddValidatorsFromAssemblyContaining<ClassReference>() because a module scan only sees its own assembly (MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.cs:51-70). It checks the shape of the address and nothing else, and its doc comment states the reason (ForgotPasswordRequestValidator.cs:9): a 400 that depended on whether the address had an account would be exactly the oracle the always-accepted response closes.
  • Why it's built this way: the command record stays app-side even though the workflow is entirely shared, the same split the change-password use case uses. The framework's controller and handler read it back only through ICommandWithRequest<ForgotPasswordRequest> (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/PasswordResetAuthControllerBase.cs:46, ForgotPasswordHandlerBase.cs:43-44, both on Common main), which leaves each app free to attach its own markers: ADC marks its ResetPasswordCommand ICacheInvalidating, and this one carries no cache or caller-scope marker, because starting a reset changes no cached state; its only extra marker is the IInternalCommand the shared handler requires for scheduling.
  • Where it's used: built by PasswordResetController in its one-line factory override CreateForgotPasswordCommand (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/Controllers/PasswordResetController.cs:36) for POST Auth/forgot-password, and handled by ForgotPasswordHandler, which the controller receives as ICommandHandler<ForgotPasswordCommand, Result> (PasswordResetController.cs:29). That inline call writes the queue row; the internal-command processor later resolves the same handler for the row and the send happens there. Covered by MMCA.ADC/Tests/Modules/Identity/MMCA.ADC.Identity.Application.Tests/Users/UseCases/ForgotPassword/ForgotPasswordHandlerTests.cs.

SendEmailConfirmationCommand

MMCA.ADC.Identity.Application · MMCA.ADC.Identity.Application.Users.UseCases.SendEmailConfirmation · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/SendEmailConfirmation/SendEmailConfirmationCommand.cs:20 · Level 4 · record (sealed)

SkiaSharpImageProcessor

MMCA.ADC.Identity.Infrastructure · MMCA.ADC.Identity.Infrastructure.Services.Users · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Infrastructure/Services/Users/SkiaSharpImageProcessor.cs:16 · Level 4 · class (sealed)

  • What it is: the SkiaSharp implementation of IImageProcessor, the avatar normalizer behind BR-116a (ADR-045). It turns an uploaded JPEG, PNG or WebP into a square JPEG of the requested edge length, or returns a validation failure.
  • Depends on: IImageProcessor, ImageContentSniffer, Result and Error.Validation; externals: SkiaSharp (SKCodec, SKBitmap, SKCanvas, SKData, SKMatrix), System.Buffers.ArrayPool<byte>.
  • Concept introduced, re-encode as sanitization. [Rubric §11, Security] and [Rubric §30, Compliance, Privacy & Data Governance] (assesses whether personal data such as photo GPS coordinates is stripped before it is stored). The class doc states the rule (SkiaSharpImageProcessor.cs:10-15): the original bytes never reach the output. The JPEG is encoded from a fresh pixel buffer (SkiaSharpImageProcessor.cs:103-105), so EXIF (including GPS), XMP, IPTC, the ICC profile and any polyglot payload in the upload are discarded by construction rather than by a metadata scrubber that has to know every tag.
  • Concept introduced, bounding the decode, not just the upload. [Rubric §11, Security] and [Rubric §12, Performance & Scalability]. ADR-045's 2 MB cap bounds the compressed file, which a decompression bomb satisfies: the remarks on MaxDecodedPixels note that a 2 MB PNG can declare 40000x40000 and cost roughly 6 GB of frame buffer once decoded (SkiaSharpImageProcessor.cs:22-26, SEC-Common-28). Three ceilings close that gap: MaxDecodedPixels = 50_000_000L (:27), MaxDecodedDimension = 20_000 (:35, so a 1 x 200000 strip inside the area limit is still refused), and a private MaxEncodedBytes of 32 MiB on the bytes read from the stream (:43), which only matters when a caller forgets its own cap.
  • Walkthrough: one public method, NormalizeToSquareJpegAsync(Stream content, int size, CancellationToken) (SkiaSharpImageProcessor.cs:59-107), checking cancellation between each stage.
    • ReadBoundedAsync (:116-142) buffers the upload into memory in pooled 81,920-byte chunks (ReadChunkBytes, :49), because request-body streams cannot seek and the codec reads the header and then the pixels from the same bytes. It returns null the moment the running total would pass MaxEncodedBytes (:127-130), which the caller maps to Image.TooLarge (:69-72).
    • OpenAllowedCodec (:156-182) checks the format twice. First by magic bytes, before Skia sees the content: HasAllowedSignature (:301-302) accepts exactly what ImageContentSniffer.IsAllowedImage admits (JPEG, PNG, WebP), the same set the avatar handler gates on. Skia also decodes GIF, BMP, ICO, WBMP, HEIF, AVIF and RAW, so sniffing first means none of those decoders ever parses an upload. Then IsAllowedFormat (:307-308) requires the decoder Skia actually chose to be JPEG, PNG or WebP as well.
    • The header dimensions are checked by TooLargeToDecode (:317-322) before any frame is allocated, since SKCodec.Create parses only the header. The decode writes into a buffer of exactly those dimensions, so a format cannot understate its header and decode into more memory than was checked.
    • Decode (:197-211) decodes the first frame only (new SKCodecOptions(0), :202): decoding every frame of an animated WebP would multiply the pixel memory for an output that is a single JPEG. Anything short of SKCodecResult.Success, including a truncated scan's IncompleteInput, is refused rather than accepted as a partly blank image.
    • RenderCoverSquare (:229-256) draws onto a size x size canvas cleared to white (:241, since JPEG has no alpha), scaled so the shorter displayed edge fills the square (upscaling small images), centered so the overflow is cropped equally from both sides. The EXIF orientation from OrientationMatrix (:265-293) is applied in the same transform, before the crop, so a portrait phone photo stored landscape and tagged "rotate 90" is cropped along the right axis. Sampling is linear with linear mipmaps (:56), so a 4000x3000 photo shrunk to a 256-pixel avatar does not alias.
    • The square is encoded at JPEG quality 85 (JpegQuality, :46) with 4:2:0 chroma downsampling (:105).
    • Failures are two validation errors: Image.TooLarge (:324-328) and Image.Undecodable (:330-334, "The uploaded file is not a supported image."), so the caller can surface them as a 400 rather than an exception.
  • Why it's built this way: the processor lives in Infrastructure behind an Application-layer interface, so SetUserAvatarHandler stays free of SkiaSharp and is testable with a fake ([Rubric §3, Clean Architecture]). It holds no state, which is why it is registered as a singleton and its native library loads on the first upload rather than at registration (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Infrastructure/DependencyInjection.cs:17-20).
  • Where it's used: registered with services.TryAddSingleton<IImageProcessor, SkiaSharpImageProcessor>() in AddModuleIdentityInfrastructure (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Infrastructure/DependencyInjection.cs:25) and called by SetUserAvatarHandler with a 256-pixel edge (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/SetUserAvatar/SetUserAvatarHandler.cs:37, :103). Exercised by MMCA.ADC/Tests/Modules/Identity/MMCA.ADC.Identity.Infrastructure.Tests/Services/Users/SkiaSharpImageProcessorTests.cs, which covers the pixel-bomb and single-dimension refusals (:57, :69), the JPEG, PNG and WebP acceptances (:79-83), the GIF, BMP, ICO and TIFF rejections (:97-102), metadata stripping (:115) and orientation-before-crop (:141).

DeleteAvatarBlobInternalCommand

MMCA.ADC.Identity.Application · MMCA.ADC.Identity.Application.Users.UseCases.DeleteAvatarBlob · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/DeleteAvatarBlob/DeleteAvatarBlobInternalCommand.cs:17 · Level 4 · record (sealed)

EmailConfirmationReminder

MMCA.ADC.Identity.UI · MMCA.ADC.Identity.UI.Components · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.UI/Components/EmailConfirmationReminder.razor.cs:15 · Level 4 · class (partial)

  • What it is: the one-line, dismissible reminder a signed-in attendee with an unconfirmed address sees in the content header, with a "resend the link" action. It never blocks the page (EmailConfirmationReminder.razor.cs:8-14).
  • Depends on: IEmailConfirmationUIService (injected, :17), ClaimNames (EmailVerified, :28), Result; externals: Blazor's AuthorizeView and ClaimsPrincipal, MudBlazor's MudAlert and MudButton (markup, EmailConfirmationReminder.razor:7-38).
  • Concept introduced, the claim-driven, non-blocking nudge. [Rubric §24, Forms, Validation & UX Safety] assesses whether the UI guides a user to a safe state without trapping them. The component decides from the token alone: IsUnconfirmed (:27-28) is true only when the email_verified claim reads "false" (ordinal, case-insensitive). The class doc records that the server issues that claim only as "false", so a confirmed account renders nothing, and that it clears on the next token refresh after confirmation (:11-13). The markup comment adds the scope: only an attendee can be signed in unconfirmed, because a privileged account is refused at sign-in until it confirms (EmailConfirmationReminder.razor:4-6). [Rubric §11, Security]: the reminder is a convenience; the enforcement for privileged accounts lives at sign-in, not here.
  • Walkthrough
    • State (:19-22): _dismissed, _sending, _sent, _failed. Dismissing (Dismiss, :33) hides the alert for this component's lifetime only (the markup comment says "for this session").
    • EmailOf (:30-31): the address from ClaimTypes.Email, falling back to the raw email claim.
    • ResendAsync (:40-59): returns when a send is already in flight or the principal carries no address (:42-45), then calls ConfirmationService.ResendEmailConfirmationAsync(email) (:51) and maps the Result straight onto _sent and _failed (:52-53); _sending clears in finally (:55-58). Its doc (:35-39) explains the mapping: the endpoint answers the same way for any well-formed request and keeps its own per-address budget, so a success reads as "sent" and only a transport failure reads as "try again".
    • Markup: once sent, the resend button is replaced by a role="status" line; a failure adds a second role="status" line (EmailConfirmationReminder.razor:15-29), so a screen reader hears the outcome.
  • Why it's built this way: an unconfirmed attendee keeps a working session, so a modal or a redirect would punish the common case; a header line with one action is enough to get the address confirmed. Reading the claim rather than calling the server keeps the reminder free on every page render.
  • Where it's used: contributed to the shell by IdentityUIModule through ContentHeaderComponentTypes (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.UI/IdentityUIModule.cs:53); the resend lands on EmailConfirmationController. Covered by EmailConfirmationReminderTests in MMCA.ADC.Identity.UI.Tests.

TicketHolderInvitedHandler

MMCA.ADC.Identity.Application · MMCA.ADC.Identity.Application.Users.IntegrationEventHandlers · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/IntegrationEventHandlers/TicketHolderInvitedHandler.cs:36 · Level 5 · class (sealed, partial)

  • What it is: the Identity-side subscriber for TicketHolderInvited, published by Engagement. It does not send the invitation itself: it schedules the Identity.SendSignInLink.v1 internal command (SendSignInLinkInternalCommand, ADR-114) that emails the ticket holder a sign-in link (BR-271) (TicketHolderInvitedHandler.cs:12-16).
  • Depends on: ScopedIntegrationEventHandlerBase<TIntegrationEvent> (base, :39), IInternalCommandScheduler (resolved from the delivery scope, :47), SendSignInLinkInternalCommand, SignInLinkPurpose (Invite, :52); externals: IServiceScopeFactory, ILogger with the [LoggerMessage] source generator.
  • Concept reinforced, schedule from the handler, send from the durable row. [Rubric §6, CQRS & Event-Driven], [Rubric §29, Resilience & Business Continuity]. The scoped-handler shape is taught at SpeakerLinkedToUserHandler; what this one adds is that the handler only schedules. The <remarks> (:17-33) give the reasons: the send runs from the internal-command row, so a mail outage defers the invitation instead of failing this delivery and a slow relay never holds the broker message; no transaction is active in the delivery scope, so the scheduler saves the row immediately; and a scheduling failure is thrown, which leaves the delivery unacknowledged for the broker to retry.
  • Walkthrough (HandleScopedAsync, :42-67)
    1. Resolve the scheduler from the scope the base opened (:47).
    2. Build the command (:49-56) from the event: MessageId as the invite id (:50), the address, SignInLinkPurpose.Invite, first and last name, event name and start.
    3. ScheduleAsync (:58); on a failed Result throw an InvalidOperationException naming the event id and the error codes (:59-64), so the base's log-and-propagate envelope fails the delivery.
    4. Log Invitation {InviteId} scheduled for event {EventId} at Information (:66, template :75-76).
    • LogHandlerFailure (:72-73) replaces the base's generic error line with one that names the event and the invitation, never the address (:69, template :78-79).
  • Why it's built this way: idempotency comes from the id, not from a check in this class. The row's InviteId is the event's MessageId, which survives the outbox and the broker, so a redelivery schedules a row the send handler recognizes as already sent (:24-28). Keeping the address out of every log line keeps personal data out of telemetry.
  • Where it's used: driven by the Identity service's broker consumer registration (MMCA.ADC/Source/Services/MMCA.ADC.Identity.Service/IdentityBrokerConsumers.cs, wired from that host's Program.cs); the scheduled row is handled by SendSignInLinkInternalCommandHandler. Its contract with the event is guarded by IntegrationEventContractTests in MMCA.ADC.Architecture.Tests.

UserList

MMCA.ADC.Identity.UI · MMCA.ADC.Identity.UI.Pages.Users · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.UI/Pages/Users/UserList.razor.cs:28 · Level 6 · class (partial)

  • What it is: the code-behind for the organizer user list page at /users, a thin shell over the framework's shared UserAdminList<TUser> (ADR-116), which renders the roster, the mobile cards, and the administration actions (lock, unlock, change role) against the framework's Admin/Users endpoints. ADC supplies what stays its own: the route, the Organizer authorization, the BR-51 roster endpoint, the extra name, creation and Signed in columns, the role vocabulary, and delete (UC-21).
  • Depends on: UserAdminList<TUser>, IUserUIService (delete only), IEntityService<UserListDTO, UserIdentifierType> (the roster read), UserListDTO, RoleNames, Result.
  • Concept introduced, splitting the roster read from the administration write. [Rubric §18, UI Architecture], [Rubric §7, Microservices Readiness]. The class doc's <remarks> (UserList.razor.cs:21-27) states the reasoning directly: the roster now reads through the standard entity-service client for UserListDTO (GET Users/paged, the generic paged entity contract), so every grid operator, the sort and the paging reach the server unchanged; the page adds a Signed in column (the live session count) whose two-value filter travels as ActiveSessionCount. Delete stays on IUserUIService, and the three account actions (lock, unlock, change role) go through the framework's client either way, since those are identical in every app. The class was previously its own DataGridListPageBase<UserListDTO> subclass with its own grid, mobile list, search, and delete wiring; that machinery moved into UserAdminList<TUser> and this class shrank to ComponentBase plus a viewer-clock hook, one data-fetch method and the Signed in filter plumbing.
  • Walkthrough
    • AssignableRoles (UserList.razor.cs:34-35): the same least-to-most-privileged role array UserDetail carries, kept here because the base's inline role editor needs it for this list.
    • Injected members (:37, :39, :42, :44, :47): UserService, the Users entity-service client, ViewerTime, the _list reference to the UserAdminList<UserListDTO>, and _mobileSignedIn, the phone's Signed in choice (true signed in, false not signed in, null no filter).
    • ViewerTime and OnAfterRenderAsync (:41-60): the Created On column renders on the viewer's clock, so the page injects ViewerTimeZone (:42) and, on first render only, awaits ViewerTime.EnsureResolvedAsync() once JS is available and calls StateHasChanged() when the zone changed (:56-59). Until then dates show on the UTC fallback.
    • FetchPageAsync (:75-82): the one data method ADC still owns, now a single expression: Users.GetPagedAsync(filters, page, pageSize, sortColumn, sortDirection, cancellationToken: cancellationToken) (:82). The grid's filter bag goes through verbatim (every column operator, the search box's Email / Email~search keys and the ActiveSessionCount filter), so no ADC-side mapping onto named filters remains.
    • SignedInText (:86-91): the Signed in cell, "{0} devices", "1 device" or "Not signed in" through the SignedIn.* resource keys.
    • SignedInChoice (:99-105) and OnSignedInFilterChangedAsync (:114-131): the column filter's two-value contract on the ActiveSessionCount key. SignedInChoice reads the choice back off the filter definition (GreaterThan 0 is true, Equal 0 is false, anything else null); the change handler sets the operator to GreaterThan or Equal with value 0 and applies it, or clears the filter when the choice is null.
    • InjectMobileSignedInFilter (:139-145) and OnMobileSignedInChangedAsync (:149-156): the phone's card list has no column filter, so the chosen value is added to the fetch bag as ActiveSessionCount with ">" or "=" against "0" (:143), the same contract the column sends, and a change reloads the cards from the first page through _list.ReloadAsync().
  • Why it's built this way: nameof(UserListDTO.ActiveSessionCount) (:143), rather than a string literal, keeps the filter key tied to the DTO's own property name, so a rename is a compile error rather than a silently dead filter. Sending the verbatim bag to the generic paged endpoint means the server, not the page, owns which properties are filterable.
  • Where it's used: routed as the organizer user-management page in the ADC web and MAUI UI; the server side it calls for the roster is UsersController, whose GET paged endpoint is gated on the UsersRead capability in IdentityPermissions (UsersController.cs:224); the lock/unlock/role actions it delegates to the base call UsersAdminController. RoleList reuses UserList.razor.cs as a reference for the same list-shell pattern applied to roles.

DeleteAvatarBlobInternalCommandHandler

MMCA.ADC.Identity.Application · MMCA.ADC.Identity.Application.Users.UseCases.DeleteAvatarBlob · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/DeleteAvatarBlob/DeleteAvatarBlobInternalCommandHandler.cs:17 · Level 6 · class (sealed)

  • What it is: the handler for DeleteAvatarBlobInternalCommand: a thin sealed subclass of the shared DeleteBlobInternalCommandHandlerBase<TCommand> that only names the blob kind for its log lines (DeleteAvatarBlobInternalCommandHandler.cs:17-24).
  • Depends on: DeleteBlobInternalCommandHandlerBase<TCommand>, IFileStorageService; externals: Microsoft.Extensions.Logging.
  • Concept reinforced, idempotent cleanup on a not-found, extracted to a shared base. [Rubric §29, Resilience & Business Continuity]: the not-found-is-success behavior now lives once in DeleteBlobInternalCommandHandlerBase<TCommand>.HandleAsync, which treats ErrorType.NotFound from fileStorage.DeleteAsync as success rather than a failure, so a retried delete (at-least-once dispatch, or a blob already removed by a prior attempt) does not surface as one. This module's handler no longer implements that logic itself; it only supplies the label.
  • Walkthrough: the whole class body is a primary constructor forwarding fileStorage and logger to the base and one property override, BlobKind => "Avatar blob" (:17-24), which the base's [LoggerMessage] lines interpolate as {BlobKind} {BlobName} deleted / was already gone / could not be deleted.
  • Why it's built this way: DeleteSessionAssetBlobInternalCommandHandler in the Conference module needed the identical delete-and-tolerate-not-found flow, so the shared logic (including the three [LoggerMessage] methods) moved to MMCA.Common.Application.InternalCommands.DeleteBlobInternalCommandHandlerBase<TCommand>; each module now contributes only its BlobKind label instead of duplicating the handler.
  • Where it's used: registered as the handler for DeleteAvatarBlobInternalCommand through the module's DI registration.

DeleteAvatarBlobInternalCommandValidator

MMCA.ADC.Identity.Application · MMCA.ADC.Identity.Application.Users.UseCases.DeleteAvatarBlob · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/DeleteAvatarBlob/DeleteAvatarBlobInternalCommandValidator.cs:10 · Level 5 · class (sealed)

  • What it is: the FluentValidation validator for DeleteAvatarBlobInternalCommand: requires BlobName to be non-empty (DeleteAvatarBlobInternalCommandValidator.cs:10-15).
  • Depends on: FluentValidation.AbstractValidator<T> (external), DeleteAvatarBlobInternalCommand.
  • Concept reinforced, the one-rule request validator. A minimal sibling of the validators taught in depth elsewhere (RegisterRequestValidator in the auth chapter, SetUserAvatarCommandValidator in this group): one RuleFor in the constructor, NotEmpty().
  • Where it's used: wired into the CQRS pipeline's decorator chain for DeleteAvatarBlobInternalCommand; its presence is asserted by the architecture fitness test CommandValidatorCoverageTests, which checks every command has a validator.

LegalAndDataCard

MMCA.ADC.Identity.UI · MMCA.ADC.Identity.UI.Pages.Users.Profile · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.UI/Pages/Users/Profile/LegalAndDataCard.razor.cs:27 · Level 6 · class (partial)

  • What it is: the "Legal and your data" card of the profile page: it shows the user's Terms of Service standing, links the legal documents, and downloads the data-subject export. It is the sub-component Profile renders as <LegalAndDataCard UserId="_userId.Value" /> (Profile.razor:121), extracted so the page's code-behind stays a container.
  • Depends on: IUserUIService (ExportAsync, LegalAndDataCard.razor.cs:144), ILegalAcceptanceUIService (resolved optionally through IServiceProvider, :46, :106), LegalAcceptanceDTO, LegalSettings via IOptions (:43), ViewerTimeZone (:49), ISensitiveFileSaver (:44), SafeFileName (:153), and IToastService (:45).
  • Concept introduced (1), one export action, delivery delegated to the head's saver. [Rubric §22, Responsive & Cross-Browser], [Rubric §30, Compliance, Privacy & Data Governance]. DownloadMyDataAsync (LegalAndDataCard.razor.cs:139-178) fetches the export once through UserService.ExportAsync(UserId, LifetimeToken) (:144), toasting Snackbar.DownloadDataFailed on a failed result (:145-149), then hands the bytes to Saver.SaveAsync(fileName, ExportContentType, file.Content, L["ShareTitle"].Value, LifetimeToken) (:156), with ExportContentType = "application/json" (:30). The card has no head branch of its own: the class remarks (:20-26) say the framework's ISensitiveFileSaver delivers the file the way each head can receive it. On a browser head that is a save through an object URL from MMCA.Common.UI's file-download.js, because the export endpoint needs the bearer token a plain download link never carries; on the MAUI head it is a write into the head's own dedicated temp folder followed by the OS share sheet, which is where "save to Files" lives on both platforms (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Capabilities/Files/ISensitiveFileSaver.cs:3-19). ADC names that folder mmca-exports when it calls UseMauiDeviceCapabilities (MMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI/MauiProgram.cs:108). The staged copy is the full personal-data export, so the saver purges the folder before each write and at app start, and never deletes the copy after the share, because Android's share request returns when the intent launches and a delete then would race the receiving app reading the file (same doc). SaveAsync returns false when no save or share surface was presented (ISensitiveFileSaver.cs:34-39), and the card turns that into a Snackbar.ShareUnavailable warning (:156-159).
  • Concept introduced (2), the file name is untrusted. [Rubric §11, Security]. The server's suggested name goes through SafeFileName.Reduce (:151-154), which trims it, strips directory segments with Path.GetFileName and returns null for an empty value, . or .. (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Capabilities/Files/SafeFileName.cs:23-33), so it cannot steer the native staging write out of its folder. On null the card falls back to user-data-{UserId}.json under InvariantCulture (:153-154). The fallback is the caller's job because the saver reduces the name again and throws ArgumentException when nothing usable is left (ISensitiveFileSaver.cs:25-28, :40).
  • Concept reinforced, the component-scoped lifetime token. [Rubric §18, UI Architecture]. Same shape as Profile: a private CancellationTokenSource (:32), a LifetimeToken property over _cts.LifetimeToken() (:53) so a call that resumes after disposal gets a cancelled token, and Dispose that cancels then disposes (:76-98). OperationCanceledException is swallowed in the load and in the download (:120-123, :161-164). The generic catch (Exception) (:165-173, under a scoped CA1031 suppression whose justification is on the pragma line) is deliberate: this runs from an OnClick callback, which on the native heads is fatal to the host if anything escapes, so any failure of the fetch or of the saver's hand-off (a staging write and the share sheet on a native head, the JS save in a browser) becomes a Snackbar.DownloadDataFailed toast (comment :169-171).
  • Walkthrough
    • Status lines (:57-73): TermsStatusText is null when the standing is unknown or the host configures no terms version, the "accepted on {date}" line when both AcceptedVersion and AcceptedOn are present (date formatted through ViewerTime.Format(acceptedOn, "d")), and "not accepted" otherwise. TermsOutdatedText appears only when an older version is on record and IsCurrent is false.
    • OnInitializedAsync (:101-124): resolves ILegalAcceptanceUIService with GetService and returns if absent, so a composition without the framework client (a component test rendering the profile alone) keeps the card working without the status line (comment :103-105). A failed read is silent, like the avatar read (:113-118).
    • OnAfterRenderAsync (:131-137): on first render resolves the viewer's time zone once JS is available and re-renders when it changed, so the acceptance date moves from the UTC fallback to the viewer's clock.
  • Why it's built this way: the standing and the export both act only on the caller, which is why the card takes a single UserId parameter (:40, [EditorRequired]) and reads the standing from the token-scoped framework client. The server side of the standing is LegalAcceptanceController; the export is served by UsersDataExportController.
  • Where it's used: rendered by Profile (Profile.razor:121). The card holds no staging folder of its own: the MAUI host passes mmca-exports to the saver's registration (MMCA.ADC/Source/Hosts/UI/MMCA.ADC.UI/MauiProgram.cs:108).

Profile

MMCA.ADC.Identity.UI · MMCA.ADC.Identity.UI.Pages.Users.Profile · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.UI/Pages/Users/Profile/Profile.razor.cs:21 · Level 6 · class (partial)

  • What it is: the code-behind for the "My Profile" page at /profile: the signed-in user's self-service surface, namely set or remove the avatar, change the password (through the shared ChangePasswordCard), reach the devices and sign-in history page, manage passkeys where they are offered, see the legal documents and download their data (the LegalAndDataCard sub-component), and delete the account. The class doc says the page manages the avatar and the delete; the password section is the shared card (Profile.razor.cs:17-20).
  • Depends on: IUserUIService, IAuthUIService (logout after delete only, Profile.razor.cs:24, :287), IToastService, IAppDialogService (the delete confirmation, :29), IPendingToastService (parks the delete confirmation across the forced reload, :30, :281), IPushRegistrationService (:31), SignInSettings via IOptions (:35), IMediaPickerService and PickedMedia, ChangePasswordCard and LegalAndDataCard (markup, Profile.razor:83, :121), plus Blazor's AuthenticationStateProvider, NavigationManager (with its LocationChanged event, imported from Microsoft.AspNetCore.Components.Routing, Profile.razor.cs:4) and InputFileChangeEventArgs (Profile.razor.cs:1-35). The localizer L is injected in the markup half (Profile.razor:4), which is also where the route and the [Authorize] attribute live (Profile.razor:1-2).
  • Concept introduced (1), the cross-head capability branch. [Rubric §22, Responsive & Cross-Browser] assesses whether one component genuinely serves different hosts. The same page runs in the Blazor web head and inside the MAUI hybrid, and the avatar affordance differs: the markup branches on MediaPicker.IsSupported (Profile.razor:47) to offer "choose photo" plus "take photo" buttons on a native head, and falls back to a browser file input on the web (the else branch of that @if). Both branches converge on one private method, UploadAvatarStreamAsync (Profile.razor.cs:207-218), so the upload contract is written once. That convergence is also why IUserUIService's upload method is typed on a raw Stream rather than on a framework-specific file type (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.UI/Services/IUserUIService.cs:33).
  • Concept introduced (2), the component-scoped CancellationTokenSource. [Rubric §18, UI Architecture]. The page holds private readonly CancellationTokenSource _cts = new() (Profile.razor.cs:40) and cancels plus disposes it through the standard disposable pattern (Profile.razor.cs:346-362). It never reads _cts.Token directly: every service call passes the LifetimeToken property (Profile.razor.cs:45, _cts.LifetimeToken()), because reading Token off a disposed source throws ObjectDisposedException; since Dispose cancels before it disposes, a load or handler that resumes after the user navigated away gets an already-cancelled token and stops through its OperationCanceledException path (comment at :42-44). Every async entry point then catches OperationCanceledException and deliberately does nothing (Profile.razor.cs:75-78, :127-130, :191-194, :235-238, :290-296), with the comment naming the two causes: component disposal and an InteractiveAuto render-mode transition. A user who navigated away must not be shown a red error toast for a request that was cancelled on their behalf; a genuine failure still toasts. The load and both upload paths also carry a generic catch (Exception) under a scoped CA1031 suppression (:79-84, :131-136, :195-200), each pragma line naming why: a failure becomes a toast, and on the native heads an exception escaping a UI event handler is fatal to the host.
  • Concept reinforced, the Result-returning UI service. [Rubric §24, Forms, Validation & UX Safety]. Every call into IUserUIService returns a Result, and the page reads it with TryGetValue, IsSuccess or IsFailure rather than with a null check (Profile.razor.cs:69, :210, :225, :269). A failed read and a successful read of nothing are therefore different states, which is what lets the avatar load stay silent on failure while an avatar upload failure toasts.
  • Walkthrough
    • OnInitializedAsync (Profile.razor.cs:53-89): awaits AuthStateProvider.GetAuthenticationStateAsync() (under a scoped BL0013 suppression whose justification is that the page reads the identity once per page load, :57-59) and reads the subject with the shared GetUserId() claims helper (:63), whose comment records that it accepts both the sub and the nameidentifier form and parses invariantly (:61-62). The page identifies its subject from the token, never from a route parameter, which is what makes it structurally incapable of acting on another account. Only when the claim parses does it fetch the avatar URL (:69-72), and a failed avatar read is deliberately silent (:67-68): the card falls back to its person icon rather than greeting the user with an error. _isLoading is cleared in finally (:85-88).
    • Client-side avatar guard (:37-38): MaxAvatarBytes = 2 * 1024 * 1024, enforced on both heads before any bytes leave the device. The browser path rejects an oversized file on its reported size with a warning toast (:176-180). The native path cannot trust a reported size, so ReadWithinAvatarLimitAsync (:148-166) copies the picked stream into a MemoryStream in 81,920-byte chunks (:151) and returns null the moment the running total would pass the limit (:155-159); its doc (:143-147) gives the reason: the picker downscales a photo but hands back the original when it cannot, and a picked stream does not always report a length. The doc comment on the constant says exactly what this is: a mirror of the server's BR-116a limit, not the enforcement point. The server re-checks in UsersController (UsersController.cs:98-104) and again in SetUserAvatarHandler.
    • Avatar paths: PickAvatarAsync (:95) and CaptureAvatarAsync (:99-100) both funnel through UploadPickedMediaAsync(pick, noMediaMessage) (:102-141), which disposes the PickedMedia with using (:107). When the picker returns null (media is null, :108-116) the behavior depends on the caller: picking passes noMediaMessage: null and returns silently, but capturing passes L["Avatar.NoPhotoTaken"] and shows an info toast, because an empty capture may be a cancel or a camera that could not be opened (the platform picker swallows that failure), so the attendee is told either way (comment at :97-98). A picked photo is then read through the size check above and an oversized one toasts Avatar.TooLarge (:118-123) before the bounded copy is uploaded (:125). The browser path OnBrowserInputChangedAsync (:168-205) opens the stream with file.OpenReadStream(MaxAvatarBytes, LifetimeToken) (:185) and wraps it in await using so the read stream is released even on failure. UploadAvatarStreamAsync (:207-218) toasts on a failed result and only assigns _avatarUrl on success (:216).
    • RemoveAvatarAsync (:220-243): the failure branch of the result toasts Avatar.RemoveFailed (:232), so the user sees an explicit outcome for "did not work".
    • Password section (Profile.razor:76-83): the code-behind carries no password state, validators, or save method. The page keeps only the card frame and heading and drops in the shared ChangePasswordCard from MMCA.Common.UI, which owns the fields, the required, min-length and match validators, the ErrorSummary, the submit and the toasts (per the markup comment, Profile.razor:76-77). [Rubric §24, Forms, Validation & UX Safety]: that client-side validation is an ergonomics layer over, never instead of, the server rules that live in ChangePasswordRequestValidator and ChangePasswordHandler.
    • Devices and sign-in history (Profile.razor:86-101): a card whose only content is a link to RoutePaths.Sessions (:98). The comment above it records why there is no logic here (:86-87): the page itself ships from MMCA.Common, so this card is only the way in from the profile.
    • Passkeys (Profile.razor:104-115): rendered only when SignInOptions.Value.OfferPasskeys is true (:108), hosting the framework's PasskeysPanel (:114). The code-behind comment (Profile.razor.cs:33-34) records that this is the same switch the login page's passkey button reads (ADR-139) and that passkeys ship off, so the card exists only where SignIn:OfferPasskeys is true (Development and the AppHost).
    • Legal and your data (Profile.razor:118-121): <LegalAndDataCard UserId="_userId.Value" />, extracted into its own component so this code-behind stays a container. See LegalAndDataCard.
    • DeleteAccountAsync (:245-301): guards on a known _userId (:247-251), then asks Dialogs.ConfirmAsync with the DeleteAccount.Confirm* title and message and destructive: true (:253-258), aborting on anything but a confirmation (:259-260). Before the delete it unregisters this device's push installation (:267): the comment (:265-266) explains that once the account is erased the access token is refused, so a later Devices DELETE could not authenticate and the phone would keep the installation. It then deletes through LifetimeToken (:269); if the server answers that the account survives, it re-registers the device (:273, comment :271-272) and toasts the failure. Both push steps run through RunPushStepAsync (:329-342), a best-effort wrapper (ADR-044) whose swallowed failure never decides the deletion. On success the confirmation is not an immediate Toast.Success: the page queues it through PendingToast.QueueAsync(ToastSeverity.Success, ..., CancellationToken.None) (:281), because the forced reload destroys anything IToastService renders on this page, so the message is parked for the shared layout to show once on the next page load; it uses CancellationToken.None rather than LifetimeToken because leaving this page cancels that token (comment :278-280). Only then does it leave the page, sign out and reload, in that order: LeaveForHomeAsync() (:286), AuthService.LogoutAsync() (:287), and NavigateTo("/", forceLoad: true) (:288). The comment above the move (:283-285) records the failure this ordering prevents: signing out while still on this [Authorize] page let the router swap the page for the login redirect, a second forced load that consumed the parked toast before the reload to home, so home showed nothing. A cancellation mid-delete deliberately does not re-register the device (:290-296): the outcome is unknown, the server may have committed the erasure, and a surviving account self-heals at the next app start through the push registration listener. The forced load matters: the account is gone, so the circuit and every piece of cached client state must be rebuilt from scratch rather than kept alive against a dead identity.
    • LeaveForHomeAsync (:308-327): moves to home in place, without a reload, and waits for the move to land so the sign-out that follows re-renders the public home instead of this page (doc :303-306). It completes a TaskCompletionSource created with RunContinuationsAsynchronously from a handler on NavigationManager.LocationChanged (:310-313), calls NavigateTo("/") (:316) and waits at most five seconds (TimeSpan.FromSeconds(5), :317). A TimeoutException is swallowed on purpose (:319-322): the sign-out goes ahead anyway and the forced reload still lands on home. The handler is unsubscribed in finally (:323-326).
  • Why it's built this way: keeping avatar, password, sessions, passkeys, legal and data, and deletion on one page mirrors the account-level scope of all of them (each acts on the caller and only the caller), and every action ends in a toast with a localized message, so the page needs no bespoke error surface. [Rubric §21, Accessibility]: the markup carries an explicit aria-label on the MudAvatar (Profile.razor:33) because MudBlazor renders role="img", which the axe role-img-alt rule requires to carry an accessible name even in the fallback-icon state, and the comment above it says so (Profile.razor:30-32).
  • Where it's used: routed at /profile for any authenticated user in both the web and MAUI heads. Its server round trips land on the Identity avatar endpoints on UsersController, AuthController's PUT password, UsersController's DELETE {userId}, and the framework's push Devices endpoints.
  • Caveats / not-in-source: the client-side password rules (minimum length, match) now live inside the shared ChangePasswordCard in MMCA.Common.UI, not in this page, so what they enforce is not determinable from these files.

UserDetail

MMCA.ADC.Identity.UI · MMCA.ADC.Identity.UI.Pages.Users.UserDetail · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.UI/Pages/Users/UserDetail/UserDetail.razor.cs:30 · Level 6 · class (sealed)

  • What it is: the code-behind for the organizer account-detail page: lock or unlock an account, change its role, start a "View as" grant on it (web hosts only), and see the account's live sessions (the Signed-in devices section) and its retained sign-ins (the Sign-in history section), one user at a time (class doc, UserDetail.razor.cs:15-23). The markup inherits the framework's DetailPageBase (UserDetail.razor:7, @inherits MMCA.Common.UI.Pages.Common.DetailPageBase), so the page-scoped token, the load guard and the disposal all come from the base.
  • Depends on: DetailPageBase (base, MMCA.Common/Source/Presentation/MMCA.Common.UI/Pages/Common/DetailPageBase.cs:28) and through it LatestLoadGuard; IUserAdminUIService<TUserDto> (closed over UserAdminDTO, :51), IAppDialogService (:53), IToastService (:55), IExternalLinkService (:64), RoleNames, SignInSummaryResponse (the sign-in row type, :41); externals: Blazor's AuthenticationStateProvider, BreadcrumbItem, the viewer-time-zone service ViewerTimeZone (:61), and RefreshSessionSummaryResponse (the session row type IUserAdminUIService.GetSessionsAsync returns, MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Administration/IUserAdminUIService.cs:32). The markup hosts the framework's UserSessionsTable, ViewAsButton and SignInHistoryTable (UserDetail.razor:112, :127, :136).
  • Concept introduced, the self-action guard on an administration page. [Rubric §11, Security], [Rubric §24, Forms, Validation & UX Safety]. CanAdminister (UserDetail.razor.cs:75-78) compares the account on screen (_user.Id) against the caller's own id, read from the authentication state during OnInitializedAsync (:90-92), and the admin actions are offered only when it is true (UserDetail.razor:73). The class <remarks> (UserDetail.razor.cs:24-29) give the reason: locking or demoting yourself removes the capability needed to undo it. The guard is a courtesy, not the enforcement: the API refuses the same self actions with 403 (UserAdministration.Self), so hiding them only spares the operator a refusal.
  • Walkthrough
    • OffersViewAs (:68-73): CanAdminister && !ExternalLinks.InterceptsLinks. Its doc explains the head restriction: the grant token travels in the same-origin API proxy's overlay cookie (ADR-137), which the MAUI head does not have, so a grant started there could never be used. InterceptsLinks is what tells the MAUI head (a native WebView host, true) from the web hosts (false) (comment :63).
    • OnInitializedAsync (:81-93): builds the breadcrumb trail and reads _currentUserId from AuthStateProvider.GetAuthenticationStateAsync(), under a scoped BL0013 suppression justified on the pragma line (read once per page load, :89-91).
    • OnAfterRenderAsync (:100-106): on first render only, asks ViewerTime.EnsureResolvedAsync(PageToken) to read the browser's time zone and calls StateHasChanged when it changed, so the Created and Locked-since instants move from the UTC fallback to the viewer's clock, the pattern UserList uses for Created On (:59-61).
    • OnParametersSetAsync (:113): calls LoadAsync on every parameter set rather than only on first render, so navigating from one account to another inside the same page instance reloads the account named in the URL, the same pattern UserList's sibling pages rely on.
    • LoadAsync (:115-149): starts with the base's BeginLoad() (:119), which supersedes any load still in flight (a route change, or the reload after an action) and returns the token and generation this load owns (DetailPageBase.cs:48-53). It fetches the account through UserAdminService.GetAsync(Id, token) (:123) and hands the result to CompleteLoad(generation, result) (:128), which records Loaded, NotFound or Failed in the base's LoadState only when the load is still current (DetailPageBase.cs:67). On a failed or superseded fetch it clears _user and resets _selectedRole to RoleNames.Attendee, but only if this generation is still current (:130-134); otherwise it adopts the user, seeds _selectedRole from its role, and goes on to LoadSessionsAsync and then LoadSignInsAsync (:139-143). An OperationCanceledException from disposal or an InteractiveAuto render-mode transition is swallowed (:145-148).
    • LoadSessionsAsync (:155-165): reads the account's live sessions through UserAdminService.GetSessionsAsync(Id, token) with the load's own token, then drops the answer if a newer load has started (LoadGuard.IsCurrent(generation), :158). A failed read sets _sessionsLoadFailed and leaves _sessions empty, kept apart from a genuinely empty answer so the section reports the failure instead of claiming the user is not signed in (:151-154).
    • LoadSignInsAsync (:171-181): the same shape for Admin/Users/{id}/sign-ins through UserAdminService.GetSignInsAsync(Id, token) (:173), one row per retained sign-in, newest first (doc :167-170); a failure sets _signInsLoadFailed, again kept apart from an empty answer.
    • ToggleLockAsync (:183-224): confirms through Dialogs.ConfirmAsync with a lock- or unlock-worded message built from the account's own email, marking the dialog destructive: locking (:192-197) so only the lock is styled as destructive, then calls UserAdminService.LockAsync or UnlockAsync, toasts the outcome, and reloads on success. _isBusy is set before the call and cleared in finally (:204, :220-223); the lock, unlock and role calls all pass PageToken and address the account by _user.Id (:208-209, :247).
    • ChangeRoleAsync (:226-261): a no-op when the selected role already matches the account's role (:228, ordinal comparison), otherwise the same confirm-then-call-then-toast-then-reload shape as ToggleLockAsync (with a non-destructive dialog, :233-237), through UserAdminService.SetRoleAsync.
  • Why it's built this way: the page declares no CancellationTokenSource and no Dispose of its own. PageToken (DetailPageBase.cs:38) is the base's _cts.LifetimeToken(), cancelled when the page is disposed, so an action that resumes after the user navigated away stops through its OperationCanceledException path; the route-driven load takes the narrower per-generation token from BeginLoad instead, so a newer load also cancels an older one. Routing the fetch through CompleteLoad is what keeps "this account does not exist" and "this account could not be fetched" as separate body states (the comment at :125-127) rather than one shared not-found message. AssignableRoles (:35-36) is [RoleNames.Attendee, RoleNames.ContentEditor, RoleNames.Organizer], least to most privileged, taken from the domain's own role vocabulary so the menu never drifts from the roles the server actually accepts. Both mutating actions confirm before acting, the same destructive-action discipline UserList's delete uses.
  • Where it's used: routed from UserList as the per-account detail page in the ADC web and MAUI UI; the account it edits is read and written through IUserAdminUIService<UserAdminDTO>, the framework's shared administration client (ADR-116), which calls the API surface UsersAdminController exposes.

ForgotPasswordHandler

MMCA.ADC.Identity.Application · MMCA.ADC.Identity.Application.Users.UseCases.ForgotPassword · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/ForgotPassword/ForgotPasswordHandler.cs:21 · Level 9 · class (sealed)

  • What it is: ADC's start-a-password-reset handler. Like the export handler it is a thin subclass of a shared workflow, and it adds no logic of its own: a body-less primary-constructor declaration that binds ForgotPasswordHandlerBase<TUser, TCommand> to the ADC User aggregate and ForgotPasswordCommand (ForgotPasswordHandler.cs:21-28). The workflow, the untracked account-by-address lookup included, lives in the base, in the v1.333.0 release ADC pins (MMCA.ADC/Directory.Packages.props:148). It runs in two halves: an inline dispatch only queues the command, and the queued execution resolves, issues and sends.
  • Depends on: ForgotPasswordHandlerBase<TUser, TCommand>, User, ForgotPasswordCommand, IUnitOfWork, IPasswordResetTokenService, IEmailSender, IInternalCommandScheduler, PasswordResetSettings, Email; externals: IOptions<T>, ILogger<T>.
  • Concept introduced, the success-always workflow. [Rubric §11, Security] (assesses whether an anonymous endpoint's responses and logs leak which accounts exist) and [Rubric §2, Design Patterns] (template method again: the base class is abstract, ForgotPasswordHandlerBase.cs:63, but declares no abstract member, so this subclass overrides nothing; its extension points are the virtual email-wording members ComposeSubject, ComposeBody and ComposeResetLink, :148, :158, :186). Every base citation below is MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/ForgotPassword/ForgotPasswordHandlerBase.cs at the v1.333.0 release ADC pins (MMCA.ADC/Directory.Packages.props:148). HandleAsync branches on InternalCommandExecution.IsActive (ForgotPasswordHandlerBase.cs:86-88):
    • Inline (the anonymous endpoint): ScheduleAsync writes one queue row through the scheduler and answers Result.Success() (:92-102). It never looks the address up, so neither the response nor its timing depends on whether the address is registered (:26-28). The one failure it returns is a failed queue write (:95-99), an infrastructure fault that does not depend on the address either. Only the request validator can otherwise produce a 400, and it only inspects the shape of the address.
    • Queued (the processor executing the row): SendAsync (:105-140) completes the row with Result.Success() and no email for a malformed address (:108-112), an address with no account (:118-122) and a request the token service throttled (:125-129); every row comes from an anonymous request, so a throttle refusal is the per-address limit doing its job, not work to retry (:34-36).
    • The logging is part of that contract rather than an afterthought. The base declares its own [LoggerMessage] methods, and PasswordResetRejected takes a plain reason string and neither an address nor an account id (ForgotPasswordHandlerBase.cs:199-200), and the comment above it says why (:197-198): the log must not become the enumeration oracle the responses are not. The one line that does carry a user id, PasswordResetRequested (:191-192), is only reachable once an account has been resolved and the email sent; PasswordResetScheduleFailed (:194-195) is logged at Error with no parameters at all.
    • The send-failure path is a resilience decision worth copying (ForgotPasswordHandlerBase.cs:131-136, remarks :36-40): a failed send propagates, so the processor logs it with the stack and retries the row with backoff (a retry issues a fresh token, replacing the undelivered one) and dead-letters it visibly if it never clears. There is no caller on that path to leak the failure to, and the token is issued at execution rather than inline because carrying it in the queue row would store the raw credential the token service keeps out of the database ([Rubric §29, Resilience & Business Continuity]).
  • Walkthrough: a primary-constructor class over six dependencies (IUnitOfWork, IPasswordResetTokenService, IEmailSender, IInternalCommandScheduler, IOptions<PasswordResetSettings>, ILogger<ForgotPasswordHandler>), every one of them forwarded straight to the base (ForgotPasswordHandler.cs:21-28), and no body: the declaration ends in a semicolon at :28.
    • The account lookup is the base's. It resolves the address through the framework's own lookup, UserEmailLookup, so the app supplies only the command record and, optionally, the email wording (ForgotPasswordHandlerBase.cs:43-46), with TUser constrained to IEmailIdentifiedUser (:70) and the untracked FindUntrackedByEmailAsync call at :114-117 (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UserEmailLookup.cs:18). Reading untracked is correct because this handler never mutates the account: it only needs the id to mint a token against, and the redeem side is a separate use case (ResetPasswordHandler). The key is the Email value object rather than a raw string, so normalization is the value object's job. The lookup only ever runs on the queued half, since the inline half never looks anything up.
    • The handler's own remarks state the split (ForgotPasswordHandler.cs:16-20): the whole workflow lives in the base, and this subclass only binds it to the ADC User aggregate. The base still exposes a protected UnitOfWork property for app-level extensions (ForgotPasswordHandlerBase.cs:74); this handler does not use it.
  • Why it's built this way: the reset credential is a cache record rather than three new columns on the hottest table in the system, so this handler needs no migration and no sweeper: IPasswordResetTokenService owns the token, its lifetime, and the per-email throttle. Queuing the send behind ADR-114 internal commands means a mail outage defers the email instead of losing it, and makes the anonymous response independent of the lookup's timing. The knobs live in PasswordResetSettings, bound from the PasswordReset section with ValidateDataAnnotations().ValidateOnStart() (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:179-182), which is what turns a bad TokenLifetimeMinutes (default 30, MMCA.Common/Source/Core/MMCA.Common.Application/Auth/PasswordResetSettings.cs:29) into a startup failure rather than a runtime surprise. One default is deliberately permissive: ResetUrl defaults to the empty string (PasswordResetSettings.cs:25), and an unconfigured host degrades to a token-only email the user pastes into the reset page by hand rather than shipping a broken link (ForgotPasswordHandlerBase.cs:186-189).
  • Where it's used: registered as ICommandHandler<ForgotPasswordCommand, Result> by the module scan, which finds it through the base class's interface exactly as it finds the export handler (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/DependencyInjection.cs:72). It is injected into PasswordResetController (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/Controllers/PasswordResetController.cs:29), whose inherited POST Auth/forgot-password action is [AllowAnonymous], [Idempotent], rate-limited by the auth-ip policy, and answers 202 Accepted on every success (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/PasswordResetAuthControllerBase.cs:75-92); the internal-command processor resolves the same handler when it executes the queued row. Covered by MMCA.ADC/Tests/Modules/Identity/MMCA.ADC.Identity.Application.Tests/Users/UseCases/ForgotPassword/ForgotPasswordHandlerTests.cs, whose four cases pin the shipped behavior: a registered address issues a token and sends (:77), an unknown address still succeeds without issuing one (:96), an inline dispatch schedules the request and looks nothing up (:110), and the lookup runs untracked (:128).
  • Caveats / not-in-source: what actually delivers the mail is not visible here. IEmailSender is resolved from the host, so whether a reset email leaves the process depends on the Identity service's SMTP configuration, which this type neither reads nor validates. Whether the queued row is ever executed also depends on the host draining the internal-command queue (InternalCommands:Enabled), which is host configuration, not this type.

SendEmailConfirmationHandler

MMCA.ADC.Identity.Application · MMCA.ADC.Identity.Application.Users.UseCases.SendEmailConfirmation · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/SendEmailConfirmation/SendEmailConfirmationHandler.cs:28 · Level 9 · class (sealed)

  • What it is: ADC's concrete handler for SendEmailConfirmationCommand: a body-less primary-constructor subclass that binds the framework base to the ADC User aggregate (SendEmailConfirmationHandler.cs:28-36). The base, in the v1.333.0 release ADC pins (MMCA.ADC/Directory.Packages.props:148), performs the account lookup itself, so ADC supplies no logic of its own.
  • Depends on: SendEmailConfirmationHandlerBase<TUser, TCommand>, User, IUnitOfWork, IEmailConfirmationTokenService, IEmailSender, IInternalCommandScheduler, EmailConfirmationSettings, SendEmailConfirmationCommand; externals: Microsoft.Extensions.Options, Microsoft.Extensions.Logging.
  • Concept reinforced, the template-method handler. [Rubric §2, Design Patterns]: the framework base class owns the whole send workflow (scheduling, account lookup, token issuance, email dispatch, logging) and declares no abstract member (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/EmailConfirmation/SendEmailConfirmationHandlerBase.cs:64), so ADC's job is a constructor that forwards its dependencies, not a reimplementation. The base resolves the account through the framework's untracked FindUntrackedByEmailAsync lookup (SendEmailConfirmationHandlerBase.cs:113-116) over TUser : IEmailIdentifiedUser (:71), and its extension points are virtual (IsAlreadyConfirmed, :159-160), none of which ADC overrides. This is the same shape as ChangePasswordHandler over ChangePasswordHandlerBase<TUser, TCommand>, and the same two-halves shape as ForgotPasswordHandler: HandleAsync branches on InternalCommandExecution.IsActive (SendEmailConfirmationHandlerBase.cs:85-87), an inline dispatch only writes a queue row (:91-101), and the queued execution resolves, issues and sends (:104-150), completing the row without an email for a malformed address, an unknown address or an already-confirmed account (:107-111, :117-121, :125-129). One difference from the password-reset base: here a failed send propagates and a throttle refusal returns its failure, so both retry the row (:37-38, throttle at :131-139).
  • Walkthrough: the primary constructor forwards unitOfWork, tokenService, emailSender, scheduler, settings, logger straight to the base (SendEmailConfirmationHandler.cs:28-36), and the class has no body: the declaration ends in a semicolon at :36. Nothing else in the type is ADC-specific.
  • Why it's built this way: keeping the lookup in the base means every app binds the same untracked read, and reading untracked is deliberate: the confirmation-send path only needs to read the user to email a token, never to mutate the entity, so skipping EF's change tracker avoids paying its cost for a query that will not be saved.
  • Where it's used: registered as the handler for SendEmailConfirmationCommand by the module scan (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/DependencyInjection.cs:72). EmailConfirmationController receives it as ICommandHandler<SendEmailConfirmationCommand, Result> and dispatches inline, which schedules (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/Controllers/EmailConfirmationController.cs:30, :37). AuthController does not call it: after registration it schedules the command straight through IInternalCommandScheduler (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/Controllers/AuthController.cs:99-103), and the processor then runs this handler on the queued half. Covered by MMCA.ADC/Tests/Modules/Identity/MMCA.ADC.Identity.Application.Tests/Users/UseCases/SendEmailConfirmation/SendEmailConfirmationHandlerTests.cs (six cases, :72 to :143, including the inline-schedules case at :143 and the send-failure-propagates case at :126).

AuditHistoryController

MMCA.ADC.Identity.API · MMCA.ADC.Identity.API.Controllers.AuditHistory · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/Controllers/AuditHistory/AuditHistoryController.cs:19 · Level 8 · class (sealed)

  • What it is: the Identity service's audit-history endpoint (ADR-075): one page of the recorded change history of one User, newest change first (AuditHistoryController.cs:9-14).
  • Depends on: AuditHistoryControllerBase (base), IAuditTrailReader (primary-constructor parameter, :19), User; externals: [Route("Admin/Identity/AuditHistory")], [ApiVersion("1.0")] (:16-18).
  • Concept reinforced, the empty-subclass mount, now with a parameter. Same shape as AdminMachineClientsController, except that the subclass passes the base its reader and the entity type it owns, typeof(User) (:20). [Rubric §30, Compliance, Privacy & Data Governance]: the class doc says the base gates every action on audit:view and refuses an entity this service does not own, and that the reader reads this service's own database, so each service host mounts its own controller (:10-13).
  • Why it's built this way: database per service (ADR-006) means no single host can read every module's audit rows, so each module mounts a same-named controller over its own entities; the Conference and Engagement APIs carry their own AuditHistoryController for the same reason.
  • Where it's used: mounted by the Identity API; the reader is the one AddAuditTrail registers (:15). MachineClientParticipationTests in MMCA.ADC.Architecture.Tests references it.

VerifiedUserLookupGrpcService

MMCA.ADC.Identity.Service · MMCA.ADC.Identity.Service.Grpc · MMCA.ADC/Source/Services/MMCA.ADC.Identity.Service/Grpc/VerifiedUserLookupGrpcService.cs:33 · Level 9 · class (sealed)

  • What it is: the server half of the second Identity gRPC edge. It subclasses the generated VerifiedUserLookupService.VerifiedUserLookupServiceBase and answers "which of these emails belong to an account with a confirmed address" for Engagement's ticket roster linking (BR-277), by delegating to the in-process IVerifiedUserLookupService (VerifiedUserLookupService in the Identity host).
  • Depends on: IVerifiedUserLookupService and IPermissionRegistry (both injected, VerifiedUserLookupGrpcService.cs:33), EngagementPermissions.TicketsManage, the caller-inspection extensions from MMCA.Common.Grpc.Authentication and MMCA.Common.Shared.Auth (:5-7), the generated GetVerifiedUsersByEmailRequest, GetVerifiedUsersByEmailResponse and VerifiedUserItem from verified_user_lookup.proto (:15), and Grpc.Core.ServerCallContext.
  • Concept introduced, one edge, two kinds of caller. [Rubric §11, Security] and [Rubric §7, Microservices Readiness]. Unlike AttendeesGrpcService, this edge is reached both from inside an HTTP request and from a background command. The doc comment (:23-29) names both: the organizer's link-existing-accounts run forwards the organizer's bearer, while the roster import runs from ProcessTicketRosterImportInternalCommand with no HttpContext and presents Engagement's service token instead. So the mapping uses the InternalCaller policy, which admits either credential (app.MapGrpcService<VerifiedUserLookupGrpcService>().RequireAuthorization(ServiceTokenDefaults.InternalCallerPolicy), MMCA.ADC/Source/Services/MMCA.ADC.Identity.Service/Program.cs:326, with ServiceTokenDefaults), and the class narrows the user half: because the reply names other people's accounts by address, a user caller must also hold EngagementPermissions.TicketsManage, the permission that run is gated on. The trust-boundary comment above the mapping (Program.cs:316-325) records that internal Container Apps ingress is not an authorization boundary, which is why neither check is optional.
  • Walkthrough (GetVerifiedUsersByEmail, :37-72)
    1. Argument guards on request and context (:41-42).
    2. The caller gate (:44-50): admitted when IsServiceCaller(), or the TicketsManage permission claim is present, or permissions.HasPermission(caller.GetRoleValues(), ...) grants it through the role; otherwise StatusCode.PermissionDenied (:49).
    3. The batch cap (:52-59): more than IVerifiedUserLookupService.MaxEmailsPerCall emails, which is 500 (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Shared/Users/IVerifiedUserLookupService.cs:22), is refused with StatusCode.InvalidArgument. The inline comment (:52-53) explains the placement: the cap belongs to the contract, so it is refused here with a clear status rather than letting the in-process guard surface as an opaque Unknown.
    4. inner.GetVerifiedUsersByEmailAsync([.. request.Emails], context.CancellationToken) (:61): the repeated field is copied into a plain collection and the server call's token is passed through, as on the sibling edge.
    5. Projection (:63-71): each result becomes a VerifiedUserItem with Email, UserId, FirstName and LastName, added to response.Users.
  • Why it's built this way: placing the permission check in the class rather than only in the mapping lets one policy admit the service token for the background path while still holding a user caller to the same permission the HTTP action requires. The cap at the boundary turns a malformed batch into a caller error instead of a server fault, [Rubric §9, API & Contract Design].
  • Where it's used: mapped at Program.cs:326; its only client is VerifiedUserLookupServiceGrpcAdapter, registered in Engagement.Service. Served over the HTTP/2 cleartext profile of ADR-012. Tests: MMCA.ADC/Tests/Services/MMCA.ADC.Services.Tests/VerifiedUsers/VerifiedUserLookupGrpcServiceCallerTests.cs, VerifiedUserLookupGrpcServiceTests.cs in the same folder, and MMCA.ADC/Tests/Integration/MMCA.ADC.Identity.IntegrationTests/Users/VerifiedUserLookupGrpcTests.cs.

VerifiedUserLookupServiceGrpcAdapter

MMCA.ADC.Identity.Contracts · MMCA.ADC.Identity.Contracts · MMCA.ADC/Source/Services/MMCA.ADC.Identity.Contracts/VerifiedUserLookupServiceGrpcAdapter.cs:13 · Level 9 · class (internal, sealed)

  • What it is: the gRPC-backed client implementation of IVerifiedUserLookupService, the counterpart of AttendeeQueryServiceGrpcAdapter for the confirmed-address lookup. Engagement keeps depending on the C# interface from MMCA.ADC.Identity.Shared, and the generated types never leave this assembly; transport failures propagate to the caller by design, which turns them into a failure Result (doc comment, VerifiedUserLookupServiceGrpcAdapter.cs:6-12).
  • Depends on: IVerifiedUserLookupService (implemented), VerifiedUserDTO, and the generated VerifiedUserLookupService.VerifiedUserLookupServiceClient and GetVerifiedUsersByEmailRequest (:13-14, :24).
  • Concept introduced: none new; this is the same adapter shape as AttendeeQueryServiceGrpcAdapter, and it is internal for the same reason, so the only way to obtain it is DependencyInjection's AddIdentityVerifiedUserLookupClient. The one detail that differs is the client-side batch cap.
  • Walkthrough
    • GetVerifiedUsersByEmailAsync (:17-33): guards emails for null and with ArgumentOutOfRangeException.ThrowIfGreaterThan(emails.Count, IVerifiedUserLookupService.MaxEmailsPerCall) (:21-22), the client-side copy of the cap the server enforces; builds the request with request.Emails.AddRange(emails) (:24-25); calls the client passing only the cancellation token, with no per-call deadline of its own (:27-29); and materializes each VerifiedUserItem into a VerifiedUserDTO(Email, UserId, FirstName, LastName) (:31-32) so callers do not hold the generated type.
  • Why it's built this way: [Rubric §29, Resilience & Business Continuity]. Checking the cap before the call means an oversized batch fails in-process with no network round trip. Letting a transport failure propagate, rather than returning an empty list, is what lets the caller turn it into a failure Result instead of silently linking nobody.
  • Where it's used: registered by AddIdentityVerifiedUserLookupClient (MMCA.ADC/Source/Services/MMCA.ADC.Identity.Contracts/DependencyInjection.cs:73), which Engagement.Service calls inside its application pipeline (MMCA.ADC/Source/Services/MMCA.ADC.Engagement.Service/Program.cs:230). The host comment (:168-177) records the consequence of a failure: it fails the explicit link run, and the import logs and skips it, recording no linked accounts, so a lookup failure never fails a roster upload. Its server-side counterpart is VerifiedUserLookupGrpcService.

AttendeeQueryServiceGrpcAdapter

MMCA.ADC.Identity.Contracts · MMCA.ADC.Identity.Contracts · MMCA.ADC/Source/Services/MMCA.ADC.Identity.Contracts/AttendeeQueryServiceGrpcAdapter.cs:14 · Level 10 · class (internal, sealed)

  • What it is: the gRPC-backed client implementation of IAttendeeQueryService. It answers "which user ids hold the Attendee role", one keyset page at a time, and "how many attendees are there" by calling the extracted Identity service instead of reading the local database.
  • Depends on: IAttendeeQueryService (implemented, from MMCA.ADC.Identity.Shared), the generated AttendeeQueryService.AttendeeQueryServiceClient, GetAttendeeUserIdPageRequest and CountAttendeesRequest types compiled from the .proto in this project, and the UserIdentifierType alias.
  • Concept introduced, the adapter that makes extraction invisible to callers. [Rubric §7, Microservices Readiness] assesses whether a module can be lifted into its own process without rewriting the code that consumes it. This class is the concrete payoff of the interface indirection set up in the Shared layer. Notification depends on the C# interface; in the monolith that interface resolves to Identity's in-process AttendeeQueryService, and in the extracted topology the composition root swaps in this adapter. The consuming code does not change, does not learn about gRPC, and never holds a generated proto type. The class doc comment (AttendeeQueryServiceGrpcAdapter.cs:6-13) says exactly that, adds that transport failures propagate to the caller by design (:12), and it is why the project is named .Contracts and holds both the .proto and the hand-written adapter (ADR-007, ADR-008). Note the accessibility: the adapter is internal (:14), so consumers cannot name it; the only way to get it is through DependencyInjection in the same project.
  • Walkthrough
    • Primary constructor (:14-15): takes the generated typed client and nothing else.
    • GetAttendeeUserIdPageAsync(afterUserId, take, cancellationToken) (:18-34): builds a GetAttendeeUserIdPageRequest { Take = take } and sets AfterUserId only when the cursor has a value (:23-27), so a first page sends no cursor at all and the server can tell "start at the beginning" from "after id 0". It makes one call, client.GetAttendeeUserIdPageAsync(request, cancellationToken: cancellationToken) (:29), with no per-call deadline of its own, then return [.. response.UserIds] (:33). The collection expression materializes protobuf's RepeatedField into a plain IReadOnlyList, which the comment (:31-32) notes is deliberate so callers do not leak the generated type; because UserIdentifierType is int, the projection is a no-op cast. The adapter does not check take against IAttendeeQueryService.MaxPageSize; the server refuses an out-of-range size (see AttendeesGrpcService).
    • CountAttendeesAsync (:37-41): one call with an empty CountAttendeesRequest (:39), returning response.Count (:40).
  • Why it's built this way: [Rubric §29, Resilience & Business Continuity]. Letting transport failures surface rather than swallowing them means a broadcast that could not determine its audience fails visibly instead of quietly notifying nobody. How long a slow or hung Identity peer can hold the call is left to the shared resilience handler the typed client is registered with and to the caller's cancellation token; the adapter sets no deadline.
  • Where it's used: registered by DependencyInjection's AddIdentityAttendeeClient in this same project, which the Notification service host calls as step 2 of its composed application pipeline (MMCA.ADC/Source/Services/MMCA.ADC.Notification.Service/Program.cs:119). The client opts in to the service token, and the host registers AddServiceTokenClient because push delivery runs from an internal command with no HttpContext (Notification.Service/Program.cs:141-144). Its server-side counterpart is AttendeesGrpcService.
  • Caveats / not-in-source: the interface returns a plain list rather than a Result, so a transport fault reaches the caller as a raw RpcException after the Polly pipeline gives up; there is no Result.Failure translation on this path.

AttendeesGrpcService

MMCA.ADC.Identity.Service · MMCA.ADC.Identity.Service.Grpc · MMCA.ADC/Source/Services/MMCA.ADC.Identity.Service/Grpc/AttendeesGrpcService.cs:34 · Level 10 · class (sealed)

  • What it is: the server half of the same bridge. It subclasses the generated AttendeeQueryService.AttendeeQueryServiceBase, checks that the caller may see the whole attendee list, and answers the two RPCs (a keyset page of attendee ids, and the attendee count) by delegating to whatever IAttendeeQueryService is registered in the Identity service host, which in that process is the real in-process implementation reading the Identity database.
  • Depends on: IAttendeeQueryService and IPermissionRegistry (both injected, AttendeesGrpcService.cs:34), NotificationPermissions.Manage, the caller-inspection extensions IsServiceCaller, HasPermissionClaim and GetRoleValues (imported from MMCA.Common.Grpc.Authentication and MMCA.Common.Shared.Auth, :5-6), the generated AttendeeQueryServiceBase, GetAttendeeUserIdPageRequest/GetAttendeeUserIdPageResponse and CountAttendeesRequest/CountAttendeesResponse from attendee_query.proto, Grpc.Core.ServerCallContext, and BCL CultureInfo for the invariant error message.
  • Concept introduced, the thin gRPC ingress over an existing interface, with its own caller check. [Rubric §9, API & Contract Design] assesses whether a published contract is a deliberate surface rather than a leaked internal shape, and [Rubric §7, Microservices Readiness] covers the extraction path. Apart from one authorization check and one argument check, this class carries no domain logic: it translates a proto request into an interface call and the result into a proto response, which is what keeps the two deployment topologies behaviorally identical. The doc comment (AttendeesGrpcService.cs:16-22) names the error handling that is not written here: exceptions from the inner service propagate as plain exceptions, and the shared server interceptor GrpcResultExceptionInterceptor translates a ResultFailureException into an RpcException carrying the right gRPC status code. A hand-written try/catch here would duplicate a cross-cutting concern that the pipeline already owns. The second doc paragraph (:23-30) states why the check is here: the replies enumerate attendee accounts rather than the caller's own, so a user caller must hold NotificationPermissions.Manage, the permission the push-notification send they serve is gated on, while a service caller is admitted; a page size outside 1 to IAttendeeQueryService.MaxPageSize is refused with InvalidArgument.
  • Walkthrough
    • GetAttendeeUserIdPage (:38-62):
      1. Argument guards on both request and context (:42-43). The generated base is a public wire surface, so both are checked even though the framework supplies them.
      2. EnsureCallerMayReadAttendees(context) (:45), the caller gate described below, runs before anything else is read.
      3. The page-size check (:47-52): request.Take is < 1 or > IAttendeeQueryService.MaxPageSize is refused with RpcException(new Status(StatusCode.InvalidArgument, ...)), the message built with string.Create(CultureInfo.InvariantCulture, ...). The cap is 10,000 (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Shared/Users/IAttendeeQueryService.cs:20); refusing it here gives the caller a clear status instead of letting the in-process ArgumentOutOfRangeException surface as an opaque fault.
      4. The cursor (:54): request.HasAfterUserId ? request.AfterUserId : null, so an absent optional field means "start at the lowest id" rather than "after id 0".
      5. await inner.GetAttendeeUserIdPageAsync(afterUserId, request.Take, context.CancellationToken) (:55-57). Notice which token is passed: the server call context's token, so a client that hangs up or hits its deadline cancels the database read on this side rather than letting it run to completion for nobody.
      6. Response construction (:59-61): a fresh GetAttendeeUserIdPageResponse, then response.UserIds.AddRange(userIds). Protobuf repeated fields are read-only collections that are populated, never assigned.
    • CountAttendees (:65-76): the same two guards and the same caller gate (:69-72), then inner.CountAttendeesAsync(context.CancellationToken) and a CountAttendeesResponse { Count = count } (:74-75).
    • EnsureCallerMayReadAttendees (:78-87): the principal comes from context.GetHttpContext().User (:80), and the call is admitted when the caller is a service caller, or carries the NotificationPermissions.Manage permission claim, or holds a role that permissions.HasPermission(caller.GetRoleValues(), ...) maps to it (:81-83). The registry fallback covers a token that carries the role but not the permission claim (the permissions parameter doc, :33). Anything else is refused with RpcException(new Status(StatusCode.PermissionDenied, ...)) (:85). Sharing one private method keeps the two RPCs from drifting apart on who may call them.
  • Why it's built this way: [Rubric §11, Security]. The endpoint is mapped with app.MapGrpcService<AttendeesGrpcService>().RequireAuthorization(ServiceTokenDefaults.InternalCallerPolicy) (MMCA.ADC/Source/Services/MMCA.ADC.Identity.Service/Program.cs:314, with ServiceTokenDefaults), and the comment above the mapping (:306-313) is worth reading in full: the response enumerates attendee user ids, so internal-only ingress is not considered sufficient (:307). The one caller is Notification's AttendeeNotificationRecipientProvider, which runs from DeliverPushNotificationPageInternalCommand with no HttpContext, so no organizer bearer exists for JwtForwardingClientInterceptor to forward (:308-310). Notification therefore presents its service token (AddServiceTokenClient plus WithServiceToken on the Attendees client), and the edge takes the InternalCaller policy, which admits either that service token or an end user's JWT (:310-312), the same policy the VerifiedUserLookupGrpcService edge uses. The mapping-level policy proves only that the caller is a service or an authenticated user; the in-class gate is what still refuses a user caller that does not hold NotificationPermissions.Manage (:312-313). Paging the id list, with a hard cap per call, also bounds what any one call can return: the audience is walked page by page rather than returned whole.
  • Where it's used: mapped at Program.cs:314; the only client is AttendeeQueryServiceGrpcAdapter. The service serves it over Kestrel's HTTP/2 cleartext channel, the transport profile of ADR-012. The caller gate is pinned by MMCA.ADC/Tests/Services/MMCA.ADC.Services.Tests/Attendees/AttendeesGrpcServiceCallerTests.cs, the RPC translation by AttendeesGrpcServiceTests.cs in the same folder, and the end-to-end edge by MMCA.ADC/Tests/Integration/MMCA.ADC.Identity.IntegrationTests/Users/AttendeesGrpcTests.cs.
  • Caveats / not-in-source: the gRPC server registration (AddGrpc) is not spelled in the Identity host's Program.cs, which carries only the two MapGrpcService calls (:314, :326). The host comments place the shared start-up sequence in MMCA.Common.ServiceHost's AddMmcaServiceHost (:47-49) and state that UseMmcaServiceHostAsync maps gRPC reflection in Development only (:297-300). Not determinable from source: where inside that package the gRPC server itself is registered, since this file does not show it.

DependencyInjection

MMCA.ADC.Identity.Contracts · MMCA.ADC.Identity.Contracts · MMCA.ADC/Source/Services/MMCA.ADC.Identity.Contracts/DependencyInjection.cs:15 · Level 11 · class (static)

  • What it is: the registration helpers the .Contracts project exposes, one per Identity gRPC edge. AddIdentityAttendeeClient(serviceName) wires a typed gRPC client for the extracted Identity service and swaps IAttendeeQueryService over to AttendeeQueryServiceGrpcAdapter; AddIdentityVerifiedUserLookupClient(serviceName) does the same for IVerifiedUserLookupService and VerifiedUserLookupServiceGrpcAdapter (class summary, DependencyInjection.cs:10-14). Both clients opt in to the service token.
  • Depends on: IServiceCollection and ServiceCollectionDescriptorExtensions.Replace; the generated AttendeeQueryService.AttendeeQueryServiceClient and VerifiedUserLookupService.VerifiedUserLookupServiceClient; IAttendeeQueryService, AttendeeQueryServiceGrpcAdapter, IVerifiedUserLookupService and VerifiedUserLookupServiceGrpcAdapter; AddTypedGrpcClient<TClient> from MMCA.Common.Grpc and WithServiceToken from MMCA.Common.Grpc.Authentication.
  • Concept introduced, Replace instead of TryAdd. [Rubric §7, Microservices Readiness] and [Rubric §3, Clean Architecture]. Everywhere else in this codebase module registration uses TryAdd, so a host can pre-empt a default. Here the semantics are inverted deliberately so the adapter wins over any registration already present (doc comment, DependencyInjection.cs:31-37). The inline comment at the point of use (:45) restates it: the gRPC adapter wins over any registration made before this call, such as the real in-process AttendeeQueryService in a host that also loads the Identity module, where TryAdd would silently do nothing. The second helper's doc comment (:55-58) applies the same rule to an in-process IVerifiedUserLookupService implementation. In the deployed topology no such registration is present: the doc comment (:33-36) records that the extracted Notification host names only its own module to ModuleLoader, so the Identity module is never discovered there, the in-process AttendeeQueryService is not registered, and this call is the only IAttendeeQueryService registration. Replace is therefore what keeps the helper correct in any host that does load the Identity module, rather than something the extracted host depends on.
  • Concept introduced, the service token as a per-client opt-in. [Rubric §11, Security]. Both helpers chain .WithServiceToken() on their typed client (:43, :72), and both doc comments give the same reason for their own edge: the call runs from an internal command with no HttpContext, so there is no user bearer to forward, and Identity maps the edge under the InternalCaller policy. For the attendee edge that command is push delivery (:26-29); for the verified-user edge it is the roster import (:60-63). The inline comment (:70-71) states the scope from Engagement's side: this is Engagement's only Identity client that sends its service token, and Identity validates it on this edge and on the Attendees edge Notification calls. The opt-in has a host-side precondition, stated in both doc comments: the calling host must register AddServiceTokenClient.
  • Walkthrough: both methods live inside an extension(IServiceCollection services) block (:17), the workspace idiom for DI registration (see primer §4).
    • AddIdentityAttendeeClient(string serviceName = "identity") (:41) does two things: AddTypedGrpcClient<AttendeeQueryService.AttendeeQueryServiceClient>(serviceName).WithServiceToken() (:43), which the framework wires to Aspire service discovery at http://{serviceName} over HTTP/2 cleartext with the standard JwtForwardingClientInterceptor and Polly resilience handler, plus the service-token opt-in; and services.Replace(ServiceDescriptor.Scoped<IAttendeeQueryService, AttendeeQueryServiceGrpcAdapter>()) (:46), with the inline comment restating the Replace-not-TryAdd rule at the point of use (:45). It then returns services for chaining (:48).
    • AddIdentityVerifiedUserLookupClient(string serviceName = "identity") (:68): AddTypedGrpcClient<VerifiedUserLookupService.VerifiedUserLookupServiceClient>(serviceName).WithServiceToken() (:72), then services.Replace(ServiceDescriptor.Scoped<IVerifiedUserLookupService, VerifiedUserLookupServiceGrpcAdapter>()) (:73), then return services (:75).
    • Both serviceName defaults of "identity" match the AppHost resource name, so the common case passes no argument.
  • Why it's built this way: keeping these helpers in the .Contracts project rather than in the consuming service means the knowledge of "how you talk to Identity remotely" lives once, next to the .proto files that define the calls, and every consumer gets it with a project reference plus one line (ADR-007). The Scoped lifetime matches the in-process implementations they replace, so swapping transports changes no lifetime assumption anywhere in the graph.
  • Where it's used: AddIdentityAttendeeClient is called by the Notification service host as step 2 of its composed application pipeline, between module registration and the Conference live-validation client (MMCA.ADC/Source/Services/MMCA.ADC.Notification.Service/Program.cs:119), and that host registers AddServiceTokenClient after the composed call (:144). AddIdentityVerifiedUserLookupClient is called by the Engagement service host after its other gRPC clients and before broker messaging (MMCA.ADC/Source/Services/MMCA.ADC.Engagement.Service/Program.cs:230), and that host registers AddServiceTokenClient after the composed call (:239). The enclosing pipeline fixes the order structurally: per the Notification host's comment (Notification.Service/Program.cs:99-100), it runs AddApplication, then the registered steps in order, then the decorators, and seals, so Replace runs after module registration and the decorators wrap what results. The same comment (:104-108) notes that the extracted host names only the Notification assembly, so nothing else registers IAttendeeQueryService and Replace simply adds the scoped gRPC adapter.
  • Caveats / not-in-source: the class has two public members, one per edge, now symmetric in shape: both carry the service token, and Identity maps both edges under ServiceTokenDefaults.InternalCallerPolicy (MMCA.ADC/Source/Services/MMCA.ADC.Identity.Service/Program.cs:314, :326). A host that calls either helper without registering AddServiceTokenClient is not caught by anything in this class; the precondition lives only in the doc comments.

AdminMachineClientsController

MMCA.ADC.Identity.API · MMCA.ADC.Identity.API.Controllers.MachineClients · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/Controllers/MachineClients/AdminMachineClientsController.cs:20 · Level 7 · class (sealed)

  • What it is: the Identity service's machine-client administration endpoint (ADR-140): list, create, rotate, promote and revoke the client credentials programs sign in with (AdminMachineClientsController.cs:7-11). The whole class is one line, public sealed class AdminMachineClientsController : MachineClientsControllerBase; (:20).
  • Depends on: MachineClientsControllerBase (base, which owns every action); externals: [ApiController], [Route("Admin/MachineClients")], [ApiVersion("1.0")] (:17-19).
  • Concept introduced, the framework controller mounted by an empty subclass. [Rubric §7, Microservices Readiness] assesses whether a capability can be hosted by whichever service owns it without a rewrite. The behavior lives once in MMCA.Common.API; the app contributes only the attributes that place it: the route the framework's UI client calls, and the API version. [Rubric §11, Security]: the <remarks> (:12-16) record the policy the base enforces: every action is gated on the clients:manage capability, which ADC grants to Organizer only, and a client may be backed by ContentEditor or Attendee while the framework refuses Organizer, because Organizer holds the administration capabilities a machine client must never carry.
  • Where it's used: mounted by the Identity API (the module that owns accounts); its anonymous-endpoint classification is pinned by AnonymousEndpointTests in MMCA.ADC.Architecture.Tests, and MachineClientControllersTests in MMCA.ADC.Identity.API.Tests cover the subclass. Its sibling for the token grant is MachineTokenController.

MachineTokenController

MMCA.ADC.Identity.API · MMCA.ADC.Identity.API.Controllers.MachineClients · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/Controllers/MachineClients/MachineTokenController.cs:20 · Level 7 · class (sealed)

  • What it is: the machine token endpoint (OAuth 2.0 client credentials, ADR-140): a program posts its client id and secret and receives a short-lived bearer for its service account (MachineTokenController.cs:7-11). Like its sibling, the class is one line over the framework base (:20).
  • Depends on: MachineTokenControllerBase (base); externals: [ApiController], [Route("auth/token")], [ApiVersion("1.0")] (:17-19).
  • Concept reinforced, the empty-subclass mount. Taught at AdminMachineClientsController. [Rubric §11, Security]: the <remarks> (:12-16) note that the endpoint is anonymous and throttled by the auth-ip rate-limit policy, both declared on the base, and that it is never a token-issuing path of the web head's same-origin proxy: a program calls the Gateway directly (through its /Auth route) and takes its bearer from the response body.
  • Where it's used: called by machine clients through the Gateway; listed in AnonymousEndpointTests and covered by MachineClientControllersTests.

AttendeeKeysetSpecification

MMCA.ADC.Identity.Application · MMCA.ADC.Identity.Application.Users.Specifications · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/Specifications/AttendeeKeysetSpecification.cs:13 · Level 8 · class (sealed)

  • What it is: one keyset batch of Attendee-role accounts that are not service accounts: the rows after afterUserId, ascending by id, at most take of them (class summary, AttendeeKeysetSpecification.cs:7-12). It is the only database read AttendeeQueryService issues, for both the page and the count.
  • Depends on: QuerySpecification<TEntity, TIdentifierType> (base), User, UserRole.Attendee, and the UserIdentifierType alias; BCL System.Linq.Expressions.
  • Concept introduced, keyset paging as a specification. [Rubric §12, Performance & Scalability]. The batch is addressed by "after this id" rather than by an offset, so reading the next batch costs the same however deep the walk is, and a row inserted behind the cursor cannot shift a later batch. The specification carries the whole shape (filter, order and size), so the caller passes it to the repository instead of composing a query itself. What it deliberately leaves out matters as much: the synthetic load-test filter is not part of this read, because an email-domain test does not translate through the Email value converter, so the caller applies it in memory and reads further batches past the rows it drops (:9-11).
  • Walkthrough
    • Constructor (:18-26): Criteria takes one of two expressions (:20-22). Both require u.Role == UserRole.Attendee.Value && !u.IsServiceAccount; when afterUserId has a value the keyset predicate u.Id > after is added, and when it is null the batch starts at the lowest id.
    • AddOrderBy(u => u.Id) (:24) gives the ascending order the keyset depends on, and ApplyPaging(0, take) (:25) caps the batch: the skip is always 0 because the cursor, not an offset, does the advancing.
    • Criteria (:29) overrides the base's abstract expression with a get-only property set once in the constructor.
  • Why it's built this way: excluding service accounts in the predicate means an account behind a machine client never counts as an attendee whatever its role (AttendeeQueryService.cs:8-12). Keeping the synthetic filter out of SQL, and the paging in the caller's loop, is what lets AttendeeQueryService return a full page or an honest short page: a page thinned by the in-memory filter would read as the end of the audience to the push-delivery walk (AttendeeQueryService.cs:14-20).
  • Where it's used: constructed only by AttendeeQueryService.ReadBatchAsync (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/AttendeeQueryService.cs:94-97), which projects each row to its id and email. GetAttendeeUserIdPageAsync reads batches of the requested page size (AttendeeQueryService.cs:40), and CountAttendeesAsync walks the same specification in batches of CountBatchSize, 1,000 (AttendeeQueryService.cs:24, :76), so the page and the count can never disagree about who is an attendee.

UserListDTOMapper

MMCA.ADC.Identity.Application · MMCA.ADC.Identity.Application.Users.DTOs · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/DTOs/UserListDTOMapper.cs:14 · Level 8 · class (sealed)

  • What it is: the hand-written mapper from the User aggregate to the organizer roster row UserListDTO, for the single and the collection case.
  • Depends on: IEntityDTOMapper<TEntity, TEntityDTO, TIdentifierType> (implemented, group 12), User, UserListDTO, and the Email value object (unwrapped through .Value).
  • Concept introduced, a roster mapper that deliberately leaves one column unset. [Rubric §9, API & Contract Design], [Rubric §30, Compliance, Privacy & Data Governance]. This mapper assigns every property by hand (UserListDTOMapper.cs:17-31), following the manual-mapping stance of ADR-001. It copies exactly seven members: Id, Email (as the string entity.Email.Value), FirstName, LastName, Role, CreatedOn and LockedOn (:23-29), so no credential or session material can reach the grid. UserListDTO.ActiveSessionCount is not set here: the aggregate has no navigation to refresh sessions, so UserListEntityQueryService fills it after the query, one live-session count call per returned page (UserListEntityQueryService.cs:23-36).
  • Walkthrough
    • MapToDTO(User entity) (:17-31): null-guards with ArgumentNullException.ThrowIfNull (:19) and returns an object initializer over the seven members.
    • MapToDTOs(IReadOnlyCollection<User>) (:34-38): null-guards and returns [.. entityCollection.Select(MapToDTO)], so the collection form reuses the single-item map and there is one definition to keep correct.
  • Why it's built this way: the roster is a different projection from UserDTO, so it gets its own mapper rather than widening the full-user DTO; the entity query pipeline takes a mapper as a constructor argument (UserListEntityQueryService.cs:44-52) and runs the grid's paging, sorting and filtering over User before mapping.
  • Where it's used: injected into UserListEntityQueryService (UserListEntityQueryService.cs:48), which passes it to its EntityQueryService<User, UserListDTO, UserIdentifierType> base; covered by UserListEntityQueryServiceTests.

ServiceAccountProvisioner

MMCA.ADC.Identity.Application · MMCA.ADC.Identity.Application.Users.Administration · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/Administration/ServiceAccountProvisioner.cs:25 · Level 8 · class (internal, sealed)

  • What it is: ADC's implementation of the framework's IServiceAccountProvisioner over the Identity User aggregate (ADR-140). It creates the service account a machine client signs as, and reads that account back when a client-credentials token is minted (ServiceAccountProvisioner.cs:8-11).
  • Depends on: IUnitOfWork (its only constructor dependency, :25), User and its CreateServiceAccount factory, the framework's ServiceAccount read model (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/MachineClients/ServiceAccount.cs:13), and Result.
  • Concept introduced, a machine identity that is still a User row, refused by its own read predicate. [Rubric §11, Security]. A machine client needs a subject to put in its token, and ADC gives it an ordinary User row flagged IsServiceAccount (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Domain/Users/User.cs:150) rather than a second identity table, so role, permission grants and soft delete all apply unchanged. The safety lives in the read: FindAsync filters on u.Id == userId && u.IsServiceAccount && u.LockedOn == null && !u.IsDeleted (ServiceAccountProvisioner.cs:47), so a token is never minted for a person, a locked account, or a deleted one. The <remarks> (:18-22) admit that the soft-delete query filter already drops deleted rows under EF and keep !IsDeleted anyway because stating every refusal in one predicate costs nothing.
  • Walkthrough
    • CreateAsync (:28-40): calls User.CreateServiceAccount(name, role) (User.cs:362), returns its errors unchanged through Result.Failure<UserIdentifierType> when the factory refuses (ServiceAccountProvisioner.cs:31-34), otherwise adds the aggregate through GetRepository<User, UserIdentifierType>(), saves, and returns the new id (:36-39). The factory generates an address under ServiceAccounts.EmailDomain, uses the client's name as first name, stores no password, leaves the email unconfirmed and sets IsServiceAccount (User.cs:347-352, :370-375).
    • FindAsync (:43-52): one projected read through GetReadRepository<User, UserIdentifierType>().GetProjectedAsync of Id, Email, Role and FirstName (:45-48), mapped to new ServiceAccount(row.Id, row.FirstName, row.Email.Value, row.Role), or null when nothing matches (:50-51).
  • Why it's built this way: [Rubric §30, Compliance, Privacy & Data Governance] and [Rubric §6, CQRS & Event-Driven]. Creating an account publishes no UserRegistered event and sends no confirmation email, because a service account is not a person registering and its reserved address cannot receive mail (ServiceAccountProvisioner.cs:14-16, echoed on the factory at User.cs:354-355). Which roles may back a client is the framework's decision; this class and the factory only require a valid ADC role (User.cs:354-357).
  • Where it's used: registered as TryAddScoped<IServiceAccountProvisioner, ServiceAccountProvisioner>() in the Application layer's DependencyInjection (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/DependencyInjection.cs:51); the comment above it notes that the Identity service's MachineClients settings validator fails startup without this registration once MachineClients:Enabled is set (:55-56). The Identity service host's AddMachineClients call names it as the source of service accounts (MMCA.ADC/Source/Services/MMCA.ADC.Identity.Service/Program.cs:176-183), behind AdminMachineClientsController and MachineTokenController.
  • Caveats / not-in-source: ADC ships machine clients switched off: appsettings.json sets MachineClients:Enabled false and only Development and the AppHost turn it on (Program.cs:178-180), so in production this class is registered but never called.

ViewAsSubjectResolver

MMCA.ADC.Identity.Application · MMCA.ADC.Identity.Application.Users.Administration · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/Administration/ViewAsSubjectResolver.cs:24 · Level 8 · class (internal, sealed)

  • What it is: ADC's implementation of the framework's IViewAsSubjectResolver over the Identity User aggregate (ADR-137): it supplies the email, role and display name a read-only view-as token is minted from, plus whether the account is soft-deleted (ViewAsSubjectResolver.cs:7-10).
  • Depends on: IUnitOfWork (:24), User, and the framework's ViewAsSubject record (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/ViewAs/ViewAsSubject.cs:15).
  • Concept introduced, reading past the soft-delete filter so a refusal is named correctly. [Rubric §11, Security]. The read passes ignoreQueryFilters: true (ViewAsSubjectResolver.cs:33), so a soft-deleted row comes back with IsDeleted set instead of vanishing, and the framework can refuse a deleted account as deleted rather than report it missing (:13-14). Two more flags on the returned subject give the framework its other refusals (:36-40): IsServiceAccount, because a machine client's account (ADR-140) is not a person and there is nobody to support, and IsLocked, because a locked account's tokens are already rejected by every host through the soft-deleted-user marker a lock writes.
  • Walkthrough: FindAsync (:27-49) issues one projected, untracked read through GetReadRepository<User, UserIdentifierType>().GetProjectedAsync of Id, Email, Role, FirstName, LastName, IsDeleted, IsServiceAccount and LockedOn, filtered on u.Id == userId (:29-34). It returns null on a miss, otherwise new ViewAsSubject(row.Id, row.Email.Value, row.Role, $"{row.FirstName} {row.LastName}", row.IsDeleted) with IsServiceAccount copied and IsLocked = row.LockedOn is not null (:41-48).
  • Why it's built this way: the projection reads mapped columns where the aggregate exposes computed properties, because computed properties do not translate to SQL: LockedOn instead of User.IsLocked (:39-40), and FirstName plus LastName instead of User.FullName, assembled the same way FullName builds it for an ordinary sign-in token so the staff user sees the name the account holder does (:17-20).
  • Where it's used: registered as TryAddScoped<IViewAsSubjectResolver, ViewAsSubjectResolver>() in the Application layer's DependencyInjection (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/DependencyInjection.cs:47), whose comment notes that with ViewAs:Enabled off on the Identity service the framework never calls it (:51-52). Its refusals are pinned by ViewAsSubjectResolverLockedAccountTests and ViewAsSubjectResolverServiceAccountTests; the grant side is AdminViewAsGrantsController.

SpeakerLinkedToUserHandler

MMCA.ADC.Identity.Application · MMCA.ADC.Identity.Application.Speakers.IntegrationEventHandlers · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Speakers/IntegrationEventHandlers/SpeakerLinkedToUserHandler.cs:43 · Level 8 · class (sealed, partial)

  • What it is: the Identity-side subscriber for Conference's SpeakerLinkedToUser integration event. It sets User.LinkedSpeakerId, the Identity half of the bidirectional User-to-Speaker link (BR-209).
  • Depends on: ScopedIntegrationEventHandlerBase<TIntegrationEvent> (base, which implements IIntegrationEventHandler<in TIntegrationEvent>); SpeakerLinkedToUser from MMCA.ADC.Conference.Shared; IUnitOfWork and IRepository<TEntity, TIdentifierType>; User (LinkSpeaker, MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Domain/Users/User.cs:483); RefreshSessionRevocation and IRefreshSessionStore (the unconfirmed-account revoke); IServiceScopeFactory, TimeProvider and ILogger with the [LoggerMessage] source generator.
  • Concept introduced, the integration-event handler as a base-class subclass. [Rubric §6, CQRS & Event-Driven] and [Rubric §7, Microservices Readiness]. Two structural facts separate this from a domain-event handler. First, integration-event handlers are registered as singletons, so they cannot constructor-inject a scoped service such as IUnitOfWork. Every handler therefore needs a DI scope per delivery. Rather than repeat that preamble, this class extends ScopedIntegrationEventHandlerBase<SpeakerLinkedToUser> (SpeakerLinkedToUserHandler.cs:43-46), which opens the async scope and hands the subclass that scope's IServiceProvider (MMCA.Common/Source/Core/MMCA.Common.Application/DomainEvents/ScopedIntegrationEventHandlerBase.cs:51-54). The subclass body is only its own resolutions plus its own logic, and the class doc says exactly that (SpeakerLinkedToUserHandler.cs:21-25). Second, this is a cross-service subscription: the event type comes from Conference's Shared assembly, travels through Conference's outbox and the broker, and lands here (ADR-003). The class doc states the direction plainly: Conference never calls Identity to set the link, so the back-link is eventually consistent, and this handler is the only place that sets User.LinkedSpeakerId while its counterpart SpeakerUnlinkedFromUserHandler is the only place that clears it (:14-20). That inversion is what allows the two modules to run as separate processes with separate databases.
  • Walkthrough (primary constructor :43-46, HandleScopedAsync :49-88)
    1. Scope-resolved services (:54-55), IUnitOfWork from the provided IServiceProvider, then GetRepository<User, UserIdentifierType>() (the mutating repository, because this path writes). The null guard on the event itself lives in the base (ScopedIntegrationEventHandlerBase.cs:68).
    2. Load (:57), GetByIdAsync(integrationEvent.UserId, ...). A missing user logs a warning and returns (:58-62, template at :111-112) rather than throwing: retrying cannot conjure an account that no longer exists.
    3. Ordering and idempotency check (:64-70), user.LinkSpeaker(speakerId, integrationEvent.DateOccurred) returns false for a stale or repeated event, and the handler logs at Debug and returns without writing (template at :114-115). The class doc explains the stamp (O-66, :26-32): Linked and Unlinked travel on separate queues with no delivery order, each event carries Conference's DateOccurred, and User.SpeakerLinkChangedOn (User.cs:95) records the newest change applied, so a Linked that occurred at or before it (a late or redelivered event) is dropped instead of re-applying the link (User.cs:485).
    4. Revoke an unconfirmed account's sessions (:72-83). A speaker link makes the account privileged, and a privileged account needs a confirmed address to sign in, so when user.IsEmailConfirmed is false the handler revokes every live refresh session through RefreshSessionRevocation.RevokeAllAsync (:77-81) and logs it (:82, template :120-121); the class doc (:33-39) adds that the refresh gate in AuthenticationService refuses the same account independently, and that a confirmed account keeps its sessions. The comment on the order (:72-74) matters: revoking before the save means a failed save redelivers and revokes again (harmless), whereas revoking after it could be skipped for good once a redelivery finds the link already applied.
    5. Persist (:85), SaveChangesAsync, followed by an information-level log (:87, template at :117-118).
    6. Failure policy, inherited. The base wraps the body in catch (Exception ex) when (ex is not OperationCanceledException && LogAndRethrow(...)) (ScopedIntegrationEventHandlerBase.cs:89): the filter always returns false, so the exception keeps propagating with its original stack. Cancellation short-circuits the filter and propagates without an error log, because host shutdown is not a delivery failure. This class overrides only the log line, LogHandlerFailure (:108-109), so the error names both sides of the link (:123-124) instead of the base's generic message.
  • Why it's built this way: [Rubric §29, Resilience & Business Continuity]. The override's <remarks> (:96-107) state why the exception is not swallowed: a swallowed fault would acknowledge the delivery, so one transient database fault would lose the BR-209 back-link permanently, leaving the user with a null LinkedSpeakerId while Conference considers the speaker linked. Propagating hands the decision to the delivery mechanism instead: the consumer wrapper leaves the inbox row unprocessed, and the framework's broker receive pipeline retries it in process, redelivers it later, and finally dead-letters it. Retrying is only safe because step 3 exists, which is the base's stated contract: subclasses must be idempotent (ScopedIntegrationEventHandlerBase.cs:33).
  • Where it's used: driven by the Identity service's broker consumer registration (MMCA.ADC/Source/Services/MMCA.ADC.Identity.Service/IdentityBrokerConsumers.cs) for SpeakerLinkedToUser; SpeakerLinkOrderingTests in MMCA.ADC.Identity.Application.Tests pin the O-66 ordering, and the full outbox to broker to consumer round trip is exercised by CrossServiceSpeakerLinkTests in the cross-service integration tier.

SpeakerUnlinkedFromUserHandler

MMCA.ADC.Identity.Application · MMCA.ADC.Identity.Application.Speakers.IntegrationEventHandlers · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Speakers/IntegrationEventHandlers/SpeakerUnlinkedFromUserHandler.cs:28 · Level 8 · class (sealed, partial)

  • What it is: the mirror of SpeakerLinkedToUserHandler. It subscribes to Conference's SpeakerUnlinkedFromUser and clears User.LinkedSpeakerId, but only when the link still points at the speaker the event names and the event is newer than the last link change applied.
  • Depends on: the same set as its sibling: ScopedIntegrationEventHandlerBase<TIntegrationEvent>, SpeakerUnlinkedFromUser, IUnitOfWork, User (UnlinkSpeaker, MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Domain/Users/User.cs:505), IServiceScopeFactory, and [LoggerMessage] logging.
  • Concept introduced, guarding against out-of-order delivery. [Rubric §29, Resilience & Business Continuity] and [Rubric §8, Data Architecture]. The scope preamble, the DateOccurred stamp (O-66) and the log-and-propagate envelope are the ones taught at SpeakerLinkedToUserHandler; the class doc points there and restates the rule: both handlers compare each event's DateOccurred with User.SpeakerLinkChangedOn and drop the older event (SpeakerUnlinkedFromUserHandler.cs:16-19). What is new here is a speaker-identity guard in front of the stamp. Linked and Unlinked arrive on separate queues with no ordering guarantee, so an Unlinked event for a previous speaker can land after the user has already been re-pointed at a new one. Clearing the column on that message would silently drop a link that is still valid. The handler therefore compares before clearing (:49-56) and, on a mismatch, logs a warning naming both speaker ids (:54, message template at :101-102) and leaves the link in place. That is the general lesson for any compensating message: an event that undoes something must verify it is undoing the thing it was written for.
  • Walkthrough (HandleScopedAsync :34-74): resolve the unit of work and the mutating repository from the scope the base opened (:39-40); load, with a warning-and-return on a missing user (:42-47); the different-speaker guard above (:49-56); then the stamp check, user.UnlinkSpeaker(speakerId, integrationEvent.DateOccurred) (:62), which returns false for a stale or repeated event, logged at Debug (:64, template :104-105). The comment (:58-60) records the subtle case: an Unlinked that lands before its own (older) Linked still records its stamp, so it saves even though there was no link to clear, and that Linked is dropped when it arrives. wasLinked (:61) captures whether a link existed, so after SaveChangesAsync (:68) the information log fires only when something was actually cleared (:70-73). Failure handling is the inherited exception filter with only the log line overridden (:95-96), carrying the same <remarks> rationale as its sibling (:82-94).
  • Why it's built this way: the early returns (not found, different speaker, stale or repeated) each map to a distinct real situation and each gets its own message and log level, so an operator reading the log can tell "nothing to do" apart from "something is off". Not found and different speaker are warnings; a stale or repeated event is routine at-least-once traffic and logs at Debug.
  • Where it's used: driven by the Identity service's broker consumer registration (MMCA.ADC/Source/Services/MMCA.ADC.Identity.Service/IdentityBrokerConsumers.cs); triggered by Conference's UnlinkUserFromSpeaker command, by the cascade cleanup that runs when a Speaker is soft-deleted (BR-70), and by Conference's account-erasure unlink (UserDeletedSpeakerErasureHandler), as the class doc records (:11-15).

UserAdministrationService

MMCA.ADC.Identity.Application · MMCA.ADC.Identity.Application.Users.Administration · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/Administration/UserAdministrationService.cs:37 · Level 9 · class (sealed)

  • What it is: ADC's subclass of the framework's UserAdministrationServiceBase<TUser, TUserDto>, closed over User and UserAdminDTO (UserAdministrationService.cs:37-43), and through it ADC's implementation of IUserAdministrationService<TUserDto>, the service UsersAdminController calls: get one account, read its role, lock/unlock, and change role. The class doc (:12-31) draws the line: the workflow (loading and saving the account, the soft-deleted user marker, the refresh-session revocation on a lock, the log lines) is the base's, and this class supplies only how ADC's User expresses a lock, its single role, and the administration DTO. It does not list or search the roster: that read is the generic entity-query path (see UserListDTOMapper and UserListEntityQueryService).
  • Depends on: IUnitOfWork, IRefreshSessionStore, TimeProvider, ISoftDeletedUserMarkerWriter and ILogger<UserAdministrationService>, all five taken by the primary constructor and forwarded unchanged to the base (:37-43); plus User, UserRole, UserAdminDTO, and the framework's Result and Error. The class itself holds no state and declares no logging of its own.
  • Concept introduced, the framework workflow with app-supplied hooks. [Rubric §11, Security]. The security-relevant steps of account administration are written once in MMCA.Common, so every app that adopts the base gets them identically, and the app overrides only the six members that describe its own aggregate. The base's SetLockedAsync (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Administration/UserAdministrationServiceBase.cs:114-159) saves the lock, then, on a lock, writes the soft-deleted user marker first and revokes the live refresh sessions through RefreshSessionRevocation.RevokeAllAsync second (UserAdministrationServiceBase.cs:138-151); the comment there gives the order (:132-133): the marker is what refuses the access tokens already issued, while the revocation only stops new ones being minted. An unlock of an account that was locked clears the marker (:138-141). A marker write or clear that throws is logged as a warning and not reported as a failure, because the lock state is already saved (:264-287). A role change, by contrast, is saved only: the live sessions stay, because the refresh path re-reads the account and mints the next access token from the stored role (comment :195-196).
  • Walkthrough (the overrides, in source order)
    • MapToDto (UserAdministrationService.cs:46-55): builds the UserAdminDTO from the aggregate (id, email, first and last name, role, CreatedOn, LockedOn, IsExternalLogin, IsEmailConfirmed); the base's GetAsync (UserAdministrationServiceBase.cs:77) returns it, or a not-found Result when the id misses.
    • IsLocked (:58): reads user.IsLocked. The base captures it before applying the new state (UserAdministrationServiceBase.cs:128), which is how an unlock knows whether there is a marker to clear.
    • ApplyLockState (:62-74): user.Lock(utcNow) or user.Unlock(), always returning success; the remark (:61) states that ADC's lock and unlock are idempotent and cannot fail. The base would otherwise return a failure before anything is saved (UserAdministrationServiceBase.cs:130-134).
    • GetRole (:77) and ApplyRole (:81): the role is read from user.Role, and applying it defers to User.ChangeRole, which stores the role's canonical spelling (:80). The base compares the role before and after ordinally and returns success with nothing saved when it did not change (UserAdministrationServiceBase.cs:194-207).
    • ValidateRequestedRole (:85-89): parses the requested role through UserRole.FromString and returns its errors unchanged on failure. The base calls it before it loads the account (UserAdministrationServiceBase.cs:179-183), so an unknown role is refused ahead of not-found (remark :84, class doc :27-29).
    • CreateExactlyOneRoleError (:92-95): the User.Role.ExactlyOne validation error, which the base returns for any request that does not carry exactly one role (UserAdministrationServiceBase.cs:174-177). An ADC account holds exactly one role, so zero or two is a validation failure rather than something to truncate silently (class doc :27-28).
  • Why it's built this way: keeping the lock, marker, revocation and logging steps in the base means an app cannot forget one of them when it implements administration for its own user type, and the base's [LoggerMessage] partials (UserAdministrationServiceBase.cs:318-328) give every app the same audit trail: one Information line per lock change and per role change, and a Warning when the marker could not be written or cleared.
  • Where it's used: registered with TryAddScoped as IUserAdministrationService<UserAdminDTO> in the Application layer's DependencyInjection (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/DependencyInjection.cs:43) and resolved by UsersAdminController; its DTO shape is the one UserDetail and UserList render. Covered by UserAdministrationServiceTests in MMCA.ADC.Identity.Application.Tests.

PasskeysController

MMCA.ADC.Identity.API · MMCA.ADC.Identity.API.Controllers.Passkeys · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/Controllers/Passkeys/PasskeysController.cs:21 · Level 9 · class (sealed)

  • What it is: ADC's passkey endpoints (ADR-139): list, register, rename and delete a signed-in account's passkeys, plus the anonymous passkey sign-in (PasskeysController.cs:7-12). The class has no body; it is the sealed subclass that carries the routing attributes over the framework's PasskeysControllerBase.
  • Depends on: PasskeysControllerBase (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/Passkeys/PasskeysControllerBase.cs:41), which itself derives from ApiControllerBase; ASP.NET Core's [ApiController] and [Route] and Asp.Versioning's [ApiVersion].
  • Concept reinforced, the attributes-only controller subclass. [Rubric §3, Clean Architecture] and [Rubric §11, Security]. The whole declaration is [ApiController], [Route("auth/passkeys")], [ApiVersion("1.0")] and public sealed class PasskeysController : PasskeysControllerBase; (PasskeysController.cs:18-21), exactly the shape the base's summary prescribes (PasskeysControllerBase.cs:17-20). The route is fixed because the framework's UI client calls auth/passkeys, and its signin action is a default token-issuing path of the web head's same-origin proxy (PasskeysController.cs:9-11). The security behavior is all inherited: registration demands a recent sign-in (auth_time within ten minutes) that a refresh never renews, so a stolen refresh token cannot plant its own passkey, and the two anonymous sign-in actions carry the auth per-IP rate limit policy (PasskeysControllerBase.cs:29-39).
  • Walkthrough: no members. Every action comes from the base.
  • Why it's built this way: off means no routes. Every action answers 404 unless the host called AddPasskeys and set Passkeys:Enabled, so ADC can inherit the base ahead of turning the feature on (PasskeysControllerBase.cs:23-27). ADC ships it switched off: only the Development configuration and the AppHost enable it, so production serves no passkey route while the table and this controller are in place (PasskeysController.cs:13-17).
  • Where it's used: discovered by MVC routing in the Identity service; covered by PasskeysControllerTests, and counted in the expected anonymous-endpoint scan of AnonymousEndpointTests (MMCA.ADC/Tests/Architecture/MMCA.ADC.Architecture.Tests/Api/AnonymousEndpointTests.cs:144-147), since its sign-in actions are anonymous by necessity.

GetUserPreferencesHandler

MMCA.ADC.Identity.Application · MMCA.ADC.Identity.Application.Users.UseCases.GetPreferences · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Application/Users/UseCases/GetPreferences/GetUserPreferencesHandler.cs:13 · Level 9 · class (sealed)

  • What it is: the read side of user preferences: given a user id, return the stored culture and theme. Another empty subclass, this one over GetUserPreferencesHandlerBase<TUser>.
  • Depends on: GetUserPreferencesHandlerBase<TUser> (base), IUnitOfWork, and User. Note what is absent: no ILogger. A query that only reads has nothing to announce.
  • Concept reinforced, the thin CQRS read handler (the subclass shape is taught at ChangePasswordHandler; the query pipeline at IQueryHandler<in TQuery, TResult>). [Rubric §6, CQRS & Event-Driven]: the base implements IQueryHandler<GetUserPreferencesQuery, Result<UserPreferencesResponse>> (MMCA.Common/Source/Core/MMCA.Common.Application/Users/UseCases/GetPreferences/GetUserPreferencesHandlerBase.cs:19-20), so it runs through the query decorator chain with no Validating and no Transactional decorator, because a read opens no transaction. Both GetUserPreferencesQuery and UserPreferencesResponse were byte-identical in the two applications and were hoisted whole (:10-13), which is why this base is generic in the aggregate only, and why its constraint is the lighter AuditableBaseEntity<UserIdentifierType>, IUserPreferences rather than the aggregate-root constraint the write bases need (:23). [Rubric §27, Internationalization]: this is the server end of "remember my language", reading User.PreferredCulture straight off the aggregate.
  • Walkthrough: a primary constructor taking IUnitOfWork and forwarding it (GetUserPreferencesHandler.cs:13-14), empty body. The inherited HandleAsync (GetUserPreferencesHandlerBase.cs:31-43) guards the query for null (:37), resolves unitOfWork.GetReadRepository<TUser, UserIdentifierType>() (:39), calls GetByIdAsync(query.UserId, ...) (:40), and returns either Error.NotFound tagged with HandlerName and the aggregate's type name or Result.Success(new UserPreferencesResponse(user.PreferredCulture, user.PreferredTheme)) (:41-44).
  • Why it's built this way: the base's <remarks> (GetUserPreferencesHandlerBase.cs:14-17) records that the two application copies disagreed on the repository (ADC read, Store write) and that the read repository is the correct choice for a handler which never calls SaveChangesAsync, so Store gained a no-tracking read on adoption. That is the ordinary payoff of consolidating duplicated code: the merge forces a decision, and the better of the two behaviors wins for everyone.
  • Where it's used: resolved as IQueryHandler<GetUserPreferencesQuery, Result<UserPreferencesResponse>> and injected into AuthController (AuthController.cs:36) as GET /Auth/preferences; the response seeds the client's culture and theme at startup.

UserConfiguration

MMCA.ADC.Identity.Infrastructure · MMCA.ADC.Identity.Infrastructure.Persistence.EntityConfiguration · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Infrastructure/Persistence/EntityConfiguration/UserConfiguration.cs:12 · Level 11 · class (internal, sealed)

  • What it is: the EF Core mapping for the User aggregate: column types and widths, the value-object conversion for Email, the ignored computed properties, and three indexes.
  • Depends on: EntityTypeConfigurationSQLServer<TEntity, TIdentifierType> (base), EmailValueConverter, User and UserInvariants, and EF Core's EntityTypeBuilder<T>.
  • Concept introduced, the engine-typed configuration base and the shared length constants. [Rubric §8, Data Architecture] assesses whether the schema is declared explicitly rather than inferred, and [Rubric §15, Best Practices & Code Quality] covers why the numbers are not literals. Two things are worth internalizing. First, the base class is what routes this entity to a physical data source: deriving from EntityTypeConfigurationSQLServer<User, UserIdentifierType> (UserConfiguration.cs:13) declares the engine, and the database name resolves from the module, which is how User lands in ADC_Identity rather than in a shared database. base.Configure(builder) (:18) must run first, because it applies the framework conventions (key, audit columns, the soft-delete global query filter) that this method then refines. Second, every length that also matters to the domain is read from UserInvariants rather than typed twice: EmailMaxLength (:23), FirstNameMaxLength (:29), LastNameMaxLength (:33) and TermsVersionMaxLength (:87). The constants themselves are 100, 100, 100 and 32 (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Domain/Users/UserInvariants.cs:12-21). That is the mechanism that stops an over-long name from passing the domain check and then being truncated by the database.
  • Walkthrough
    • Email (:20-24): HasConversion(new EmailValueConverter()) maps the Email value object onto a plain column, then HasMaxLength and IsRequired(), and deliberately no IsUnicode(false). The comment (:20) states why: an address may be in any script, and varchar collapses non-Latin addresses onto ?, so the column is nvarchar. IsUnicode(false) remains on the strings whose values are ASCII by definition (role names, provider keys, culture and theme codes, the avatar URL, the terms version): these become varchar, not nvarchar, halving the storage. The rule is the split, not a blanket default: anything a person may enter in any script omits IsUnicode(false) and so stays nvarchar (M148).
    • Names (:26-34): FirstName and LastName, both required, both bounded by the domain constants above, and both deliberately left Unicode. The comment (:26-27) states why: names are human text in any script, so a non-Latin name is stored as entered instead of being corrupted to ? by a varchar code page.
    • Credentials (:36-41): PasswordHash and PasswordSalt are configured with no options at all, deliberately. The comment states that EF maps byte[] to varbinary(max) by default so no explicit length is needed (BR-204), and that external-login accounts hold empty arrays.
    • Fixed-width strings: Role at 50 (:43-46), LoginProvider at 50 and ProviderKey at 256 (:57-64), PreferredCulture and PreferredTheme at 10 each (:66-73), AvatarUrl at 512 (:75-78).
    • LinkedSpeakerId (:51): configured as a plain scalar property with no relationship at all. That is the visible consequence of ADR-006: Speaker lives in another database, so there is no foreign key to declare, and the comment above it (:48-50) says so in as many words (a nullable scalar reference to the Conference Speaker, never a cross-database FK) and records the intent, a link that is unique when non-null (BR-208, BR-209).
    • SpeakerLinkChangedOn (:55): a nullable instant configured with no options. The comment (:53-54) names its job (O-66): it records when Conference made the last applied link change, so the SpeakerLinkedToUserHandler and SpeakerUnlinkedFromUserHandler can drop an event that arrives after a newer one.
    • LockedOn (:82): the administrative lock instant (users:manage), nullable and configured with no explicit options; the comment (:80-81) states that null means the account is usable and the instant is what an operator needs to answer "since when" it was locked.
    • Terms acceptance (:84-90): AcceptedTermsVersion is bounded by TermsVersionMaxLength and IsUnicode(false) (:86-88), and TermsAcceptedOn is a nullable instant configured with no options (:90). Both are nullable because accounts that predate the terms, and accounts created through external sign-in, have accepted nothing yet (comment :84-85).
    • IsEmailConfirmed (:92-97): required, with HasDefaultValue(false) (ADR-116). The comment explains the default: it keeps the column non-nullable for rows written by anything that does not set the flag, and the migration backfills the accounts that existed before it did.
    • IsServiceAccount (:99-103): required, with HasDefaultValue(false) (ADR-140). It is set only on the service accounts a machine client signs as, and the default keeps the column non-nullable so every account that existed before it reads as a person (comment :99-100).
    • Ignored members (:105-108): FullName, IsExternalLogin and IsLocked are computed on the aggregate, so builder.Ignore keeps EF from expecting columns for them.
    • Indexes (:110-121): a unique index on Email with no hand-written filter (:113), which is the BR-200 "email is the identity" rule enforced at the storage layer; a unique filtered index on LinkedSpeakerId with HasFilter("[LinkedSpeakerId] IS NOT NULL") (:115-117), which makes the User-to-Speaker link 1:1 while still allowing the many users who have no linked speaker; and a unique filtered composite on (LoginProvider, ProviderKey) (:119-121), so one external identity cannot be attached to two accounts.
  • Concept introduced, what soft delete does to a unique index. [Rubric §8, Data Architecture]. Read the Email index again: it declares IsUnique() and no filter (:113), yet the row it guards is never physically deleted. A soft-deleted row still occupies its unique slot, so without help the address of a deleted account could never be reused. The help is a model-finalizing convention rather than a hand-written filter, and the comment above the index block says so (:110-112): SoftDeleteUniqueIndexConvention walks every soft-deletable entity type at model finalization (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/Conventions/SoftDeleteUniqueIndexConvention.cs:46-50), building the predicate through the same SoftDeleteFilterSql.Build a hand-authored index would reach (:57), and no-opping for Cosmos (:43-44). The behavior to internalize is that a hand-authored filter is extended, not skipped: an index with no filter gets the soft-delete clause outright (:66-71), an index that already constrains the soft-delete column is left exactly as it is (:73-76), and any other hand-written predicate is kept and AND-ed with the soft-delete clause (:78-80). So all three indexes here end up excluding deleted rows: Email gains the clause alone, and the two that spell their own HasFilter keep their own predicate plus the appended one. The convention's doc comment records that skipping them, as an earlier version did, silently left exactly the hand-authored partial-unique indexes as the only ones a soft-deleted row could keep blocking (:19-26).
  • Why it's built this way: [Rubric §12, Performance & Scalability]: the two hand-filtered indexes are sparse-column cases where the majority of rows are null, so filtering keeps each index small and keeps writes to the common rows out of it entirely. [Rubric §11, Security]: the unique constraints on email and on the provider pair are the last line of defence behind the application-level uniqueness probes, so a race between two concurrent registrations fails at the database rather than producing two accounts.
  • Where it's used: discovered by assembly scan through IEntityConfigurationAssemblyProvider and applied when the sealed per-engine context SQLServerDbContext builds its model from that provider (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/SQLServerDbContext.cs:15, provider parameter at line 18); the resulting schema is materialized by the per-service Identity migrations project.
  • Caveats / not-in-source: two small mismatches are worth knowing. First, the file comment warns that spelling the soft-delete clause here "would double it" (:110-112), but the convention guards that case with SoftDeleteFilterSql.ContainsPredicate and leaves such a filter untouched (SoftDeleteUniqueIndexConvention.cs:73-76), so the comment is more cautious than the code requires. Second, the erasure path is what frees the two provider slots on an already-deleted row: User.Anonymize nulls LoginProvider and ProviderKey and rewrites the address to a per-id deleted-{Id}@anonymized.invalid placeholder (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Domain/Users/User.cs:667-707); LinkedSpeakerId is not cleared there, but because the convention appends the soft-delete clause to that index too, a soft-deleted user no longer blocks the slot.

IdentityModuleDbSeeder

MMCA.ADC.Identity.Infrastructure · MMCA.ADC.Identity.Infrastructure.Persistence.DbContexts.Seeding · MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.Infrastructure/Persistence/DbContexts/Seeding/IdentityModuleDbSeeder.cs:27 · Level 12 · class

  • What it is: the development and test seeder for Identity. It supplies three fixed accounts (one Organizer, two Attendees) to the framework's IdentityModuleDbSeederBase<TUser>, which owns the per-account idiom.
  • Depends on: IdentityModuleDbSeederBase<TUser> (base, itself a DbSeeder), IUnitOfWork, IPasswordHasher, SeedAccount, Email, User and UserRole, and Result in its generic form.
  • Concept introduced, the hoisted seeder with two typed hooks. [Rubric §17, DevOps] assesses repeatable environment setup, and [Rubric §15, Best Practices & Code Quality] covers the de-duplication. The five-step idiom (normalize the email, skip if it already exists, hash the password, build the aggregate, add, save) was written out five times across the two applications' Identity modules and now lives once in the base (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Persistence/DbContexts/Seeding/IdentityModuleDbSeederBase.cs:110-138). Only two things could not be hoisted, and the base's <remarks> (:13-24) names both: CreateUser, because the two applications' User.Create(...) factories take the same values in different parameter orders and only the application can spell its own role vocabulary; and EmailExistsAsync, because the existence predicate must be written against the concrete User (never an interface member) so EF translates it byte-for-byte the way it did before the hoist. That second point is the general lesson for hoisting anything that ends up inside an expression tree: a where TUser : ISomething constraint would compile and then fail at query translation.
  • Concept introduced, seeding gated where the gate has one home. [Rubric §11, Security]. The base exposes a ShouldSeed opt-in that defaults to true (IdentityModuleDbSeederBase.cs:90), and this subclass deliberately does not override it (IdentityModuleDbSeeder.cs:18-20): ADC's Seeding:IncludeSampleUsers gate stays in IdentityModuleSeeder in the API layer, which reads the key with GetValue<bool> and returns before constructing this seeder at all (MMCA.ADC/Source/Modules/Identity/MMCA.ADC.Identity.API/IdentityModuleSeeder.cs:29-31). One gate, one home. The class doc carries an explicit security notice (IdentityModuleDbSeeder.cs:21-25): the seed credentials ("Admin123!", "Password") are intentionally weak, exist only for local development convenience, and a deployed host must either disable seeding or supply environment-sourced secrets. The default of false when the configuration key is absent (IdentityModuleSeeder.cs:25-28) is what makes that safe by omission rather than by remembering.
  • Walkthrough
    • Accounts (:33-38): a collection-expression IReadOnlyList<SeedAccount> with three entries, each (email, password, role, firstName, lastName). The roles come from UserRole's constants, not string literals.
    • EmailExistsAsync (:41-48): resolves the mutating repository through UnitOfWork.GetRepository<User, UserIdentifierType>() and returns ExistsAsync(u => u.Email == email, ...) directly, a non-async override that hands back the repository's Task<bool> without an extra state machine or await. The predicate compares the Email value object, which is why the base normalizes the raw string with Email.Create(account.Email).Value first (IdentityModuleDbSeederBase.cs:112-113): both sides of the comparison then go through the same value converter and the SQL matches.
    • CreateUser (:51-70): a null guard (:53), then User.Create(email, firstName, lastName, passwordHash, passwordSalt, role) in ADC's parameter order (:55-61), returning the aggregate's own generic Result (:69). Between the two, any successfully created account whose role is not UserRole.Attendee is confirmed with user.ConfirmEmail() (:66-67). The comment (:63-65) gives the reason: a seeded privileged account is an operator account at a known address, and a privileged account must have a confirmed email to sign in (AuthenticationService's CheckEmailConfirmed), so the seeded Organizer would otherwise be locked out; seeded attendees keep the unconfirmed default. A failure here is not thrown: the base skips that one account and moves on (IdentityModuleDbSeederBase.cs:122-126).
    • Idempotency and isolation come from the base loop: SeedAsync short-circuits on ShouldSeed and then iterates the accounts (:60-71), and each account is saved individually (:110-112), so re-running against an already-seeded database is a no-op and one invalid account cannot roll back the others.
  • Why it's built this way: seeding goes through IUnitOfWork and the domain factory rather than through raw SQL or EF HasData, so seeded rows satisfy exactly the same invariants, audit stamping, and password hashing (ADR-032) as rows created through the API. That is what makes the seeded database a faithful small copy of a real one rather than a fixture that only looks like one.
  • Where it's used: constructed by IdentityModuleSeeder (IdentityModuleSeeder.cs:33-36), which the module system invokes through the IModuleSeeder contract during database initialization (DatabaseInitializationExtensions); in practice that means the local Aspire AppHost and E2E CI, and nothing else.
  • Caveats / not-in-source: the account list is a compile-time constant, so changing which accounts exist in a development environment is a code change and a rebuild, not configuration. The class is also the one non-sealed type in this unit (IdentityModuleDbSeeder.cs:27), a plain public class; nothing in the repo subclasses it today.

⬅ ADC Engagement Live Layer (Real-Time Polls & Session Q&A) • Index • ADC Application Host, UI Shell & Cross-Module Composition ➡