H· Hawiyati Documentation

User Registration & Identity Lifecycle

This document describes how Hawiyati creates, verifies, and manages user accounts across three deployment scenarios: greenfield consumer registration, enterprise provisioning, and SP-initiated access. It defines the assurance level model, account state transitions, the limited-session completion token design, and the governed bulk import pipeline. All implementation decisions trace to the September 2026 architecture review.

This document describes how Hawiyati creates, verifies, and manages user accounts across three deployment scenarios: greenfield consumer registration, enterprise provisioning, and SP-initiated access. It defines the assurance level model, account state transitions, the limited-session completion token design, and the governed bulk import pipeline. All implementation decisions trace to the September 2026 architecture review.

Hawiyati IAM Platform — Component Architecture HAWIYATI IAM PLATFORM — COMPONENT ARCHITECTURE Spring Boot 3.5 · Java 25 · gRPC EXTERNAL ACTORS ENTRY LAYER & FEDERATION HTTPS · SAML 2.0 · OIDC · WebAuthn PLATFORM SERVICES HTTPS internal · gRPC DATA & INFRASTRUCTURE JDBC · Redis pub/sub · gRPC User Browser Browser · Mobile App Administrator Admin Console SAML Service Provider SAML 2.0 OIDC Relying Party OIDC · OAuth 2.0 SCIM Client HR System · Directory hawiyati-gateway Spring Cloud Gateway · :8080 Routing · TLS termination hawiyati-http-server IdP Login · MFA · FIDO2 · :8085 SAML ACS · OIDC callback · Account BFF hawiyati-federation SAML 2.0 · OIDC · :8087 Assertion & token issuance · Policy hawiyati-admin Admin Console · :8095 · WebFlux hawiyati-account Account Portal · :8096 · BFF/OIDC hawiyati-scim SCIM 2.0 API · :8098 hawiyati-session · :9004 hawiyati-cache · :9003 hawiyati-infra · :9002 PostgreSQL hawiyati · hawiyati_identity Redis / Valkey Sessions · Cache · Rate limits Audit & Logs CEF Syslog · OTel · SIEM PKI & Keystore SAML · OIDC · mkcert TLS External Actor External System Entry / Federation Platform Service gRPC Service Data Store

The sections below cover user registration, KYC, and identity lifecycle implementation. For a full module map with ports, gRPC boundaries, and deployment topology, see the Implementation Guide.

Overview & Scope

This document describes how Hawiyati creates, verifies, and manages user accounts across three deployment scenarios: greenfield consumer registration, enterprise provisioning, and SP-initiated access. It defines the assurance level model, account state transitions, the limited-session completion token design, and the governed bulk import pipeline. All implementation decisions trace to the September 2026 architecture review.

The governing constraint throughout this document: lab/ocr-mrz-test fixes must not be synced to hawiyati-kyc until the team explicitly confirms. Until that promotion happens, KYC-04 (supported documents reference) must describe only verified production behavior.

ℹ
Design principle

Assurance level is sourced exclusively from kyc_profiles.current_level — a column that already exists in the database. No users.assurance_level column is added. Adding such a column would create two competing sources of truth and has historically caused consistency bugs in identity systems.

Three deployment scenarios

ScenarioPrimary userEntry pathKYC required
Greenfield consumer End user Self-service /idp/register Policy-driven; default L1 for most SPs
Enterprise / workforce Employee or contractor SCIM provision, LDAP JIT, invitation, or CSV import Source-assurance carry-over or grace period
SP-initiated End user arriving from a service SAML AuthnRequest or OIDC authorization → registration SP minimum assurance triggers KYC gating after login

Assurance Levels L0–L4

Hawiyati defines five assurance levels aligned with NIST SP 800-63A-4. Levels describe identity proofing assurance (IAL) for a registered identity. The Java type is IdentityAssuranceLevel — an enum with satisfies(), fromString(), and capAtFreezeLevel() methods. Unknown values fail closed to L0.

LevelNameEvidence requiredStatus
L0 Unverified Email or phone confirmation only — no identity document. Default on registration. Active
L1 Self-asserted Name, date of birth, address provided and consistent; no documentary evidence required. Active
L2 Document-verified Government-issued identity document: Algerian CIN, passport, or driving licence. OCR-extracted fields pass consistency checks. Document fingerprint stored. Active
L3 Biometric-verified Document verification plus liveness detection and face match against the chip or reference photo. Frozen — not yet in production
L4 In-person supervised All L3 evidence collected by a trained officer in a controlled environment with chain-of-custody records. Frozen — not yet in production
⚠
L3/L4 freeze

