Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,11 @@
import com.generalbytes.batm.server.extensions.IRestService;
import com.generalbytes.batm.server.extensions.aml.verification.IIdentityVerificationProvider;
import com.generalbytes.batm.server.extensions.common.sumsub.api.SumsubApiFactory;
import com.generalbytes.batm.server.extensions.common.sumsub.api.digest.SumsubSignatureDigest;
import com.generalbytes.batm.server.extensions.common.sumsub.api.digest.SumsubTimestampProvider;
import com.generalbytes.batm.server.extensions.util.ExtensionParameters;
import com.generalbytes.batm.server.extensions.extra.identityverification.sumsub.api.ISumSubApi;
import com.generalbytes.batm.server.extensions.extra.identityverification.sumsub.api.SumsubDocumentClient;
import com.generalbytes.batm.server.extensions.extra.identityverification.sumsub.api.SumsubDocumentDownloader;
import com.generalbytes.batm.server.extensions.extra.identityverification.sumsub.api.SumsubIdentityPieceCreator;
import lombok.extern.slf4j.Slf4j;

import java.util.HashSet;
Expand Down Expand Up @@ -100,7 +101,10 @@ private SumSubIdentityVerificationProvider initializeProvider(String token,
int linkExpiryInSeconds) {
ISumSubApi api = createApi(token, secret);
SumSubApiService apiService = createSumSubApiService(api, levelName, linkExpiryInSeconds);
SumSubWebhookProcessor webhookProcessor = createWebhookProcessor(webhookSecret, apiService);
SumsubDocumentClient documentClient = new SumsubDocumentClient(token, secret, "https://api.sumsub.com");
SumsubIdentityPieceCreator identityPieceCreator = new SumsubIdentityPieceCreator();
SumsubDocumentDownloader documentDownloader = new SumsubDocumentDownloader(documentClient, identityPieceCreator, 3, 1);
SumSubWebhookProcessor webhookProcessor = createWebhookProcessor(webhookSecret, apiService, documentDownloader);
return new SumSubIdentityVerificationProvider(apiService, webhookProcessor);
}

Expand All @@ -112,9 +116,9 @@ private ISumSubApi createApi(String token, String secret) {
return apiFactory.createSumsubIdentityVerificationApi(token, secret);
}

