Skip to content

Identity Module Specification

Purpose

The identity module implements the Identity Domain inside the Spring Boot Modulith. It protects authentication interpretation, user account lifecycle, organization membership access, roles, permissions, access policies, sessions, API keys, MFA state, tenant isolation, and auditable authorization decisions.

Keycloak is the official identity provider for authentication, SSO, token issuing, MFA support, federation, clients, roles, groups, and service accounts. The identity module remains the Algosure business source of truth for memberships, tenant access, authorization semantics, permission decisions, API key governance, and audit context.

Owned Domain

Identity owns authentication identity interpretation, user accounts, organization memberships, invitations, roles, permissions, access policies, authorization decisions, sessions, API keys, MFA state, and tenant isolation rules. It references OrganizationId but does not own organization profile facts. It may request entitlement signals from billing but does not own subscription facts.

Owned Aggregates

Aggregate Responsibility
User Account Account identity, status, authentication references, verified email state, profile access metadata, and account lifecycle.
Membership User-to-OrganizationId access relationship, membership status, tenant role assignments, and access scope.
Invitation Tenant-scoped invitation recipient, expiry, roles, status, and acceptance.
Access Control Roles, permissions, assignments, and access policies.
Session Active sessions, refresh state, revocation state, device metadata, and expiry.
API Key Programmatic access metadata, hashed secret, scopes, expiry, and revocation.
MFA Registered factors, verification state, recovery state, and enforcement requirements.
Authorization Decision Auditable decision records for protected actions.

Owned Entities

User Account, Authentication Identity, Organization Membership, Invitation, Role, Permission, Role Assignment, Access Policy, Session, API Key, MFA Factor, and Authorization Decision.

Owned Value Objects

UserId, AuthenticationIdentityId, OrganizationId reference, MembershipId, EmailAddress, RoleCode, PermissionCode, ResourceReference, ActionCode, TenantScope, SessionId, SessionStatus, ApiKeyPrefix, ApiKeyHash, MfaFactorType, AuthorizationResult, AuthorizationReason, and RiskLevel.

Commands

Command Responsibility
CreateUserAccount Create a domain user account after a governed authentication signal.
LinkAuthenticationIdentity Link a Keycloak or federated identity subject to a user account.
CreateInvitation Issue a tenant-scoped invitation with proposed roles.
AcceptInvitation Accept an invitation and create or update membership access.
ActivateMembership Activate organization membership after domain checks.
SuspendMembership Remove organization access while preserving audit history.
AssignRole Grant a role within platform or tenant scope.
AssignPermission Grant direct permission only where explicitly allowed.
RecordAuthorizationDecision Record auditable allow, deny, challenge, or error decisions.
CreateApiKey Create scoped programmatic access with one-time plaintext disclosure.
RevokeApiKey Revoke programmatic access.
EnableMfa Register and verify an MFA factor.
RevokeSession Revoke active or refreshable access.

Queries

Query Responsibility
GetUserAccount Retrieve user account summary and lifecycle state.
GetMembershipsForUser Resolve active tenant access for a user.
GetOrganizationMembers List members and role assignments for an organization.
GetRolesAndPermissions Provide governed role and permission catalogue views.
EvaluateAuthorization Return allow, deny, challenge, or error for actor, resource, action, tenant, and context.
GetSessions Inspect active and historical session state where authorized.
GetApiKeys List non-secret API key metadata.
GetIdentityAuditEvents Retrieve redacted security audit records where authorized.

Application Services

Service Responsibility
IdentityAccessApplicationService Orchestrates user, membership, role, permission, and authorization use cases.
AuthenticationApplicationService Interprets Keycloak tokens and authentication callbacks into Identity domain state.
InvitationApplicationService Governs invitation lifecycle and membership creation.
SessionApplicationService Handles session creation, revocation, and refresh-state interpretation.
ApiKeyApplicationService Governs API key issuance, rotation, scope validation, and revocation.
MfaApplicationService Coordinates MFA enrollment, challenge, and recovery rules.
AuthorizationApplicationService Evaluates tenant, role, permission, entitlement, policy, and risk context.

Domain Services

Authentication Policy, Tenant Isolation Policy, Authorization Policy, Entitlement-Aware Access Policy, Invitation Policy, Role Assignment Policy, Session Policy, API Key Policy, MFA Policy, and Security Audit Policy.