KycDecisionService.approve() refuses to set kyc_profiles.current_level above L2 until a production-grade biometric integration is approved. The cap is enforced by IdentityAssuranceLevel.capAtFreezeLevel(). Any session requesting L3 or L4 achieves at most L2 and is routed to manual review.

Java enum definition

IdentityAssuranceLevel.java — hawiyati-kyc
public enum IdentityAssuranceLevel { L0, L1, L2, L3, L4; /** Unknown strings fail closed to L0 — never fail open */ public static IdentityAssuranceLevel fromString(String s) { if (s == null) return L0; return switch (s.toUpperCase().trim()) { case "L1" -> L1; case "L2" -> L2; case "L3" -> L3; case "L4" -> L4; default -> L0; }; } public boolean satisfies(IdentityAssuranceLevel required) { return this.ordinal() >= required.ordinal(); } /** L3/L4 freeze until biometric production approval */ public static IdentityAssuranceLevel capAtFreezeLevel(IdentityAssuranceLevel level) { return level.ordinal() > L2.ordinal() ? L2 : level; } }

Authorization contract

Minimum assurance for a request is read from the AuthenticationPolicy associated with the current SP entity ID and action (login, resource, API scope). It is never derived from a username lookup alone. Effective assurance for an authorization decision combines:

1
Identity Proofing Assurance (IAL)
kyc_profiles.current_level via KycGateService.effectiveLevelFor(username)
2
Authentication Assurance (AAL)
Factor used in the current session — password only = AAL1, TOTP/FIDO2/passkey = AAL2
3
SP Policy Minimum
Read from AuthenticationPolicy for the current SP and action
✓
Decision
If effective ≥ required → issue assertion. Otherwise → completion token and KYC gate.

Account Status Model

User status is represented by two independent boolean flags on the users table. No status enum column is added. Presentation states like ACTIVE_LIMITED are computed at request time from kyc_profiles.current_level plus the SP/action policy minimum. Adding a third column would require a migration and introduce a third source of truth.

activependingApprovalPresentation stateAllowed operations
truefalse ACTIVE Full access; no KYC gate if assurance ≥ SP minimum
truefalse ACTIVE_LIMITED (computed) Login succeeds; SAML/OIDC issuance gated behind KYC completion token flow; account portal, KYC, consent, logout accessible
falsetrue MIGRATED_UNCLAIMED Account exists but cannot authenticate; activation requires identity claim flow
falsefalse SUSPENDED No operations; admin unlock required
falsetrue PENDING_APPROVAL Self-registered but awaiting admin activation; blocked from login
ℹ
ACTIVE_LIMITED is not stored

ACTIVE_LIMITED is never written to the database. It is the runtime result of: user is active AND effectiveLevelFor(user) does not satisfy policyMinimumFor(spEntityId). This keeps the database normalized and prevents stale states.

Account state transitions

New → active
Self-service registration
active=true, pendingApproval=false on creation (no approval gate configured) or active=false, pendingApproval=true if registration policy requires admin approval.
Import → unclaimed
Bulk import / SCIM provision
All imported or provisioned accounts enter as active=false, pendingApproval=true (MIGRATED_UNCLAIMED). Never immediately active.
Unclaimed → active
Account claim
User redeems a claim token via email link. Token is purpose-bound, user-bound, single-use, and atomically consumed. Sets active=true, pendingApproval=false.
Active → suspended
Admin suspension
Admin sets active=false, pendingApproval=false. Existing sessions are revoked. Restoration requires explicit admin unsuspend.

Source of Truth Decisions

Decision tree for choosing a primary user onboarding route
Choose one authoritative onboarding route per population to prevent duplicate and conflicting identities.

Every identity record must carry source_instance_id (origin system) and external_id (immutable source key). These are added in V58 migration. The combination (source_instance_id, external_id) is unique-indexed, preventing duplicate accounts from the same source.

DataAuthoritative storeNever
Assurance levelkyc_profiles.current_levelNot users.assurance_level
Source identity keyusers.external_id + users.source_instance_idNot a nullable scim_external_id column
Completion sessionidentity_completion_session DB table (HMAC-SHA256 token hash)Not a boolean kycRequired WebSession attribute
SP business intentonboarding_continuation.sp_entity_idNot a raw sp_initiation_url (open-redirect risk)
Claim tokenaccount_claim_token.token_hash (HMAC-SHA256)Not raw token in DB
Document deduplicationdocument_fingerprint.fingerprint (HMAC-SHA256 of normalized fields)Not file SHA-256 (cropping defeats it)

Identity lifecycle from creation and verification through deletion
Registration is the beginning of a governed lifecycle, not merely an account-creation form.

Self-Service Registration Flow

