diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerService.java b/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerService.java index 116d7e8a5..4a44e14fe 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerService.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerService.java @@ -735,11 +735,11 @@ public class WhisperServerService extends Application braintreeManager.captureOneTimePayment(request.payerId, request.paymentId, request.paymentToken, request.currency, request.amount, request.level, getClientPlatform(userAgent))) - .thenCompose( - chargeSuccessDetails -> oneTimeDonationsManager.putPaidAt(chargeSuccessDetails.paymentId(), Instant.now())) - .thenApply(paymentId -> Response.ok( - new ConfirmPayPalBoostResponse(paymentId)).build()); + .thenApply(chargeSuccessDetails -> { + oneTimeDonationsManager.putPaidAt(chargeSuccessDetails.paymentId(), Instant.now()); + return Response.ok( + new ConfirmPayPalBoostResponse(chargeSuccessDetails.paymentId())).build(); + }); } public static class CreateBoostReceiptCredentialsRequest { @@ -355,11 +357,11 @@ public class OneTimeDonationController { case APPLE_APP_STORE -> throw new BadRequestException("cannot use app store purchases for one-time donations"); }; - return paymentDetailsFut.thenCompose(paymentDetails -> { + return paymentDetailsFut.thenApply(paymentDetails -> { if (paymentDetails == null) { throw new WebApplicationException(Response.Status.NOT_FOUND); } else if (paymentDetails.status() == PaymentStatus.PROCESSING) { - return CompletableFuture.completedFuture(Response.noContent().build()); + return Response.noContent().build(); } else if (paymentDetails.status() != PaymentStatus.SUCCEEDED) { throw new WebApplicationException(Response.status(Response.Status.PAYMENT_REQUIRED) .entity(new CreateBoostReceiptCredentialsErrorResponse(paymentDetails.chargeFailure())).build()); @@ -395,31 +397,33 @@ public class OneTimeDonationController { throw new BadRequestException("invalid receipt credential request", e); } final long finalLevel = level; - return issuedReceiptsManager.recordIssuance(paymentDetails.id(), request.processor, - receiptCredentialRequest, clock.instant()) - .thenCompose(_ -> oneTimeDonationsManager.getPaidAt(paymentDetails.id(), paymentDetails.created())) - .thenApply(paidAt -> { - Instant expiration = paidAt - .plus(levelExpiration) - .truncatedTo(ChronoUnit.DAYS) - .plus(1, ChronoUnit.DAYS); - ReceiptCredentialResponse receiptCredentialResponse; - try { - receiptCredentialResponse = zkReceiptOperations.issueReceiptCredential( - receiptCredentialRequest, expiration.getEpochSecond(), finalLevel); - } catch (VerificationFailedException e) { - throw new BadRequestException("receipt credential request failed verification", e); - } - Metrics.counter(SubscriptionController.RECEIPT_ISSUED_COUNTER_NAME, - Tags.of( - Tag.of(SubscriptionController.PROCESSOR_TAG_NAME, request.processor.toString()), - Tag.of(SubscriptionController.TYPE_TAG_NAME, "boost"), - UserAgentTagUtil.getPlatformTag(userAgent))) - .increment(); - return Response.ok( - new CreateBoostReceiptCredentialsSuccessResponse(receiptCredentialResponse.serialize())) - .build(); - }); + try { + issuedReceiptsManager.recordIssuance(paymentDetails.id(), request.processor, + receiptCredentialRequest, clock.instant()); + } catch (final WriteConflictException _) { + throw new WebApplicationException(Response.Status.CONFLICT); + } + final Instant paidAt = oneTimeDonationsManager.getPaidAt(paymentDetails.id(), paymentDetails.created()); + final Instant expiration = paidAt + .plus(levelExpiration) + .truncatedTo(ChronoUnit.DAYS) + .plus(1, ChronoUnit.DAYS); + final ReceiptCredentialResponse receiptCredentialResponse; + try { + receiptCredentialResponse = zkReceiptOperations.issueReceiptCredential( + receiptCredentialRequest, expiration.getEpochSecond(), finalLevel); + } catch (final VerificationFailedException e) { + throw new BadRequestException("receipt credential request failed verification", e); + } + Metrics.counter(SubscriptionController.RECEIPT_ISSUED_COUNTER_NAME, + Tags.of( + Tag.of(SubscriptionController.PROCESSOR_TAG_NAME, request.processor.toString()), + Tag.of(SubscriptionController.TYPE_TAG_NAME, "boost"), + UserAgentTagUtil.getPlatformTag(userAgent))) + .increment(); + return Response.ok( + new CreateBoostReceiptCredentialsSuccessResponse(receiptCredentialResponse.serialize())) + .build(); }); } diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/mappers/SubscriptionExceptionMapper.java b/service/src/main/java/org/whispersystems/textsecuregcm/mappers/SubscriptionExceptionMapper.java index 7331225e8..b816bfc25 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/mappers/SubscriptionExceptionMapper.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/mappers/SubscriptionExceptionMapper.java @@ -22,6 +22,7 @@ import org.whispersystems.textsecuregcm.subscriptions.SubscriptionNotFoundExcept import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPaymentRequiredException; import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorConflictException; import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorException; +import org.whispersystems.textsecuregcm.subscriptions.SubscriptionReceiptAlreadyRedeemedException; public class SubscriptionExceptionMapper implements ExceptionMapper { @VisibleForTesting @@ -56,11 +57,12 @@ public class SubscriptionExceptionMapper implements ExceptionMapper Response.Status.NOT_FOUND; - case SubscriptionForbiddenException e -> Response.Status.FORBIDDEN; - case SubscriptionInvalidArgumentsException e -> Response.Status.BAD_REQUEST; - case SubscriptionProcessorConflictException e -> Response.Status.CONFLICT; - case SubscriptionPaymentRequiredException e -> Response.Status.PAYMENT_REQUIRED; + case SubscriptionNotFoundException _ -> Response.Status.NOT_FOUND; + case SubscriptionForbiddenException _ -> Response.Status.FORBIDDEN; + case SubscriptionInvalidArgumentsException _ -> Response.Status.BAD_REQUEST; + case SubscriptionProcessorConflictException _ -> Response.Status.CONFLICT; + case SubscriptionPaymentRequiredException _ -> Response.Status.PAYMENT_REQUIRED; + case SubscriptionReceiptAlreadyRedeemedException _ -> Response.Status.CONFLICT; default -> Response.Status.INTERNAL_SERVER_ERROR; }); diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/storage/IssuedReceiptsManager.java b/service/src/main/java/org/whispersystems/textsecuregcm/storage/IssuedReceiptsManager.java index 802e7884b..8bee5d966 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/storage/IssuedReceiptsManager.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/storage/IssuedReceiptsManager.java @@ -10,9 +10,6 @@ import static org.whispersystems.textsecuregcm.util.AttributeValues.n; import static org.whispersystems.textsecuregcm.util.AttributeValues.s; import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.Throwables; -import jakarta.ws.rs.ClientErrorException; -import jakarta.ws.rs.core.Response.Status; import java.nio.charset.StandardCharsets; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; @@ -22,8 +19,6 @@ import java.util.EnumMap; import java.util.List; import java.util.Map; import java.util.Objects; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.CompletionException; import java.util.function.Consumer; import javax.annotation.Nonnull; import javax.crypto.Mac; @@ -31,10 +26,11 @@ import javax.crypto.spec.SecretKeySpec; import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialRequest; import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider; import software.amazon.awssdk.core.SdkBytes; -import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient; +import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.model.ConditionalCheckFailedException; import software.amazon.awssdk.services.dynamodb.model.DeleteItemRequest; +import software.amazon.awssdk.services.dynamodb.model.DeleteItemResponse; import software.amazon.awssdk.services.dynamodb.model.ReturnValue; import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest; @@ -46,42 +42,40 @@ public class IssuedReceiptsManager { private final String table; private final Duration expiration; - private final DynamoDbAsyncClient dynamoDbAsyncClient; + private final DynamoDbClient dynamoDbClient; private final byte[] receiptTagGenerator; private final EnumMap maxIssuedReceiptsPerPaymentId; public IssuedReceiptsManager( - @Nonnull String table, - @Nonnull Duration expiration, - @Nonnull DynamoDbAsyncClient dynamoDbAsyncClient, - @Nonnull byte[] receiptTagGenerator, - @Nonnull EnumMap maxIssuedReceiptsPerPaymentId) { + @Nonnull final String table, + @Nonnull final Duration expiration, + @Nonnull final DynamoDbClient dynamoDbClient, + @Nonnull final byte[] receiptTagGenerator, + @Nonnull final EnumMap maxIssuedReceiptsPerPaymentId) { this.table = Objects.requireNonNull(table); this.expiration = Objects.requireNonNull(expiration); - this.dynamoDbAsyncClient = Objects.requireNonNull(dynamoDbAsyncClient); + this.dynamoDbClient = Objects.requireNonNull(dynamoDbClient); this.receiptTagGenerator = Objects.requireNonNull(receiptTagGenerator); this.maxIssuedReceiptsPerPaymentId = Objects.requireNonNull(maxIssuedReceiptsPerPaymentId); } - /** - * Returns a future that completes normally if either this processor item was never issued a receipt credential - * previously OR if it was issued a receipt credential previously for the exact same receipt credential request - * enabling clients to retry in case they missed the original response. - *

- * If this item has already been used to issue another receipt, throws a 409 conflict web application exception. - *

- * For {@link PaymentProvider#STRIPE}, item is expected to refer to an invoice line item (subscriptions) or a - * payment intent (one-time). - */ - public CompletableFuture recordIssuance( - String processorItemId, - PaymentProvider processor, - ReceiptCredentialRequest request, - Instant now) { + /// Returns normally if either this processor item was never issued a receipt credential + /// previously OR if it was issued a receipt credential previously for the exact same receipt credential request + /// enabling clients to retry in case they missed the original response. + /// + /// If this item has already been used to issue another receipt, throws [WriteConflictException]. + /// + /// For [PaymentProvider#STRIPE], item is expected to refer to an invoice line item (subscriptions) or a + /// payment intent (one-time). + public void recordIssuance( + final String processorItemId, + final PaymentProvider processor, + final ReceiptCredentialRequest request, + final Instant now) throws WriteConflictException { final AttributeValue key = dynamoDbKey(processor, processorItemId); final byte[] tag = generateIssuedReceiptTag(request); - UpdateItemRequest updateItemRequest = UpdateItemRequest.builder() + final UpdateItemRequest updateItemRequest = UpdateItemRequest.builder() .tableName(table) .key(Map.of(KEY_PROCESSOR_ITEM_ID, key)) .conditionExpression("attribute_not_exists(#key) OR contains(#tags, :tag) OR size(#tags) < :maxTags") @@ -97,39 +91,31 @@ public class IssuedReceiptsManager { ":exp", n(now.plus(expiration).getEpochSecond()), ":maxTags", n(maxIssuedReceiptsPerPaymentId.get(processor)))) .build(); - return dynamoDbAsyncClient.updateItem(updateItemRequest).handle((updateItemResponse, throwable) -> { - if (throwable != null) { - Throwable rootCause = Throwables.getRootCause(throwable); - if (rootCause instanceof ConditionalCheckFailedException) { - throw new ClientErrorException(Status.CONFLICT, rootCause); - } - Throwables.throwIfUnchecked(throwable); - throw new CompletionException(throwable); - } - return null; - }); + try { + dynamoDbClient.updateItem(updateItemRequest); + } catch (final ConditionalCheckFailedException _) { + throw new WriteConflictException(); + } } - /** - * Clear the recorded issuances for a particular item - * - * @param processorItemId The itemId within the processor to clear - * @param processor The processor - * @return a future that yields true if the item was deleted, false if the item already did not exist - */ - public CompletableFuture clearIssuance(String processorItemId, PaymentProvider processor) { + /// Clear the recorded issuances for a particular item + /// + /// @param processorItemId The itemId within the processor to clear + /// @param processor The processor + /// @return true if the item was deleted, false if the item did not exist + public boolean clearIssuance(final String processorItemId, final PaymentProvider processor) { final AttributeValue key = dynamoDbKey(processor, processorItemId); final DeleteItemRequest deleteItemRequest = DeleteItemRequest.builder() .tableName(table) .key(Map.of(KEY_PROCESSOR_ITEM_ID, key)) .returnValues(ReturnValue.ALL_OLD) .build(); - return dynamoDbAsyncClient.deleteItem(deleteItemRequest) - .thenApply(item -> item.hasAttributes() && !item.attributes().isEmpty()); + final DeleteItemResponse item = dynamoDbClient.deleteItem(deleteItemRequest); + return item.hasAttributes() && !item.attributes().isEmpty(); } @VisibleForTesting - static AttributeValue dynamoDbKey(final PaymentProvider processor, String processorItemId) { + static AttributeValue dynamoDbKey(final PaymentProvider processor, final String processorItemId) { if (processor == PaymentProvider.STRIPE) { // As the first processor, Stripe’s IDs were not prefixed. Its item IDs have documented prefixes (`il_`, `pi_`) // that will not collide with `SubscriptionProcessor` names @@ -141,18 +127,18 @@ public class IssuedReceiptsManager { @VisibleForTesting - byte[] generateIssuedReceiptTag(ReceiptCredentialRequest request) { + byte[] generateIssuedReceiptTag(final ReceiptCredentialRequest request) { return generateHmac("issuedReceiptTag", mac -> mac.update(request.serialize())); } - private byte[] generateHmac(String type, Consumer byteConsumer) { + private byte[] generateHmac(final String type, final Consumer byteConsumer) { try { - Mac mac = Mac.getInstance("HmacSHA256"); + final Mac mac = Mac.getInstance("HmacSHA256"); mac.init(new SecretKeySpec(receiptTagGenerator, "HmacSHA256")); mac.update(type.getBytes(StandardCharsets.UTF_8)); byteConsumer.accept(mac); return mac.doFinal(); - } catch (NoSuchAlgorithmException | InvalidKeyException e) { + } catch (final NoSuchAlgorithmException | InvalidKeyException e) { throw new AssertionError(e); } } diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/storage/OneTimeDonationsManager.java b/service/src/main/java/org/whispersystems/textsecuregcm/storage/OneTimeDonationsManager.java index 5eb300f28..afbaa4022 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/storage/OneTimeDonationsManager.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/storage/OneTimeDonationsManager.java @@ -12,11 +12,11 @@ import java.time.Duration; import java.time.Instant; import java.util.Map; import java.util.Objects; -import java.util.concurrent.CompletableFuture; import javax.annotation.Nonnull; import org.whispersystems.textsecuregcm.util.AttributeValues; -import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient; +import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.GetItemRequest; +import software.amazon.awssdk.services.dynamodb.model.GetItemResponse; import software.amazon.awssdk.services.dynamodb.model.PutItemRequest; public class OneTimeDonationsManager { @@ -27,18 +27,18 @@ public class OneTimeDonationsManager { private static final String ONETIME_DONATION_NOT_FOUND_COUNTER_NAME = name(OneTimeDonationsManager.class, "onetimeDonationNotFound"); private final String table; private final Duration ttl; - private final DynamoDbAsyncClient dynamoDbAsyncClient; + private final DynamoDbClient dynamoDbClient; public OneTimeDonationsManager( - @Nonnull String table, - @Nonnull Duration ttl, - @Nonnull DynamoDbAsyncClient dynamoDbAsyncClient) { + @Nonnull final String table, + @Nonnull final Duration ttl, + @Nonnull final DynamoDbClient dynamoDbClient) { this.table = Objects.requireNonNull(table); this.ttl = Objects.requireNonNull(ttl); - this.dynamoDbAsyncClient = Objects.requireNonNull(dynamoDbAsyncClient); + this.dynamoDbClient = Objects.requireNonNull(dynamoDbClient); } - public CompletableFuture getPaidAt(final String paymentId, final Instant fallbackTimestamp) { + public Instant getPaidAt(final String paymentId, final Instant fallbackTimestamp) { final GetItemRequest getItemRequest = GetItemRequest.builder() .consistentRead(Boolean.TRUE) .tableName(table) @@ -46,24 +46,22 @@ public class OneTimeDonationsManager { .projectionExpression(ATTR_PAID_AT) .build(); - return dynamoDbAsyncClient.getItem(getItemRequest).thenApply(getItemResponse -> { - if (!getItemResponse.hasItem()) { - Metrics.counter(ONETIME_DONATION_NOT_FOUND_COUNTER_NAME).increment(); - return fallbackTimestamp; - } + final GetItemResponse getItemResponse = dynamoDbClient.getItem(getItemRequest); + if (!getItemResponse.hasItem()) { + Metrics.counter(ONETIME_DONATION_NOT_FOUND_COUNTER_NAME).increment(); + return fallbackTimestamp; + } - return Instant.ofEpochSecond(AttributeValues.getLong(getItemResponse.item(), ATTR_PAID_AT, fallbackTimestamp.getEpochSecond())); - }); + return Instant.ofEpochSecond(AttributeValues.getLong(getItemResponse.item(), ATTR_PAID_AT, fallbackTimestamp.getEpochSecond())); } - public CompletableFuture putPaidAt(final String paymentId, final Instant paidAt) { - return dynamoDbAsyncClient.putItem(PutItemRequest.builder() + public void putPaidAt(final String paymentId, final Instant paidAt) { + dynamoDbClient.putItem(PutItemRequest.builder() .tableName(table) .item(Map.of( KEY_PAYMENT_ID, AttributeValues.fromString(paymentId), ATTR_PAID_AT, AttributeValues.fromLong(paidAt.getEpochSecond()), ATTR_TTL, AttributeValues.fromLong(paidAt.plus(ttl).getEpochSecond()))) - .build()) - .thenApply(unused -> paymentId); + .build()); } } diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/storage/SubscriptionManager.java b/service/src/main/java/org/whispersystems/textsecuregcm/storage/SubscriptionManager.java index e8de9f7f4..3f1441ca6 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/storage/SubscriptionManager.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/storage/SubscriptionManager.java @@ -12,6 +12,7 @@ import java.util.List; import java.util.Locale; import java.util.Objects; import java.util.Optional; +import java.util.concurrent.CompletionException; import java.util.function.BiFunction; import java.util.function.Function; import java.util.stream.Collectors; @@ -37,7 +38,9 @@ import org.whispersystems.textsecuregcm.subscriptions.SubscriptionNotFoundExcept import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPaymentRequiredException; import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorConflictException; import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorException; +import org.whispersystems.textsecuregcm.subscriptions.SubscriptionReceiptAlreadyRedeemedException; import org.whispersystems.textsecuregcm.subscriptions.SubscriptionReceiptRequestedForOpenPaymentException; +import org.whispersystems.textsecuregcm.util.ExceptionUtils; import org.whispersystems.textsecuregcm.util.ua.ClientPlatform; /** @@ -175,38 +178,41 @@ public class SubscriptionManager { * user an entitlement * @throws SubscriptionReceiptRequestedForOpenPaymentException if a receipt was requested while a payment transaction * was still open + * @throws SubscriptionReceiptAlreadyRedeemedException if the receipt was already redeemed by a different request * @throws RateLimitExceededException if rate-limited */ public ReceiptResult createReceiptCredentials( final SubscriberCredentials subscriberCredentials, final SubscriptionController.GetReceiptCredentialsRequest request, final Function expiration) - throws SubscriptionForbiddenException, SubscriptionNotFoundException, SubscriptionInvalidArgumentsException, SubscriptionPaymentRequiredException, RateLimitExceededException, SubscriptionReceiptRequestedForOpenPaymentException { + throws SubscriptionForbiddenException, SubscriptionNotFoundException, SubscriptionInvalidArgumentsException, SubscriptionPaymentRequiredException, RateLimitExceededException, SubscriptionReceiptRequestedForOpenPaymentException, SubscriptionReceiptAlreadyRedeemedException { final Subscriptions.Record record = getSubscriber(subscriberCredentials); if (record.subscriptionId == null) { throw new SubscriptionNotFoundException(); } - ReceiptCredentialRequest receiptCredentialRequest; + final ReceiptCredentialRequest receiptCredentialRequest; try { receiptCredentialRequest = new ReceiptCredentialRequest(request.receiptCredentialRequest()); - } catch (InvalidInputException e) { + } catch (final InvalidInputException e) { throw new SubscriptionInvalidArgumentsException("invalid receipt credential request", e); } final PaymentProvider processor = record.getProcessorCustomer().orElseThrow().processor(); final SubscriptionPaymentProcessor manager = getProcessor(processor); final SubscriptionPaymentProcessor.ReceiptItem receipt = manager.getReceiptItem(record.subscriptionId); - issuedReceiptsManager - .recordIssuance(receipt.itemId(), manager.getProvider(), receiptCredentialRequest, subscriberCredentials.now()); - ReceiptCredentialResponse receiptCredentialResponse; + final ReceiptCredentialResponse receiptCredentialResponse; try { + issuedReceiptsManager + .recordIssuance(receipt.itemId(), manager.getProvider(), receiptCredentialRequest, subscriberCredentials.now()); receiptCredentialResponse = zkReceiptOperations.issueReceiptCredential( receiptCredentialRequest, expiration.apply(receipt).getEpochSecond(), receipt.level()); - } catch (VerificationFailedException e) { + } catch (final VerificationFailedException e) { throw new SubscriptionInvalidArgumentsException("receipt credential request failed verification", e); + } catch (final WriteConflictException _) { + throw new SubscriptionReceiptAlreadyRedeemedException(); } return new ReceiptResult(receiptCredentialResponse, receipt, processor); } diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/SubscriptionReceiptAlreadyRedeemedException.java b/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/SubscriptionReceiptAlreadyRedeemedException.java new file mode 100644 index 000000000..842868ae4 --- /dev/null +++ b/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/SubscriptionReceiptAlreadyRedeemedException.java @@ -0,0 +1,16 @@ +/* + * Copyright 2026 Signal Messenger, LLC + * SPDX-License-Identifier: AGPL-3.0-only + */ +package org.whispersystems.textsecuregcm.subscriptions; + +public class SubscriptionReceiptAlreadyRedeemedException extends SubscriptionException { + + public SubscriptionReceiptAlreadyRedeemedException() { + super(null, null); + } + + public SubscriptionReceiptAlreadyRedeemedException(final String message) { + super(null, message); + } +} diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/workers/ClearIssuedReceiptRedemptionsCommand.java b/service/src/main/java/org/whispersystems/textsecuregcm/workers/ClearIssuedReceiptRedemptionsCommand.java index 14db0e34a..f8c648ff1 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/workers/ClearIssuedReceiptRedemptionsCommand.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/workers/ClearIssuedReceiptRedemptionsCommand.java @@ -68,7 +68,7 @@ public class ClearIssuedReceiptRedemptionsCommand extends AbstractCommandWithDep throw new IllegalStateException("Cannot clear issued receipts for a non-IAP processor: " + processorType); }; final SubscriptionPaymentProcessor.ReceiptItem receiptItem = processor.getReceiptItem(subscriber.subscriptionId); - final boolean deleted = issuedReceiptsManager.clearIssuance(receiptItem.itemId(), processorType).join(); + final boolean deleted = issuedReceiptsManager.clearIssuance(receiptItem.itemId(), processorType); logger.info("Deleted issuances for receiptItem: {}, subscriberId: {}, hadExistingIssuances: {}", receiptItem.itemId(), subscriberId, deleted); } catch (Exception ex) { diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/workers/CommandDependencies.java b/service/src/main/java/org/whispersystems/textsecuregcm/workers/CommandDependencies.java index 605024598..97d25bf26 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/workers/CommandDependencies.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/workers/CommandDependencies.java @@ -320,7 +320,7 @@ public record CommandDependencies( final IssuedReceiptsManager issuedReceiptsManager = new IssuedReceiptsManager( configuration.getDynamoDbTables().getIssuedReceipts().getTableName(), configuration.getDynamoDbTables().getIssuedReceipts().getExpiration(), - dynamoDbAsyncClient, + dynamoDbClient, configuration.getDynamoDbTables().getIssuedReceipts().getGenerator(), configuration.getDynamoDbTables().getIssuedReceipts().getmaxIssuedReceiptsPerPaymentId()); diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/controllers/OneTimeDonationControllerTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/controllers/OneTimeDonationControllerTest.java index 41230828a..3a3068b00 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/controllers/OneTimeDonationControllerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/controllers/OneTimeDonationControllerTest.java @@ -9,6 +9,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.when; @@ -20,12 +21,17 @@ import io.dropwizard.testing.junit5.ResourceExtension; import jakarta.ws.rs.client.Entity; import jakarta.ws.rs.core.Response; import java.time.Instant; +import java.util.Base64; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.stream.Stream; +import org.signal.libsignal.zkgroup.ServerSecretParams; +import org.signal.libsignal.zkgroup.receipts.ClientZkReceiptOperations; +import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialRequest; +import org.signal.libsignal.zkgroup.receipts.ReceiptSerial; import org.assertj.core.api.InstanceOfAssertFactories; import org.glassfish.jersey.server.ServerProperties; import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory; @@ -48,6 +54,7 @@ import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider; import org.whispersystems.textsecuregcm.subscriptions.PaymentStatus; import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorException; import org.whispersystems.textsecuregcm.tests.util.AuthHelper; +import org.whispersystems.textsecuregcm.storage.WriteConflictException; import org.whispersystems.textsecuregcm.util.SystemMapper; @ExtendWith(DropwizardExtensionsSupport.class) @@ -284,4 +291,28 @@ class OneTimeDonationControllerTest extends AbstractV1SubscriptionControllerTest assertThat(response.getStatus()).isEqualTo(422); } + @Test + void createBoostReceiptAlreadyRedeemed() throws Exception { + final ReceiptCredentialRequest receiptCredentialRequest = new ClientZkReceiptOperations( + ServerSecretParams.generate().getPublicParams()).createReceiptCredentialRequestContext( + new ReceiptSerial(new byte[ReceiptSerial.SIZE])).getRequest(); + + when(STRIPE_MANAGER.getPaymentDetails(any())).thenReturn(CompletableFuture.completedFuture(new PaymentDetails( + "id", + Collections.emptyMap(), + PaymentStatus.SUCCEEDED, + Instant.now(), + null))); + doThrow(WriteConflictException.class).when(ISSUED_RECEIPTS_MANAGER).recordIssuance(any(), any(), any(), any()); + + final Response response = RESOURCE_EXTENSION.target("/v1/subscription/boost/receipt_credentials") + .request() + .post(Entity.json(Map.of( + "paymentIntentId", "foo", + "receiptCredentialRequest", Base64.getEncoder().encodeToString(receiptCredentialRequest.serialize()), + "processor", "STRIPE" + ))); + assertThat(response.getStatus()).isEqualTo(409); + } + } diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/controllers/SubscriptionControllerTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/controllers/SubscriptionControllerTest.java index 1f49194ab..12b1a7b54 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/controllers/SubscriptionControllerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/controllers/SubscriptionControllerTest.java @@ -10,6 +10,7 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.times; @@ -90,6 +91,7 @@ import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPaymentRequire import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorConflictException; import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorException; import org.whispersystems.textsecuregcm.subscriptions.SubscriptionReceiptRequestedForOpenPaymentException; +import org.whispersystems.textsecuregcm.storage.WriteConflictException; import org.whispersystems.textsecuregcm.tests.util.AuthHelper; import org.whispersystems.textsecuregcm.util.MockUtils; import org.whispersystems.textsecuregcm.util.SystemMapper; @@ -782,6 +784,41 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest { .isEqualTo("card_declined"); } + @Test + void createReceiptCredentialAlreadyRedeemed() + throws InvalidInputException, VerificationFailedException, SubscriptionException, WriteConflictException { + final byte[] subscriberUserAndKey = new byte[32]; + Arrays.fill(subscriberUserAndKey, (byte) 1); + final String subscriberId = Base64.getEncoder().encodeToString(subscriberUserAndKey); + + when(CLOCK.instant()).thenReturn(Instant.now()); + when(SUBSCRIPTIONS.get(any(), any())) + .thenReturn(Subscriptions.GetResult.found(Subscriptions.Record.from( + Arrays.copyOfRange(subscriberUserAndKey, 0, 16), + Map.of(Subscriptions.KEY_PASSWORD, b(new byte[16]), + Subscriptions.KEY_CREATED_AT, n(Instant.now().getEpochSecond()), + Subscriptions.KEY_ACCESSED_AT, n(Instant.now().getEpochSecond()), + Subscriptions.KEY_PROCESSOR_ID_CUSTOMER_ID, + b(new ProcessorCustomer("customer", PaymentProvider.STRIPE).toDynamoBytes()), + Subscriptions.KEY_SUBSCRIPTION_ID, s("subscriptionId"))))); + when(STRIPE_MANAGER.getReceiptItem(any())) + .thenReturn(new CustomerAwareSubscriptionPaymentProcessor.ReceiptItem( + "itemId", + PaymentTime.periodStart(Instant.ofEpochSecond(10).plus(Duration.ofDays(1))), + 5L)); + doThrow(WriteConflictException.class).when(ISSUED_RECEIPTS_MANAGER).recordIssuance(any(), any(), any(), any()); + + final ReceiptCredentialRequest receiptRequest = new ClientZkReceiptOperations( + ServerSecretParams.generate().getPublicParams()).createReceiptCredentialRequestContext( + new ReceiptSerial(new byte[ReceiptSerial.SIZE])).getRequest(); + final Response response = RESOURCE_EXTENSION + .target(String.format("/v1/subscription/%s/receipt_credentials", subscriberId)) + .request() + .post(Entity.json(new SubscriptionController.GetReceiptCredentialsRequest(receiptRequest.serialize()))); + + assertThat(response.getStatus()).isEqualTo(409); + } + @ParameterizedTest @CsvSource({"5, P45D", "201, P13D"}) public void createReceiptCredential(long level, Duration expectedExpirationWindow) @@ -813,8 +850,6 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest { "itemId", PaymentTime.periodStart(Instant.ofEpochSecond(10).plus(Duration.ofDays(1))), level)); - when(ISSUED_RECEIPTS_MANAGER.recordIssuance(eq("itemId"), eq(PaymentProvider.BRAINTREE), eq(receiptRequest), any())) - .thenReturn(CompletableFuture.completedFuture(null)); when(ZK_OPS.issueReceiptCredential(any(), anyLong(), eq(level))).thenReturn(receiptCredentialResponse); when(receiptCredentialResponse.serialize()).thenReturn(new byte[0]); final Response response = RESOURCE_EXTENSION diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/storage/IssuedReceiptsManagerTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/storage/IssuedReceiptsManagerTest.java index 740dc8fa8..18e626462 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/IssuedReceiptsManagerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/storage/IssuedReceiptsManagerTest.java @@ -6,20 +6,18 @@ package org.whispersystems.textsecuregcm.storage; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -import jakarta.ws.rs.ClientErrorException; import java.time.Duration; import java.time.Instant; import java.util.EnumMap; import java.util.List; import java.util.Map; import java.util.Set; -import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors; import java.util.stream.IntStream; -import org.assertj.core.api.Condition; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; @@ -42,7 +40,7 @@ class IssuedReceiptsManagerTest { @RegisterExtension static final DynamoDbExtension DYNAMO_DB_EXTENSION = new DynamoDbExtension(Tables.ISSUED_RECEIPTS); - private static EnumMap MAX_TAGS_MAP = new EnumMap<>(Map.of( + private static final EnumMap MAX_TAGS_MAP = new EnumMap<>(Map.of( PaymentProvider.STRIPE, 1, PaymentProvider.BRAINTREE, 2, PaymentProvider.GOOGLE_PLAY_BILLING, 3, @@ -55,18 +53,17 @@ class IssuedReceiptsManagerTest { issuedReceiptsManager = new IssuedReceiptsManager( Tables.ISSUED_RECEIPTS.tableName(), Duration.ofDays(90), - DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient(), + DYNAMO_DB_EXTENSION.getDynamoDbClient(), TestRandomUtil.nextBytes(16), MAX_TAGS_MAP); } @Test - void testRecordIssuance() { - Instant now = Instant.ofEpochSecond(NOW_EPOCH_SECONDS); + void testRecordIssuance() throws WriteConflictException { + final Instant now = Instant.ofEpochSecond(NOW_EPOCH_SECONDS); final ReceiptCredentialRequest receiptCredentialRequest = randomReceiptCredentialRequest(); - CompletableFuture future = issuedReceiptsManager.recordIssuance("item-1", PaymentProvider.STRIPE, + issuedReceiptsManager.recordIssuance("item-1", PaymentProvider.STRIPE, receiptCredentialRequest, now); - assertThat(future).succeedsWithin(Duration.ofSeconds(3)); final Map item = getItem(PaymentProvider.STRIPE, "item-1").item(); final Set tagSet = item.get(IssuedReceiptsManager.KEY_ISSUED_RECEIPT_TAG_SET).bs() @@ -76,32 +73,25 @@ class IssuedReceiptsManagerTest { assertThat(tagSet).containsExactly(issuedReceiptsManager.generateIssuedReceiptTag(receiptCredentialRequest)); // same request should succeed - future = issuedReceiptsManager.recordIssuance("item-1", PaymentProvider.STRIPE, receiptCredentialRequest, + issuedReceiptsManager.recordIssuance("item-1", PaymentProvider.STRIPE, receiptCredentialRequest, now); - assertThat(future).succeedsWithin(Duration.ofSeconds(3)); // same item with new request should fail - byte[] request2 = TestRandomUtil.nextBytes(20); + final byte[] request2 = TestRandomUtil.nextBytes(20); when(receiptCredentialRequest.serialize()).thenReturn(request2); - future = issuedReceiptsManager.recordIssuance("item-1", PaymentProvider.STRIPE, receiptCredentialRequest, - now); - assertThat(future).failsWithin(Duration.ofSeconds(3)). - withThrowableOfType(Throwable.class). - havingCause(). - isExactlyInstanceOf(ClientErrorException.class). - has(new Condition<>( - e -> e instanceof ClientErrorException && ((ClientErrorException) e).getResponse().getStatus() == 409, - "status 409")); + assertThatThrownBy( + () -> issuedReceiptsManager.recordIssuance("item-1", PaymentProvider.STRIPE, receiptCredentialRequest, + now)) + .isExactlyInstanceOf(WriteConflictException.class); // different item with new request should be okay though - future = issuedReceiptsManager.recordIssuance("item-2", PaymentProvider.STRIPE, receiptCredentialRequest, + issuedReceiptsManager.recordIssuance("item-2", PaymentProvider.STRIPE, receiptCredentialRequest, now); - assertThat(future).succeedsWithin(Duration.ofSeconds(3)); } @ParameterizedTest @EnumSource(PaymentProvider.class) - void testIssueMax(PaymentProvider processor) { + void testIssueMax(final PaymentProvider processor) throws WriteConflictException { final Instant now = Instant.ofEpochSecond(NOW_EPOCH_SECONDS); final int maxTags = MAX_TAGS_MAP.get(processor); @@ -110,12 +100,10 @@ class IssuedReceiptsManagerTest { .toList(); for (int i = 0; i < maxTags; i++) { // Should be allowed to insert up to maxTags - assertThat(issuedReceiptsManager.recordIssuance("item-1", processor, requests.get(i), now)) - .succeedsWithin(Duration.ofSeconds(3)); + issuedReceiptsManager.recordIssuance("item-1", processor, requests.get(i), now); for (int j = 0; j < i; j++) { // Also should be allowed to repeat any previous tag - assertThat(issuedReceiptsManager.recordIssuance("item-1", processor, requests.get(j), now)) - .succeedsWithin(Duration.ofSeconds(3)); + issuedReceiptsManager.recordIssuance("item-1", processor, requests.get(j), now); } } @@ -128,14 +116,8 @@ class IssuedReceiptsManagerTest { .toArray(byte[][]::new)); // Should not be allowed to insert past maxTags - assertThat(issuedReceiptsManager.recordIssuance("item-1", processor, randomReceiptCredentialRequest(), now)) - .failsWithin(Duration.ofSeconds(3)) - .withThrowableOfType(Throwable.class) - .havingCause() - .isExactlyInstanceOf(ClientErrorException.class) - .has(new Condition<>( - e -> e instanceof ClientErrorException && ((ClientErrorException) e).getResponse().getStatus() == 409, - "status 409")); + assertThatThrownBy(() -> issuedReceiptsManager.recordIssuance("item-1", processor, randomReceiptCredentialRequest(), now)) + .isExactlyInstanceOf(WriteConflictException.class); } diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/storage/OnetimeDonationsManagerTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/storage/OnetimeDonationsManagerTest.java index 1ab2bee52..f73dec637 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/OnetimeDonationsManagerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/storage/OnetimeDonationsManagerTest.java @@ -23,7 +23,7 @@ public class OnetimeDonationsManagerTest { oneTimeDonationsManager = new OneTimeDonationsManager( DynamoDbExtensionSchema.Tables.ONETIME_DONATIONS.tableName(), Duration.ofDays(90), - DYNAMO_DB_EXTENSION.getDynamoDbAsyncClient()); + DYNAMO_DB_EXTENSION.getDynamoDbClient()); } @Test @@ -31,9 +31,9 @@ public class OnetimeDonationsManagerTest { final String validPaymentIntentId = "abc"; final Instant paidAt = Instant.ofEpochSecond(1_000_000); final Instant fallBackTimestamp = Instant.ofEpochSecond(2_000_000); - oneTimeDonationsManager.putPaidAt(validPaymentIntentId, paidAt).join(); + oneTimeDonationsManager.putPaidAt(validPaymentIntentId, paidAt); - assertThat(oneTimeDonationsManager.getPaidAt(validPaymentIntentId, fallBackTimestamp).join()).isEqualTo(paidAt); - assertThat(oneTimeDonationsManager.getPaidAt("invalidPaymentId", fallBackTimestamp).join()).isEqualTo(fallBackTimestamp); + assertThat(oneTimeDonationsManager.getPaidAt(validPaymentIntentId, fallBackTimestamp)).isEqualTo(paidAt); + assertThat(oneTimeDonationsManager.getPaidAt("invalidPaymentId", fallBackTimestamp)).isEqualTo(fallBackTimestamp); } }