mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-12-02 12:06:53 +00:00
Fix handling write conflicts when redeeming subscription receipt
credentials
This commit is contained in:
1 parent
d6c7c5e7bf
commit
50ef5272f7
13 files changed
+223
-163
No files matched your search
@@ -735,11 +735,11 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
IssuedReceiptsManager issuedReceiptsManager = new IssuedReceiptsManager(
|
||||
config.getDynamoDbTables().getIssuedReceipts().getTableName(),
|
||||
config.getDynamoDbTables().getIssuedReceipts().getExpiration(),
|
||||
dynamoDbAsyncClient,
|
||||
dynamoDbClient,
|
||||
config.getDynamoDbTables().getIssuedReceipts().getGenerator(),
|
||||
config.getDynamoDbTables().getIssuedReceipts().getmaxIssuedReceiptsPerPaymentId());
|
||||
OneTimeDonationsManager oneTimeDonationsManager = new OneTimeDonationsManager(
|
||||
config.getDynamoDbTables().getOnetimeDonations().getTableName(), config.getDynamoDbTables().getOnetimeDonations().getExpiration(), dynamoDbAsyncClient);
|
||||
config.getDynamoDbTables().getOnetimeDonations().getTableName(), config.getDynamoDbTables().getOnetimeDonations().getExpiration(), dynamoDbClient);
|
||||
RedeemedReceiptsManager redeemedReceiptsManager = new RedeemedReceiptsManager(clock,
|
||||
config.getDynamoDbTables().getRedeemedReceipts().getTableName(),
|
||||
dynamoDbClient,
|
||||
|
||||
+35
-31
@@ -58,6 +58,7 @@ import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.IssuedReceiptsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.OneTimeDonationsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.WriteConflictException;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.BraintreeManager;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.ChargeFailure;
|
||||
import org.whispersystems.textsecuregcm.subscriptions.CustomerAwareSubscriptionPaymentProcessor;
|
||||
@@ -309,10 +310,11 @@ public class OneTimeDonationController {
|
||||
validateRequestCurrencyAmount(request, BigDecimal.valueOf(request.amount), braintreeManager))
|
||||
.thenCompose(_ -> 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();
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
+7
-5
@@ -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<SubscriptionException> {
|
||||
@VisibleForTesting
|
||||
@@ -56,11 +57,12 @@ public class SubscriptionExceptionMapper implements ExceptionMapper<Subscription
|
||||
|
||||
// Otherwise, we'll return a generic error message WebApplicationException, with a detailed error if one is provided
|
||||
final Response.Status status = (switch (exception) {
|
||||
case SubscriptionNotFoundException e -> 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;
|
||||
});
|
||||
|
||||
|
||||
+41
-55
@@ -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<PaymentProvider, Integer> maxIssuedReceiptsPerPaymentId;
|
||||
|
||||
public IssuedReceiptsManager(
|
||||
@Nonnull String table,
|
||||
@Nonnull Duration expiration,
|
||||
@Nonnull DynamoDbAsyncClient dynamoDbAsyncClient,
|
||||
@Nonnull byte[] receiptTagGenerator,
|
||||
@Nonnull EnumMap<PaymentProvider, Integer> maxIssuedReceiptsPerPaymentId) {
|
||||
@Nonnull final String table,
|
||||
@Nonnull final Duration expiration,
|
||||
@Nonnull final DynamoDbClient dynamoDbClient,
|
||||
@Nonnull final byte[] receiptTagGenerator,
|
||||
@Nonnull final EnumMap<PaymentProvider, Integer> 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.
|
||||
* <p>
|
||||
* If this item has already been used to issue another receipt, throws a 409 conflict web application exception.
|
||||
* <p>
|
||||
* For {@link PaymentProvider#STRIPE}, item is expected to refer to an invoice line item (subscriptions) or a
|
||||
* payment intent (one-time).
|
||||
*/
|
||||
public CompletableFuture<Void> 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<Boolean> 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<Mac> byteConsumer) {
|
||||
private byte[] generateHmac(final String type, final Consumer<Mac> 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);
|
||||
}
|
||||
}
|
||||
|
||||
+17
-19
@@ -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<Instant> 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<String> 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());
|
||||
}
|
||||
}
|
||||
+13
-7
@@ -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<CustomerAwareSubscriptionPaymentProcessor.ReceiptItem, Instant> 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);
|
||||
}
|
||||
|
||||
+16
@@ -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);
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -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) {
|
||||
|
||||
+1
-1
@@ -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());
|
||||
|
||||
|
||||
Reference in new issue
Block a user