Direct registration at /idp/register creates a Hawiyati-native account. The server collects a username, password, email, and consent. Username availability is not checked before submission — the unique constraint raises a DataIntegrityViolationException which the server maps to the generic error unique_attribute_taken without revealing which field is taken.

✕
P0 security gap — ACT-P0-01

The current RegistrationController.java:311 performs a pre-check if (userService.existsByUsername(username)) before the database insert. This discloses whether a username is registered, enabling account enumeration. The fix is to remove the pre-check entirely and rely only on the constraint exception.

1
Form submission
User POSTs username, password, email, OTP (if required), consent version
2
Policy evaluation
Registration policy checks: allowed domains, approval required, KYC required, MFA enforcement
3
Account creation
Insert user: active=true, pendingApproval=false (or pending if approval required). Consent record captures version, IP, user-agent.
4
Email / OTP verification
If email verification is configured, send link. Account is active=false until confirmed.
5
SP continuation (if SP-initiated)
If registration arrived from a SAML/OIDC flow, create onboarding_continuation record storing only sp_entity_id. Redirect user to KYC or account setup. Initiation URL is resolved from SP registry at redemption — never stored.
✓
Activation complete
User reaches account portal or is redirected to SP (if continuation token present)

Consent record

The ConsentRecord entity already captures ip_address and user_agent (ACT-P0-06 confirmed complete). A regression test is required to prevent this from being stripped in future refactors.


Invitation & Admin-Driven Registration

When registration is closed or policy-restricted, administrators create accounts and invite users to claim them. The invite sends an account claim token. The token is 256-bit random, stored as HMAC-SHA256, and is single-use. There is no plaintext token in the database.

1
Admin creates account
active=false, pendingApproval=true. Email or external ID set; no password yet.
2
Claim token generated
AccountClaimTokenService.generate(userId, "CLAIM_LINK", 72) — 256-bit random, 72-hour TTL, stored as SHA-256 hash with purpose and userId binding
3
Notification enqueued
NotificationOutboxService.enqueueIfAbsent() with template key claim-link-v1 and userId. Raw token is NOT in the payload.
4
User clicks email link
Browser visits /account/claim?token=<raw> — token verified and atomically consumed in one conditional UPDATE
✓
Account activated
active=true, pendingApproval=false. User sets their password and proceeds to KYC if required.

SP-Initiated Registration

When a user arrives at Hawiyati from an SP (SAML AuthnRequest or OIDC authorization request) and has no account, the IdP must either create an account or guide the user through self-service registration while preserving the SP's business intent for up to 7 days. Live protocol state (AuthnRequest, PKCE verifier, nonce) lives in Redis/WebSession for 10–15 minutes only and is never replayed after it expires.

⚠
Open-redirect risk — ACT-P0-05

Storing a raw sp_initiation_url from the caller and following it after registration is an open-redirect vulnerability. The fix: store only the registered sp_entity_id as a foreign key to the SP registry. The initiation URL is resolved from the registry at consumption time — an SP not in the registry cannot redirect the user anywhere.

Intent persistence design

What is storedWhereTTLPurpose
Live SAML/OIDC protocol state (AuthnRequest, state, nonce, PKCE)WebSession / Redis10–15 minProtocol-level; expired state is discarded, never replayed
SP business intent (which SP the user came from)onboarding_continuation DB table7 daysSurvives KYC flow; consumed by fresh SP-initiation on completion

On activation the continuation is consumed atomically (UPDATE … WHERE consumed=FALSE checking affectedRows == 1) and the user is redirected to spRegistryService.getInitiationUrl(spEntityId) — a fresh SP flow, not a replay of the stale protocol object.


Enterprise Provisioning

Enterprise accounts can enter Hawiyati via three channels, all producing MIGRATED_UNCLAIMED accounts:

ChannelTriggerIdentity bindingNext step
SCIM 2.0 POST /scim/v2/Users from directory external_id + source_instance_id from HawiyatiExtension Account claim token or LDAP JIT on first login
LDAP JIT Successful LDAP bind at login DN or samAccountName mapped to external_id Immediate activation; KYC grace period applies
CSV bulk import Admin uploads file, approves, commits external_id from CSV column Invitation email with claim token sent to all rows
ℹ
SCIM extension — permitted fields only

The Hawiyati SCIM extension (urn:hawiyati:params:scim:schemas:extension:2.0:User) carries only: externalId, sourceInstanceId, pendingApproval. Password hashes, assurance levels, and migration tier fields are explicitly forbidden from SCIM channels. Receiving any of these fields must not silently map them — the field mapping must not exist.


KYC capture, validation, biometric, risk, review, and decision workflow
Assurance policy determines which biometric and manual-review stages are required.

KYC State Machine

