Skip to content

User-write observability (audit, security logging, rate limiting, invalidation) ​

User writes have one route per operation under /api/v1/users/*, with ?scope=tenant (the session's tenant, the default) or ?scope=global (a platform role) — the separate admin track was removed by ADR 0011. Both scopes share four controls. This page is the operation × control matrix and the per-endpoint rate-limit decision.

The four controls ​

ControlMechanismWhere
AuditAuditSaveChangesInterceptor writes an AuditEntry on commit for every changed IAuditableEntity. Each entry names the caller (IAuditContext.UserId), the token tenant, the target (entity id), the operation (ChangeType), before/after values and the correlation id.GrydAudit.Infrastructure/Interceptors/AuditSaveChangesInterceptor.cs; context adapter HttpContextAuditContext
Security logStructured Serilog warning on a security decision (a block), carrying an EventType and RiskLevel, with all personal data masked.AuthTracingConstants.SecurityEvents + the emitting site
Rate limitPer-endpoint ASP.NET rate-limiting policy; 429 on rejection.GrydAuthRateLimitingPolicies / GrydAuthRateLimitingExtensions
Cache / token invalidationAuthorization-affecting domain events → AuthorizationAffectingEventHandler bumps TokenVersion and blacklists the user's tokens; affected users resolved by AffectedUsersResolver.GrydAuth.Application/Features/Security/EventHandlers + AffectedUsersResolver

Both scopes funnel their writes through the same MediatR handlers and the same SaveChangesAsync, so audit and invalidation are automatic for both. The audit entry does not carry a scope field; every non-tenant scope decision is recorded separately in the scope audit trail (ADR 0011, D15).

Operation × control matrix ​

Operation (endpoint)Audit entity (change)Security log on blockRate limitInvalidation event
Create user (POST /users)User (Created) + UserTenant (Created) + UserAppIdtenant_link_request_probe on existing-email (anti-enumeration)tenant-user-create (per IP, US 4.2)UserAssignedToTenantEvent
Update user (PUT /users/{id})User (Updated); UserTenant (Updated) when IsActive flipscross_tenant_access_denied on cross-tenant target (404)none (see below)UserTenantActivated/UserTenantDeactivated when IsActive flips
Delete/unlink user (DELETE /users/{id})UserTenant (unlink)cross_tenant_access_deniednoneUserRemovedFromTenantEvent (and UserDeletedEvent on the scope=global delete)
Assign role (POST /users/{id}/roles/{roleId})UserRole (Created)role_assignment_escalation_blocked (US 5.1) · cross_tenant_access_deniednoneUserRoleAssignedEvent
Remove role (DELETE /users/{id}/roles/{roleId})UserRole (Deleted)cross_tenant_access_deniednoneUserRoleRemovedEvent
Assign permission (POST /users/{id}/permissions/{permId})UserPermission (Created)role_assignment_escalation_blocked (US 5.1) · cross_tenant_access_deniednoneUserPermissionAssignedEvent
Remove permission (DELETE /users/{id}/permissions/{permId})UserPermission (Deleted)cross_tenant_access_deniednoneUserPermissionRemovedEvent
Link to tenant (POST /users/{id}/tenants?scope=global)UserTenant (Created)—noneUserAssignedToTenantEvent
Any throttled request—rate_limit_exceeded (429)the tripped policy—

Per-endpoint rate-limit decision ​

  • POST /users → tenant-user-create (per IP). This is the only tenant-track write that is an enumeration vector: it answers a generic USER_EMAIL_UNAVAILABLE for an already-used e-mail (anti-disclosure, D8), so an attacker could probe e-mail existence. It runs on its own IP partition, deliberately off the shared auth:{ip} budget (US 4.2).
  • All other tenant-track writes (PUT/DELETE /users/{id}, role/permission assign/remove): no dedicated policy. They operate on an already-resolved, known user in the caller's own tenant, gated by a privileged permission (update:users / delete:users) and by tenant isolation (a cross-tenant target answers 404). They are not enumeration vectors and do not leak existence, so a per-IP anti-enumeration limiter adds no security value. They remain subject to the global request pipeline. Revisit if abuse is observed in practice.

Security-event catalog ​

Domain-specific event types live in AuthTracingConstants.SecurityEvents:

Event typeEmitted whenRisk
role_assignment_escalation_blockeda grant would exceed the caller's own permissions (US 5.1)High
cross_tenant_access_denieda tenant-scoped request targeted a user outside the caller's tenant (US 5.4)Medium
rate_limit_exceededa request was throttled with 429 (US 5.4)Medium
tenant_link_request_probea tenant-scoped create hit an existing global e-mail (US 4.2)Medium

All of these follow docs/security/security-logging-policy.md: only ids, event types and decisions are logged in the clear; e-mail and IP are masked via SensitiveDataMasker; no tokens, claims or raw personal data ever reach the logs.

Cache-invalidation coverage note ​

AffectedUsersResolver covers every authorization-affecting write: role/permission assign-remove (direct and via RolePermission*), tenant assign/remove, tenant activate/deactivate, user deactivate/delete. Profile-only updates are intentionally not authorization-affecting — UserUpdatedEvent / UserProfileUpdatedEvent do not implement IAuthorizationAffectingEvent, because a name/e-mail edit changes no role, permission or tenant membership and therefore must not invalidate live sessions. Authorization changes that ride along an update (an IsActive flip) raise the UserTenant activation events, which are covered.

The public Auth application compositions keep AuthorizationAffectingEventHandler registered only for IAuthorizationAffectingEvent; the transactional save loop owns that explicit dispatch. Concrete platform-role audit and tenant-cache consumers remain registered for their own events. Each distinct event retains its own invalidation; two events affecting the same user are not combined. Manual hosts must keep the same ownership and avoid adding a second concrete marker binding after Auth composition. See ADR 0013 for the registration boundary and its limits.

Membership intent producer ​

Stage 3b.1a exports auth.tenant-membership.state-changed V1 only from tenant PUT /users/{id} activation/deactivation and inactive-link reactivation via POST /tenants/{id}/members/bulk. New links, other callers, global/role/profile-only writes and no-ops export nothing. Existing audit/security remain.

Manual handlers require ICurrentUserService and IAuthMembershipOutbox. Real transitions capture an authenticated, nonempty actor before mutation; no-op needs no new attribution. Typed Stage takes the tracked link, its exact pending activation/deactivation event, and that actor. It uses the same Auth context/UoW without saving; the outer transaction owns commit. A staging failure poisons the context: discard it.

Apply migration AddAuthMembershipOutbox before new writers. It adds three Core tables in auth_outbox and UserTenant.AccessChangeSequence: default 0, checked increment, concurrency token, hidden from visible audit diffs. Coordinate all writers; old binaries cannot maintain the stream. No backfill. Events capture positive positions.

AuthMembershipStateChangedV1 freezes tenant/link/subject, previous/current state, actor and UTC time at microsecond precision. MessageId=SourceEventId identifies one attempt, not HTTP replay. Module registration starts no worker. Hosts opt into the Audit route with AddAuthMembershipAuditIntegration and separately enable AddOutboxWorker. ADR 0012 defines composition, receipt recovery and attribution limits.

Consuming the removal fact from a product ​

auth.tenant-membership.removed V1 (AuthMembershipRemovedV1) is the one fact of a membership leaving: UserTenantLinkRemover does not emit one fact per role or permission the link carried. A product registers its own AddLocalConsumer<TContext, AuthMembershipRemovedV1, THandler>(producerId, consumerId, AuthMembershipRemovalIntegrationContract.Kind, AuthMembershipRemovalIntegrationContract.Version, factory) beside the mandatory Audit route of AddAuthMembershipAuditIntegration, over a database of its own. What it can rely on, and what the PostgreSQL suite AuthMembershipProductConsumerPostgresTests pins:

  • The removal commits first. A consumer that throws is retried; it cannot undo the removal.
  • It may read the removed link from a separate unit of work: the row is a tombstone (IsDeleted, the AccessChangeSequence the fact carries), already committed when the fact is delivered.
  • A rolled-back removal delivers nothing: the fact is stored with the change or not at all.
  • A redelivery does not repeat the effect: the product's own receipt, in its own transaction, answers it.
  • A worker-only host works. AddGrydAuthReaders has no writable Auth context; it resolves the producer, the routes and the consumer, and reads Auth through the reader ports.

Register every route BEFORE starting the worker. The routing plan is frozen when the worker starts, and a message whose kind has no route ends as OUTBOX_NO_CONSUMERS (dead letter). Compose, build the provider, then enable AddOutboxWorker; never add a consumer to a running host.

Access-grant facts ​

Every change of who may do what is also a durable fact, staged in the same transaction as the change. A product that mirrors access (a cached permission set, a search index) consumes them instead of polling Auth.

Kind (V1)PayloadStream (AggregateId)Sequence
auth.user-role.changedAuthUserRoleChangedV1: SourceEventId, TenantId, UserTenantId, UserId, RoleId, RoleName, Change, Sequence, ActorUserId, ActorType, OccurredAtUserTenant.IdUserTenant.AccessChangeSequence
auth.user-permission.changedAuthUserPermissionChangedV1: the same with PermissionId, PermissionName instead of the roleUserTenant.IdUserTenant.AccessChangeSequence
auth.role-permission.changedAuthRolePermissionChangedV1: SourceEventId, TenantId, RoleId, RoleName, PermissionId, PermissionName, Change, Sequence, ActorUserId, ActorType, OccurredAtRole.IdRole.AccessChangeSequence
  • Change is granted or revoked. A change that alters nothing (already granted, never held) stages nothing.
  • A user stream is shared with the membership transitions: activation, deactivation, unlink and every grant of one UserTenant advance the same AccessChangeSequence, one position per event. A consumer orders by it and must not expect only grant facts to be contiguous.
  • Author. ActorType is User and ActorUserId is the authenticated caller captured before the change, or System with a null ActorUserId. The system authors two things only: federated sign-in mapping a provider's groups onto roles, and the tenant catalog reconciliation converging an EXISTING catalog role onto its template. A role created by provisioning a tenant records no fact (nobody holds it yet), and neither does removing a whole membership per grant (see the removal fact above).
  • There is no list of users on a role fact. The holders of a role change with the role, and a list would be stale by delivery. A consumer that needs them reads them with IPermissionHolderReader.

Reading the holders ​

IPermissionHolderReader.ReadAsync(permissionName, afterUserId, limit, ct) returns user ids, ascending, by keyset: pass the last id of a page as afterUserId, and stop when a page is shorter than limit (1 to 500). A holder is an active, non-deleted user whose membership of the session's tenant is in force (active, not removed, inside its assignment period) and who has the permission directly or through a role. The tenant is the session's: a delivery already runs in the fact's tenant, and a session without one fails like every other Auth reader. It is registered by AddGrydAuthReaders and by the full composition. The query reads committed data as of now, so a consumer that handles granted and revoked for the same role in order converges on the same set.

Composition and the update trap ​

AddAuthMembershipAuditIntegration also registers an acknowledging route for each of the three kinds (AuthAccessGrantAcknowledgementConsumers: auth.acknowledge-user-role-v1, auth.acknowledge-user-permission-v1, auth.acknowledge-role-permission-v1). It writes nothing: Auth already audits these changes inside the transaction of the act. Its only job is that a host updated BEFORE its product consumers exist completes the new facts instead of sending them to dead letter, because the plan is frozen at start. A product adds its own AddLocalConsumer for a kind next to it with its own consumer id. Keep consumer ids across deployments.

The same builder registers auth.acknowledge-tenant-governance-contacts-v1 for auth.tenant-governance-contacts.changed (see Governance contacts).

A host that enforces route admission (RequireRouteAdmission) must declare the three new kinds with AdmitRoute; until it does, their messages stay pending. Admit them in the same release that updates Auth.

Writers ​

Only two doors write these facts, and an architecture test keeps it so: IRolePermissionComposer (including Remove, and the two catalog entries ComposeNewFromCatalogTemplate and ConvergeFromCatalogTemplate) and IUserAccessGrantComposer (the ...AsSystem entries belong to federated sign-in alone). Handlers keep their guards and ceilings and call the door afterwards. A concurrent writer on the same position loses with a 409: the membership or role token, or the fact's own identity, whichever the database meets first.

Apply migration AddRoleAccessChangeSequence before new writers: Role.AccessChangeSequence, default 0, concurrency token, hidden from visible audit diffs. Old binaries cannot maintain the stream.

Tenant-created fact ​

Creating an organization, root or child, is also a durable fact, staged in the same transaction as the creation. A product consumes it to provision its own processes, settings and seeded policies for the new organization. A rolled back creation leaves no message.

Kind (V1)PayloadStream (AggregateId)Sequence
auth.tenant.createdAuthTenantCreatedV1: SourceEventId, TenantId, Name, Type, ParentTenantId, Sequence, ActorUserId, ActorType, OccurredAtTenantLifecycleStream.For(tenantId)1 (later lifecycle facts use 2..n)
  • Type is company or group; ParentTenantId is the group of a child and null for a root. The message scope is Tenant with TenantId the new organization, so the consumer runs in the frame of the organization it provisions.
  • The stream is derived from the tenant id (a version 8 UUID) and is not the tenant id itself: the governance-contact fact already uses the tenant id as its stream, with Sequence starting at 1.
  • Who generates it: the creation endpoints of an organization and of a child organization. Who does not: the Default organization created by migration, the reference seed (it assigns fixed ids and discards the events the factory raised), and the bulk link of children (POST {id}/children/bulk), which creates no organization.
  • Consuming it: add a consumer next to the Auth ones with AddLocalConsumer, with an id of your own. Delivery is at least once, so the consumer must be idempotent (key it by SourceEventId or TenantId). Auth registers an acknowledging route, auth.acknowledge-tenant-created-v1, so a host that has no product consumer yet does not dead-letter the message.
  • A host that sets RequireRouteAdmission must AdmitRoute the new kind in the same version that adopts it.

Released under the MIT License.