mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-12-02 15:56:53 +00:00
Add LoginPurchaseManager
This commit is contained in:
1 parent
894cd8e0a3
commit
7a34493d53
2 files changed
+264
No files matched your search
+107
@@ -0,0 +1,107 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.subscriptions;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import org.signal.libsignal.zkgroup.VerificationFailedException;
|
||||
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialRequest;
|
||||
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialResponse;
|
||||
import org.signal.libsignal.zkgroup.receipts.ServerZkReceiptOperations;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.storage.IssuedReceiptsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.WriteConflictException;
|
||||
|
||||
public class LoginPurchaseManager {
|
||||
|
||||
private final Map<PaymentProvider, OneTimePaymentProcessor> oneTimePaymentProcessors;
|
||||
private final IssuedReceiptsManager issuedReceiptsManager;
|
||||
private final ServerZkReceiptOperations zkReceiptOperations;
|
||||
private final long loginLevel;
|
||||
private final Clock clock;
|
||||
|
||||
// Signal Login receipt credentials expire after 5 years
|
||||
@VisibleForTesting
|
||||
final static Duration LOGIN_EXPIRATION = Duration.ofDays(366 * 5);
|
||||
|
||||
/// Construct a LoginPurchaseManager
|
||||
///
|
||||
/// @param oneTimePaymentProcessors The processor to use for each supported [PaymentProvider]
|
||||
/// @param issuedReceiptsManager Tracks which purchases have already had receipt credentials issued for them
|
||||
/// @param zkReceiptOperations Used to issue receipt credentials
|
||||
/// @param loginLevel The receipt level that identifies a Signal Login purchase. Purchases for any other
|
||||
/// level are rejected.
|
||||
/// @param clock A clock
|
||||
public LoginPurchaseManager(
|
||||
final Map<PaymentProvider, OneTimePaymentProcessor> oneTimePaymentProcessors,
|
||||
final IssuedReceiptsManager issuedReceiptsManager,
|
||||
final ServerZkReceiptOperations zkReceiptOperations,
|
||||
final long loginLevel,
|
||||
final Clock clock) {
|
||||
this.oneTimePaymentProcessors = oneTimePaymentProcessors;
|
||||
this.issuedReceiptsManager = issuedReceiptsManager;
|
||||
this.zkReceiptOperations = zkReceiptOperations;
|
||||
this.loginLevel = loginLevel;
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
/// Verify a completed one-time purchase and issue a receipt credential for it.
|
||||
///
|
||||
/// Repeated calls must use the same `receiptCredentialRequest`; a second request for a purchase that was already
|
||||
/// redeemed fails with [SubscriptionReceiptAlreadyRedeemedException].
|
||||
///
|
||||
/// @param paymentProvider The provider that processed the purchase
|
||||
/// @param purchaseId The identifier for the purchase in the `paymentProvider`
|
||||
/// @param receiptCredentialRequest The request for the receipt to generate. All retries for the same purchaseId must
|
||||
/// use the same request
|
||||
/// @return The receipt credential
|
||||
///
|
||||
public ReceiptCredentialResponse generateReceipt(
|
||||
final PaymentProvider paymentProvider,
|
||||
final String purchaseId,
|
||||
final ReceiptCredentialRequest receiptCredentialRequest)
|
||||
throws RateLimitExceededException, SubscriptionInvalidArgumentsException, IOException, SubscriptionNotFoundException, SubscriptionReceiptRequestedForOpenPaymentException, SubscriptionPaymentRequiredException, SubscriptionReceiptAlreadyRedeemedException, VerificationFailedException {
|
||||
|
||||
final OneTimePaymentProcessor oneTimePaymentProcessor = oneTimePaymentProcessors.get(paymentProvider);
|
||||
if (oneTimePaymentProcessor == null) {
|
||||
throw new SubscriptionInvalidArgumentsException("unknown payment provider: " + paymentProvider);
|
||||
}
|
||||
|
||||
final PaymentDetails paymentDetails = oneTimePaymentProcessor
|
||||
.claimOneTimePurchase(purchaseId)
|
||||
.orElseThrow(SubscriptionNotFoundException::new);
|
||||
if (paymentDetails.status() == PaymentStatus.PROCESSING) {
|
||||
throw new SubscriptionReceiptRequestedForOpenPaymentException();
|
||||
} else if (paymentDetails.status() != PaymentStatus.SUCCEEDED) {
|
||||
throw Optional.ofNullable(paymentDetails.chargeFailure())
|
||||
.<SubscriptionPaymentRequiredException>map(
|
||||
cf -> new SubscriptionChargeFailurePaymentRequiredException(paymentProvider, cf))
|
||||
.orElseGet(SubscriptionPaymentRequiredException::new);
|
||||
} else if (paymentDetails.level() == null || paymentDetails.level() != loginLevel) {
|
||||
throw new SubscriptionInvalidArgumentsException("purchase was for an unexpected product");
|
||||
}
|
||||
|
||||
try {
|
||||
issuedReceiptsManager.recordIssuance(paymentDetails.id(), paymentProvider, receiptCredentialRequest,
|
||||
clock.instant());
|
||||
} catch (WriteConflictException _) {
|
||||
throw new SubscriptionReceiptAlreadyRedeemedException();
|
||||
}
|
||||
|
||||
// Calculating the expiration from the creation date works for IAP purchases. However, for other processors, the
|
||||
// creation date of the payment intent might be days before the payment actually completed. If we support non-IAP
|
||||
// processors we should attempt to get the latest date. see OneTimeDonationController/OneTimeDonationManager
|
||||
final Instant expiration = paymentDetails.created().plus(LOGIN_EXPIRATION).truncatedTo(ChronoUnit.DAYS);
|
||||
|
||||
return zkReceiptOperations.issueReceiptCredential(
|
||||
receiptCredentialRequest, expiration.getEpochSecond(), loginLevel);
|
||||
}
|
||||
}
|
||||
+157
@@ -0,0 +1,157 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.subscriptions;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Stream;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.signal.libsignal.zkgroup.ServerSecretParams;
|
||||
import org.signal.libsignal.zkgroup.receipts.ClientZkReceiptOperations;
|
||||
import org.signal.libsignal.zkgroup.receipts.ReceiptCredential;
|
||||
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialRequestContext;
|
||||
import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialResponse;
|
||||
import org.signal.libsignal.zkgroup.receipts.ReceiptSerial;
|
||||
import org.signal.libsignal.zkgroup.receipts.ServerZkReceiptOperations;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.storage.IssuedReceiptsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.WriteConflictException;
|
||||
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class LoginPurchaseManagerTest {
|
||||
|
||||
private static final PaymentProvider PROVIDER = PaymentProvider.APPLE_APP_STORE;
|
||||
private static final String PURCHASE_ID = "purchaseId";
|
||||
private static final long LEVEL = 123L;
|
||||
private static final Instant NOW = Instant.now();
|
||||
private static final Instant PURCHASED_AT = NOW.minus(Duration.ofHours(3));
|
||||
private static final ChargeFailure CHARGE_FAILURE =
|
||||
new ChargeFailure("generic_decline", "some failure message", null, null, null);
|
||||
|
||||
private static final ServerSecretParams SERVER_SECRET_PARAMS = ServerSecretParams.generate();
|
||||
|
||||
@Mock
|
||||
private OneTimePaymentProcessor paymentProcessor;
|
||||
@Mock
|
||||
private IssuedReceiptsManager issuedReceiptsManager;
|
||||
|
||||
private final ClientZkReceiptOperations clientZkReceiptOperations =
|
||||
new ClientZkReceiptOperations(SERVER_SECRET_PARAMS.getPublicParams());
|
||||
|
||||
private ReceiptCredentialRequestContext receiptCredentialRequestContext;
|
||||
private LoginPurchaseManager loginPurchaseManager;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
receiptCredentialRequestContext = clientZkReceiptOperations.createReceiptCredentialRequestContext(
|
||||
new ReceiptSerial(TestRandomUtil.nextBytes(ReceiptSerial.SIZE)));
|
||||
|
||||
loginPurchaseManager = new LoginPurchaseManager(
|
||||
Map.of(PROVIDER, paymentProcessor),
|
||||
issuedReceiptsManager,
|
||||
new ServerZkReceiptOperations(SERVER_SECRET_PARAMS),
|
||||
LEVEL,
|
||||
Clock.fixed(NOW, ZoneOffset.UTC));
|
||||
}
|
||||
|
||||
@Test
|
||||
void generateReceiptSuccess() throws Exception {
|
||||
when(paymentProcessor.claimOneTimePurchase(PURCHASE_ID))
|
||||
.thenReturn(Optional.of(new PaymentDetails(PURCHASE_ID, LEVEL, PaymentStatus.SUCCEEDED, PURCHASED_AT, null)));
|
||||
|
||||
final ReceiptCredentialResponse receipt =
|
||||
loginPurchaseManager.generateReceipt(PROVIDER, PURCHASE_ID, receiptCredentialRequestContext.getRequest());
|
||||
final ReceiptCredential receiptCredential =
|
||||
clientZkReceiptOperations.receiveReceiptCredential(receiptCredentialRequestContext, receipt);
|
||||
|
||||
assertThat(receiptCredential.getReceiptLevel()).isEqualTo(LEVEL);
|
||||
assertThat(receiptCredential.getReceiptExpirationTime()).isEqualTo(PURCHASED_AT
|
||||
.plus(LoginPurchaseManager.LOGIN_EXPIRATION)
|
||||
.truncatedTo(ChronoUnit.DAYS)
|
||||
.getEpochSecond());
|
||||
|
||||
verify(issuedReceiptsManager).recordIssuance(
|
||||
PURCHASE_ID, PROVIDER, receiptCredentialRequestContext.getRequest(), NOW);
|
||||
}
|
||||
|
||||
static Stream<Arguments> generateReceiptErrors() {
|
||||
return Stream.of(
|
||||
Arguments.of(Optional.empty(), SubscriptionNotFoundException.class),
|
||||
Arguments.of(
|
||||
Optional.of(new PaymentDetails(PURCHASE_ID, LEVEL, PaymentStatus.PROCESSING, PURCHASED_AT, null)),
|
||||
SubscriptionReceiptRequestedForOpenPaymentException.class),
|
||||
Arguments.of(
|
||||
Optional.of(new PaymentDetails(PURCHASE_ID, LEVEL, PaymentStatus.FAILED, PURCHASED_AT, CHARGE_FAILURE)),
|
||||
SubscriptionChargeFailurePaymentRequiredException.class),
|
||||
Arguments.of(
|
||||
Optional.of(new PaymentDetails(PURCHASE_ID, LEVEL, PaymentStatus.FAILED, PURCHASED_AT, null)),
|
||||
SubscriptionPaymentRequiredException.class),
|
||||
Arguments.of(Optional.of(new PaymentDetails(PURCHASE_ID, LEVEL, PaymentStatus.UNKNOWN, PURCHASED_AT, null)),
|
||||
SubscriptionPaymentRequiredException.class));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void generateReceiptErrors(final Optional<PaymentDetails> paymentDetails, final Class<? extends Exception> expectedException)
|
||||
throws SubscriptionInvalidArgumentsException, RateLimitExceededException, IOException {
|
||||
when(paymentProcessor.claimOneTimePurchase(PURCHASE_ID)).thenReturn(paymentDetails);
|
||||
assertThatExceptionOfType(expectedException).isThrownBy(() -> {
|
||||
loginPurchaseManager.generateReceipt(PROVIDER, PURCHASE_ID, receiptCredentialRequestContext.getRequest());
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void generateReceiptUnknownLevel() throws Exception {
|
||||
when(paymentProcessor.claimOneTimePurchase(PURCHASE_ID))
|
||||
.thenReturn(Optional.of(new PaymentDetails(PURCHASE_ID, null, PaymentStatus.SUCCEEDED, PURCHASED_AT, null)));
|
||||
assertThatExceptionOfType(SubscriptionInvalidArgumentsException.class).isThrownBy(() -> {
|
||||
loginPurchaseManager.generateReceipt(PROVIDER, PURCHASE_ID, receiptCredentialRequestContext.getRequest());
|
||||
});
|
||||
verifyNoInteractions(issuedReceiptsManager);
|
||||
}
|
||||
|
||||
@Test
|
||||
void generateReceiptNonLoginLevel() throws Exception {
|
||||
when(paymentProcessor.claimOneTimePurchase(PURCHASE_ID))
|
||||
.thenReturn(Optional.of(new PaymentDetails(PURCHASE_ID, LEVEL + 1, PaymentStatus.SUCCEEDED, PURCHASED_AT, null)));
|
||||
assertThatExceptionOfType(SubscriptionInvalidArgumentsException.class).isThrownBy(() -> {
|
||||
loginPurchaseManager.generateReceipt(PROVIDER, PURCHASE_ID, receiptCredentialRequestContext.getRequest());
|
||||
});
|
||||
verifyNoInteractions(issuedReceiptsManager);
|
||||
}
|
||||
|
||||
@Test
|
||||
void generateReceiptAlreadyRedeemed() throws Exception {
|
||||
when(paymentProcessor.claimOneTimePurchase(PURCHASE_ID))
|
||||
.thenReturn(Optional.of(new PaymentDetails(PURCHASE_ID, LEVEL, PaymentStatus.SUCCEEDED, PURCHASED_AT, null)));
|
||||
doThrow(new WriteConflictException())
|
||||
.when(issuedReceiptsManager).recordIssuance(any(), any(), any(), any());
|
||||
assertThatExceptionOfType(SubscriptionReceiptAlreadyRedeemedException.class).isThrownBy(() -> {
|
||||
loginPurchaseManager.generateReceipt(PROVIDER, PURCHASE_ID, receiptCredentialRequestContext.getRequest());
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user