KYC verification is modeled as a state machine on KycVerificationSession. Each session is scoped to one user and one attempt. The state machine prevents illegal transitions: a session cannot jump from PENDING to APPROVED without passing through evidence capture and review states.

StateMeaningAllowed transitions
PENDINGSession created; awaiting document upload→ DOCUMENT_UPLOADED
DOCUMENT_UPLOADEDFile received; OCR processing queued→ PROCESSING
PROCESSINGOCR/MRZ extraction in progress→ DOCUMENT_VALIDATED, → PROCESSING_FAILED
DOCUMENT_VALIDATEDFields extracted; decision engine evaluating→ MANUAL_REVIEW_REQUIRED, → APPROVED (automated only)
MANUAL_REVIEW_REQUIREDLow confidence score or duplicate-document risk flag; awaiting human reviewer→ APPROVED, → REJECTED
APPROVEDTerminal — identity proofed; kyc_profiles.current_level updated— (terminal)
REJECTEDTerminal — insufficient evidence; user may start a new session— (terminal, new session allowed)
PROCESSING_FAILEDOCR system error; user may retry→ PENDING (retry)

Approval logic

When a reviewer or automated decision approves a session:

1
Resolve achieved level
IdentityAssuranceLevel.capAtFreezeLevel(requested) — L3/L4 requests become L2
2
Update only KYC profile
Write to kyc_profiles.current_level — never to users table. Only upgrade, never downgrade via this path.
3
Emit audit event
KYC_APPROVED with achieved level, reviewer ID, and session ID
✓
Completion session invalidated
Any open completion token for this user is invalidated. Next login proceeds without KYC gate if effective level ≥ SP minimum.

Supported document types (production)

DocumentCountryCapture sidesMRZMax file size
Algerian National ID (CIN)DZAFront + Back (both required)TD1 (3-line)10 MB per side
Algerian PassportDZAPhoto/data page onlyTD3 (2-line)10 MB
Foreign PassportAnyPhoto/data page onlyTD3 (2-line)10 MB
Driving LicenceDZAFront + Back (both required)None10 MB per side
⚠
Lab promotion pending

Advanced OCR/MRZ pipeline (lab/ocr-mrz-test) is not yet promoted to hawiyati-kyc. Do not document these features as production-supported until the promotion is explicitly confirmed.


Evidence & Document Fingerprinting

When a document is captured, Hawiyati computes an HMAC-SHA256 fingerprint of the normalized document identity — country, document type, and document number. This fingerprint is stored in document_fingerprint (schema: hawiyati_identity). A duplicate match is a risk signal that routes the session to manual review. It is not a hard rejection, because legitimate scenarios exist (document reuse after name change, duplicate legitimate applications).

Normalization algorithm

KycEvidenceService.java — fingerprint computation
String normalized = (country.toUpperCase().trim() + "|" + docType.toUpperCase().trim() + "|" + docNumber.trim().toUpperCase()) .replaceAll("\\s+", ""); Mac mac = Mac.getInstance("HmacSHA256"); mac.init(new SecretKeySpec(hmacKey, "HmacSHA256")); String fingerprint = HexFormat.of().formatHex( mac.doFinal(normalized.getBytes(StandardCharsets.UTF_8)));
ℹ
Why not file hash?

A SHA-256 hash of the uploaded image file is defeated by any crop, rotation, re-encoding, or quality change. The HMAC fingerprint hashes only the semantically meaningful fields (country, document type, document number), which are stable across capture variations. The raw document number is never stored in the fingerprint table.

Duplicate detection behavior

ScenarioAction
Fingerprint matches a different userSet session.duplicateDocumentRisk=true, transition to MANUAL_REVIEW_REQUIRED. Log warning with session ID and existing user ID. Do not hard-reject.
Fingerprint matches the same userAllow — same user retrying or updating their submission. Save the new fingerprint record; deduplicate by userId.
No existing fingerprint foundSave new document_fingerprint record. Continue automated validation.

Key management

The HMAC key is injected from application config (hawiyati.kyc.document-fingerprint-key, base64-encoded 256-bit key). The key_version column in document_fingerprint enables key rotation — old fingerprints can be re-keyed on rotation by re-normalizing and re-hashing each row.


Limited Completion Session (KYC Gate)

When a user authenticates successfully but their kyc_profiles.current_level does not satisfy the SP's minimum assurance, Hawiyati issues a first-party completion token instead of throwing an exception or storing a boolean flag on the WebSession. The token is stored server-side as HMAC-SHA256, has a 15-minute TTL, and is single-use.

✕
P0 gap — ACT-P0-03 — deadlocking KYC gate

