KYC and Identity Verification Domain
Overview
This backend slice handles the KYC lifecycle from the server side: it prepares identity-prefill data for link-token creation, polls provider verification status, and forwards balance, transaction, income, and asset-report requests through a provider-agnostic gateway. The same pattern keeps provider-specific details out of the use cases while still letting the HTTP layer bind to a concrete implementation such as PlaidKycGateway.
The applicant side is tied in through ApplicantService, which persists applicant records, links them to customer ownership, and enforces consent-grant validity before creating new applicant entries. Together, these pieces support identity verification, account discovery, and downstream financial-data retrieval without hard-coding provider behavior into business logic.
Architecture Overview
flowchart TB
subgraph PresentationLayer[Presentation Layer]
HttpEndpoints[http_endpoints]
end
subgraph BusinessLayer[Business Layer]
GenerateLinkToken[generate_link_token_id_verification]
PollVerification[kyc_get_identity_verification_status]
GetBalances[get_user_account_balances]
GetTransactions[get_transaction_data]
GetAssetReport[get_asset_report]
ApplicantServiceNode[ApplicantService]
end
subgraph GatewayLayer[Gateway Abstraction]
KycGatewayNode[KycGateway]
end
subgraph ProviderLayer[Provider Adapter]
PlaidKycGatewayNode[PlaidKycGateway]
end
subgraph PersistenceLayer[Persistence]
ApplicantModelNode[ApplicantModel]
ConsentGrantModelNode[ConsentGrantModel]
end
HttpEndpoints --> GenerateLinkToken
HttpEndpoints --> PollVerification
GenerateLinkToken --> KycGatewayNode
PollVerification --> KycGatewayNode
GetBalances --> KycGatewayNode
GetTransactions --> KycGatewayNode
GetAssetReport --> KycGatewayNode
KycGatewayNode --> PlaidKycGatewayNode
ApplicantServiceNode --> ApplicantModelNode
ApplicantServiceNode --> ConsentGrantModelNode
Component Structure
Use Case Functions
kyc.py
backend/src/usecase/kyc.py
| Method | Description |
|---|---|
generate_link_token_id_verification |
Passes applicant prefill data to KycGateway.create_link_token_id_verification and returns the raw link-token payload. |
kyc_get_identity_verification_status |
Passes a verification id to KycGateway.get_identity_verification_status and returns the provider response unchanged. |
get_user_account_balances |
Calls KycGateway.get_account_balances for an access token and wraps provider errors with a clearer message. |
get_transaction_data |
Logs retrieval progress, calls KycGateway.get_transaction_data, and rethrows failures as a transaction-specific exception. |
get_asset_report |
Logs generation progress, calls KycGateway.get_asset_report, and rethrows failures as an asset-report-specific exception. |
The file is intentionally thin: each function accepts a KycGateway instead of a provider class, so higher-level code can remain independent of provider details. The only hard provider binding in the provided context happens at the HTTP boundary, where PlaidKycGateway is instantiated.
ApplicantService
[!NOTE]
get_user_account_balancesis annotated as returningList[AccountBalance], but it returnskyc_gateway.get_account_balances(access_token)directly. The test doubles and calling code treat that result as a dictionary with keys such asstatus,accounts, andrequest_id, so the runtime shape does not match the declared return annotation.
backend/src/services/applicant_service.py
Constructor dependencies
| Type | Description |
|---|---|
Session |
SQLAlchemy session used for applicant queries, inserts, commits, and refreshes. |
Properties
| Property | Type | Description |
|---|---|---|
db |
Session |
Active SQLAlchemy session retained for all applicant data access operations. |
| Method | Description |
|---|---|
list_applicants |
Returns all ApplicantModel rows for a given customer_id. |
get_applicant |
Returns the first ApplicantModel row matching both customer_id and applicant_id. |
create_applicant |
Validates an optional consent grant, creates a new applicant row, commits it, and refreshes the model instance. |
create_applicant assigns a new applicant_id with uuid4(), stores applicant_reference, user_accounts, credit_data, and consent_grant_id, and rejects creation when the supplied consent grant is not active, revoked, or owned by the same customer.
ApplicantModel
backend/src/models/applicant.py
backend/src/models/applicant.py is an alias module that re-exports ApplicantModel from src.infra.mysql.models so the service layer can import the applicant model from a stable namespace.
Properties
| Property | Type | Description |
|---|---|---|
applicant_id |
str |
External applicant identifier generated by ApplicantService.create_applicant. |
customer_id |
str |
Owning customer identifier used for tenant scoping. |
applicant_reference |
`str | None` |
user_accounts |
`dict | None` |
credit_data |
`dict | None` |
consent_grant_id |
`str | None` |
created_at |
`datetime | None` |
Gateway Contract
KycGateway
backend/src/domain/kyc_gateway.py
KycGateway is the provider-agnostic contract that the use cases target. The provided tests and use cases show the gateway methods that higher layers depend on, while the concrete provider adapter stays hidden behind that interface.
| Method | Description |
|---|---|
create_link_token_id_verification |
Creates a provider link token using prefill identity data. |
get_identity_verification_status |
Retrieves verification status for a provider verification id. |
get_account_balances |
Retrieves account balances for an access token. |
get_transaction_data |
Retrieves transaction data for an access token and optional lookback window. |
get_asset_report |
Retrieves an asset report for an access token and optional requested span. |
get_income_data |
Retrieves income-related data for an access token. |
The abstraction keeps use cases free of provider-specific request/response details. In the provided HTTP layer, PlaidKycGateway is the concrete implementation that gets instantiated, but the use cases never depend on that class directly.
PlaidKycGateway
backend/src/infra/external_apis/plaid_client.py
PlaidKycGateway is the concrete provider adapter referenced by the HTTP handlers and tests. Its implementation is not shown here, but it is the class that the HTTP boundary uses when it needs a real KYC provider integration.
Test Gateway Doubles
TestKycGateway
backend/tests/domain/test_kyc_gateway.py
| Method | Description |
|---|---|
get_transaction_data |
Returns a deterministic transaction payload for contract testing. |
create_link_token_id_verification |
Returns a deterministic link-token payload for contract testing. |
get_identity_verification_status |
Returns a deterministic verification-status payload for contract testing. |
get_account_balances |
Returns a deterministic balance payload for contract testing. |
get_income_data |
Returns a deterministic income payload for contract testing. |
get_asset_report |
Returns a deterministic asset-report payload for contract testing. |
This class is used as a direct KycGateway implementation in domain tests.
MockKycGateway
backend/tests/usecase/test_kyc.py
| Method | Description |
|---|---|
get_transaction_data |
Returns a deterministic transaction payload for use-case tests. |
create_link_token_id_verification |
Returns a deterministic link-token payload for use-case tests. |
get_identity_verification_status |
Returns a deterministic verification-status payload for use-case tests. |
get_account_balances |
Returns a deterministic balance payload for use-case tests. |
get_income_data |
Returns a deterministic income payload for use-case tests. |
get_asset_report |
Returns a deterministic asset-report payload for use-case tests. |
This mock is used to verify that generate_link_token_id_verification and kyc_get_identity_verification_status remain thin pass-through use cases.
Data Shapes
Link Token Prefill Payload
The HTTP layer builds this object before calling generate_link_token_id_verification.
| Property | Type | Description |
|---|---|---|
user_id |
str |
Server-generated identifier built as user_ plus a UUID string. |
email |
str |
Applicant email from the incoming request. |
phone |
str |
Applicant phone number. |
first_name |
str |
Applicant first name. |
last_name |
str |
Applicant last name. |
dob_year |
int |
Year portion of the applicant date of birth. |
dob_month |
int |
Month portion of the applicant date of birth. |
dob_day |
int |
Day portion of the applicant date of birth. |
street |
str |
Street address. |
city |
str |
City. |
region |
str |
Region or state. |
postal_code |
str |
Postal code. |
country |
str |
Country code or country name. |
Link Token Response Payload
The HTTP layer expects and forwards this payload shape from the gateway.
| Property | Type | Description |
|---|---|---|
link_token |
str |
Provider link token used by the frontend identity-verification flow. |
verification |
`dict | object` |
Verification Status Payload
kyc_get_identity_verification_status forwards this shape unchanged.
| Property | Type | Description |
|---|---|---|
status |
str |
Verification status returned by the provider. |
Account Balance Payload
The gateway test doubles return this balance shape.
| Property | Type | Description |
|---|---|---|
status |
str |
Result indicator for the balance retrieval call. |
accounts |
list |
Account list returned by the provider. |
request_id |
str |
Provider request identifier. |
Account item shape
| Property | Type | Description |
|---|---|---|
account_id |
str |
Provider account identifier. |
name |
str |
Display name for the account. |
balances |
dict |
Balance block containing currency and current values. |
Balance block shape
| Property | Type | Description |
|---|---|---|
available |
float |
Available balance. |
current |
float |
Current balance. |
iso_currency_code |
str |
ISO currency code. |
Transaction Data Payload
The transaction use case forwards the gateway response unchanged.
| Property | Type | Description |
|---|---|---|
status |
str |
Retrieval status, such as success. |
transactions |
list |
Transaction list returned by the provider. |
accounts |
list |
Account list associated with the access token. |
total_transactions |
int |
Total count of retrieved transactions. |
request_id |
str |
Provider request identifier. |
Asset Report Payload
The asset-report use case forwards the gateway response unchanged.
| Property | Type | Description |
|---|---|---|
report_generated_at |
str |
Timestamp for when the report was produced. |
days_requested |
int |
Requested lookback span in days. |
accounts |
list |
Accounts included in the asset report. |
Asset account item shape
| Property | Type | Description |
|---|---|---|
account_id |
str |
Provider account identifier. |
name |
str |
Account display name. |
type |
str |
Account type. |
subtype |
str |
Account subtype. |
balances |
dict |
Balance block for the asset-report account. |
Income Data Payload
The gateway tests also exercise income retrieval through the same contract.
| Property | Type | Description |
|---|---|---|
income_sources |
list |
List of income sources for the applicant. |
paystubs |
list |
Paystub entries returned by the provider. |
tax_forms |
list |
Tax-form entries returned by the provider. |
total_income |
dict |
Aggregated income totals. |
last_year_income |
float |
Last-year income value. |
last_year_income_before_tax |
float |
Last-year pre-tax income value. |
max_number_of_overlapping_income_streams |
int |
Maximum concurrent income streams. |
number_of_income_streams |
int |
Count of income streams. |
API Integration
Verify Identity Verification Status
backend/src/interface/http_endpoints.py
{
"title": "Verify Identity Verification Status",
"description": "Returns the provider verification status for a verification id by calling the KYC gateway from the HTTP boundary.",
"method": "GET",
"baseUrl": "<BackendApiBaseUrl>",
"endpoint": "/identity_verification_status/{verification_id}",
"headers": [],
"queryParams": [],
"pathParams": [
{
"name": "verification_id",
"type": "string",
"required": true,
"description": "Provider verification identifier"
}
],
"bodyType": "none",
"requestBody": "",
"formData": [],
"rawBody": "",
"responses": {
"200": {
"description": "Success",
"body": "{\n \"status\": \"success\"\n}"
},
"500": {
"description": "Server error raised by the HTTP handler",
"body": "{\n \"detail\": \"string\"\n}"
}
}
}
The handler creates a PlaidKycGateway, calls kyc_get_identity_verification_status, and returns the gateway response directly. Any exception is caught and converted into an HTTP 500 response.
Link Token Generation Helper
backend/src/interface/http_endpoints.py
The link-token generation helper is not shown with a route decorator in the provided code, but its runtime behavior is visible:
- builds a server-generated
user_id - maps request fields into
user_data - instantiates
PlaidKycGateway - calls
generate_link_token_id_verification - extracts
link_token - passes through optional
verification - raises HTTP 500 when the provider response does not include a link token
Feature Flows
Link Token Generation
sequenceDiagram
participant User
participant Http as http_endpoints
participant Usecase as generate_link_token_id_verification
participant Gateway as KycGateway
participant Provider as PlaidKycGateway
User->>Http: submit identity prefill data
Http->>Http: build user_data and user_id
Http->>Usecase: call generate_link_token_id_verification
Usecase->>Gateway: create_link_token_id_verification
Gateway->>Provider: provider request
Provider-->>Gateway: link token payload
Gateway-->>Usecase: link token payload
Usecase-->>Http: link token payload
Http-->>User: link_token and verification
The HTTP layer generates a fresh user_id for every request and maps the applicant fields into a provider-ready payload. The use case itself does not transform the response; it simply passes the gateway result back to the caller.
Verification Status Polling
sequenceDiagram
participant User
participant Http as GET identity verification status
participant Usecase as kyc_get_identity_verification_status
participant Gateway as KycGateway
participant Provider as PlaidKycGateway
User->>Http: poll by verification_id
Http->>Usecase: pass verification_id
Usecase->>Gateway: get_identity_verification_status
Gateway->>Provider: provider lookup
Provider-->>Gateway: status payload
Gateway-->>Usecase: status payload
Usecase-->>Http: status payload
Http-->>User: status payload
This path is a straight pass-through: the use case does not decorate or persist the status, and the HTTP handler returns the provider response as-is unless an exception is raised.
Account Balance Retrieval
sequenceDiagram
participant Caller
participant Usecase as get_user_account_balances
participant Gateway as KycGateway
participant Provider as PlaidKycGateway
Caller->>Usecase: access_token
Usecase->>Gateway: get_account_balances
Gateway->>Provider: provider balances request
Provider-->>Gateway: account payload
Gateway-->>Usecase: account payload
Usecase-->>Caller: account payload
The use case only adds an exception wrapper around the gateway call. The test doubles return a payload with status, accounts, and request_id, which is the shape the surrounding code consumes.
Transaction Data Retrieval
sequenceDiagram
participant Caller
participant Usecase as get_transaction_data
participant Gateway as KycGateway
participant Provider as PlaidKycGateway
Caller->>Usecase: access_token and lookback_days
Usecase->>Usecase: log start message
Usecase->>Gateway: get_transaction_data
Gateway->>Provider: provider transactions request
Provider-->>Gateway: transaction payload
Gateway-->>Usecase: transaction payload
Usecase->>Usecase: log success message
Usecase-->>Caller: transaction payload
The function logs the first eight characters of the access token, then delegates to the gateway with the provided lookback window. Errors are logged with stack information and re-raised with a transaction-specific message.
Asset Report Retrieval
sequenceDiagram
participant Caller
participant Usecase as get_asset_report
participant Gateway as KycGateway
participant Provider as PlaidKycGateway
Caller->>Usecase: access_token and days_requested
Usecase->>Usecase: log start message
Usecase->>Gateway: get_asset_report
Gateway->>Provider: provider asset report request
Provider-->>Gateway: asset report payload
Gateway->>Usecase: asset report payload
Usecase->>Usecase: log success message
Usecase-->>Caller: asset report payload
The asset-report use case mirrors the transaction flow: it logs the request, delegates to the gateway, and wraps provider failures in a clearer error message.
Applicant Record Creation
sequenceDiagram
participant Caller
participant Service as ApplicantService
participant DB as Session
participant Grant as ConsentGrantModel
participant Applicant as ApplicantModel
Caller->>Service: create_applicant
Service->>DB: query consent grant
DB-->>Service: grant row or empty
Service->>Service: validate active and revoked state
Service->>DB: add applicant
Service->>DB: commit
Service->>DB: refresh applicant
DB-->>Service: refreshed applicant
Service-->>Caller: applicant model
The service only creates an applicant after validating an optional consent grant against the active, non-revoked grant set for the same customer. If the consent grant lookup fails, the method raises ValueError and does not write the applicant row.
Error Handling
kyc.py uses a layered error style:
kyc_get_identity_verification_statusis a direct pass-through and leaves error handling to the caller.get_user_account_balancescatches any exception and rethrowsException("Failed to retrieve account balances: ...").get_transaction_datalogs the failure withexc_info=Trueand rethrowsException("Failed to retrieve transaction data: ...").get_asset_reportlogs the failure and rethrowsException("Failed to generate asset report: ...").ApplicantService.create_applicantraisesValueError("Consent grant is invalid or inactive")when the grant lookup does not match an active grant for the customer.
The HTTP handler for verification status converts any error into HTTPException(status_code=500, detail=str(e)), so provider-specific details are not exposed beyond the handler boundary.
Dependencies
KycGateway: provider-agnostic contract used by the use cases.PlaidKycGateway: concrete provider adapter instantiated in the HTTP boundary.Session: SQLAlchemy session injected intoApplicantService.ApplicantModel: applicant persistence model used by the service and tests.ConsentGrantModel: consent validation model referenced byApplicantService.uuid4: used to generate applicant ids.logging: used by transaction and asset-report use cases.pytest: used by the gateway and use-case tests.
Testing Considerations
backend/tests/domain/test_kyc_gateway.pyverifies that the KYC contract methods return deterministic dictionaries and that the gateway interface can be implemented without provider access.backend/tests/usecase/test_kyc.pyverifies thatgenerate_link_token_id_verificationreturns the link token from the gateway and thatkyc_get_identity_verification_statusreturns a success dictionary.- The test doubles return a stable
accountspayload for balance retrieval, which is the shape the surrounding code expects. - The
ApplicantService.create_applicantpath should be covered with both valid and invalid consent-grant setups because the method rejects inactive or mismatched grants before writing the applicant row. - Transaction and asset-report use cases should be tested for wrapped exceptions, since both methods catch provider failures and rethrow feature-specific error messages.
Key Classes Reference
| Class | Location | Responsibility |
|---|---|---|
kyc.py |
backend/src/usecase/kyc.py |
Thin KYC use cases for link tokens, verification polling, balances, transactions, and asset reports. |
ApplicantService |
backend/src/services/applicant_service.py |
Applicant persistence and consent-grant validation. |
ApplicantModel |
backend/src/models/applicant.py |
Re-export of the applicant persistence model. |
KycGateway |
backend/src/domain/kyc_gateway.py |
Provider-agnostic KYC gateway contract. |
PlaidKycGateway |
backend/src/infra/external_apis/plaid_client.py |
Concrete provider adapter used by the HTTP boundary. |
http_endpoints.py |
backend/src/interface/http_endpoints.py |
HTTP boundary for KYC link-token and verification-status flows. |
test_kyc_gateway.py |
backend/tests/domain/test_kyc_gateway.py |
Contract test gateway implementation. |
test_kyc.py |
backend/tests/usecase/test_kyc.py |
Use-case tests with a deterministic mock gateway. |