Policies

Identity policies must fail closed when actor, tenant, resource, action, entitlement, or session context is missing. High-impact access may require recent MFA verification and explicit approval controls.

Repositories

UserAccountRepository, AuthenticationIdentityRepository, MembershipRepository, InvitationRepository, AccessControlRepository, SessionRepository, ApiKeyRepository, MfaRepository, AuthorizationDecisionRepository, and IdentityAuditRepository. Repositories are internal to identity.infrastructure.persistence and may not be imported by other modules.

Events Published

UserAccountCreated, AuthenticationIdentityLinked, UserSignedIn, SignInFailed, SessionCreated, SessionRevoked, InvitationCreated, InvitationAccepted, MembershipActivated, MembershipSuspended, RoleAssigned, PermissionAssigned, AuthorizationDecisionRecorded, ApiKeyCreated, ApiKeyRevoked, MfaEnabled, and MfaChallengeRequired.

Events Consumed

OrganizationRegistered, OrganizationActivated, OrganizationSuspended, OrganizationArchived, EntitlementChanged, SubscriptionSuspended, AdministrativePolicyChanged, and SecurityPolicyChanged. Consumed events update Identity-owned access state or read models only where the event is relevant to authorization.

REST API Responsibility

The module owns API responsibilities for user accounts, authentication interpretation, memberships, invitations, roles, permissions, authorization evaluation, sessions, API keys, MFA, and identity audit views. Final endpoint paths and schemas are intentionally deferred to OpenAPI work.

Database Ownership

Identity owns conceptual persistence for identity user accounts, authentication identities, organization memberships, invitations, roles, permissions, role assignments, permission assignments, access policies, sessions, API keys, MFA factors, authorization decisions, and identity audit logs. API key secrets are stored as hashes only. Token contents, session secrets, and MFA secrets must not be logged.

Module Dependencies

Allowed dependencies are shared kernel identifiers, Keycloak integration adapters through approved infrastructure boundaries, organization context APIs and events, billing entitlement APIs and events, notification events for user messages, analytics event projections, and administration policy events.

Forbidden Dependencies

Identity must not mutate Organization profile facts, Billing subscription facts, Analytics projections, Notification delivery records, or Administration configuration stores. Other modules must not import Identity repositories, aggregates, policies, session internals, API key hashes, or Keycloak adapter internals.

AIOS Interaction Boundary

AIOS may request authorization checks, actor context summaries, and tenant-scoped permission decisions through governed application services. AIOS may not bypass Identity, inspect secrets, create memberships, assign roles, or elevate access without approved Identity commands and auditable actor context.

Security And Tenant Rules

  • Keycloak JWT access tokens must be validated by Spring Security before protected application services run.
  • Refresh token handling remains an authentication platform concern; Identity records domain session and revocation context where required.
  • Organization-scoped actions require OrganizationId, actor identity, active membership or approved service account, permission, entitlement where applicable, and audit metadata.
  • Service accounts require least-privilege scopes, tenant boundaries, rotation, expiry, and auditable usage.
  • Default authorization result is deny.

Test Strategy

Tests must cover authorization decisions, tenant isolation, role and permission mapping, invitation expiry, membership suspension, API key hash-only storage rules, MFA challenge rules, event publication, idempotent event consumption, Keycloak token interpretation boundaries, and Spring Modulith dependency verification.

Future Microservice Extraction Notes

Identity is extraction-sensitive because it is a security boundary. Future extraction requires stable authorization APIs, event contracts, audit event delivery, Keycloak client separation, explicit service-to-service authentication, and no direct database dependency from other modules.

Mermaid Component Diagram

flowchart TD
    Api[identity.api.rest]
    App[identity.application.service]
    Command[identity.application.command]
    Query[identity.application.query]
    Domain[identity.domain.model]
    Policy[identity.domain.policy]
    Repo[identity.infrastructure.persistence]
    Messaging[identity.infrastructure.messaging]
    Keycloak[Keycloak IdP]
    Org[organization module]
    Billing[billing module]
    Notification[notification module]
    Analytics[analytics module]

    Api --> App
    App --> Command
    App --> Query
    App --> Domain
    Domain --> Policy
    App --> Repo
    App --> Messaging
    App --> Keycloak
    App --> Org
    App --> Billing
    Messaging --> Notification
    Messaging --> Analytics