The current LoginController.java:876–901 throws KycRequiredException which propagates through the reactive chain and causes a response deadlock. It uses a boolean kycRequired session attribute which cannot be validated, expires with the session, and grants no route restrictions. Both issues are fixed by this design.

Token design

PropertyValue
Entropy256-bit (32 bytes, SecureRandom), URL-safe base64 ≥43 characters
Stored formSHA-256 hash only — raw token never persisted
TTL15 minutes (expiresAt = NOW() + 900s)
CardinalitySingle-use; consumed atomically on validation
BindingsuserId, spEntityId, purpose = KYC_COMPLETION
Tablehawiyati_identity.identity_completion_session (V54)

Route allowlist — what a completion token grants

A user holding only a completion token (no full session assertion) may access the following routes only. Any request outside this list receives a 403.

  • /account/status ALLOWED
  • /account/kyc/** ALLOWED
  • /account/consent/** ALLOWED
  • /logout ALLOWED
  • /support ALLOWED
  • /saml/idp/sso DENIED — no assertion issuance
  • /oidc/token DENIED — no token issuance
  • /api/** DENIED — no general API access

SP Transaction Continuation

When a user arrives from an SP and must register or complete KYC before the SP assertion can be issued, the IdP must remember which SP they came from for up to 7 days. This is the onboarding_continuation table introduced in V55.

Token design

PropertyValue
Stored datasp_entity_id (FK to SP registry) only. No raw URL stored.
Token format256-bit random; SHA-256 stored in DB; browser holds raw token in query parameter
TTL7 days (configurable)
RedemptionAtomic UPDATE … SET consumed=TRUE WHERE consumed=FALSE AND userId=?; checks affectedRows == 1
User bindinguser_id column; wrong-user attempt returns empty
URL resolutionspRegistryService.getInitiationUrl(spEntityId) at consumption time
✓
Open-redirect prevention

Because only a registered SP entity ID is stored (not the caller-supplied URL), an attacker who obtains a continuation token cannot redirect the user to an arbitrary domain. The initiation URL is always resolved from the verified SP registry entry.

OnboardingContinuationRepository.java — atomic consume
@Modifying @Query("UPDATE OnboardingContinuation c SET c.consumed = TRUE " + "WHERE c.tokenHash = :hash AND c.userId = :userId " + "AND c.consumed = FALSE AND c.expiresAt > CURRENT_TIMESTAMP") int atomicConsume(@Param("hash") String hash, @Param("userId") UUID userId);

Secure invitation and account claim flow
Claim tokens are single-use entry points; identity matching and authenticator binding complete the claim.

Account Claim Tokens

Account claim tokens are purpose-bound, user-bound, single-use tokens used for invitation flows, password-reset links, and migration activation. They live in account_claim_token (V57).

Security properties

ThreatMitigation
Token replaySingle-use atomic conditional update; atomicRedeem(hash, userId, purpose) returns 0 rows if already consumed
Brute force256-bit token space = 2256 — computationally infeasible; redemption endpoint rate-limited
Wrong channelpurpose column binding — a password-reset token cannot be used for account claim and vice versa
Cross-user claimuserId binding — token redeemable only for the user it was created for
Concurrent double-redemptionConditional UPDATE checks consumed=FALSE; exactly one concurrent thread wins

SCIM account provisioning and reconciliation sequence
The enterprise source remains authoritative while Hawiyati enforces local security and audit controls.

SCIM Provisioning Model

Hawiyati implements SCIM 2.0 inbound provisioning at hawiyati-scim (port 8098). The custom Hawiyati extension carries only the fields needed for identity correlation — not credential migration or assurance assertion.

Hawiyati SCIM extension schema

urn:hawiyati:params:scim:schemas:extension:2.0:User — permitted fields
record HawiyatiExtension( String externalId, // stable source-system identifier String sourceInstanceId, // source system name (e.g. "ldap-prod-01") Boolean pendingApproval // true = hold for manual activation ) {}
✕
Explicitly prohibited

The SCIM extension must never accept: importedPasswordHash, assuranceLevel, migrationTier, or any credential field. These are excluded from the field mapping — not just ignored. Password hashes over SCIM could bypass authentication security; assurance level assertions over SCIM would allow callers to forge elevated trust without evidence.

Provisioned account behavior

Every SCIM-created account enters as active=false, pendingApproval=true (MIGRATED_UNCLAIMED). The account cannot authenticate until the user claims it via an invitation email. KYC grace period applies per the configured migration policy.


Governed Bulk CSV Import

The bulk import pipeline allows administrators to create many accounts from a CSV file. It uses a staged approval workflow to prevent accidental mass account creation, and Apache Commons CSV for parsing — never split(",") which cannot handle quoted fields containing commas.

Pipeline stages

1
UPLOADED
Admin POSTs CSV file via POST /api/v1/import/batches. Max 50,000 rows, max 50 MB. Header validated against required columns.
2
DRY_RUN_COMPLETE
All rows parsed and staged in import_batch_row. Duplicates flagged. Validation errors listed. No user accounts created yet.
3
APPROVED
SUPER_ADMIN reviews summary and approves. POST /api/v1/import/batches/{id}/approve. Timestamp and approver ID recorded.
4
COMMITTING
Accounts created row by row. Duplicate external_id rows are SKIPPED with reason. Idempotent — re-commit of same batch is safe.
✓
DONE
All committed rows: active=false, pendingApproval=true. Claim tokens generated. Notifications enqueued via outbox.

Required CSV columns

CSV header — all columns required
external_id,username,email,first_name,last_name
⚠
Document classification

MIG-03 (CSV Migration Runbook) must remain INTERNAL until this feature is implemented and verified. Do not publish it as a supported customer document before Phase D of the implementation plan is complete and tested.


Notification Outbox

All outbound notifications (claim links, activation emails, KYC status updates) are written to the notification_outbox table (V59) in the same transaction as the triggering action. A background dispatcher job reads and sends them. This decouples notification reliability from the caller's transaction.

Design properties

PropertyValue
Multi-node safetySELECT … FOR UPDATE SKIP LOCKED — two nodes dispatching concurrently claim disjoint rows
Idempotencyidempotency_key unique column; enqueueIfAbsent() is a no-op if key exists
Payload contentTemplate key + template parameters only — no raw bearer tokens, no raw URLs
Retry scheduleExponential backoff: 30s → 2m → 8m → 32m → 128m (after 5 attempts: DEAD)
Dispatch interval@Scheduled(fixedDelay = 30_000) — 30s between dispatch cycles
Batch size50 rows per dispatch cycle
Dispatch query — SKIP LOCKED
SELECT * FROM hawiyati_identity.notification_outbox WHERE status IN ('PENDING', 'RETRYING') AND next_attempt_at <= NOW() ORDER BY next_attempt_at LIMIT 50 FOR UPDATE SKIP LOCKED

Admin Lifecycle Operations

Administrators can perform lifecycle operations on user KYC profiles via REST endpoints in hawiyati-admin. All endpoints follow the existing /api/v1 REST + React pattern. No Thymeleaf controllers are used for admin features.

✕
No upward assurance override

The admin lifecycle API permits only downgrade, invalidation, and reverification requests. An admin may never set a user's assurance level higher than it currently is via the admin API. Upward assurance must come from a completed KYC session with verified evidence.

EndpointRole requiredAction
POST /api/v1/users/{id}/kyc/invalidate ROLE_SUPER_ADMIN Downgrade kyc_profiles.current_level to target level. Rejects if target > current. Emits KYC_INVALIDATED audit event.
POST /api/v1/users/{id}/kyc/request-reverification ROLE_ADMIN Flags profile with reverificationRequired=true and reason code. Next login triggers KYC gate. Emits KYC_REVERIFICATION_REQUESTED audit event.

Delivery Phases A–F

The implementation is structured as six phases with explicit gates. Phase A produces design documents only — no database migration may be written until Phase A is approved. This prevents the database schema from being designed before the architectural decisions are settled.

PhaseScopeGate
A Architecture prerequisites — three design documents (assurance model, threat model, admin API pattern) All three docs approved before any schema migration
B P0/P1 correctness — enumeration fix, assurance enum, completion token (V54), continuation (V55), fingerprint (V56), consent test Phase A docs approved
C Account claim (V57), SCIM cleanup (V58), outbox (V59), admin lifecycle API Phase B complete
D Governed bulk import (V60) Phase C complete
E DEFERRED — credential continuity (hash migration, JIT proxy). Requires separate security design, per-source cryptographic assessment, and risk acceptance. Separate security design approved; risk acceptance signed
F DEFERRED — operations, reverification workflows, customer support tooling Phase D stable in production
⏸
Phase E — credential continuity is deferred

The original plan included Tasks 8 and 9: importing password hashes and a JIT authentication proxy. Both require a separate threat model and risk acceptance because: (1) algorithm strings from callers are not trustworthy, (2) PBKDF2/Argon2 require exact parameter profiles to verify correctly, (3) SHA-256 alone materially weakens authentication, and (4) a configurable proxy endpoint is an SSRF and credential-exfiltration surface. Preferred alternatives: federation/LDAP continuity, account claim token + password reset, or hardened connector service.


Governed user migration and reconciliation flow
Dry runs, pilots, acceptance gates, account claim, and post-cutover reconciliation reduce migration risk.

Migration Sequence (planned as V54–V60)

This guide was authored when the Flyway head was V53. The actual head as of 2026-10-17 is V62 (migrations V54–V62 were applied for other features: module config, KYC settings, CASCADE repairs). Renumber the migrations in this plan starting from V63 before implementing, and verify the live head with SELECT version FROM flyway_schema_history ORDER BY installed_rank DESC LIMIT 1.

V54 identity_completion_session First-party KYC completion token; hashed, 15-min TTL, single-use B3
V55 onboarding_continuation SP intent persistence; stores sp_entity_id FK only, never raw URL B4
V56 document_fingerprint HMAC-SHA256 of normalized country|docType|docNumber in hawiyati_identity schema B5
V57 account_claim_token Purpose-bound, user-bound, single-use invitation and claim tokens C1
V58 ALTER users Adds external_id and source_instance_id columns; unique index (source, external) C2
V59 notification_outbox Transactional outbox with SKIP LOCKED dispatch and exponential backoff C3
V60 import_batch + import_batch_row Governed bulk import tables with staged workflow (UPLOADED→DRY_RUN→APPROVED→DONE) D1

P0 — Critical Fixes

These issues are security vulnerabilities or functional blockers that prevent the registration flow from working correctly.

P0 Critical Must be fixed before any production traffic
Remove username enumeration pre-check ACT-P0-01
A pre-existence check before the database insert reveals whether a username is taken. The constraint exception already provides an opaque error. Remove the pre-check entirely.
  • Delete if (userService.existsByUsername(username)) block at RegistrationController.java:311
  • Verify DataIntegrityViolationException catch at line 245 returns unique_attribute_taken
  • Write HTTP-behavior test: response body must not contain username_taken for any username
Files: hawiyati-http-server/…/RegistrationController.java · RegistrationControllerTest.java
Replace deadlocking KYC gate with completion token ACT-P0-03
The current KycRequiredException path causes a reactive chain deadlock and stores an unverifiable boolean on the WebSession. Replace with first-party completion token (V54).
  • Create V54 migration: identity_completion_session table
  • Create CompletionSessionService with issue(), validate(), isAllowedRoute()
  • Replace exception throw in LoginController.enforceAssuranceGate() with token issuance and redirect
  • Add WebFilter denying SAML/OIDC issuance endpoints when only a completion token is present
Files: V54 migration · IdentityCompletionSession.java · CompletionSessionService.java · LoginController.java
Typed IdentityAssuranceLevel enum + KYC profile update ACT-P0-04
Replace raw string comparisons with a typed enum. KycDecisionService.approve() must update kyc_profiles.current_level only — never users. Caps at L2 until biometric approved.
  • Check if KycAssuranceLevel already exists; add satisfies(), fromString(), capAtFreezeLevel() to it or create IdentityAssuranceLevel
  • Update KycDecisionService.approve() to write kyc_profiles.current_level only
  • Add KycGateService.effectiveLevelFor(username) reading from kyc_profiles
Files: IdentityAssuranceLevel.java · KycDecisionService.java · KycGateService.java
Secure onboarding continuation — SP entity ID only ACT-P0-05
Store only the registered SP entity ID, never a raw initiation URL. Hashed token, atomic conditional redemption, user-binding check. Open-redirect fix.
  • Create V55 migration: onboarding_continuation — note: no sp_initiation_url column
  • Create OnboardingContinuationService with create() and consume()
  • Wire into RegistrationController (on SP-initiated registration) and LoginController (on continuation redemption)
Files: V55 migration · OnboardingContinuation.java · OnboardingContinuationService.java
Consent regression test ACT-P0-06
ACT-P0-06 is confirmed complete — ConsentRecord already has ip_address and user_agent. Add a regression test so these fields cannot be silently removed.
  • Test: register() verifies consentRepo.save() is called with non-null IP and user-agent
Files: UserServiceTest.java

P1 — High Priority

P1 High
Document fingerprint — HMAC of normalized fields ACT-P1-01
Compute HMAC-SHA256 of normalized country|docType|docNumber. Store in hawiyati_identity schema (not hawiyati_kyc). Duplicate match = manual review signal, not hard block.
  • Create V56 migration in hawiyati_identity schema
  • Implement KycEvidenceService.documentFingerprint() with normalization
  • Add duplicate-detection logic: different user → MANUAL_REVIEW_REQUIRED, same user → allow
  • HMAC key from config property — never hardcoded
Files: V56 migration · DocumentFingerprint.java · KycEvidenceService.java
Hardened account claim token ACT-P1-02
Purpose-bound, user-bound, single-use claim tokens with atomic redemption for invitation and claim flows.
  • Create V57 migration: account_claim_token
  • Implement AccountClaimTokenService with generate() and redeem()
  • Wire into invitation flow and account activation endpoint
Files: V57 migration · AccountClaimToken.java · AccountClaimTokenService.java

P2 — Medium Priority

P2 Medium
Notification outbox with SKIP LOCKED ACT-P2-01
Transactional outbox for all notifications. Template-key-based dispatch — no raw tokens or URLs in payload.
  • Create V59 migration: notification_outbox
  • Implement NotificationOutboxService.enqueue() and enqueueIfAbsent()
  • Implement OutboxDispatchJob with SKIP LOCKED query and exponential backoff
Files: V59 migration · NotificationOutbox.java · NotificationOutboxService.java · OutboxDispatchJob.java
SCIM extension — externalId and sourceInstanceId only ACT-P2-02
Add external identity columns (V58). Clean SCIM extension to three permitted fields only. Explicitly remove any credential or assurance field mapping.
  • Create V58 migration: ALTER users ADD external_id, source_instance_id
  • Update ScimUser.HawiyatiExtension record — verify no importedPasswordHash or assuranceLevel field exists
  • Update ScimUserService.createUser() to map only the three permitted fields
Files: V58 migration · ScimUser.java · ScimUserService.java
Admin KYC lifecycle API ACT-P2-03
REST endpoints for downgrade/invalidation and reverification requests. No upward assurance override. Audit event on every operation.
  • Create ApiKycLifecycleController under hawiyati-admin/…/admin/api/
  • Implement /api/v1/users/{id}/kyc/invalidate (SUPER_ADMIN) with upward-override guard
  • Implement /api/v1/users/{id}/kyc/request-reverification (ADMIN)
Files: ApiKycLifecycleController.java · ApiKycLifecycleControllerTest.java

P3 — Low Priority

P3 Low
Governed bulk CSV import ACT-P3-01 (Phase D)
Staged bulk import with Apache Commons CSV, approval gate, and MIGRATED_UNCLAIMED state for all imported accounts.
  • Add commons-csv 1.10.0 to hawiyati-admin pom.xml
  • Create V60 migration: import_batch + import_batch_row
  • Implement ImportBatchService — max 50,000 rows, 50 MB; quoted-field-safe CSV parsing
  • Create ApiImportController at /api/v1/import/batches — upload, status, approve, commit
  • All committed rows: active=false, pendingApproval=true
Files: V60 migration · ImportBatchService.java · ApiImportController.java
KYC consent version placeholder ACT-P0-07
KYC submission should record the consent version presented to the user. Placeholder test added; full implementation deferred to a focused KYC consent design.
  • Add @Disabled test documenting the requirement in KycConsentTest.java
Files: KycConsentTest.java

Security Controls

Authentication boundary

ControlEnforcement pointNotes
Username enumeration preventionRegistrationControllerOnly constraint exception permitted; no pre-check
SAML/OIDC issuance gateIssuance WebFilterDenied if only a completion token is present in session
Completion token expiryCompletionSessionService.validate()15-minute TTL enforced at DB level via expires_at
Continuation token user bindingatomicConsume(hash, userId)Returns 0 rows on userId mismatch
Claim token purpose bindingatomicRedeem(hash, userId, purpose)Password-reset token ≠ claim token
No upward assurance overrideApiKycLifecycleControllerReturns 400 if target > current
SP allowlist for continuationOnboardingContinuationServiceOnly registered SPs; URL resolved from registry
SCIM credential isolationScimUserService field mappingNo credential/assurance field accepted from SCIM

Required integration tests

TestCategory
Registration response identical for taken vs. available usernameEnumeration
Completion token holder cannot POST to SAML assertion endpointAuthorization boundary
Continuation token from user A cannot be consumed by user BIDOR
Claim token with wrong purpose returns emptyAuthorization
Admin invalidate with target > current returns 400No upward override
CSV with 50,001 rows rejected with clear errorLimit enforcement
Quoted CSV field containing comma parses correctlyParsing correctness
Concurrent continuation redemption — exactly one winsConcurrency (Testcontainers)
SKIP LOCKED — two dispatchers claim disjoint outbox rowsConcurrency (Testcontainers)
Document fingerprint duplicate routes to manual review, not hard blockDuplicate detection
✓
All blocking JPA calls on boundedElastic

Every blocking database operation in a WebFlux pipeline must be wrapped with .subscribeOn(Schedulers.boundedElastic()). This applies to CompletionSessionService, OnboardingContinuationService, and KycGateService when called from reactive login flows.

HawiyatiDocumentation · v2026 · Spring Boot 3.5