private SumSubWebhookProcessor createWebhookProcessor(String webhookSecret, SumSubApiService apiService) {
private SumSubWebhookProcessor createWebhookProcessor(String webhookSecret, SumSubApiService apiService, SumsubDocumentDownloader documentDownloader) {
return new SumSubWebhookProcessor(
ctx, apiService, module.getSubWebhookParser(), new SumSubApplicantReviewedResultMapper(), webhookSecret
ctx, apiService, module.getSubWebhookParser(), new SumSubApplicantReviewedResultMapper(), webhookSecret, documentDownloader
);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,22 +7,26 @@
import com.generalbytes.batm.server.extensions.aml.verification.ApplicantCheckResult;
import com.generalbytes.batm.server.extensions.aml.verification.IdentityCheckWebhookException;
import com.generalbytes.batm.server.extensions.common.sumsub.SumsubException;
import com.generalbytes.batm.server.extensions.extra.identityverification.sumsub.api.SumsubDocumentDownloader;
import com.generalbytes.batm.server.extensions.extra.identityverification.sumsub.api.digest.SumSubWebhookSecretDigest;
import com.generalbytes.batm.server.extensions.extra.identityverification.sumsub.api.vo.ApplicantInfoResponse;
import com.generalbytes.batm.server.extensions.extra.identityverification.sumsub.api.vo.ApplicantReviewedWebhook;
import com.generalbytes.batm.server.extensions.extra.identityverification.sumsub.api.vo.BaseWebhookBody;
import com.generalbytes.batm.server.extensions.extra.identityverification.sumsub.api.vo.CreateIdentityVerificationSessionResponse;
import com.generalbytes.batm.server.extensions.extra.identityverification.sumsub.api.vo.InspectionImage;
import com.generalbytes.batm.server.extensions.extra.identityverification.sumsub.api.vo.InspectionInfoResponse;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.Response.Status;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import si.mazi.rescu.HttpStatusIOException;

import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.Response.Status;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
* The SumSubWebhookProcessor class is responsible for processing incoming webhooks from the SumSub
Expand All @@ -37,11 +41,14 @@
@AllArgsConstructor
public class SumSubWebhookProcessor {

private static final ExecutorService documentDownloadExecutorService = Executors.newSingleThreadExecutor();

private final IExtensionContext ctx;
private final SumSubApiService apiService;
private final SumSubWebhookParser webhookParser;
private final SumSubApplicantReviewedResultMapper checkResultMapper;
private final String webhookSecretKey;
private final SumsubDocumentDownloader documentDownloader;

/**
* Processes incoming webhook payloads by verifying their signatures and handling the webhook
Expand Down Expand Up @@ -95,7 +102,7 @@ private void processApplicantReviewedWebhook(ApplicantReviewedWebhook applicantR
// after discussing with GB, this is intended due to some inconsistent webhook issues they have with Veriff
// but with Sum&Substance, we need to update the state since they do ongoing monitoring,
// and we should update the state with new webhook information
if (identity.getState() != IIdentityBase.STATE_TO_BE_VERIFIED) {
if (identity != null && identity.getState() != IIdentityBase.STATE_TO_BE_VERIFIED) {
// only update the state to STATE_TO_BE_VERIFIED and add a new note
ctx.updateIdentity(identity.getPublicId(), identity.getExternalId(), IIdentityBase.STATE_TO_BE_VERIFIED,
identity.getType(), identity.getCreated(), identity.getRegistered(), identity.getVipBuyDiscount(),
Expand All @@ -106,6 +113,7 @@ private void processApplicantReviewedWebhook(ApplicantReviewedWebhook applicantR
identity.getLimitCashTotalIdentity(), identity.getConfigurationCashCurrency());
}
ctx.processIdentityVerificationResult(rawPayload, result);
processDocuments(applicantReviewedWebhook, identity, inspectionInfoResponse);
} catch (HttpStatusIOException e) {
log.error("Error getting info from SumSub: HTTP response code: {}, body: {}, error message: {}", e.getHttpStatusCode(), e.getHttpBody(), e.getMessage());
throw new IdentityCheckWebhookException(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), "",
Expand All @@ -115,6 +123,20 @@ private void processApplicantReviewedWebhook(ApplicantReviewedWebhook applicantR
}
}

private void processDocuments(ApplicantReviewedWebhook applicantReviewedWebhook, IIdentity identity, InspectionInfoResponse inspectionInfoResponse) {
if (identity == null) {
log.info("Skipping document download, missing identity");
return;
}
List<InspectionImage> images = inspectionInfoResponse.getImages();
if (images != null && !images.isEmpty()) {
String identityPublicId = identity.getPublicId();
String inspectionId = applicantReviewedWebhook.getInspectionId();
documentDownloadExecutorService.submit(() ->
documentDownloader.downloadAndStoreDocuments(identityPublicId, inspectionId, images, ctx));
}
}

private void sendLevelChangedSMSToIdentity(String identityId) throws IdentityCheckWebhookException {
try {
IIdentity identity = ctx.findIdentityByIdentityId(identityId);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
package com.generalbytes.batm.server.extensions.extra.identityverification.sumsub.api;

import com.generalbytes.batm.server.coinutil.Hex;
import com.generalbytes.batm.server.extensions.common.sumsub.SumsubException;
import com.google.common.io.ByteStreams;
import lombok.extern.slf4j.Slf4j;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Objects;

/**
* HTTP client for downloading document images from Sumsub API.
* This class exists because Rescu REST proxy {@link ISumSubApi} does not support binary responses.
*
* <p><a href="https://docs.sumsub.com/reference/get-document-images">Get document images</a>
*/
@Slf4j
public class SumsubDocumentClient {

private static final String ALGORITHM = "HmacSHA256";
private static final String HEADER_APP_TOKEN = "X-App-Token";
private static final String HEADER_APP_TS = "X-App-Access-Ts";
private static final String HEADER_APP_SIG = "X-App-Access-Sig";
private static final String DEFAULT_CONTENT_TYPE = "image/jpeg";

private final String token;
private final Mac mac;
private final String baseUrl;

public SumsubDocumentClient(String token, String secret, String baseUrl) {
this.token = token;
this.baseUrl = baseUrl.endsWith("/") ? baseUrl.substring(0, baseUrl.length() - 1) : baseUrl;
try {
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd put this try-catch into a private method

this.mac = Mac.getInstance(ALGORITHM);
this.mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), ALGORITHM));
} catch (InvalidKeyException e) {
throw new SumsubException("Failed to initialize SumsubDocumentClient, is the secret key configured properly?", e);
} catch (NoSuchAlgorithmException e) {
throw new SumsubException(e);
}
}

/**
* Downloads a document image by inspection ID and image ID.
*
* @param inspectionId the inspection ID from the webhook
* @param imageId the image ID from {@link com.generalbytes.batm.server.extensions.extra.identityverification.sumsub.api.vo.InspectionImage#getImageId()}
* @return the downloaded content and its content type
*/
public DownloadedDocument downloadDocument(String inspectionId, String imageId) throws IOException {
HttpURLConnection httpConnection = createHttpConnection(inspectionId, imageId);
validateResponseCode(httpConnection, imageId);
String contentType = getContentType(httpConnection);

try (InputStream is = httpConnection.getInputStream()) {
byte[] content = ByteStreams.toByteArray(is);
return new DownloadedDocument(content, contentType);
}
}

private HttpURLConnection createHttpConnection(String inspectionId, String imageId) throws IOException {
String path = "/resources/inspections/" + inspectionId + "/resources/" + imageId;
String url = baseUrl + path;

long timestamp = System.currentTimeMillis() / 1000;
String timestampString = String.valueOf(timestamp);
String signature = computeSignature(timestampString, path);
HttpURLConnection httpConnection = (HttpURLConnection) new URL(url).openConnection();
httpConnection.setRequestMethod("GET");
httpConnection.setRequestProperty(HEADER_APP_TOKEN, token);
httpConnection.setRequestProperty(HEADER_APP_TS, timestampString);
httpConnection.setRequestProperty(HEADER_APP_SIG, signature);
return httpConnection;
}

private static String getContentType(HttpURLConnection httpConnection) {
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Static is unnecessary.

String contentType = httpConnection.getContentType();
if (contentType != null && contentType.contains(";")) {
contentType = contentType.split(";")[0].trim();
}
if (contentType == null || contentType.isBlank()) {
contentType = DEFAULT_CONTENT_TYPE;
}
return contentType;
}

private static void validateResponseCode(HttpURLConnection httpConnection, String imageId) throws IOException {
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Static is unnecessary.

if (httpConnection.getResponseCode() != HttpURLConnection.HTTP_OK) {
try (InputStream errorStream = httpConnection.getErrorStream()) {
String errorResponse = errorStream != null ? new String(ByteStreams.toByteArray(errorStream), StandardCharsets.UTF_8) : "";
throw new IOException("Error downloading document " + imageId + ": " + httpConnection.getResponseCode() + ": " + errorResponse);
}
}
}

private String computeSignature(String ts, String path) {
String combined = ts + "GET" + path;
mac.update(combined.getBytes(StandardCharsets.UTF_8));
return Hex.bytesToHexString(mac.doFinal());
}

public record DownloadedDocument(byte[] content, String contentType) {
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is just an idea, but if you extracted this record, you could make it package-private. It's not needed anywhere outside this package anyway, if I'm not wrong.

@Override
public boolean equals(Object o) {
if (!(o instanceof DownloadedDocument that)) return false;
return Objects.deepEquals(content(), that.content()) && Objects.equals(contentType(), that.contentType());
}

@Override
public int hashCode() {
return Objects.hash(Arrays.hashCode(content()), contentType());
}

@Override
public String toString() {
return "DownloadedDocument{" +
"contentType='" + contentType + '\'' +
'}';
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
package com.generalbytes.batm.server.extensions.extra.identityverification.sumsub.api;

import com.generalbytes.batm.server.extensions.IExtensionContext;
import com.generalbytes.batm.server.extensions.IIdentityPiece;
import com.generalbytes.batm.server.extensions.extra.identityverification.sumsub.api.vo.InspectionImage;
import com.generalbytes.batm.server.extensions.extra.identityverification.sumsub.api.vo.enums.SumSubDocumentType;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
* Orchestrates downloading document images from Sumsub and storing them as identity pieces.
* Uses {@link SumsubDocumentClient} for HTTP download and {@link SumsubIdentityPieceCreator} for piece creation.
*
* <p><a href="https://docs.sumsub.com/reference/get-document-images">Get document images</a>
*/
@Slf4j
public class SumsubDocumentDownloader {

private final SumsubDocumentClient client;
private final SumsubIdentityPieceCreator creator;
private final int maxDownloadRetries;
private final int retryDelaySeconds; // with increasing backoff (attemptNumber * retryDelaySeconds)

public SumsubDocumentDownloader(SumsubDocumentClient client, SumsubIdentityPieceCreator creator,
int maxDownloadRetries, int retryDelaySeconds) {
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would make maxDownloadRetries and retryDelaySeconds as constants in the class. It seems unnecessary to set them in the constructor.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I refactored it to use constants in the calling class, but kept the constructor injection for easier testability.

this.client = client;
this.creator = creator;
this.maxDownloadRetries = maxDownloadRetries;
this.retryDelaySeconds = retryDelaySeconds;
}

/**
* Filters images to mappable types, downloads each, and stores as identity pieces.
* Unmappable document types are skipped.
*/
public void downloadAndStoreDocuments(String identityPublicId, String inspectionId,
List<InspectionImage> images, IExtensionContext ctx) {
if (images == null || images.isEmpty()) {
return;
}

List<InspectionImage> mappableImages = images.stream()
.filter(img -> {
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You could put this filtering logic into a method and give it a nice name to make ti more readable.

if (img.getImageId() == null || img.getIdDocDef() == null) {
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would divide it into two conditions and write a specific message - for possible easier debugging.

log.warn("Skipping image with null imageId or idDocDef");
return false;
}
SumSubDocumentType docType = img.getIdDocDef().getIdDocType();
if (!SumsubIdentityPieceCreator.isMappableDocumentType(docType)) {
log.debug("Skipping unmappable document type from Sumsub: {}", docType);
return false;
}
return true;
})
.toList();

if (mappableImages.isEmpty()) {
return;
}

List<InspectionImage> failedImages = retryDownload(mappableImages, identityPublicId, inspectionId, ctx, 1);

if (!failedImages.isEmpty()) {
List<String> failedImageDetails = failedImages.stream()
.map(img -> img.getImageId() + " (" + (img.getIdDocDef() != null ? img.getIdDocDef().getIdDocType() : "unknown") + ")")
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe extract this into a method. It's hard to tell what it's supposed to do.

.toList();
log.error("Failed to download the following images after {} attempts: {}", maxDownloadRetries, failedImageDetails);
}
}

private List<InspectionImage> retryDownload(List<InspectionImage> images, String identityPublicId, String inspectionId,
IExtensionContext extensionContext, int attempt) {
if (attempt > maxDownloadRetries) {
return images;
}

List<InspectionImage> failedThisRound = attemptDownload(images, identityPublicId, inspectionId, extensionContext, attempt);

if (failedThisRound.isEmpty()) {
log.info("All images downloaded successfully for applicantId: {}", identityPublicId);
return Collections.emptyList();
}

addRetryDelay(attempt);
return retryDownload(failedThisRound, identityPublicId, inspectionId, extensionContext, attempt + 1);
}

private List<InspectionImage> attemptDownload(List<InspectionImage> images,
String identityPublicId,
String inspectionId,
IExtensionContext ctx,
int attempt) {
List<InspectionImage> failedImages = new ArrayList<>();
for (InspectionImage image : images) {
try {
SumSubDocumentType docType = image.getIdDocDef().getIdDocType();
log.info("Attempt {}: Downloading image ({}) for applicantId: {}", attempt, docType, identityPublicId);
SumsubDocumentClient.DownloadedDocument download = client.downloadDocument(inspectionId, String.valueOf(image.getImageId()));
IIdentityPiece piece = creator.createIdentityPiece(docType, download.contentType(), download.content());
ctx.addIdentityPiece(identityPublicId, piece);
int fileSizeKiloBytes = download.content().length / 1000;
log.info("Sumsub document ({}, {}) downloaded: {} kB", docType, image.getImageId(), fileSizeKiloBytes);
} catch (IOException e) {
log.warn("Attempt {} failed for image ID: {}, type: {}, error: {}", attempt, image.getImageId(), image.getIdDocDef().getIdDocType(), e.getMessage());
failedImages.add(image);
}
}
return failedImages;
}

private void addRetryDelay(int attempt) {
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

add could be confusing. Consider a better name like waitBeforeRetry or applyRetryDelay.

try {
TimeUnit.SECONDS.sleep((long) attempt * retryDelaySeconds);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
log.error("Retry interrupted", e);
}
}
}
Loading