diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerService.java b/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerService.java index d082d9241..6ba137e82 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerService.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerService.java @@ -180,6 +180,7 @@ import org.whispersystems.textsecuregcm.grpc.PaymentsGrpcService; import org.whispersystems.textsecuregcm.grpc.ProfileAnonymousGrpcService; import org.whispersystems.textsecuregcm.grpc.ProfileGrpcService; import org.whispersystems.textsecuregcm.grpc.RequestAttributesInterceptor; +import org.whispersystems.textsecuregcm.grpc.SubscriptionsGrpcService; import org.whispersystems.textsecuregcm.grpc.ValidatingInterceptor; import org.whispersystems.textsecuregcm.grpc.net.ManagedEventLoopGroup; import org.whispersystems.textsecuregcm.grpc.net.ManagedGrpcServer; @@ -949,6 +950,10 @@ public class WhisperServerService extends Application spamFilters = ServiceLoader.load(SpamFilter.class) .stream() .map(ServiceLoader.Provider::get) @@ -1080,7 +1085,10 @@ public class WhisperServerService extends Application ServerInterceptors.intercept(bindableService, // Note: interceptors run in the reverse order they are added; the remote deprecation filter // depends on the user-agent context so it has to come first here! @@ -1231,18 +1239,13 @@ public class WhisperServerService extends Application buildCurrencyConfiguration() { - final List subscriptionPaymentProcessors = List.of(stripeManager, braintreeManager); - return oneTimeDonationConfiguration.currencies() - .entrySet().stream() - .collect(Collectors.toMap(Entry::getKey, currencyAndConfig -> { - final String currency = currencyAndConfig.getKey(); - final OneTimeDonationCurrencyConfiguration currencyConfig = currencyAndConfig.getValue(); - - final Map> oneTimeLevelsToSuggestedAmounts = Map.of( - String.valueOf(oneTimeDonationConfiguration.boost().level()), currencyConfig.boosts(), - String.valueOf(oneTimeDonationConfiguration.gift().level()), List.of(currencyConfig.gift()) - ); - - final Function, Map> extractSubscriptionAmounts = levels -> - levels.entrySet().stream() - .filter(levelIdAndConfig -> levelIdAndConfig.getValue().prices().containsKey(currency)) - .collect(Collectors.toMap( - levelIdAndConfig -> String.valueOf(levelIdAndConfig.getKey()), - levelIdAndConfig -> levelIdAndConfig.getValue().prices().get(currency).amount())); - - final List supportedPaymentMethods = Arrays.stream(PaymentMethod.values()) - .filter(paymentMethod -> subscriptionPaymentProcessors.stream() - .anyMatch(manager -> manager.supportsPaymentMethod(paymentMethod) - && manager.getSupportedCurrenciesForPaymentMethod(paymentMethod).contains(currency))) - .map(PaymentMethod::name) - .collect(Collectors.toList()); - - if (supportedPaymentMethods.isEmpty()) { - throw new RuntimeException("Configuration has currency with no processor support: " + currency); - } - - return new CurrencyConfiguration( - currencyConfig.minimum(), - oneTimeLevelsToSuggestedAmounts, - extractSubscriptionAmounts.apply(subscriptionConfiguration.getDonationLevels()), - extractSubscriptionAmounts.apply(subscriptionConfiguration.getBackupLevels()), - supportedPaymentMethods); - })); - } @VisibleForTesting GetSubscriptionConfigurationResponse buildGetSubscriptionConfigurationResponse( final List acceptableLanguages) { - final Map donationLevels = new HashMap<>(); - - subscriptionConfiguration.getDonationLevels().forEach((levelId, levelConfig) -> { - final LevelConfiguration levelConfiguration = new LevelConfiguration( - "" /* deprecated and unused */, - badgeTranslator.translate(acceptableLanguages, levelConfig.badge())); - donationLevels.put(String.valueOf(levelId), levelConfiguration); - }); - - final Badge boostBadge = badgeTranslator.translate(acceptableLanguages, - oneTimeDonationConfiguration.boost().badge()); - donationLevels.put(String.valueOf(oneTimeDonationConfiguration.boost().level()), - new LevelConfiguration( - "" /* deprecated and unused */, - // NB: the one-time badges are PurchasableBadge, which has a `duration` field - new PurchasableBadge( - boostBadge, - oneTimeDonationConfiguration.boost().expiration()))); - - final Badge giftBadge = badgeTranslator.translate(acceptableLanguages, oneTimeDonationConfiguration.gift().badge()); - donationLevels.put(String.valueOf(oneTimeDonationConfiguration.gift().level()), - new LevelConfiguration( - "" /* deprecated and unused */, - new PurchasableBadge( - giftBadge, - oneTimeDonationConfiguration.gift().expiration()))); final long maxTotalBackupMediaBytes = dynamicConfigurationManager.getConfiguration().getBackupConfiguration().maxTotalMediaSize(); @@ -224,7 +155,11 @@ public class SubscriptionController { e.getValue().playProductId(), e.getValue().mediaTtl().toDays()))); - return new GetSubscriptionConfigurationResponse(buildCurrencyConfiguration(), donationLevels, + return new GetSubscriptionConfigurationResponse( + buildCurrencyConfiguration(List.of(stripeManager, braintreeManager), oneTimeDonationConfiguration, + subscriptionConfiguration), + buildDonationLevelsConfiguration(subscriptionConfiguration, oneTimeDonationConfiguration, badgeTranslator, + acceptableLanguages), new BackupConfiguration(backupLevels, subscriptionConfiguration.getbackupFreeTierMediaDuration().toDays()), oneTimeDonationConfiguration.sepaMaximumEuros()); } @@ -542,33 +477,12 @@ public class SubscriptionController { @Schema(description = "A map of lower-cased ISO 3 currency codes to minimums and level-specific scalar amounts") Map currencies, @Schema(description = "A map of numeric donation level IDs to level-specific badge configuration") - Map levels, + Map levels, @Schema(description = "Backup specific configuration") BackupConfiguration backup, @Schema(description = "The maximum value of a one-time donation SEPA transaction") BigDecimal sepaMaximumEuros) {} - @Schema(description = "Configuration for a currency - use to present appropriate client interfaces") - public record CurrencyConfiguration( - @Schema(description = "The minimum amount that may be submitted for a one-time donation in the currency") - BigDecimal minimum, - @Schema(description = "A map of numeric one-time donation level IDs to the list of default amounts to be presented") - Map> oneTime, - @Schema(description = "A map of numeric subscription level IDs to the amount charged for that level") - Map subscription, - @Schema(description = "A map of numeric backup level IDs to the amount charged for that level") - Map backupSubscription, - @Schema(description = "The payment methods that support the given currency") - List supportedPaymentMethods) {} - - @Schema(description = "Configuration for a donation level - use to present appropriate client interfaces") - public record LevelConfiguration( - @Deprecated(forRemoval = true) // may be removed after 2025-01-28 - @Schema(description = "The localized name for the level") - String name, - @Schema(description = "The displayable badge associated with the level") - Badge badge) {} - public record BackupConfiguration( @Schema(description = "A map of numeric backup level IDs to level-specific backup configuration") Map levels, @@ -768,7 +682,8 @@ public class SubscriptionController { SubscriberCredentials subscriberCredentials = SubscriberCredentials.process(authenticatedAccount, subscriberId, clock); try { final SubscriptionManager.ReceiptResult receiptCredential = subscriptionManager.createReceiptCredentials( - subscriberCredentials, request, this::receiptExpirationWithGracePeriod); + subscriberCredentials, request.receiptCredentialRequest(), + r -> SubscriptionsUtil.receiptExpirationWithGracePeriod(subscriptionConfiguration, r)); final ReceiptCredentialResponse receiptCredentialResponse = receiptCredential.receiptCredentialResponse(); final CustomerAwareSubscriptionPaymentProcessor.ReceiptItem receipt = receiptCredential.receiptItem(); @@ -823,19 +738,6 @@ public class SubscriptionController { } } - private Instant receiptExpirationWithGracePeriod(CustomerAwareSubscriptionPaymentProcessor.ReceiptItem receiptItem) { - final PaymentTime paymentTime = receiptItem.paymentTime(); - return switch (subscriptionConfiguration.getSubscriptionLevel(receiptItem.level()).type()) { - case DONATION -> paymentTime.receiptExpiration( - subscriptionConfiguration.getBadgeExpiration(), - subscriptionConfiguration.getBadgeGracePeriod()); - case BACKUP -> paymentTime.receiptExpiration( - subscriptionConfiguration.getBackupExpiration(), - subscriptionConfiguration.getBackupGracePeriod()); - }; - } - - private String getSubscriptionTemplateId(long level, String currency, PaymentProvider processor) { final SubscriptionLevelConfiguration config = subscriptionConfiguration.getSubscriptionLevel(level); if (config == null) { @@ -854,13 +756,4 @@ public class SubscriptionController { SetSubscriptionLevelErrorResponse.Error.Type.UNSUPPORTED_CURRENCY, null)))) .build())); } - - @Nullable - private static ClientPlatform getClientPlatform(@Nullable final String userAgentString) { - try { - return UserAgentUtil.parseUserAgentString(userAgentString).platform(); - } catch (final UnrecognizedUserAgentException e) { - return null; - } - } } diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/ProfileGrpcHelper.java b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/ProfileGrpcHelper.java index 7b9c02679..1f3f999de 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/ProfileGrpcHelper.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/ProfileGrpcHelper.java @@ -15,8 +15,8 @@ import java.util.HexFormat; import java.util.List; import java.util.Optional; import java.util.UUID; -import org.signal.chat.profile.Badge; -import org.signal.chat.profile.BadgeSvg; +import org.signal.chat.common.Badge; +import org.signal.chat.common.BadgeSvg; import org.signal.chat.profile.DataEtag; import org.signal.chat.profile.GetExpiringProfileKeyCredentialResult; import org.signal.chat.profile.GetUnversionedProfileResult; diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/SubscriptionsGrpcService.java b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/SubscriptionsGrpcService.java new file mode 100644 index 000000000..43a2350a1 --- /dev/null +++ b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/SubscriptionsGrpcService.java @@ -0,0 +1,554 @@ +package org.whispersystems.textsecuregcm.grpc; + +import static org.whispersystems.textsecuregcm.grpc.SubscriptionsUtil.getClientPlatform; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Empty; +import java.math.BigDecimal; +import java.time.Clock; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Optional; +import java.util.stream.Collectors; +import org.signal.chat.errors.FailedPrecondition; +import org.signal.chat.errors.FailedUnidentifiedAuthorization; +import org.signal.chat.errors.NotFound; +import org.signal.chat.subscriptions.CreatePayPalPaymentMethodRequest; +import org.signal.chat.subscriptions.CreatePayPalPaymentMethodResponse; +import org.signal.chat.subscriptions.CreatePaymentMethodRequest; +import org.signal.chat.subscriptions.CreatePaymentMethodResponse; +import org.signal.chat.subscriptions.DeleteSubscriberRequest; +import org.signal.chat.subscriptions.DeleteSubscriberResponse; +import org.signal.chat.subscriptions.GetBankMandateRequest; +import org.signal.chat.subscriptions.GetBankMandateResponse; +import org.signal.chat.subscriptions.GetConfigurationRequest; +import org.signal.chat.subscriptions.GetConfigurationResponse; +import org.signal.chat.subscriptions.GetReceiptCredentialsRequest; +import org.signal.chat.subscriptions.GetReceiptCredentialsResponse; +import org.signal.chat.subscriptions.GetSubscriptionInformationRequest; +import org.signal.chat.subscriptions.GetSubscriptionInformationResponse; +import org.signal.chat.subscriptions.PaymentMethod; +import org.signal.chat.subscriptions.SetDefaultPaymentMethodRequest; +import org.signal.chat.subscriptions.SetDefaultPaymentMethodResponse; +import org.signal.chat.subscriptions.SetIapSubscriptionRequest; +import org.signal.chat.subscriptions.SetIapSubscriptionResponse; +import org.signal.chat.subscriptions.SetSubscriptionLevelRequest; +import org.signal.chat.subscriptions.SetSubscriptionLevelResponse; +import org.signal.chat.subscriptions.SimpleSubscriptionsGrpc; +import org.signal.chat.subscriptions.UpdateSubscriberRequest; +import org.signal.chat.subscriptions.UpdateSubscriberResponse; +import org.whispersystems.textsecuregcm.badges.BadgeTranslator; +import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfiguration; +import org.whispersystems.textsecuregcm.configuration.SubscriptionConfiguration; +import org.whispersystems.textsecuregcm.configuration.SubscriptionLevelConfiguration; +import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration; +import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException; +import org.whispersystems.textsecuregcm.entities.Badge; +import org.whispersystems.textsecuregcm.entities.PurchasableBadge; +import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager; +import org.whispersystems.textsecuregcm.storage.SubscriberCredentials; +import org.whispersystems.textsecuregcm.storage.SubscriptionManager; +import org.whispersystems.textsecuregcm.storage.Subscriptions; +import org.whispersystems.textsecuregcm.subscriptions.AppleAppStoreManager; +import org.whispersystems.textsecuregcm.subscriptions.BankMandateTranslator; +import org.whispersystems.textsecuregcm.subscriptions.BankTransferType; +import org.whispersystems.textsecuregcm.subscriptions.BraintreeManager; +import org.whispersystems.textsecuregcm.subscriptions.ChargeFailure; +import org.whispersystems.textsecuregcm.subscriptions.CurrencyConfiguration; +import org.whispersystems.textsecuregcm.subscriptions.CustomerAwareSubscriptionPaymentProcessor; +import org.whispersystems.textsecuregcm.subscriptions.GooglePlayBillingManager; +import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider; +import org.whispersystems.textsecuregcm.subscriptions.ProcessorCustomer; +import org.whispersystems.textsecuregcm.subscriptions.StripeManager; +import org.whispersystems.textsecuregcm.subscriptions.SubscriptionChargeFailurePaymentRequiredException; +import org.whispersystems.textsecuregcm.subscriptions.SubscriptionForbiddenException; +import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInformation; +import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidArgumentsException; +import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidIdempotencyKeyException; +import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidLevelException; +import org.whispersystems.textsecuregcm.subscriptions.SubscriptionNotFoundException; +import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPaymentRequiredException; +import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPaymentRequiresActionException; +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.subscriptions.SubscriptionStatus; + +public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.SubscriptionsImplBase { + + private final Clock clock; + private final SubscriptionConfiguration subscriptionConfiguration; + private final OneTimeDonationConfiguration oneTimeDonationConfiguration; + private final SubscriptionManager subscriptionManager; + private final StripeManager stripeManager; + private final BraintreeManager braintreeManager; + private final GooglePlayBillingManager googlePlayBillingManager; + private final AppleAppStoreManager appleAppStoreManager; + private final BadgeTranslator badgeTranslator; + private final BankMandateTranslator bankMandateTranslator; + private final DynamicConfigurationManager dynamicConfigurationManager; + + public SubscriptionsGrpcService(final Clock clock, final SubscriptionConfiguration subscriptionConfiguration, + final OneTimeDonationConfiguration oneTimeDonationConfiguration, final SubscriptionManager subscriptionManager, + final StripeManager stripeManager, final BraintreeManager braintreeManager, + final GooglePlayBillingManager googlePlayBillingManager, final AppleAppStoreManager appleAppStoreManager, + final BadgeTranslator badgeTranslator, final BankMandateTranslator bankMandateTranslator, + final DynamicConfigurationManager dynamicConfigurationManager) { + this.clock = clock; + this.subscriptionConfiguration = subscriptionConfiguration; + this.oneTimeDonationConfiguration = oneTimeDonationConfiguration; + this.subscriptionManager = subscriptionManager; + this.stripeManager = stripeManager; + this.braintreeManager = braintreeManager; + this.googlePlayBillingManager = googlePlayBillingManager; + this.appleAppStoreManager = appleAppStoreManager; + this.badgeTranslator = badgeTranslator; + this.bankMandateTranslator = bankMandateTranslator; + this.dynamicConfigurationManager = dynamicConfigurationManager; + } + + @Override + public UpdateSubscriberResponse updateSubscriber(final UpdateSubscriberRequest request) { + + try { + final SubscriberCredentials subscriberCredentials = SubscriberCredentials.process( + request.getSubscriberId().toByteArray(), clock); + subscriptionManager.updateSubscriber(subscriberCredentials); + return UpdateSubscriberResponse.newBuilder().setSuccess(Empty.getDefaultInstance()).build(); + } catch (final SubscriptionForbiddenException e) { + return UpdateSubscriberResponse.newBuilder().setSubscriberIdMismatch( + FailedUnidentifiedAuthorization.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build(); + } + + } + + @Override + public DeleteSubscriberResponse deleteSubscriber(final DeleteSubscriberRequest request) + throws RateLimitExceededException { + try { + final SubscriberCredentials subscriberCredentials = SubscriberCredentials.process( + request.getSubscriberId().toByteArray(), clock); + subscriptionManager.deleteSubscriber(subscriberCredentials); + return DeleteSubscriberResponse.newBuilder().setSuccess(Empty.getDefaultInstance()).build(); + } catch (final SubscriptionNotFoundException e) { + return DeleteSubscriberResponse.newBuilder().setSubscriberNotFound(NotFound.newBuilder().build()).build(); + } catch (final SubscriptionInvalidArgumentsException e) { + return DeleteSubscriberResponse.newBuilder().setCannotCancelSubscription( + FailedPrecondition.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build(); + } + } + + @Override + public CreatePaymentMethodResponse createPaymentMethod(final CreatePaymentMethodRequest request) { + final SubscriberCredentials subscriberCredentials = SubscriberCredentials.process( + request.getSubscriberId().toByteArray(), clock); + final PaymentMethod paymentMethod; + final CustomerAwareSubscriptionPaymentProcessor customerAwareSubscriptionPaymentProcessor = switch (request.getPaymentMethod()) { + case PAYMENT_METHOD_CARD, PAYMENT_METHOD_SEPA_DEBIT, PAYMENT_METHOD_IDEAL -> stripeManager; + default -> throw GrpcExceptions.fieldViolation("payment_method", "Unsupported payment method"); + }; + + try { + final String token = subscriptionManager.addPaymentMethodToCustomer(subscriberCredentials, + customerAwareSubscriptionPaymentProcessor, + getClientPlatform(RequestAttributesUtil.getUserAgent().orElse(null)), + CustomerAwareSubscriptionPaymentProcessor::createPaymentMethodSetupToken); + return CreatePaymentMethodResponse.newBuilder().setResult( + CreatePaymentMethodResponse.CreatePaymentMethodResult.newBuilder().setClientSecret(token) + .setPaymentProvider(customerAwareSubscriptionPaymentProcessor.getProvider().toProto()).build()).build(); + } catch (final SubscriptionNotFoundException e) { + return CreatePaymentMethodResponse.newBuilder().setSubscriberNotFound(NotFound.newBuilder()).build(); + } catch (final SubscriptionForbiddenException e) { + return CreatePaymentMethodResponse.newBuilder().setSubscriberIdMismatch( + FailedUnidentifiedAuthorization.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build(); + } catch (final SubscriptionProcessorConflictException e) { + return CreatePaymentMethodResponse.newBuilder().setSubscriptionProcessorConflict( + FailedPrecondition.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build(); + } + } + + @Override + public CreatePayPalPaymentMethodResponse createPayPalPaymentMethod(final CreatePayPalPaymentMethodRequest request) { + final SubscriberCredentials subscriberCredentials = SubscriberCredentials.process( + request.getSubscriberId().toByteArray(), clock); + final Locale locale = RequestAttributesUtil.getAcceptableLanguages().stream().filter(r -> !"*".equals(r.getRange())) + .findFirst().map(r -> Locale.forLanguageTag(r.getRange())).orElse(Locale.US); + try { + final BraintreeManager.PayPalBillingAgreementApprovalDetails details = subscriptionManager.addPaymentMethodToCustomer( + subscriberCredentials, braintreeManager, getClientPlatform(RequestAttributesUtil.getUserAgent().orElse(null)), + (mgr, customerId) -> mgr.createPayPalBillingAgreement(request.getReturnUrl(), request.getCancelUrl(), + locale.toLanguageTag())).join(); + return CreatePayPalPaymentMethodResponse.newBuilder().setResult( + CreatePayPalPaymentMethodResponse.CreatePayPalPaymentMethodResult.newBuilder() + .setApprovalUrl(details.approvalUrl()).setToken(details.billingAgreementToken()).build()).build(); + } catch (final SubscriptionNotFoundException e) { + return CreatePayPalPaymentMethodResponse.newBuilder().setSubscriberNotFound(NotFound.newBuilder().build()) + .build(); + } catch (final SubscriptionForbiddenException e) { + return CreatePayPalPaymentMethodResponse.newBuilder().setSubscriberIdMismatch( + FailedUnidentifiedAuthorization.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build(); + } catch (final SubscriptionProcessorConflictException e) { + return CreatePayPalPaymentMethodResponse.newBuilder().setSubscriptionProcessorConflict( + FailedPrecondition.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build(); + } + } + + @Override + public SetDefaultPaymentMethodResponse setDefaultPaymentMethod(final SetDefaultPaymentMethodRequest request) { + final SubscriberCredentials subscriberCredentials = SubscriberCredentials.process( + request.getSubscriberId().toByteArray(), clock); + final CustomerAwareSubscriptionPaymentProcessor manager; + final String paymentMethodId = switch (request.getRequestCase()) { + case STRIPE -> { + manager = stripeManager; + yield request.getStripe().getPaymentMethodToken(); + } + case BRAINTREE -> { + manager = braintreeManager; + yield request.getBraintree().getPaymentMethodToken(); + } + case SEPA -> { + manager = stripeManager; + yield stripeManager.getGeneratedSepaIdFromSetupIntent(request.getSepa().getSetupIntentId()).join(); + } + default -> throw GrpcExceptions.fieldViolation("request", "No payment method specified"); + }; + + try { + final Subscriptions.Record record = subscriptionManager.getSubscriber(subscriberCredentials); + return record.getProcessorCustomer().map( + processorCustomer -> setDefaultPaymentMethodForCustomer(manager, processorCustomer, paymentMethodId, + record.subscriptionId)).orElseGet(() -> + // a missing customer ID indicates the client made requests out of order, + // and needs to call create_payment_method to create a customer for the given payment method + SetDefaultPaymentMethodResponse.newBuilder().setPaymentMethodNotSetUp(FailedPrecondition.newBuilder().build()) + .build()); + } catch (final SubscriptionNotFoundException e) { + return SetDefaultPaymentMethodResponse.newBuilder().setSubscriberNotFound(NotFound.newBuilder().build()).build(); + } catch (final SubscriptionForbiddenException e) { + return SetDefaultPaymentMethodResponse.newBuilder().setSubscriberIdMismatch( + FailedUnidentifiedAuthorization.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build(); + } + } + + private static SetDefaultPaymentMethodResponse setDefaultPaymentMethodForCustomer( + final CustomerAwareSubscriptionPaymentProcessor processor, final ProcessorCustomer processorCustomer, + final String paymentMethodId, final String subscriptionId) { + try { + processor.setDefaultPaymentMethodForCustomer(processorCustomer.customerId(), paymentMethodId, subscriptionId); + return SetDefaultPaymentMethodResponse.newBuilder().setSuccess(Empty.getDefaultInstance()).build(); + } catch (final SubscriptionInvalidArgumentsException e) { + // Here, invalid arguments must mean that the client has made requests out of order, and needs to finish + // setting up the paymentMethod first + return SetDefaultPaymentMethodResponse.newBuilder() + .setPaymentMethodNotSetUp(FailedPrecondition.newBuilder().setDescription(e.errorDetail().orElse("")).build()) + .build(); + } + + } + + @Override + public SetSubscriptionLevelResponse setSubscriptionLevel(final SetSubscriptionLevelRequest request) { + final SubscriberCredentials subscriberCredentials = SubscriberCredentials.process( + request.getSubscriberId().toByteArray(), clock); + try { + final Subscriptions.Record record = subscriptionManager.getSubscriber(subscriberCredentials); + return record.getProcessorCustomer().map( + processorCustomer -> setSubscriptionLevelForCustomer(processorCustomer, subscriberCredentials, record, + request)).orElseGet(() -> SetSubscriptionLevelResponse.newBuilder() + .setPaymentMethodNotSetUp(FailedPrecondition.newBuilder().build()).build()); + + } catch (final SubscriptionNotFoundException e) { + return SetSubscriptionLevelResponse.newBuilder().setSubscriberNotFound(NotFound.newBuilder().build()).build(); + } catch (final SubscriptionForbiddenException e) { + return SetSubscriptionLevelResponse.newBuilder().setSubscriberIdMismatch( + FailedUnidentifiedAuthorization.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build(); + } + } + + private SetSubscriptionLevelResponse setSubscriptionLevelForCustomer(final ProcessorCustomer processorCustomer, + final SubscriberCredentials subscriberCredentials, final Subscriptions.Record subscriptionRecord, + final SetSubscriptionLevelRequest request) { + final SubscriptionLevelConfiguration config = subscriptionConfiguration.getSubscriptionLevel(request.getLevel()); + if (config == null) { + return SetSubscriptionLevelResponse.newBuilder().setUnsupportedLevel(FailedPrecondition.newBuilder().build()) + .build(); + } + final Optional templateId = Optional.ofNullable( + config.prices().get(request.getCurrency().toLowerCase(Locale.ROOT))) + .map(priceConfiguration -> priceConfiguration.processorIds().get(processorCustomer.processor())); + if (templateId.isEmpty()) { + return SetSubscriptionLevelResponse.newBuilder().setUnsupportedCurrency(FailedPrecondition.newBuilder().build()) + .build(); + } + + final CustomerAwareSubscriptionPaymentProcessor manager; + switch (processorCustomer.processor()) { + case STRIPE -> manager = stripeManager; + case BRAINTREE -> manager = braintreeManager; + default -> { + return SetSubscriptionLevelResponse.newBuilder().setUnsupportedOperation(FailedPrecondition.newBuilder() + .setDescription( + "Operation cannot be performed with the '" + processorCustomer.processor() + "' payment provider") + .build()).build(); + } + } + + try { + subscriptionManager.updateSubscriptionLevelForCustomer(subscriberCredentials, subscriptionRecord, manager, + request.getLevel(), request.getCurrency(), request.getIdempotencyKey(), templateId.get(), + (l1, l2) -> SubscriptionsUtil.subscriptionsAreSameType(subscriptionConfiguration, l1, l2)); + return SetSubscriptionLevelResponse.newBuilder().setSuccess( + SetSubscriptionLevelResponse.SetSubscriptionLevelResult.newBuilder().setLevel(request.getLevel()).build()) + .build(); + } catch (final SubscriptionInvalidIdempotencyKeyException e) { + return SetSubscriptionLevelResponse.newBuilder() + .setInvalidIdempotencyKey(FailedPrecondition.newBuilder().setDescription(e.errorDetail().orElse("")).build()) + .build(); + } catch (final SubscriptionProcessorException e) { + return SetSubscriptionLevelResponse.newBuilder() + .setChargeFailure(toChargeFailure(e.getProcessor(), e.getChargeFailure())).build(); + } catch (final SubscriptionPaymentRequiresActionException e) { + return SetSubscriptionLevelResponse.newBuilder().setPaymentRequiresAction(FailedPrecondition.newBuilder().build()) + .build(); + } catch (final SubscriptionInvalidLevelException e) { + return SetSubscriptionLevelResponse.newBuilder() + .setInvalidLevelTransition(FailedPrecondition.newBuilder().build()).build(); + } catch (final SubscriptionProcessorConflictException e) { + return SetSubscriptionLevelResponse.newBuilder().setSubscriptionProcessorConflict( + FailedPrecondition.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build(); + } + + } + + @Override + public SetIapSubscriptionResponse setIapSubscription(final SetIapSubscriptionRequest request) + throws RateLimitExceededException { + final SubscriberCredentials subscriberCredentials = SubscriberCredentials.process( + request.getSubscriberId().toByteArray(), clock); + try { + final long level = switch (request.getRequestCase()) { + case APP_STORE -> subscriptionManager.updateAppStoreTransactionId(subscriberCredentials, appleAppStoreManager, + request.getAppStore().getOriginalTransactionId()); + case PLAY_BILLING -> + subscriptionManager.updatePlayBillingPurchaseToken(subscriberCredentials, googlePlayBillingManager, + request.getPlayBilling().getPurchaseToken()); + default -> throw GrpcExceptions.fieldViolation("request", "must set request type"); + }; + return SetIapSubscriptionResponse.newBuilder() + .setSuccess(SetIapSubscriptionResponse.SetIapSubscriptionResult.newBuilder().setLevel(level).build()).build(); + } catch (final SubscriptionNotFoundException e) { + return SetIapSubscriptionResponse.newBuilder().setSubscriberNotFound(NotFound.newBuilder().build()).build(); + } catch (final SubscriptionForbiddenException e) { + return SetIapSubscriptionResponse.newBuilder().setSubscriberIdMismatch( + FailedUnidentifiedAuthorization.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build(); + } catch (final SubscriptionProcessorConflictException e) { + return SetIapSubscriptionResponse.newBuilder().setSubscriptionProcessorConflict( + FailedPrecondition.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build(); + } catch (final SubscriptionPaymentRequiredException e) { + return SetIapSubscriptionResponse.newBuilder().setPaymentRequired(FailedPrecondition.newBuilder().build()) + .build(); + } catch (final SubscriptionInvalidArgumentsException e) { + return SetIapSubscriptionResponse.newBuilder() + .setInvalidTransaction(FailedPrecondition.newBuilder().setDescription(e.errorDetail().orElse("")).build()) + .build(); + } + } + + @Override + public GetSubscriptionInformationResponse getSubscriptionInformation(final GetSubscriptionInformationRequest request) + throws RateLimitExceededException { + final SubscriberCredentials subscriberCredentials = SubscriberCredentials.process( + request.getSubscriberId().toByteArray(), clock); + try { + return subscriptionManager.getSubscriptionInformation(subscriberCredentials) + .map(SubscriptionsGrpcService::buildSubscriptionInformationResponse).orElseGet( + () -> GetSubscriptionInformationResponse.newBuilder().setNoSubscription(Empty.getDefaultInstance()) + .build()); + } catch (final SubscriptionNotFoundException e) { + return GetSubscriptionInformationResponse.newBuilder().setSubscriberNotFound(NotFound.newBuilder().build()) + .build(); + } catch (final SubscriptionForbiddenException e) { + return GetSubscriptionInformationResponse.newBuilder().setSubscriberIdMismatch( + FailedUnidentifiedAuthorization.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build(); + } + } + + private static GetSubscriptionInformationResponse buildSubscriptionInformationResponse( + final SubscriptionInformation info) { + + final GetSubscriptionInformationResponse.Subscription.Builder subscription = GetSubscriptionInformationResponse.Subscription.newBuilder() + .setLevel(info.level()).setEndOfCurrentPeriod(info.endOfCurrentPeriod().getEpochSecond()) + .setActive(info.active()).setCancelAtPeriodEnd(info.cancelAtPeriodEnd()).setCurrency(info.price().currency()) + .setAmount(info.price().amount().longValue()).setStatus(toProtoSubscriptionStatus(info.status())) + .setProcessor(info.paymentProvider().toProto()).setPaymentMethod(toProtoPaymentMethod(info.paymentMethod())) + .setPaymentProcessing(info.paymentProcessing()); + if (info.billingCycleAnchor() != null) { + subscription.setBillingCycleAnchor(info.billingCycleAnchor().getEpochSecond()); + } + if (info.chargeFailure() != null) { + subscription.setChargeFailure(toChargeFailure(info.paymentProvider(), info.chargeFailure())); + } + return GetSubscriptionInformationResponse.newBuilder().setSuccess(subscription.build()).build(); + + } + + @Override + public GetReceiptCredentialsResponse getReceiptCredentials(final GetReceiptCredentialsRequest request) + throws RateLimitExceededException { + final SubscriberCredentials subscriberCredentials = SubscriberCredentials.process( + request.getSubscriberId().toByteArray(), clock); + try { + final SubscriptionManager.ReceiptResult result = subscriptionManager.createReceiptCredentials( + subscriberCredentials, request.getReceiptCredentialRequest().toByteArray(), + r -> SubscriptionsUtil.receiptExpirationWithGracePeriod(subscriptionConfiguration, r)); + return GetReceiptCredentialsResponse.newBuilder().setSuccess( + GetReceiptCredentialsResponse.GetReceiptCredentialsResult.newBuilder() + .setReceiptCredentialResponse(ByteString.copyFrom(result.receiptCredentialResponse().serialize())) + .build()).build(); + } catch (final SubscriptionReceiptRequestedForOpenPaymentException e) { + return GetReceiptCredentialsResponse.newBuilder().setNoPaidInvoice(FailedPrecondition.newBuilder().build()) + .build(); + } catch (final SubscriptionChargeFailurePaymentRequiredException e) { + return GetReceiptCredentialsResponse.newBuilder().setPaymentRequired( + GetReceiptCredentialsResponse.PaymentRequired.newBuilder() + .setChargeFailure(toChargeFailure(e.getProcessor(), e.getChargeFailure())).build()).build(); + } catch (final SubscriptionPaymentRequiredException e) { + return GetReceiptCredentialsResponse.newBuilder() + .setPaymentRequired(GetReceiptCredentialsResponse.PaymentRequired.newBuilder().build()).build(); + } catch (final SubscriptionInvalidArgumentsException e) { + throw GrpcExceptions.invalidArguments(e.errorDetail().orElse("")); + } catch (final SubscriptionReceiptAlreadyRedeemedException e) { + return GetReceiptCredentialsResponse.newBuilder().setAlreadyRedeemed(FailedPrecondition.newBuilder().build()) + .build(); + } catch (final SubscriptionNotFoundException e) { + return GetReceiptCredentialsResponse.newBuilder().setSubscriberNotFound(NotFound.newBuilder().build()).build(); + } catch (final SubscriptionForbiddenException e) { + return GetReceiptCredentialsResponse.newBuilder().setSubscriberIdMismatch( + FailedUnidentifiedAuthorization.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build(); + } + } + + private static org.signal.chat.subscriptions.SubscriptionStatus toProtoSubscriptionStatus( + final SubscriptionStatus status) { + return switch (status) { + case ACTIVE -> org.signal.chat.subscriptions.SubscriptionStatus.SUBSCRIPTION_STATUS_ACTIVE; + case INCOMPLETE -> org.signal.chat.subscriptions.SubscriptionStatus.SUBSCRIPTION_STATUS_INCOMPLETE; + case PAST_DUE -> org.signal.chat.subscriptions.SubscriptionStatus.SUBSCRIPTION_STATUS_PAST_DUE; + case CANCELED -> org.signal.chat.subscriptions.SubscriptionStatus.SUBSCRIPTION_STATUS_CANCELED; + case UNPAID -> org.signal.chat.subscriptions.SubscriptionStatus.SUBSCRIPTION_STATUS_UNPAID; + case UNKNOWN -> org.signal.chat.subscriptions.SubscriptionStatus.SUBSCRIPTION_STATUS_UNKNOWN; + }; + } + + private static PaymentMethod toProtoPaymentMethod( + final org.whispersystems.textsecuregcm.subscriptions.PaymentMethod paymentMethod) { + if (paymentMethod == null) { + return PaymentMethod.PAYMENT_METHOD_UNKNOWN; + } + return switch (paymentMethod) { + case CARD -> PaymentMethod.PAYMENT_METHOD_CARD; + case SEPA_DEBIT -> PaymentMethod.PAYMENT_METHOD_SEPA_DEBIT; + case IDEAL -> PaymentMethod.PAYMENT_METHOD_IDEAL; + case PAYPAL -> PaymentMethod.PAYMENT_METHOD_PAYPAL; + case GOOGLE_PLAY_BILLING -> PaymentMethod.PAYMENT_METHOD_GOOGLE_PLAY_BILLING; + case APPLE_APP_STORE -> PaymentMethod.PAYMENT_METHOD_APPLE_APP_STORE; + case UNKNOWN -> PaymentMethod.PAYMENT_METHOD_UNKNOWN; + }; + } + + @Override + public GetConfigurationResponse getConfiguration(final GetConfigurationRequest request) { + final long maxBackupBytes = dynamicConfigurationManager.getConfiguration().getBackupConfiguration() + .maxTotalMediaSize(); + + final Map backupLevels = subscriptionConfiguration.getBackupLevels() + .entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, + e -> GetConfigurationResponse.BackupLevelConfiguration.newBuilder().setStorageAllowanceBytes(maxBackupBytes) + .setPlayProductId(e.getValue().playProductId()).setMediaTtlDays(e.getValue().mediaTtl().toDays()) + .build())); + + return GetConfigurationResponse.newBuilder().putAllCurrencies(buildCurrencyConfigurations()) + .putAllLevels(buildLevelConfigurations()).setBackup( + GetConfigurationResponse.BackupConfiguration.newBuilder().putAllLevels(backupLevels) + .setFreeTierMediaDays(subscriptionConfiguration.getbackupFreeTierMediaDuration().toDays()).build()) + .setSepaMaximumEuros(oneTimeDonationConfiguration.sepaMaximumEuros().toString()).build(); + } + + private Map buildCurrencyConfigurations() { + return SubscriptionsUtil.buildCurrencyConfiguration(List.of(stripeManager, braintreeManager), + oneTimeDonationConfiguration, subscriptionConfiguration).entrySet().stream() + .collect(Collectors.toMap(Map.Entry::getKey, e -> toProtoCurrencyConfiguration(e.getKey(), e.getValue()))); + } + + private Map buildLevelConfigurations() { + return SubscriptionsUtil.buildDonationLevelsConfiguration(subscriptionConfiguration, oneTimeDonationConfiguration, + badgeTranslator, RequestAttributesUtil.getAvailableAcceptedLocales()).entrySet().stream().collect( + Collectors.toMap(Map.Entry::getKey, entry -> GetConfigurationResponse.LevelConfiguration.newBuilder() + .setBadge(toProtoBadge(entry.getValue().badge())).build())); + } + + private static GetConfigurationResponse.CurrencyConfiguration toProtoCurrencyConfiguration(final String currency, + final CurrencyConfiguration config) { + final GetConfigurationResponse.CurrencyConfiguration.Builder builder = GetConfigurationResponse.CurrencyConfiguration.newBuilder() + .setMinimum(config.minimum().toString()) + .addAllSupportedPaymentMethods( + config.supportedPaymentMethods().stream().map(SubscriptionsGrpcService::toProtoPaymentMethod).toList()); + config.oneTime().forEach((levelId, amounts) -> builder.putOneTime(levelId, + GetConfigurationResponse.AmountList.newBuilder() + .addAllAmounts( + amounts.stream().map(BigDecimal::toString).toList()) + .build())); + config.subscription() + .forEach((levelId, amount) -> builder.putSubscription(levelId, + amount.toString())); + config.backupSubscription() + .forEach((levelId, amount) -> builder.putBackupSubscription(levelId, + amount.toString())); + return builder.build(); + } + + private static GetConfigurationResponse.Badge toProtoBadge(final Badge badge) { + final org.signal.chat.common.Badge commonBadge = org.signal.chat.common.Badge.newBuilder().setId(badge.getId()) + .setCategory(badge.getCategory()).setName(badge.getName()).setDescription(badge.getDescription()) + .addAllSprites6(badge.getSprites6()).setSvg(badge.getSvg()).addAllSvgs(badge.getSvgs().stream() + .map(s -> org.signal.chat.common.BadgeSvg.newBuilder().setLight(s.getLight()).setDark(s.getDark()).build()) + .toList()).build(); + final GetConfigurationResponse.Badge.Builder builder = GetConfigurationResponse.Badge.newBuilder() + .setBadge(commonBadge); + if (badge instanceof final PurchasableBadge purchasableBadge) { + builder.setDurationSeconds(purchasableBadge.getDuration().toSeconds()); + } + return builder.build(); + } + + @Override + public GetBankMandateResponse getBankMandate(final GetBankMandateRequest request) { + final BankTransferType bankTransferType = switch (request.getBankTransferType()) { + case BANK_TRANSFER_TYPE_SEPA_DEBIT -> BankTransferType.SEPA_DEBIT; + default -> throw GrpcExceptions.fieldViolation("bank_transfer_type", "Unsupported bank transfer type"); + }; + final String mandate = bankMandateTranslator.translate(RequestAttributesUtil.getAvailableAcceptedLocales(), + bankTransferType); + return GetBankMandateResponse.newBuilder().setMandate(mandate).build(); + } + + private static org.signal.chat.subscriptions.ChargeFailure toChargeFailure(final PaymentProvider processor, + final ChargeFailure chargeFailure) { + final org.signal.chat.subscriptions.ChargeFailure.Builder builder = org.signal.chat.subscriptions.ChargeFailure.newBuilder() + .setProcessor(processor.toProto()).setCode(chargeFailure.code()).setMessage(chargeFailure.message()); + if (chargeFailure.outcomeNetworkStatus() != null) { + builder.setOutcomeNetworkStatus(chargeFailure.outcomeNetworkStatus()); + } + if (chargeFailure.outcomeReason() != null) { + builder.setOutcomeReason(chargeFailure.outcomeReason()); + } + if (chargeFailure.outcomeType() != null) { + builder.setOutcomeType(chargeFailure.outcomeType()); + } + return builder.build(); + } + +} diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/SubscriptionsUtil.java b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/SubscriptionsUtil.java new file mode 100644 index 000000000..c5cdd9565 --- /dev/null +++ b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/SubscriptionsUtil.java @@ -0,0 +1,127 @@ +package org.whispersystems.textsecuregcm.grpc; + +import java.math.BigDecimal; +import java.time.Instant; +import java.util.Arrays; +import java.util.EnumSet; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.function.Function; +import java.util.stream.Collectors; +import javax.annotation.Nullable; +import org.whispersystems.textsecuregcm.badges.BadgeTranslator; +import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfiguration; +import org.whispersystems.textsecuregcm.configuration.OneTimeDonationCurrencyConfiguration; +import org.whispersystems.textsecuregcm.configuration.SubscriptionConfiguration; +import org.whispersystems.textsecuregcm.configuration.SubscriptionLevelConfiguration; +import org.whispersystems.textsecuregcm.entities.Badge; +import org.whispersystems.textsecuregcm.entities.PurchasableBadge; +import org.whispersystems.textsecuregcm.subscriptions.CurrencyConfiguration; +import org.whispersystems.textsecuregcm.subscriptions.CustomerAwareSubscriptionPaymentProcessor; +import org.whispersystems.textsecuregcm.subscriptions.LevelConfiguration; +import org.whispersystems.textsecuregcm.subscriptions.PaymentMethod; +import org.whispersystems.textsecuregcm.util.ua.ClientPlatform; +import org.whispersystems.textsecuregcm.util.ua.UnrecognizedUserAgentException; +import org.whispersystems.textsecuregcm.util.ua.UserAgentUtil; + +public class SubscriptionsUtil { + @Nullable + public static ClientPlatform getClientPlatform(@Nullable final String userAgentString) { + try { + return UserAgentUtil.parseUserAgentString(userAgentString).platform(); + } catch (final UnrecognizedUserAgentException e) { + return null; + } + } + + public static boolean subscriptionsAreSameType(final SubscriptionConfiguration subscriptionConfiguration, final long level1, final long level2) { + return subscriptionConfiguration.getSubscriptionLevel(level1).type() + == subscriptionConfiguration.getSubscriptionLevel(level2).type(); + } + + public static Instant receiptExpirationWithGracePeriod( + final SubscriptionConfiguration subscriptionConfiguration, + final CustomerAwareSubscriptionPaymentProcessor.ReceiptItem receiptItem) { + return switch (subscriptionConfiguration.getSubscriptionLevel(receiptItem.level()).type()) { + case DONATION -> receiptItem.paymentTime().receiptExpiration( + subscriptionConfiguration.getBadgeExpiration(), + subscriptionConfiguration.getBadgeGracePeriod()); + case BACKUP -> receiptItem.paymentTime().receiptExpiration( + subscriptionConfiguration.getBackupExpiration(), + subscriptionConfiguration.getBackupGracePeriod()); + }; + } + + public static Map buildCurrencyConfiguration(final List subscriptionPaymentProcessors, + final OneTimeDonationConfiguration oneTimeDonationConfiguration, + final SubscriptionConfiguration subscriptionConfiguration) { + return oneTimeDonationConfiguration.currencies() + .entrySet().stream() + .collect(Collectors.toMap(Map.Entry::getKey, currencyAndConfig -> { + final String currency = currencyAndConfig.getKey(); + final OneTimeDonationCurrencyConfiguration currencyConfig = currencyAndConfig.getValue(); + + final Map> oneTimeLevelsToSuggestedAmounts = Map.of( + oneTimeDonationConfiguration.boost().level(), currencyConfig.boosts(), + oneTimeDonationConfiguration.gift().level(), List.of(currencyConfig.gift()) + ); + + final Function, Map> extractSubscriptionAmounts = levels -> + levels.entrySet().stream() + .filter(levelIdAndConfig -> levelIdAndConfig.getValue().prices().containsKey(currency)) + .collect(Collectors.toMap( + Map.Entry::getKey, + levelIdAndConfig -> levelIdAndConfig.getValue().prices().get(currency).amount())); + + final List supportedPaymentMethods = Arrays.stream(PaymentMethod.values()) + .filter(paymentMethod -> subscriptionPaymentProcessors.stream() + .anyMatch(manager -> manager.supportsPaymentMethod(paymentMethod) + && manager.getSupportedCurrenciesForPaymentMethod(paymentMethod).contains(currency))) + .collect(Collectors.toList()); + + if (supportedPaymentMethods.isEmpty()) { + throw new RuntimeException("Configuration has currency with no processor support: " + currency); + } + + return new CurrencyConfiguration( + currencyConfig.minimum(), + oneTimeLevelsToSuggestedAmounts, + extractSubscriptionAmounts.apply(subscriptionConfiguration.getDonationLevels()), + extractSubscriptionAmounts.apply(subscriptionConfiguration.getBackupLevels()), + supportedPaymentMethods); + })); + } + + public static Map buildDonationLevelsConfiguration( + final SubscriptionConfiguration subscriptionConfiguration, + final OneTimeDonationConfiguration oneTimeDonationConfiguration, + final BadgeTranslator badgeTranslator, + final List acceptableLanguages) { + final Map donationLevels = new HashMap<>(); + + subscriptionConfiguration.getDonationLevels().forEach((levelId, levelConfig) -> { + final LevelConfiguration levelConfiguration = new LevelConfiguration( + badgeTranslator.translate(acceptableLanguages, levelConfig.badge())); + donationLevels.put(levelId, levelConfiguration); + }); + + final Badge boostBadge = badgeTranslator.translate(acceptableLanguages, + oneTimeDonationConfiguration.boost().badge()); + donationLevels.put(oneTimeDonationConfiguration.boost().level(), + new LevelConfiguration( + // NB: the one-time badges are PurchasableBadge, which has a `duration` field + new PurchasableBadge( + boostBadge, + oneTimeDonationConfiguration.boost().expiration()))); + + final Badge giftBadge = badgeTranslator.translate(acceptableLanguages, oneTimeDonationConfiguration.gift().badge()); + donationLevels.put(oneTimeDonationConfiguration.gift().level(), + new LevelConfiguration( + new PurchasableBadge( + giftBadge, + oneTimeDonationConfiguration.gift().expiration()))); + return donationLevels; + } +} diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/storage/SubscriberCredentials.java b/service/src/main/java/org/whispersystems/textsecuregcm/storage/SubscriberCredentials.java index 813b3e5c8..8f0a683c9 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/storage/SubscriberCredentials.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/storage/SubscriberCredentials.java @@ -26,17 +26,23 @@ public record SubscriberCredentials(@Nonnull byte[] subscriberBytes, @Nonnull Instant now) { public static SubscriberCredentials process( - Optional authenticatedAccount, - String subscriberId, - Clock clock) throws SubscriptionException { - Instant now = clock.instant(); + final Optional authenticatedAccount, + final String subscriberId, + final Clock clock) throws SubscriptionException { if (authenticatedAccount.isPresent()) { throw new SubscriptionForbiddenException("must not use authenticated connection for subscriber operations"); } - byte[] subscriberBytes = convertSubscriberIdStringToBytes(subscriberId); - byte[] subscriberUser = getUser(subscriberBytes); - byte[] subscriberKey = getKey(subscriberBytes); - byte[] hmac = computeHmac(subscriberUser, subscriberKey); + final byte[] subscriberBytes = convertSubscriberIdStringToBytes(subscriberId); + return process(subscriberBytes, clock); + } + + public static SubscriberCredentials process( + final byte[] subscriberBytes, + final Clock clock) { + final Instant now = clock.instant(); + final byte[] subscriberUser = getUser(subscriberBytes); + final byte[] subscriberKey = getKey(subscriberBytes); + final byte[] hmac = computeHmac(subscriberUser, subscriberKey); return new SubscriberCredentials(subscriberBytes, subscriberUser, subscriberKey, hmac, now); } 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 3f1441ca6..539193ead 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/storage/SubscriptionManager.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/storage/SubscriptionManager.java @@ -30,12 +30,14 @@ import org.whispersystems.textsecuregcm.subscriptions.GooglePlayBillingManager; import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider; import org.whispersystems.textsecuregcm.subscriptions.ProcessorCustomer; import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInformation; +import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidIdempotencyKeyException; import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPaymentProcessor; import org.whispersystems.textsecuregcm.subscriptions.SubscriptionForbiddenException; import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidArgumentsException; import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidLevelException; import org.whispersystems.textsecuregcm.subscriptions.SubscriptionNotFoundException; import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPaymentRequiredException; +import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPaymentRequiresActionException; import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorConflictException; import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorException; import org.whispersystems.textsecuregcm.subscriptions.SubscriptionReceiptAlreadyRedeemedException; @@ -165,10 +167,11 @@ public class SubscriptionManager { /** * Create a ZK receipt credential for a subscription that can be used to obtain the user entitlement * - * @param subscriberCredentials Subscriber credentials derived from the subscriberId - * @param request The ZK Receipt credential request - * @param expiration A function that takes a {@link CustomerAwareSubscriptionPaymentProcessor.ReceiptItem} - * and returns the expiration time of the receipt + * @param subscriberCredentials Subscriber credentials derived from the subscriberId + * @param receiptCredentialRequestBytes The raw bytes of the ZK Receipt credential request + * @param expiration A function that takes a + * {@link CustomerAwareSubscriptionPaymentProcessor.ReceiptItem} and returns the + * expiration time of the receipt * @return the requested ZK receipt credential * @throws SubscriptionForbiddenException if the subscriber credentials were incorrect * @throws SubscriptionNotFoundException if the subscriber did not exist or did not have a @@ -178,12 +181,13 @@ 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 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 byte[] receiptCredentialRequestBytes, final Function expiration) throws SubscriptionForbiddenException, SubscriptionNotFoundException, SubscriptionInvalidArgumentsException, SubscriptionPaymentRequiredException, RateLimitExceededException, SubscriptionReceiptRequestedForOpenPaymentException, SubscriptionReceiptAlreadyRedeemedException { final Subscriptions.Record record = getSubscriber(subscriberCredentials); @@ -193,7 +197,7 @@ public class SubscriptionManager { final ReceiptCredentialRequest receiptCredentialRequest; try { - receiptCredentialRequest = new ReceiptCredentialRequest(request.receiptCredentialRequest()); + receiptCredentialRequest = new ReceiptCredentialRequest(receiptCredentialRequestBytes); } catch (final InvalidInputException e) { throw new SubscriptionInvalidArgumentsException("invalid receipt credential request", e); } @@ -239,7 +243,7 @@ public class SubscriptionManager { * @throws SubscriptionForbiddenException if the subscriber credentials were incorrect * @throws SubscriptionNotFoundException if the subscriber did not exist or did not have a subscription * attached - * @throws SubscriptionProcessorConflictException if the new payment processor the existing processor associated with + * @throws SubscriptionProcessorConflictException if the new payment processor does not match the existing processor associated with * the subscriberId */ public R addPaymentMethodToCustomer( @@ -313,7 +317,7 @@ public class SubscriptionManager { final String idempotencyKey, final String subscriptionTemplateId, final LevelTransitionValidator transitionValidator) - throws SubscriptionInvalidArgumentsException, SubscriptionProcessorConflictException, SubscriptionProcessorException { + throws SubscriptionInvalidLevelException, SubscriptionInvalidIdempotencyKeyException, SubscriptionPaymentRequiresActionException, SubscriptionProcessorConflictException, SubscriptionProcessorException { if (record.subscriptionId != null) { // we already have a subscription in our records so let's check the level and currency, @@ -364,7 +368,7 @@ public class SubscriptionManager { * @throws SubscriptionForbiddenException if the subscriber credentials were incorrect * @throws SubscriptionNotFoundException if the subscriber did not exist or did not have a subscription * attached - * @throws SubscriptionProcessorConflictException if the new payment processor the existing processor associated with + * @throws SubscriptionProcessorConflictException if the new payment processor does not match the existing processor associated with * the subscriberId * @throws SubscriptionPaymentRequiredException if the subscription is not in a state that grants the user an * entitlement @@ -416,7 +420,7 @@ public class SubscriptionManager { * @return the subscription level for the accepted subscription * @throws SubscriptionForbiddenException if the subscriber credentials are incorrect * @throws SubscriptionNotFoundException if the originalTransactionId does not exist - * @throws SubscriptionProcessorConflictException if the new payment processor the existing processor associated with + * @throws SubscriptionProcessorConflictException if the new payment processor does not match the existing processor associated with * the subscriber * @throws SubscriptionInvalidArgumentsException if the originalTransactionId is malformed or does not represent a * valid subscription diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/CurrencyConfiguration.java b/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/CurrencyConfiguration.java new file mode 100644 index 000000000..69e79226e --- /dev/null +++ b/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/CurrencyConfiguration.java @@ -0,0 +1,20 @@ +package org.whispersystems.textsecuregcm.subscriptions; + +import io.swagger.v3.oas.annotations.media.Schema; + +import java.math.BigDecimal; +import java.util.List; +import java.util.Map; + +@Schema(description = "Configuration for a currency - use to present appropriate client interfaces") +public record CurrencyConfiguration( + @Schema(description = "The minimum amount that may be submitted for a one-time donation in the currency") + BigDecimal minimum, + @Schema(description = "A map of numeric one-time donation level IDs to the list of default amounts to be presented") + Map> oneTime, + @Schema(description = "A map of numeric subscription level IDs to the amount charged for that level") + Map subscription, + @Schema(description = "A map of numeric backup level IDs to the amount charged for that level") + Map backupSubscription, + @Schema(description = "The payment methods that support the given currency") + List supportedPaymentMethods) {} diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/CustomerAwareSubscriptionPaymentProcessor.java b/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/CustomerAwareSubscriptionPaymentProcessor.java index a85e90502..4be6445ec 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/CustomerAwareSubscriptionPaymentProcessor.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/CustomerAwareSubscriptionPaymentProcessor.java @@ -56,14 +56,13 @@ public interface CustomerAwareSubscriptionPaymentProcessor extends SubscriptionP * @param level The level of the subscription * @param lastSubscriptionCreatedAt The timestamp of the last successfully created subscription * @return A subscription identifier - * @throws SubscriptionProcessorException If there was a failure processing the charge - * @throws SubscriptionInvalidArgumentsException If there was a failure because an idempotency key was reused on a - * modified request, or if the payment requires additional steps - * before charging - * @throws SubscriptionProcessorConflictException If there was no payment method on the customer + * @throws SubscriptionProcessorException If there was a failure processing the charge + * @throws SubscriptionPaymentRequiresActionException If the payment requires additional steps before charging + * @throws SubscriptionInvalidIdempotencyKeyException If the idempotency key was reused on a modified request + * @throws SubscriptionProcessorConflictException If there was no payment method on the customer */ SubscriptionId createSubscription(String customerId, String templateId, long level, long lastSubscriptionCreatedAt) - throws SubscriptionProcessorException, SubscriptionInvalidArgumentsException, SubscriptionProcessorConflictException; + throws SubscriptionProcessorException, SubscriptionPaymentRequiresActionException, SubscriptionInvalidIdempotencyKeyException, SubscriptionProcessorConflictException; /** * Update an existing subscription on a customer @@ -73,14 +72,15 @@ public interface CustomerAwareSubscriptionPaymentProcessor extends SubscriptionP * @param level The target level of the subscription * @param idempotencyKey An idempotency key to prevent retries of successful requests * @return A subscription identifier - * @throws SubscriptionProcessorException If there was a failure processing the charge - * @throws SubscriptionInvalidArgumentsException If there was a failure because an idempotency key was reused on a - * modified request, or if the payment requires additional steps - * before charging - * @throws SubscriptionProcessorConflictException If there was no payment method on the customer + * @throws SubscriptionProcessorException If there was a failure processing the charge + * @throws SubscriptionInvalidIdempotencyKeyException If the idempotency key was reused on a modified request + * @throws SubscriptionInvalidLevelException If the level transition is not permitted + * @throws SubscriptionPaymentRequiresActionException If the payment requires additional steps before charging + * @throws SubscriptionProcessorConflictException If there was no payment method on the customer */ SubscriptionId updateSubscription(Object subscription, String templateId, long level, String idempotencyKey) - throws SubscriptionInvalidArgumentsException, SubscriptionProcessorException, SubscriptionProcessorConflictException; + throws SubscriptionInvalidIdempotencyKeyException, SubscriptionInvalidLevelException, + SubscriptionPaymentRequiresActionException, SubscriptionProcessorException, SubscriptionProcessorConflictException; /** * @param subscription diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/LevelConfiguration.java b/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/LevelConfiguration.java new file mode 100644 index 000000000..450cb71a7 --- /dev/null +++ b/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/LevelConfiguration.java @@ -0,0 +1,9 @@ +package org.whispersystems.textsecuregcm.subscriptions; + +import io.swagger.v3.oas.annotations.media.Schema; +import org.whispersystems.textsecuregcm.entities.Badge; + +@Schema(description = "Configuration for a donation level - use to present appropriate client interfaces") +public record LevelConfiguration( + @Schema(description = "The displayable badge associated with the level") + Badge badge) {} diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/PaymentProvider.java b/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/PaymentProvider.java index a122dfd17..d747fdb67 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/PaymentProvider.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/PaymentProvider.java @@ -47,4 +47,13 @@ public enum PaymentProvider { public byte getId() { return id; } + + public org.signal.chat.subscriptions.PaymentProvider toProto() { + return switch (this) { + case STRIPE -> org.signal.chat.subscriptions.PaymentProvider.PAYMENT_PROVIDER_STRIPE; + case BRAINTREE -> org.signal.chat.subscriptions.PaymentProvider.PAYMENT_PROVIDER_BRAINTREE; + case GOOGLE_PLAY_BILLING -> org.signal.chat.subscriptions.PaymentProvider.PAYMENT_PROVIDER_GOOGLE_PLAY_BILLING; + case APPLE_APP_STORE -> org.signal.chat.subscriptions.PaymentProvider.PAYMENT_PROVIDER_APPLE_APP_STORE; + }; + } } diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/StripeManager.java b/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/StripeManager.java index 1f13c77f9..e65584de6 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/StripeManager.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/StripeManager.java @@ -285,7 +285,8 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor @Override public SubscriptionId createSubscription(String customerId, String priceId, long level, long lastSubscriptionCreatedAt) - throws SubscriptionProcessorException, SubscriptionInvalidArgumentsException { + throws SubscriptionProcessorException, SubscriptionInvalidIdempotencyKeyException, + SubscriptionPaymentRequiresActionException { // this relies on Stripe's idempotency key to avoid creating more than one subscription if the client // retries this request SubscriptionCreateParams params = SubscriptionCreateParams.builder() @@ -307,7 +308,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor commonOptions(generateIdempotencyKeyForCreateSubscription(customerId, lastSubscriptionCreatedAt))); return new SubscriptionId(subscription.getId()); } catch (IdempotencyException e) { - throw new SubscriptionInvalidArgumentsException(e.getStripeError().getMessage()); + throw new SubscriptionInvalidIdempotencyKeyException(e.getStripeError().getMessage()); } catch (CardException e) { throw new SubscriptionProcessorException(getProvider(), createChargeFailureFromCardException(e)); } catch (StripeException e) { @@ -320,7 +321,8 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor @Override public SubscriptionId updateSubscription(Object subscriptionObj, String priceId, long level, String idempotencyKey) - throws SubscriptionInvalidArgumentsException, SubscriptionProcessorException { + throws SubscriptionInvalidIdempotencyKeyException, SubscriptionPaymentRequiresActionException, + SubscriptionProcessorException { final Subscription subscription = getSubscription(subscriptionObj); @@ -359,7 +361,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor commonOptions(generateIdempotencyKeyForSubscriptionUpdate(subscription.getCustomer(), idempotencyKey))); return new SubscriptionId(subscription1.getId()); } catch (IdempotencyException e) { - throw new SubscriptionInvalidArgumentsException(e.getStripeError().getMessage()); + throw new SubscriptionInvalidIdempotencyKeyException(e.getStripeError().getMessage()); } catch (CardException e) { throw new SubscriptionProcessorException(getProvider(), createChargeFailureFromCardException(e)); } catch (StripeException e) { diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/SubscriptionInvalidIdempotencyKeyException.java b/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/SubscriptionInvalidIdempotencyKeyException.java new file mode 100644 index 000000000..45ded4d65 --- /dev/null +++ b/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/SubscriptionInvalidIdempotencyKeyException.java @@ -0,0 +1,12 @@ +/* + * Copyright 2026 Signal Messenger, LLC + * SPDX-License-Identifier: AGPL-3.0-only + */ +package org.whispersystems.textsecuregcm.subscriptions; + +public class SubscriptionInvalidIdempotencyKeyException extends SubscriptionInvalidArgumentsException { + + public SubscriptionInvalidIdempotencyKeyException(final String message) { + super(message); + } +} diff --git a/service/src/main/proto/org/signal/chat/common.proto b/service/src/main/proto/org/signal/chat/common.proto index 3c2c640ac..6c3a9c63c 100644 --- a/service/src/main/proto/org/signal/chat/common.proto +++ b/service/src/main/proto/org/signal/chat/common.proto @@ -115,3 +115,27 @@ message UploadForm { // The URL to upload to with the appropriate protocol string signed_upload_location = 4; } + +message BadgeSvg { + // File name of the scalable vector graphic for light mode. + string light = 1; + // File name of the scalable vector graphic for dark mode. + string dark = 2; +} + +message Badge { + // An ID that uniquely identifies the badge. + string id = 1; + // The category the badge falls in ("donor" or "other"). + string category = 2; + // The badge name. + string name = 3; + // The badge description. + string description = 4; + // Different size badge SVG files. + repeated string sprites6 = 5; + // File name of the scalable vector graphic representing this badge. + string svg = 6; + // Pairs of light/dark SVG files designed for display at different sizes. + repeated BadgeSvg svgs = 7; +} diff --git a/service/src/main/proto/org/signal/chat/profile.proto b/service/src/main/proto/org/signal/chat/profile.proto index 63aa2b14e..062618733 100644 --- a/service/src/main/proto/org/signal/chat/profile.proto +++ b/service/src/main/proto/org/signal/chat/profile.proto @@ -268,7 +268,7 @@ message GetUnversionedProfileResult { // A list of capabilities enabled on the account. repeated common.DeviceCapability capabilities = 4; // A list of badges associated with the account. - repeated Badge badges = 5; + repeated common.Badge badges = 5; } message GetUnversionedProfileResponse { @@ -338,30 +338,6 @@ message ProfileAvatarUploadAttributes { bytes signature = 7; } -message Badge { - // An ID that uniquely identifies the badge. - string id = 1; - // The category the badge falls in ("donor" or "other"). - string category = 2; - // The badge name. - string name = 3; - // The badge description. - string description = 4; - // Different size badge SVG files. - repeated string sprites6 = 5; - // File name of the scalable vector graphic representing this badge. - string svg = 6; - // Pairs of light/dark SVG files designed for display at different sizes. - repeated BadgeSvg svgs = 7; -} - -message BadgeSvg { - // File name of the scalable vector graphic for light mode. - string light = 1; - // File name of the scalable vector graphic for dark mode. - string dark = 2; -} - enum CredentialType { CREDENTIAL_TYPE_UNSPECIFIED = 0; CREDENTIAL_TYPE_EXPIRING_PROFILE_KEY = 1; diff --git a/service/src/main/proto/org/signal/chat/subscriptions.proto b/service/src/main/proto/org/signal/chat/subscriptions.proto new file mode 100644 index 000000000..63c06ee36 --- /dev/null +++ b/service/src/main/proto/org/signal/chat/subscriptions.proto @@ -0,0 +1,490 @@ +/* + * Copyright 2026 Signal Messenger, LLC + * SPDX-License-Identifier: AGPL-3.0-only + */ + +syntax = "proto3"; + +option java_multiple_files = true; + +package org.signal.chat.subscriptions; + +import "google/protobuf/empty.proto"; +import "org/signal/chat/common.proto"; +import "org/signal/chat/require.proto"; +import "org/signal/chat/errors.proto"; +import "org/signal/chat/tag.proto"; + +service Subscriptions { + option (require.auth) = AUTH_ONLY_ANONYMOUS; + // Creates a subscriber record if it does not exist, otherwise refreshes its last access time. + + // Subscribers MUST periodically hit this endpoint to update the access time on the subscription record. Subscribers + // SHOULD attempt to make an update call approximately every 3 days. Not accessing this endpoint for an extended + // period of time will result in the subscription being canceled. + rpc UpdateSubscriber(UpdateSubscriberRequest) returns (UpdateSubscriberResponse) {} + + // Cancels any current subscription at the end of the current subscription period. + // + // Note: Apple IAP subscriptions do not support server-side cancellation, so this method should only be called after + // cancelling a subscription from storekit to keep server data up to date. + rpc DeleteSubscriber(DeleteSubscriberRequest) returns (DeleteSubscriberResponse) {} + + // Returns a client secret that can be used to set up a new payment method with the payment processor. + rpc CreatePaymentMethod(CreatePaymentMethodRequest) returns (CreatePaymentMethodResponse) {} + + // Returns a PayPal billing agreement approval URL and token that can be used to set up PayPal as a payment method. + rpc CreatePayPalPaymentMethod(CreatePayPalPaymentMethodRequest) returns (CreatePayPalPaymentMethodResponse) {} + + // Sets the default payment method for a subscriber. + rpc SetDefaultPaymentMethod(SetDefaultPaymentMethodRequest) returns (SetDefaultPaymentMethodResponse) {} + + // Sets the subscription level and currency for a subscriber. + rpc SetSubscriptionLevel(SetSubscriptionLevelRequest) returns (SetSubscriptionLevelResponse) {} + + // Returns information about the current subscription associated with the provided subscriberId if one exists. + // + // Although it uses [Stripe's values](https://stripe.com/docs/billing/subscriptions/overview#subscription-statuses), + // the status field in the response is generic, with [Braintree-specific values](https://developer.paypal.com/braintree/docs/guides/recurring-billing/overview#subscription-statuses) mapped + // to Stripe's. Since we don't support trials or unpaid subscriptions, the associated statuses will never be returned + // by the API. + rpc GetSubscriptionInformation(GetSubscriptionInformationRequest) returns (GetSubscriptionInformationResponse) {} + + // Create a receipt from a valid payment invoice that can be used to obtain an entitlement + // + // This request is repeatable so long as the ReceiptCredentialRequest remains the same. Clients should use the same + // ReceiptCredentialRequest value until they attempt to redeem the resulting ReceiptCredentialPresentation. After + // this point, the ReceiptCredentialRequest MUST NOT be reused or you may not be able to redeem a valid payment + // invoice. Clients SHOULD retry requests at this endpoint with the same ReceiptCredentialRequest value until + // receiving a response. After receiving a response, clients should then compute the ReceiptCredentialPresentation + // and redeem it at the receipt redemption endpoint. Once the first attempt is made there, the same + // ReceiptCredentialRequest MUST NOT be used again to request receipt credentials. + // + // Note that you may in fact redeem TWO or more invoices for the same ReceiptCredentialRequest while retrying this + // operation if a later invoice gets paid while you are retrying. However, the returned receipt is always for the + // latest invoice, so it will have the latest expiration possible and no entitlement time will be lost. The important + // thing is not to reuse ReceiptCredentialRequest after you have started attempting to redeem the associated + // ReceiptCredentialPresentation. Then you may produce a ReceiptCredentialPresentation for a later invoice that + // cannot be redeemed. + // + // Clients MUST validate that the generated receipt credential's level and expiration matches their expectations. + rpc GetReceiptCredentials(GetReceiptCredentialsRequest) returns (GetReceiptCredentialsResponse) {} + + // Set a token that represents an IAP subscription made with App Store/Google Play Billing. + // + // To set up an App Store subscription: + // 1. Create a subscriber with UpdateSubscriber (you must regularly refresh this subscriber) + // 2. [Create a subscription](https://developer.apple.com/documentation/storekit/in-app_purchase/) with the App Store + // directly via StoreKit and obtain a originalTransactionId. + // 3. Call this RPC with the originalTransactionId + // 4. Obtain a receipt via GetReceiptCredentials which can then be used to obtain the + // entitlement + // + // Play Billing: Set a purchaseToken that represents an IAP subscription made with Google Play Billing. + // + // To set up a subscription with Google Play Billing: + // 1. Create a subscriber with UpdateSubscriber (you must regularly refresh this subscriber) + // 2. [Create a subscription](https://developer.android.com/google/play/billing/integrate) with Google Play Billing + // directly and obtain a purchaseToken. Do not [acknowledge](https://developer.android.com/google/play/billing/integrate#subscriptions) + // the purchaseToken. + // 3. Call this RPC with the purchaseToken + // 4. Obtain a receipt via GetReceiptCredentials which can then be used to obtain the + // entitlement + // + // After calling this method, the payment is confirmed. Callers must durably store their subscriberId before calling + // this method to ensure their payment is tracked. + // + // Once a purchaseToken to is posted to a subscriberId, the same subscriberId must not be used with another payment + // method. A different playbilling purchaseToken can be posted to the same subscriberId, in this case the subscription + // associated with the old purchaseToken will be cancelled. + rpc SetIapSubscription(SetIapSubscriptionRequest) returns (SetIapSubscriptionResponse) {} + + // Returns all configuration for badges, donation subscriptions, backup subscriptions, and one-time donation ( + // "boost" and "gift") minimum and suggested amounts. + rpc GetConfiguration(GetConfigurationRequest) returns (GetConfigurationResponse) {} + + // Returns a localized bank mandate for the specified bank transfer type + rpc GetBankMandate(GetBankMandateRequest) returns (GetBankMandateResponse) {} +} + +message UpdateSubscriberRequest { + bytes subscriberId = 1 [(require.exactlySize) = 32]; +} + +message UpdateSubscriberResponse { + oneof response { + google.protobuf.Empty success = 1; + // subscriberId authentication failure + errors.FailedUnidentifiedAuthorization subscriber_id_mismatch = 2 [(tag.reason) = "subscriber_id_mismatch"]; + } +} + +message DeleteSubscriberRequest { + bytes subscriberId = 1 [(require.exactlySize) = 32]; +} + +message DeleteSubscriberResponse { + oneof response { + google.protobuf.Empty success = 1; + errors.NotFound subscriber_not_found = 2 [(tag.reason) = "subscriber_not_found"]; + // The associated subscription is not a type that can be cancelled by the server. Cancel client-side, and then retry. + errors.FailedPrecondition cannot_cancel_subscription = 3 [(tag.reason) = "cannot_cancel_subscription"]; + } +} + +enum PaymentProvider { + PAYMENT_PROVIDER_UNKNOWN = 0; + PAYMENT_PROVIDER_STRIPE = 1; + PAYMENT_PROVIDER_BRAINTREE = 2; + PAYMENT_PROVIDER_GOOGLE_PLAY_BILLING = 3; + PAYMENT_PROVIDER_APPLE_APP_STORE = 4; +} + +enum PaymentMethod { + PAYMENT_METHOD_UNKNOWN = 0; + // A credit card or debit card, including those from Apple Pay and Google Pay + PAYMENT_METHOD_CARD = 1; + // A SEPA debit account + PAYMENT_METHOD_SEPA_DEBIT = 2; + // An iDEAL account + PAYMENT_METHOD_IDEAL = 3; + // A PayPal account + PAYMENT_METHOD_PAYPAL = 4; + PAYMENT_METHOD_GOOGLE_PLAY_BILLING = 5; + PAYMENT_METHOD_APPLE_APP_STORE = 6; +} + +enum SubscriptionStatus { + SUBSCRIPTION_STATUS_UNKNOWN = 0; + // The subscription is in good standing and the most recent payment was successful. + SUBSCRIPTION_STATUS_ACTIVE = 1; + // Payment failed when creating the subscription, or the subscription's start date is in the future. + SUBSCRIPTION_STATUS_INCOMPLETE = 2; + // Payment on the latest renewal failed but there are processor retries left, or payment wasn't attempted. + SUBSCRIPTION_STATUS_PAST_DUE = 3; + // The subscription has been canceled. + SUBSCRIPTION_STATUS_CANCELED = 4; + // The latest renewal hasn't been paid but the subscription remains in place. + SUBSCRIPTION_STATUS_UNPAID = 5; +} + +message CreatePaymentMethodRequest { + // Only PAYMENT_METHOD_CARD, PAYMENT_METHOD_SEPA_DEBIT, and PAYMENT_METHOD_IDEAL are supported; + // other values will result in an INVALID_ARGUMENT error. + bytes subscriberId = 1 [(require.exactlySize) = 32]; + PaymentMethod paymentMethod = 2 [(require.specified) = true]; +} + +message CreatePaymentMethodResponse { + message CreatePaymentMethodResult { + string clientSecret = 1; + PaymentProvider paymentProvider = 2; + } + + oneof response { + CreatePaymentMethodResult result = 1; + errors.NotFound subscriber_not_found = 2 [(tag.reason) = "subscriber_not_found"]; + // subscriberId authentication failure + errors.FailedUnidentifiedAuthorization subscriber_id_mismatch = 3 [(tag.reason) = "subscriber_id_mismatch"]; + // New payment processor does not match existing processor associated with the subscription + errors.FailedPrecondition subscription_processor_conflict = 4 [(tag.reason) = "subscription_processor_conflict"]; + } +} + +message CreatePayPalPaymentMethodRequest { + bytes subscriberId = 1 [(require.exactlySize) = 32]; + // a callback URL (e.g. an in-client URL handler) for when the user approved the payment + string returnUrl = 2; + // a callback URL (e.g. an in-client URL handler) for when the user did not approve the payment + string cancelUrl = 3; +} + +message CreatePayPalPaymentMethodResponse { + message CreatePayPalPaymentMethodResult { + // a URL to open where the user may approve the payment + string approvalUrl = 1; + // an opaque PayPal payment identifier to use with SetDefaultPaymentMethodRequest + string token = 2; + } + + oneof response { + CreatePayPalPaymentMethodResult result = 1; + errors.NotFound subscriber_not_found = 2 [(tag.reason) = "subscriber_not_found"]; + // subscriberId authentication failure + errors.FailedUnidentifiedAuthorization subscriber_id_mismatch = 3 [(tag.reason) = "subscriber_id_mismatch"]; + // New payment processor does not match existing processor associated with the subscription + errors.FailedPrecondition subscription_processor_conflict = 4 [(tag.reason) = "subscription_processor_conflict"]; + } +} + +message SetDefaultPaymentMethodRequest { + message StripePaymentMethod { + string paymentMethodToken = 1 [(require.nonEmpty) = true]; + } + message BraintreePaymentMethod { + string paymentMethodToken = 1 [(require.nonEmpty) = true]; + } + message SepaPaymentMethod { + string setupIntentId = 1 [(require.nonEmpty) = true]; + } + + bytes subscriberId = 1 [(require.exactlySize) = 32]; + oneof request { + StripePaymentMethod stripe = 2; + BraintreePaymentMethod braintree = 3; + SepaPaymentMethod sepa = 4; + } +} + +message SetDefaultPaymentMethodResponse { + oneof response { + google.protobuf.Empty success = 1; + errors.NotFound subscriber_not_found = 2 [(tag.reason) = "subscriber_not_found"]; + // subscriberId authentication failure + errors.FailedUnidentifiedAuthorization subscriber_id_mismatch = 3 [(tag.reason) = "subscriber_id_mismatch"]; + errors.FailedPrecondition payment_method_not_set_up = 4 [(tag.reason) = "payment_method_not_set_up"]; + } +} + +message SetSubscriptionLevelRequest { + bytes subscriberId = 1 [(require.exactlySize) = 32]; + uint64 level = 2; + string currency = 3; + string idempotencyKey = 4; +} + +// Information about a charge failure. + +// Meaningfully interpreting chargeFailure response fields requires inspecting the processor field first. +// +// For Stripe, code will be one of the [codes defined here](https://stripe.com/docs/api/charges/object#charge_object-failure_code), +// while message [may contain a further textual description](https://stripe.com/docs/api/charges/object#charge_object-failure_message). +// The outcome fields are optional, but present values will directly map to Stripe [response properties](https://stripe.com/docs/api/charges/object#charge_object-outcome-network_status) +// +// For Braintree, the outcome fields will be null. The code and message will contain one of +// - a processor decline code (as a string) in code, and associated text in message, as defined this [table](https://developer.paypal.com/braintree/docs/reference/general/processor-responses/authorization-responses) +// - `gateway` in code, with a [reason](https://developer.paypal.com/braintree/articles/control-panel/transactions/gateway-rejections) in message +// - `code` = "unknown", message = "unknown" +// +// IAP payment processors will never include charge failure information, and detailed order information should be +// retrieved from the payment processor directly +message ChargeFailure { + PaymentProvider processor = 1; + // See [Stripe failure codes](https://stripe.com/docs/api/charges/object#charge_object-failure_code) or + // [Braintree decline codes](https://developer.paypal.com/braintree/docs/reference/general/processor-responses/authorization-responses#decline-codes) + // depending on which processor was used + string code = 2; + // See [Stripe failure codes](https://stripe.com/docs/api/charges/object#charge_object-failure_code) or + // [Braintree decline codes](https://developer.paypal.com/braintree/docs/reference/general/processor-responses/authorization-responses#decline-codes) + // depending on which processor was used + string message = 3; + // See [Outcome Network Status](https://stripe.com/docs/api/charges/object#charge_object-outcome-network_status) + optional string outcome_network_status = 4; + // See [Outcome Reason](https://stripe.com/docs/api/charges/object#charge_object-outcome-reason) + optional string outcome_reason = 5; + // See [Outcome Type](https://stripe.com/docs/api/charges/object#charge_object-outcome-type) + optional string outcome_type = 6; +} + +message SetSubscriptionLevelResponse { + message SetSubscriptionLevelResult { + uint64 level = 1; + } + + oneof response { + SetSubscriptionLevelResult success = 1; + errors.NotFound subscriber_not_found = 2 [(tag.reason) = "subscriber_not_found"]; + // subscriberId authentication failure + errors.FailedUnidentifiedAuthorization subscriber_id_mismatch = 3 [(tag.reason) = "subscriber_id_mismatch"]; + // New payment processor does not match existing processor associated with the subscription + errors.FailedPrecondition subscription_processor_conflict = 4 [(tag.reason) = "subscription_processor_conflict"]; + errors.FailedPrecondition payment_method_not_set_up = 5 [(tag.reason) = "payment_method_not_set_up"]; + // The payment processor does not support this operation + errors.FailedPrecondition unsupported_operation = 6 [(tag.reason) = "unsupported_operation"]; + // The requested level was invalid + errors.FailedPrecondition unsupported_level = 7 [(tag.reason) = "unsupported_level"]; + // The requested currency was invalid + errors.FailedPrecondition unsupported_currency = 8 [(tag.reason) = "unsupported_currency"]; + // The card could not be charged + errors.FailedPrecondition payment_requires_action = 9 [(tag.reason) = "payment_requires_action"]; + // Cannot transition from existing level to the requested level + errors.FailedPrecondition invalid_level_transition = 10 [(tag.reason) = "invalid_level_transition"]; + // The idempotency key was invalid or re-used with a modified request + errors.FailedPrecondition invalid_idempotency_key = 11 [(tag.reason) = "invalid_idempotency_key"]; + // The payment failed; see charge failure details + ChargeFailure charge_failure = 12 [(tag.reason) = "charge_failure"]; + } +} + +message SetIapSubscriptionRequest { + message AppStorePurchase { + string original_transaction_id = 1 [(require.nonEmpty) = true]; + } + message PlayBillingPurchase { + string purchase_token = 1 [(require.nonEmpty) = true]; + } + + bytes subscriberId = 1 [(require.exactlySize) = 32]; + oneof request { + AppStorePurchase app_store = 2; + PlayBillingPurchase play_billing = 3; + } +} + +message SetIapSubscriptionResponse { + message SetIapSubscriptionResult { + uint64 level = 1; + } + + oneof response { + SetIapSubscriptionResult success = 1; + errors.NotFound subscriber_not_found = 2 [(tag.reason) = "subscriber_not_found"]; + // subscriberId authentication failure + errors.FailedUnidentifiedAuthorization subscriber_id_mismatch = 3 [(tag.reason) = "subscriber_id_mismatch"]; + // New payment processor does not match existing processor associated with the subscription + errors.FailedPrecondition subscription_processor_conflict = 4 [(tag.reason) = "subscription_processor_conflict"]; + errors.FailedPrecondition payment_required = 5 [(tag.reason) = "payment_required"]; + errors.FailedPrecondition invalid_transaction = 6 [(tag.reason) = "invalid_transaction"]; + } +} + +message GetReceiptCredentialsRequest { + bytes subscriberId = 1 [(require.exactlySize) = 32]; + bytes receiptCredentialRequest = 2 [(require.exactlySize) = 97]; +} + +message GetReceiptCredentialsResponse { + message GetReceiptCredentialsResult { + bytes receiptCredentialResponse = 1; + } + + message PaymentRequired { + optional ChargeFailure charge_failure = 1; + } + + oneof response { + GetReceiptCredentialsResult success = 1; + errors.NotFound subscriber_not_found = 2 [(tag.reason) = "subscriber_not_found"]; + // subscriberId authentication failure + errors.FailedUnidentifiedAuthorization subscriber_id_mismatch = 3 [(tag.reason) = "subscriber_id_mismatch"]; + // No invoice has been issued for this subscription OR invoice is in 'draft' or 'open' state + errors.FailedPrecondition no_paid_invoice = 4 [(tag.reason) = "no_paid_invoice"]; + // Invoice is in any state other than 'draft', 'open', or 'paid'; Charge failure details may be present + PaymentRequired payment_required = 5 [(tag.reason) = "payment_required"]; + // Latest paid receipt on subscription was already redeemed for a receipt credential but with a different GetReceiptCredentialRequest + errors.FailedPrecondition already_redeemed = 6 [(tag.reason) = "already_redeemed"]; + } +} + +message GetSubscriptionInformationRequest { + bytes subscriberId = 1 [(require.exactlySize) = 32]; +} + +message GetSubscriptionInformationResponse { + message Subscription { + // The subscription level + uint64 level = 1; + // If present, UNIX Epoch Timestamp in seconds, can be used to calculate next billing date. + optional uint64 billing_cycle_anchor = 2; + // UNIX Epoch Timestamp in seconds, when the current subscription period ends + uint64 end_of_current_period = 3; + // Whether there is a currently active subscription + bool active = 4; + // If true, an active subscription will not auto-renew at the end of the current period + bool cancel_at_period_end = 5; + // A three-letter ISO 4217 currency code for currency used in the subscription + string currency = 6; + // The amount paid for the subscription in the currency's smallest unit + uint64 amount = 7; + // The subscription's status, mapped to Stripe's statuses. trialing will never be returned + SubscriptionStatus status = 8; + // The payment provider associated with the subscription + PaymentProvider processor = 9; + // The payment method associated with the subscription + PaymentMethod payment_method = 10; + // Whether the latest charge for the subscription is in a non-terminal state + bool payment_processing = 11; + // if present, contains information that may be interpreted to help the user fix a failure + optional ChargeFailure charge_failure = 12; + } + + oneof response { + Subscription success = 1; + google.protobuf.Empty no_subscription = 2; + errors.NotFound subscriber_not_found = 3 [(tag.reason) = "subscriber_not_found"]; + // subscriberId authentication failure + errors.FailedUnidentifiedAuthorization subscriber_id_mismatch = 4 [(tag.reason) = "subscriber_id_mismatch"]; + } +} + +message GetConfigurationRequest {} + +message GetConfigurationResponse { + message Badge { + common.Badge badge = 1; + // Present only for one-time (purchasable) badges + optional uint64 duration_seconds = 2; + } + + message AmountList { + // NOTE: this is a string instead of a numeric type because it is intended + // for display purposes only + repeated string amounts = 1; + } + + message CurrencyConfiguration { + // Minimum one-time donation + // NOTE: this is a string instead of a numeric type because it is intended + // for display purposes only + string minimum = 1; + // Map of one-time donation level IDs to suggested amounts + map one_time = 2; + // Map of subscription level IDs to the amount charged + map subscription = 3; + // Map of backup subscription level IDs to the amount charged + map backup_subscription = 4; + repeated PaymentMethod supported_payment_methods = 5; + } + + message LevelConfiguration { + Badge badge = 1; + } + + // Configuration for a backup level - use to present appropriate client interfaces + message BackupLevelConfiguration { + // The amount of media storage in bytes that a paying subscriber may store + uint64 storage_allowance_bytes = 1; + // The play billing productID associated with this backup level + string play_product_id = 2; + // The duration, in days, for which your backed up media is retained on the server after you stop refreshing with a paid credential + uint64 media_ttl_days = 3; + } + + message BackupConfiguration { + // A map of numeric backup level IDs to level-specific backup configuration + map levels = 1; + // The number of days of media a free tier backup user gets + uint64 free_tier_media_days = 2; + } + + // Map of lower-cased ISO 3 currency codes to currency-specific configuration + map currencies = 1; + // Map of numeric donation level IDs to level-specific badge configuration + map levels = 2; + BackupConfiguration backup = 3; + // Maximum value of a one-time SEPA donation + string sepa_maximum_euros = 4; +} + +enum BankTransferType { + BANK_TRANSFER_TYPE_UNKNOWN = 0; + BANK_TRANSFER_TYPE_SEPA_DEBIT = 1; +} + +message GetBankMandateRequest { + BankTransferType bank_transfer_type = 1 [(require.specified) = true]; +} + +message GetBankMandateResponse { + string mandate = 1; +} diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/controllers/AbstractV1SubscriptionControllerTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/controllers/AbstractV1SubscriptionControllerTest.java index 41ed51de2..6642366e0 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/controllers/AbstractV1SubscriptionControllerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/controllers/AbstractV1SubscriptionControllerTest.java @@ -8,25 +8,21 @@ package org.whispersystems.textsecuregcm.controllers; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -import com.fasterxml.jackson.databind.ObjectMapper; import java.time.Clock; import org.signal.libsignal.zkgroup.receipts.ServerZkReceiptOperations; import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfiguration; -import org.whispersystems.textsecuregcm.configuration.SubscriptionConfiguration; import org.whispersystems.textsecuregcm.storage.IssuedReceiptsManager; import org.whispersystems.textsecuregcm.subscriptions.BraintreeManager; import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider; import org.whispersystems.textsecuregcm.subscriptions.StripeManager; +import org.whispersystems.textsecuregcm.tests.util.SubscriptionConfigTestHelper; import org.whispersystems.textsecuregcm.util.MockUtils; -import org.whispersystems.textsecuregcm.util.SystemMapper; class AbstractV1SubscriptionControllerTest { static final Clock CLOCK = mock(Clock.class); - private static final ObjectMapper YAML_MAPPER = SystemMapper.yamlMapper(); - - static final OneTimeDonationConfiguration ONETIME_CONFIG = ConfigHelper.getOneTimeConfig(); + static final OneTimeDonationConfiguration ONETIME_CONFIG = SubscriptionConfigTestHelper.getOneTimeConfig(); static final StripeManager STRIPE_MANAGER = MockUtils.buildMock(StripeManager.class, mgr -> when(mgr.getProvider()).thenReturn(PaymentProvider.STRIPE)); static final BraintreeManager BRAINTREE_MANAGER = MockUtils.buildMock(BraintreeManager.class, mgr -> @@ -35,183 +31,5 @@ class AbstractV1SubscriptionControllerTest { static final ServerZkReceiptOperations ZK_OPS = mock(ServerZkReceiptOperations.class); - /** - * Encapsulates {@code static} configuration, to keep the class header simpler and avoid illegal forward references - */ - record ConfigHelper() { - - static SubscriptionConfiguration getSubscriptionConfig() { - return readValue(SUBSCRIPTION_CONFIG_YAML, SubscriptionConfiguration.class); - } - - static OneTimeDonationConfiguration getOneTimeConfig() { - return readValue(ONETIME_CONFIG_YAML, OneTimeDonationConfiguration.class); - } - - private static T readValue(String yaml, Class type) { - try { - return YAML_MAPPER.readValue(yaml, type); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - private static final String SUBSCRIPTION_CONFIG_YAML = """ - badgeExpiration: P30D - badgeGracePeriod: P15D - backupExpiration: P3D - backupGracePeriod: P10D - backupFreeTierMediaDuration: P30D - backupLevels: - 201: - playProductId: testPlayProductId - mediaTtl: P40D - prices: - usd: - amount: '5' - processorIds: - STRIPE: R4 - BRAINTREE: M4 - jpy: - amount: '500' - processorIds: - STRIPE: Q4 - BRAINTREE: N4 - bif: - amount: '5000' - processorIds: - STRIPE: S4 - BRAINTREE: O4 - eur: - amount: '5' - processorIds: - STRIPE: A4 - BRAINTREE: B4 - levels: - 5: - badge: B1 - prices: - usd: - amount: '5' - processorIds: - STRIPE: R1 - BRAINTREE: M1 - jpy: - amount: '500' - processorIds: - STRIPE: Q1 - BRAINTREE: N1 - bif: - amount: '5000' - processorIds: - STRIPE: S1 - BRAINTREE: O1 - eur: - amount: '5' - processorIds: - STRIPE: A1 - BRAINTREE: B1 - 15: - badge: B2 - prices: - usd: - amount: '15' - processorIds: - STRIPE: R2 - BRAINTREE: M2 - jpy: - amount: '1500' - processorIds: - STRIPE: Q2 - BRAINTREE: N2 - bif: - amount: '15000' - processorIds: - STRIPE: S2 - BRAINTREE: O2 - eur: - amount: '15' - processorIds: - STRIPE: A2 - BRAINTREE: B2 - 35: - badge: B3 - prices: - usd: - amount: '35' - processorIds: - STRIPE: R3 - BRAINTREE: M3 - jpy: - amount: '3500' - processorIds: - STRIPE: Q3 - BRAINTREE: N3 - bif: - amount: '35000' - processorIds: - STRIPE: S3 - BRAINTREE: O3 - eur: - amount: '35' - processorIds: - STRIPE: A3 - BRAINTREE: B3 - """; - - private static final String ONETIME_CONFIG_YAML = """ - boost: - level: 1 - expiration: P45D - badge: BOOST - gift: - level: 100 - expiration: P60D - badge: GIFT - currencies: - usd: - minimum: '2.50' # fractional to test BigDecimal conversion - gift: '20' - boosts: - - '5.50' - - '6' - - '7' - - '8' - - '9' - - '10' - eur: - minimum: '3' - gift: '5' - boosts: - - '5' - - '10' - - '20' - - '30' - - '50' - - '100' - jpy: - minimum: '250' - gift: '2000' - boosts: - - '550' - - '600' - - '700' - - '800' - - '900' - - '1000' - bif: - minimum: '2500' - gift: '20000' - boosts: - - '5500' - - '6000' - - '7000' - - '8000' - - '9000' - - '10000' - sepaMaximumEuros: '10000' - """; - - } - } + 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 2799c361a..e1123e5ca 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/controllers/SubscriptionControllerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/controllers/SubscriptionControllerTest.java @@ -79,6 +79,7 @@ import org.whispersystems.textsecuregcm.subscriptions.BankMandateTranslator; import org.whispersystems.textsecuregcm.subscriptions.ChargeFailure; import org.whispersystems.textsecuregcm.subscriptions.CustomerAwareSubscriptionPaymentProcessor; import org.whispersystems.textsecuregcm.subscriptions.GooglePlayBillingManager; +import org.whispersystems.textsecuregcm.subscriptions.LevelConfiguration; import org.whispersystems.textsecuregcm.subscriptions.PaymentMethod; import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider; import org.whispersystems.textsecuregcm.subscriptions.ProcessorCustomer; @@ -91,7 +92,9 @@ 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.tests.util.SubscriptionConfigTestHelper; import org.whispersystems.textsecuregcm.util.MockUtils; import org.whispersystems.textsecuregcm.util.SystemMapper; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; @@ -100,7 +103,7 @@ import software.amazon.awssdk.services.dynamodb.model.AttributeValue; class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest { private static final long MAX_TOTAL_BACKUP_MEDIA_BYTES = 1234L; - private static final SubscriptionConfiguration SUBSCRIPTION_CONFIG = ConfigHelper.getSubscriptionConfig(); + private static final SubscriptionConfiguration SUBSCRIPTION_CONFIG = SubscriptionConfigTestHelper.getSubscriptionConfig(); private static final Subscriptions SUBSCRIPTIONS = mock(Subscriptions.class); private static final GooglePlayBillingManager PLAY_MANAGER = MockUtils.buildMock(GooglePlayBillingManager.class, mgr -> when(mgr.getProvider()).thenReturn(PaymentProvider.GOOGLE_PLAY_BILLING)); @@ -913,95 +916,95 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest { assertThat(currency.minimum()).isEqualByComparingTo( BigDecimal.valueOf(2.5).setScale(2, RoundingMode.HALF_EVEN)); assertThat(currency.oneTime()).isEqualTo( - Map.of("1", + Map.of(1L, List.of(BigDecimal.valueOf(5.5).setScale(2, RoundingMode.HALF_EVEN), BigDecimal.valueOf(6), BigDecimal.valueOf(7), BigDecimal.valueOf(8), - BigDecimal.valueOf(9), BigDecimal.valueOf(10)), "100", + BigDecimal.valueOf(9), BigDecimal.valueOf(10)), 100L, List.of(BigDecimal.valueOf(20)))); assertThat(currency.subscription()).isEqualTo( - Map.of("5", BigDecimal.valueOf(5), "15", BigDecimal.valueOf(15), "35", BigDecimal.valueOf(35))); - assertThat(currency.backupSubscription()).isEqualTo(Map.of("201", BigDecimal.valueOf(5))); - assertThat(currency.supportedPaymentMethods()).isEqualTo(List.of("CARD", "PAYPAL")); + Map.of(5L, BigDecimal.valueOf(5), 15L, BigDecimal.valueOf(15), 35L, BigDecimal.valueOf(35))); + assertThat(currency.backupSubscription()).isEqualTo(Map.of(201L, BigDecimal.valueOf(5))); + assertThat(currency.supportedPaymentMethods()).isEqualTo(List.of(PaymentMethod.CARD, PaymentMethod.PAYPAL)); }); assertThat(currencyMap).extractingByKey("jpy").satisfies(currency -> { assertThat(currency.minimum()).isEqualByComparingTo( BigDecimal.valueOf(250)); assertThat(currency.oneTime()).isEqualTo( - Map.of("1", + Map.of(1L, List.of(BigDecimal.valueOf(550), BigDecimal.valueOf(600), BigDecimal.valueOf(700), BigDecimal.valueOf(800), - BigDecimal.valueOf(900), BigDecimal.valueOf(1000)), "100", + BigDecimal.valueOf(900), BigDecimal.valueOf(1000)), 100L, List.of(BigDecimal.valueOf(2000)))); assertThat(currency.subscription()).isEqualTo( - Map.of("5", BigDecimal.valueOf(500), "15", BigDecimal.valueOf(1500), "35", BigDecimal.valueOf(3500))); - assertThat(currency.backupSubscription()).isEqualTo(Map.of("201", BigDecimal.valueOf(500))); - assertThat(currency.supportedPaymentMethods()).isEqualTo(List.of("CARD", "PAYPAL")); + Map.of(5L, BigDecimal.valueOf(500), 15L, BigDecimal.valueOf(1500), 35L, BigDecimal.valueOf(3500))); + assertThat(currency.backupSubscription()).isEqualTo(Map.of(201L, BigDecimal.valueOf(500))); + assertThat(currency.supportedPaymentMethods()).isEqualTo(List.of(PaymentMethod.CARD, PaymentMethod.PAYPAL)); }); assertThat(currencyMap).extractingByKey("bif").satisfies(currency -> { assertThat(currency.minimum()).isEqualByComparingTo( BigDecimal.valueOf(2500)); assertThat(currency.oneTime()).isEqualTo( - Map.of("1", + Map.of(1L, List.of(BigDecimal.valueOf(5500), BigDecimal.valueOf(6000), BigDecimal.valueOf(7000), BigDecimal.valueOf(8000), - BigDecimal.valueOf(9000), BigDecimal.valueOf(10000)), "100", + BigDecimal.valueOf(9000), BigDecimal.valueOf(10000)), 100L, List.of(BigDecimal.valueOf(20000)))); assertThat(currency.subscription()).isEqualTo( - Map.of("5", BigDecimal.valueOf(5000), "15", BigDecimal.valueOf(15000), "35", BigDecimal.valueOf(35000))); - assertThat(currency.backupSubscription()).isEqualTo(Map.of("201", BigDecimal.valueOf(5000))); - assertThat(currency.supportedPaymentMethods()).isEqualTo(List.of("CARD")); + Map.of(5L, BigDecimal.valueOf(5000), 15L, BigDecimal.valueOf(15000), 35L, BigDecimal.valueOf(35000))); + assertThat(currency.backupSubscription()).isEqualTo(Map.of(201L, BigDecimal.valueOf(5000))); + assertThat(currency.supportedPaymentMethods()).isEqualTo(List.of(PaymentMethod.CARD)); }); assertThat(currencyMap).extractingByKey("eur").satisfies(currency -> { assertThat(currency.minimum()).isEqualByComparingTo( BigDecimal.valueOf(3)); assertThat(currency.oneTime()).isEqualTo( - Map.of("1", + Map.of(1L, List.of(BigDecimal.valueOf(5), BigDecimal.valueOf(10), - BigDecimal.valueOf(20), BigDecimal.valueOf(30), BigDecimal.valueOf(50), BigDecimal.valueOf(100)), "100", + BigDecimal.valueOf(20), BigDecimal.valueOf(30), BigDecimal.valueOf(50), BigDecimal.valueOf(100)), 100L, List.of(BigDecimal.valueOf(5)))); assertThat(currency.subscription()).isEqualTo( - Map.of("5", BigDecimal.valueOf(5), "15", BigDecimal.valueOf(15), "35", BigDecimal.valueOf(35))); - assertThat(currency.backupSubscription()).isEqualTo(Map.of("201", BigDecimal.valueOf(5))); - final List expectedPaymentMethods = List.of("CARD", "SEPA_DEBIT", "IDEAL"); + Map.of(5L, BigDecimal.valueOf(5), 15L, BigDecimal.valueOf(15), 35L, BigDecimal.valueOf(35))); + assertThat(currency.backupSubscription()).isEqualTo(Map.of(201L, BigDecimal.valueOf(5))); + final List expectedPaymentMethods = List.of(PaymentMethod.CARD, PaymentMethod.SEPA_DEBIT, PaymentMethod.IDEAL); assertThat(currency.supportedPaymentMethods()).isEqualTo(expectedPaymentMethods); }); }); - assertThat(response.levels()).containsKeys("1", "5", "15", "35", "100").satisfies(levelsMap -> { - assertThat(levelsMap).extractingByKey("1").satisfies( - level -> assertThat(level).extracting(SubscriptionController.LevelConfiguration::badge) + assertThat(response.levels()).containsKeys(1L, 5L, 15L, 35L, 100L).satisfies(levelsMap -> { + assertThat(levelsMap).extractingByKey(1L).satisfies( + level -> assertThat(level).extracting(LevelConfiguration::badge) .satisfies(badge -> { assertThat(badge.getId()).isEqualTo("BOOST"); assertThat(badge.getName()).isEqualTo("boost1"); })); - assertThat(levelsMap).extractingByKey("100").satisfies( - level -> assertThat(level).extracting(SubscriptionController.LevelConfiguration::badge) + assertThat(levelsMap).extractingByKey(100L).satisfies( + level -> assertThat(level).extracting(LevelConfiguration::badge) .satisfies(badge -> { assertThat(badge.getId()).isEqualTo("GIFT"); assertThat(badge.getName()).isEqualTo("gift1"); })); - assertThat(levelsMap).extractingByKey("5").satisfies(level -> { - assertThat(level).extracting(SubscriptionController.LevelConfiguration::badge) + assertThat(levelsMap).extractingByKey(5L).satisfies(level -> { + assertThat(level).extracting(LevelConfiguration::badge) .satisfies(badge -> { assertThat(badge.getId()).isEqualTo("B1"); assertThat(badge.getName()).isEqualTo("name1"); }); }); - assertThat(levelsMap).extractingByKey("15").satisfies(level -> - assertThat(level).extracting(SubscriptionController.LevelConfiguration::badge) + assertThat(levelsMap).extractingByKey(15L).satisfies(level -> + assertThat(level).extracting(LevelConfiguration::badge) .satisfies(badge -> { assertThat(badge.getId()).isEqualTo("B2"); assertThat(badge.getName()).isEqualTo("name2"); })); - assertThat(levelsMap).extractingByKey("35").satisfies(level -> { - assertThat(level).extracting(SubscriptionController.LevelConfiguration::badge) + assertThat(levelsMap).extractingByKey(35L).satisfies(level -> { + assertThat(level).extracting(LevelConfiguration::badge) .satisfies(badge -> { assertThat(badge.getId()).isEqualTo("B3"); assertThat(badge.getName()).isEqualTo("name3"); diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/grpc/SubscriptionsGrpcServiceTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/SubscriptionsGrpcServiceTest.java new file mode 100644 index 000000000..09396a054 --- /dev/null +++ b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/SubscriptionsGrpcServiceTest.java @@ -0,0 +1,724 @@ +/* + * Copyright 2026 Signal Messenger, LLC + * SPDX-License-Identifier: AGPL-3.0-only + */ + +package org.whispersystems.textsecuregcm.grpc; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import com.google.common.net.InetAddresses; +import com.google.protobuf.ByteString; +import java.math.BigDecimal; +import java.time.Clock; +import java.time.Instant; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.CompletableFuture; +import java.util.stream.Stream; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.EnumSource; +import org.junit.jupiter.params.provider.MethodSource; +import org.mockito.Mock; +import org.signal.chat.subscriptions.CreatePaymentMethodRequest; +import org.signal.chat.subscriptions.CreatePaymentMethodResponse; +import org.signal.chat.subscriptions.CreatePayPalPaymentMethodRequest; +import org.signal.chat.subscriptions.CreatePayPalPaymentMethodResponse; +import org.signal.chat.subscriptions.DeleteSubscriberRequest; +import org.signal.chat.subscriptions.DeleteSubscriberResponse; +import org.signal.chat.subscriptions.GetBankMandateRequest; +import org.signal.chat.subscriptions.GetBankMandateResponse; +import org.signal.chat.subscriptions.GetConfigurationRequest; +import org.signal.chat.subscriptions.GetConfigurationResponse; +import org.signal.chat.subscriptions.GetReceiptCredentialsRequest; +import org.signal.chat.subscriptions.GetReceiptCredentialsResponse; +import org.signal.chat.subscriptions.GetSubscriptionInformationRequest; +import org.signal.chat.subscriptions.GetSubscriptionInformationResponse; +import org.signal.chat.subscriptions.PaymentMethod; +import org.signal.chat.subscriptions.SetDefaultPaymentMethodRequest; +import org.signal.chat.subscriptions.SetDefaultPaymentMethodResponse; +import org.signal.chat.subscriptions.SetIapSubscriptionRequest; +import org.signal.chat.subscriptions.SetIapSubscriptionResponse; +import org.signal.chat.subscriptions.SetSubscriptionLevelRequest; +import org.signal.chat.subscriptions.SetSubscriptionLevelResponse; +import org.signal.chat.subscriptions.SubscriptionsGrpc; +import org.signal.chat.subscriptions.UpdateSubscriberRequest; +import org.signal.chat.subscriptions.UpdateSubscriberResponse; +import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialResponse; +import org.whispersystems.textsecuregcm.badges.BadgeTranslator; +import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfiguration; +import org.whispersystems.textsecuregcm.configuration.SubscriptionConfiguration; +import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicBackupConfiguration; +import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration; +import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException; +import org.whispersystems.textsecuregcm.entities.Badge; +import org.whispersystems.textsecuregcm.entities.BadgeSvg; +import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager; +import org.whispersystems.textsecuregcm.storage.SubscriptionManager; +import org.whispersystems.textsecuregcm.storage.Subscriptions; +import org.whispersystems.textsecuregcm.subscriptions.AppleAppStoreManager; +import org.whispersystems.textsecuregcm.subscriptions.BankMandateTranslator; +import org.whispersystems.textsecuregcm.subscriptions.BankTransferType; +import org.whispersystems.textsecuregcm.subscriptions.BraintreeManager; +import org.whispersystems.textsecuregcm.subscriptions.ChargeFailure; +import org.whispersystems.textsecuregcm.subscriptions.GooglePlayBillingManager; +import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider; +import org.whispersystems.textsecuregcm.subscriptions.ProcessorCustomer; +import org.whispersystems.textsecuregcm.subscriptions.StripeManager; +import org.whispersystems.textsecuregcm.subscriptions.SubscriptionChargeFailurePaymentRequiredException; +import org.whispersystems.textsecuregcm.subscriptions.SubscriptionException; +import org.whispersystems.textsecuregcm.subscriptions.SubscriptionForbiddenException; +import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInformation; +import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidArgumentsException; +import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidIdempotencyKeyException; +import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidLevelException; +import org.whispersystems.textsecuregcm.subscriptions.SubscriptionNotFoundException; +import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPaymentRequiredException; +import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPaymentRequiresActionException; +import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPrice; +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.subscriptions.SubscriptionStatus; +import org.whispersystems.textsecuregcm.tests.util.SubscriptionConfigTestHelper; +import org.whispersystems.textsecuregcm.util.TestClock; +import org.whispersystems.textsecuregcm.util.TestRandomUtil; + +public class SubscriptionsGrpcServiceTest extends + SimpleBaseGrpcTest { + + private final Clock clock = TestClock.pinned(Instant.ofEpochSecond(100)); + + private final SubscriptionConfiguration subscriptionConfiguration = + SubscriptionConfigTestHelper.getSubscriptionConfig(); + + private final OneTimeDonationConfiguration oneTimeDonationConfiguration = + SubscriptionConfigTestHelper.getOneTimeConfig(); + + @Mock + private SubscriptionManager subscriptionManager; + + @Mock + private StripeManager stripeManager; + + @Mock + private BraintreeManager braintreeManager; + + @Mock + private GooglePlayBillingManager googlePlayBillingManager; + + @Mock + private AppleAppStoreManager appleAppStoreManager; + + @Mock + private BadgeTranslator badgeTranslator; + + @Mock + private BankMandateTranslator bankMandateTranslator; + + @Mock + private DynamicConfigurationManager dynamicConfigurationManager; + + private static final ByteString SUBSCRIBER_ID = ByteString.copyFrom(TestRandomUtil.nextBytes(32)); + private static final long LEVEL = 5L; + private static final String CURRENCY = "usd"; + + @Override + protected SubscriptionsGrpcService createServiceBeforeEachTest() { + getMockRequestAttributesInterceptor().setRequestAttributes( + new RequestAttributes(InetAddresses.forString("127.0.0.1"), null, "en-us")); + return new SubscriptionsGrpcService(clock, subscriptionConfiguration, oneTimeDonationConfiguration, + subscriptionManager, stripeManager, braintreeManager, googlePlayBillingManager, appleAppStoreManager, + badgeTranslator, bankMandateTranslator, dynamicConfigurationManager); + } + + @Test + void updateSubscriber() { + final UpdateSubscriberResponse response = unauthenticatedServiceStub().updateSubscriber( + UpdateSubscriberRequest.newBuilder() + .setSubscriberId(SUBSCRIBER_ID) + .build()); + assertEquals(UpdateSubscriberResponse.ResponseCase.SUCCESS, response.getResponseCase()); + } + + @Test + void updateSubscriberIdMismatch() throws SubscriptionForbiddenException { + doThrow(new SubscriptionForbiddenException("subscriberId mismatch")) + .when(subscriptionManager).updateSubscriber(any()); + final UpdateSubscriberResponse response = unauthenticatedServiceStub().updateSubscriber( + UpdateSubscriberRequest.newBuilder() + .setSubscriberId(SUBSCRIBER_ID) + .build()); + assertEquals(UpdateSubscriberResponse.ResponseCase.SUBSCRIBER_ID_MISMATCH, response.getResponseCase()); + } + + @Test + void deleteSubscriber() { + final DeleteSubscriberResponse response = unauthenticatedServiceStub().deleteSubscriber( + DeleteSubscriberRequest.newBuilder() + .setSubscriberId(SUBSCRIBER_ID) + .build()); + assertEquals(DeleteSubscriberResponse.ResponseCase.SUCCESS, response.getResponseCase()); + } + + @Test + void deleteSubscriberNotFound() + throws SubscriptionNotFoundException, SubscriptionInvalidArgumentsException, RateLimitExceededException { + doThrow(new SubscriptionNotFoundException()) + .when(subscriptionManager).deleteSubscriber(any()); + final DeleteSubscriberResponse response = unauthenticatedServiceStub().deleteSubscriber( + DeleteSubscriberRequest.newBuilder() + .setSubscriberId(SUBSCRIBER_ID) + .build()); + assertEquals(DeleteSubscriberResponse.ResponseCase.SUBSCRIBER_NOT_FOUND, response.getResponseCase()); + } + + @Test + void deleteSubscriberCannotCancel() + throws SubscriptionNotFoundException, SubscriptionInvalidArgumentsException, RateLimitExceededException { + doThrow(new SubscriptionInvalidArgumentsException("cannot cancel subscription")) + .when(subscriptionManager).deleteSubscriber(any()); + final DeleteSubscriberResponse response = unauthenticatedServiceStub().deleteSubscriber( + DeleteSubscriberRequest.newBuilder() + .setSubscriberId(SUBSCRIBER_ID) + .build()); + assertEquals(DeleteSubscriberResponse.ResponseCase.CANNOT_CANCEL_SUBSCRIPTION, response.getResponseCase()); + } + + @ParameterizedTest + @EnumSource(value = PaymentMethod.class, names = {"PAYMENT_METHOD_CARD", "PAYMENT_METHOD_SEPA_DEBIT", + "PAYMENT_METHOD_IDEAL"}) + void createPaymentMethod(final PaymentMethod paymentMethod) + throws SubscriptionForbiddenException, SubscriptionNotFoundException, SubscriptionProcessorConflictException { + when(subscriptionManager.addPaymentMethodToCustomer(any(), any(), any(), any())).thenReturn("test-client-secret"); + when(stripeManager.getProvider()).thenReturn(PaymentProvider.STRIPE); + final CreatePaymentMethodRequest.Builder builder = CreatePaymentMethodRequest.newBuilder() + .setSubscriberId(SUBSCRIBER_ID) + .setPaymentMethod(paymentMethod); + final CreatePaymentMethodResponse response = unauthenticatedServiceStub().createPaymentMethod(builder.build()); + assertEquals(CreatePaymentMethodResponse.ResponseCase.RESULT, response.getResponseCase()); + // Currently, only stripe is chosen as the payment provider for all supported payment methods + assertEquals(org.signal.chat.subscriptions.PaymentProvider.PAYMENT_PROVIDER_STRIPE, + response.getResult().getPaymentProvider()); + assertEquals("test-client-secret", response.getResult().getClientSecret()); + } + + @Test + void createPaymentMethodUnsupportedPaymentMethod() { + GrpcTestUtils.assertStatusInvalidArgument( + () -> unauthenticatedServiceStub().createPaymentMethod( + CreatePaymentMethodRequest.newBuilder() + .setSubscriberId(SUBSCRIBER_ID) + .setPaymentMethod(PaymentMethod.PAYMENT_METHOD_PAYPAL) + .build())); + } + + @Test + void createPaymentMethodProcessorConflict() + throws SubscriptionForbiddenException, SubscriptionNotFoundException, SubscriptionProcessorConflictException { + doThrow(new SubscriptionProcessorConflictException()) + .when(subscriptionManager).addPaymentMethodToCustomer(any(), any(), any(), any()); + final CreatePaymentMethodResponse response = unauthenticatedServiceStub().createPaymentMethod( + CreatePaymentMethodRequest.newBuilder() + .setSubscriberId(SUBSCRIBER_ID) + .setPaymentMethod(PaymentMethod.PAYMENT_METHOD_CARD) + .build()); + assertEquals(CreatePaymentMethodResponse.ResponseCase.SUBSCRIPTION_PROCESSOR_CONFLICT, response.getResponseCase()); + } + + @Test + void createPayPalPaymentMethod() + throws SubscriptionForbiddenException, SubscriptionNotFoundException, SubscriptionProcessorConflictException { + final BraintreeManager.PayPalBillingAgreementApprovalDetails details = + new BraintreeManager.PayPalBillingAgreementApprovalDetails("https://fake-approval", "test-billing-token"); + when(subscriptionManager.addPaymentMethodToCustomer(any(), any(), any(), any())) + .thenReturn(CompletableFuture.completedFuture(details)); + final CreatePayPalPaymentMethodResponse response = unauthenticatedServiceStub().createPayPalPaymentMethod( + CreatePayPalPaymentMethodRequest.newBuilder() + .setSubscriberId(SUBSCRIBER_ID) + .setReturnUrl("https://fake-return") + .setCancelUrl("https://fake-cancel") + .build()); + assertEquals(CreatePayPalPaymentMethodResponse.ResponseCase.RESULT, response.getResponseCase()); + assertEquals("https://fake-approval", response.getResult().getApprovalUrl()); + assertEquals("test-billing-token", response.getResult().getToken()); + } + + @Test + void createPayPalPaymentMethodProcessorConflict() + throws SubscriptionForbiddenException, SubscriptionNotFoundException, SubscriptionProcessorConflictException { + doThrow(new SubscriptionProcessorConflictException()) + .when(subscriptionManager).addPaymentMethodToCustomer(any(), any(), any(), any()); + final CreatePayPalPaymentMethodResponse response = unauthenticatedServiceStub().createPayPalPaymentMethod( + CreatePayPalPaymentMethodRequest.newBuilder() + .setSubscriberId(SUBSCRIBER_ID) + .setReturnUrl("https://fake-return") + .setCancelUrl("https://fake-cancel") + .build()); + assertEquals(CreatePayPalPaymentMethodResponse.ResponseCase.SUBSCRIPTION_PROCESSOR_CONFLICT, + response.getResponseCase()); + } + + @ParameterizedTest + @EnumSource(value = SetDefaultPaymentMethodRequest.RequestCase.class, names = {"STRIPE", "BRAINTREE", "SEPA"}) + void setDefaultPaymentMethod(final SetDefaultPaymentMethodRequest.RequestCase requestCase) + throws SubscriptionNotFoundException, SubscriptionForbiddenException { + final PaymentProvider provider = requestCase == SetDefaultPaymentMethodRequest.RequestCase.BRAINTREE + ? PaymentProvider.BRAINTREE : PaymentProvider.STRIPE; + final Subscriptions.Record record = mock(Subscriptions.Record.class); + when(record.getProcessorCustomer()).thenReturn(Optional.of(new ProcessorCustomer("test-customer", provider))); + when(subscriptionManager.getSubscriber(any())).thenReturn(record); + if (requestCase == SetDefaultPaymentMethodRequest.RequestCase.SEPA) { + when(stripeManager.getGeneratedSepaIdFromSetupIntent(any())) + .thenReturn(CompletableFuture.completedFuture("sepa-id")); + } + final SetDefaultPaymentMethodRequest.Builder builder = SetDefaultPaymentMethodRequest.newBuilder() + .setSubscriberId(SUBSCRIBER_ID); + switch (requestCase) { + case STRIPE -> builder.setStripe(SetDefaultPaymentMethodRequest.StripePaymentMethod.newBuilder() + .setPaymentMethodToken("test-stripe-token").build()); + case BRAINTREE -> builder.setBraintree(SetDefaultPaymentMethodRequest.BraintreePaymentMethod.newBuilder() + .setPaymentMethodToken("test-braintree-token").build()); + case SEPA -> builder.setSepa(SetDefaultPaymentMethodRequest.SepaPaymentMethod.newBuilder() + .setSetupIntentId("test-setup-intent-id").build()); + default -> throw new IllegalArgumentException("Unexpected case: " + requestCase); + } + final SetDefaultPaymentMethodResponse response = + unauthenticatedServiceStub().setDefaultPaymentMethod(builder.build()); + assertEquals(SetDefaultPaymentMethodResponse.ResponseCase.SUCCESS, response.getResponseCase()); + } + + @Test + void setDefaultPaymentMethodNoRequest() { + GrpcTestUtils.assertStatusInvalidArgument( + () -> unauthenticatedServiceStub().setDefaultPaymentMethod( + SetDefaultPaymentMethodRequest.newBuilder() + .setSubscriberId(SUBSCRIBER_ID) + .build())); + } + + @Test + void setDefaultPaymentMethodSubscriptionNotFound() + throws SubscriptionNotFoundException, SubscriptionForbiddenException { + doThrow(new SubscriptionNotFoundException()) + .when(subscriptionManager).getSubscriber(any()); + final SetDefaultPaymentMethodResponse response = unauthenticatedServiceStub().setDefaultPaymentMethod( + SetDefaultPaymentMethodRequest.newBuilder() + .setSubscriberId(SUBSCRIBER_ID) + .setStripe(SetDefaultPaymentMethodRequest.StripePaymentMethod.newBuilder() + .setPaymentMethodToken("test-token").build()) + .build()); + assertEquals(SetDefaultPaymentMethodResponse.ResponseCase.SUBSCRIBER_NOT_FOUND, response.getResponseCase()); + } + + @Test + void setDefaultPaymentMethodNoCustomer() throws SubscriptionNotFoundException, SubscriptionForbiddenException { + final Subscriptions.Record record = mock(Subscriptions.Record.class); + when(record.getProcessorCustomer()).thenReturn(Optional.empty()); + when(subscriptionManager.getSubscriber(any())).thenReturn(record); + final SetDefaultPaymentMethodResponse response = unauthenticatedServiceStub().setDefaultPaymentMethod( + SetDefaultPaymentMethodRequest.newBuilder() + .setSubscriberId(SUBSCRIBER_ID) + .setStripe(SetDefaultPaymentMethodRequest.StripePaymentMethod.newBuilder() + .setPaymentMethodToken("test-token").build()) + .build()); + assertEquals(SetDefaultPaymentMethodResponse.ResponseCase.PAYMENT_METHOD_NOT_SET_UP, response.getResponseCase()); + } + + private void mockValidSubscription() throws SubscriptionNotFoundException, SubscriptionForbiddenException { + final Subscriptions.Record record = mock(Subscriptions.Record.class); + when(record.getProcessorCustomer()).thenReturn( + Optional.of(new ProcessorCustomer("test-customer", PaymentProvider.STRIPE))); + when(subscriptionManager.getSubscriber(any())).thenReturn(record); + } + + @Test + void setSubscriptionLevel() throws SubscriptionException { + mockValidSubscription(); + final SetSubscriptionLevelResponse response = unauthenticatedServiceStub().setSubscriptionLevel( + SetSubscriptionLevelRequest.newBuilder() + .setSubscriberId(SUBSCRIBER_ID) + .setLevel(LEVEL) + .setCurrency(CURRENCY) + .setIdempotencyKey("test-idempotency-key") + .build()); + assertEquals(SetSubscriptionLevelResponse.ResponseCase.SUCCESS, response.getResponseCase()); + assertEquals(LEVEL, response.getSuccess().getLevel()); + } + + @Test + void setSubscriptionLevelNotFound() throws SubscriptionNotFoundException, SubscriptionForbiddenException { + doThrow(new SubscriptionNotFoundException()) + .when(subscriptionManager).getSubscriber(any()); + final SetSubscriptionLevelResponse response = unauthenticatedServiceStub().setSubscriptionLevel( + SetSubscriptionLevelRequest.newBuilder() + .setSubscriberId(SUBSCRIBER_ID) + .setLevel(LEVEL).setCurrency(CURRENCY).setIdempotencyKey("test-idempotency-key") + .build()); + assertEquals(SetSubscriptionLevelResponse.ResponseCase.SUBSCRIBER_NOT_FOUND, response.getResponseCase()); + } + + @Test + void setSubscriptionLevelNoCustomer() throws SubscriptionNotFoundException, SubscriptionForbiddenException { + final Subscriptions.Record record = mock(Subscriptions.Record.class); + when(record.getProcessorCustomer()).thenReturn(Optional.empty()); + when(subscriptionManager.getSubscriber(any())).thenReturn(record); + final SetSubscriptionLevelResponse response = unauthenticatedServiceStub().setSubscriptionLevel( + SetSubscriptionLevelRequest.newBuilder() + .setSubscriberId(SUBSCRIBER_ID) + .setLevel(LEVEL).setCurrency(CURRENCY).setIdempotencyKey("test-idempotency-key") + .build()); + assertEquals(SetSubscriptionLevelResponse.ResponseCase.PAYMENT_METHOD_NOT_SET_UP, response.getResponseCase()); + } + + @Test + void setSubscriptionLevelUnsupportedLevel() throws SubscriptionNotFoundException, SubscriptionForbiddenException { + final Subscriptions.Record record = mock(Subscriptions.Record.class); + when(record.getProcessorCustomer()).thenReturn( + Optional.of(new ProcessorCustomer("test-customer", PaymentProvider.STRIPE))); + when(subscriptionManager.getSubscriber(any())).thenReturn(record); + final SetSubscriptionLevelResponse response = unauthenticatedServiceStub().setSubscriptionLevel( + SetSubscriptionLevelRequest.newBuilder() + .setSubscriberId(SUBSCRIBER_ID) + .setLevel(999L).setCurrency(CURRENCY).setIdempotencyKey("test-idempotency-key") + .build()); + assertEquals(SetSubscriptionLevelResponse.ResponseCase.UNSUPPORTED_LEVEL, response.getResponseCase()); + } + + @Test + void setSubscriptionLevelUnsupportedCurrency() throws SubscriptionNotFoundException, SubscriptionForbiddenException { + final Subscriptions.Record record = mock(Subscriptions.Record.class); + when(record.getProcessorCustomer()).thenReturn( + Optional.of(new ProcessorCustomer("test-customer", PaymentProvider.STRIPE))); + when(subscriptionManager.getSubscriber(any())).thenReturn(record); + final SetSubscriptionLevelResponse response = unauthenticatedServiceStub().setSubscriptionLevel( + SetSubscriptionLevelRequest.newBuilder() + .setSubscriberId(SUBSCRIBER_ID) + .setLevel(LEVEL).setCurrency("xyz").setIdempotencyKey("test-idempotency-key") + .build()); + assertEquals(SetSubscriptionLevelResponse.ResponseCase.UNSUPPORTED_CURRENCY, response.getResponseCase()); + } + + @ParameterizedTest + @MethodSource + void setSubscriptionLevelUpdateExceptions(final SubscriptionException exception, + final SetSubscriptionLevelResponse.ResponseCase expectedCase) + throws SubscriptionException { + mockValidSubscription(); + doThrow(exception).when(subscriptionManager).updateSubscriptionLevelForCustomer( + any(), any(), any(), anyLong(), any(), any(), any(), any()); + final SetSubscriptionLevelResponse response = unauthenticatedServiceStub().setSubscriptionLevel( + SetSubscriptionLevelRequest.newBuilder() + .setSubscriberId(SUBSCRIBER_ID) + .setLevel(LEVEL).setCurrency(CURRENCY).setIdempotencyKey("test-idempotency-key") + .build()); + assertEquals(expectedCase, response.getResponseCase()); + } + + static Stream setSubscriptionLevelUpdateExceptions() { + return Stream.of( + Arguments.of(new SubscriptionInvalidIdempotencyKeyException("bad key"), + SetSubscriptionLevelResponse.ResponseCase.INVALID_IDEMPOTENCY_KEY), + Arguments.of(new SubscriptionPaymentRequiresActionException(), + SetSubscriptionLevelResponse.ResponseCase.PAYMENT_REQUIRES_ACTION), + Arguments.of(new SubscriptionInvalidLevelException(), + SetSubscriptionLevelResponse.ResponseCase.INVALID_LEVEL_TRANSITION), + Arguments.of(new SubscriptionProcessorConflictException(), + SetSubscriptionLevelResponse.ResponseCase.SUBSCRIPTION_PROCESSOR_CONFLICT) + ); + } + + @Test + void setSubscriptionLevelChargeFailure() + throws SubscriptionException { + mockValidSubscription(); + doThrow(new SubscriptionProcessorException(PaymentProvider.STRIPE, + new ChargeFailure("card_declined", "Insufficient funds", null, null, null))) + .when(subscriptionManager).updateSubscriptionLevelForCustomer( + any(), any(), any(), anyLong(), any(), any(), any(), any()); + final SetSubscriptionLevelResponse response = unauthenticatedServiceStub().setSubscriptionLevel( + SetSubscriptionLevelRequest.newBuilder() + .setSubscriberId(SUBSCRIBER_ID) + .setLevel(LEVEL).setCurrency(CURRENCY).setIdempotencyKey("test-idempotency-key") + .build()); + assertEquals(SetSubscriptionLevelResponse.ResponseCase.CHARGE_FAILURE, response.getResponseCase()); + assertEquals(org.signal.chat.subscriptions.PaymentProvider.PAYMENT_PROVIDER_STRIPE, + response.getChargeFailure().getProcessor()); + assertEquals("card_declined", response.getChargeFailure().getCode()); + assertEquals("Insufficient funds", response.getChargeFailure().getMessage()); + } + + @Test + void getSubscriptionInformation() + throws SubscriptionNotFoundException, SubscriptionForbiddenException, RateLimitExceededException { + final SubscriptionInformation info = new SubscriptionInformation( + new SubscriptionPrice(CURRENCY, BigDecimal.valueOf(500)), + LEVEL, + Instant.ofEpochSecond(100), + Instant.ofEpochSecond(1000), + true, + false, + SubscriptionStatus.ACTIVE, + PaymentProvider.STRIPE, + org.whispersystems.textsecuregcm.subscriptions.PaymentMethod.CARD, + false, + null); + when(subscriptionManager.getSubscriptionInformation(any())).thenReturn(Optional.of(info)); + final GetSubscriptionInformationResponse response = unauthenticatedServiceStub().getSubscriptionInformation( + GetSubscriptionInformationRequest.newBuilder() + .setSubscriberId(SUBSCRIBER_ID) + .build()); + assertEquals(GetSubscriptionInformationResponse.ResponseCase.SUCCESS, response.getResponseCase()); + assertEquals(LEVEL, response.getSuccess().getLevel()); + assertEquals(CURRENCY, response.getSuccess().getCurrency()); + assertEquals(500L, response.getSuccess().getAmount()); + assertEquals(1000L, response.getSuccess().getEndOfCurrentPeriod()); + assertTrue(response.getSuccess().getActive()); + assertFalse(response.getSuccess().getCancelAtPeriodEnd()); + assertEquals(org.signal.chat.subscriptions.PaymentProvider.PAYMENT_PROVIDER_STRIPE, + response.getSuccess().getProcessor()); + assertEquals(PaymentMethod.PAYMENT_METHOD_CARD, response.getSuccess().getPaymentMethod()); + } + + @Test + void getSubscriptionInformationNoSubscription() + throws SubscriptionNotFoundException, SubscriptionForbiddenException, RateLimitExceededException { + when(subscriptionManager.getSubscriptionInformation(any())).thenReturn(Optional.empty()); + final GetSubscriptionInformationResponse response = unauthenticatedServiceStub().getSubscriptionInformation( + GetSubscriptionInformationRequest.newBuilder() + .setSubscriberId(SUBSCRIBER_ID) + .build()); + assertEquals(GetSubscriptionInformationResponse.ResponseCase.NO_SUBSCRIPTION, response.getResponseCase()); + } + + @Test + void getReceiptCredentials() throws Exception { + final ReceiptCredentialResponse receiptCredentialResponse = mock(ReceiptCredentialResponse.class); + final byte[] responseBytes = TestRandomUtil.nextBytes(16); + when(receiptCredentialResponse.serialize()).thenReturn(responseBytes); + when(subscriptionManager.createReceiptCredentials(any(), any(), any())) + .thenReturn(new SubscriptionManager.ReceiptResult(receiptCredentialResponse, null, PaymentProvider.STRIPE)); + final GetReceiptCredentialsResponse response = unauthenticatedServiceStub().getReceiptCredentials( + GetReceiptCredentialsRequest.newBuilder() + .setSubscriberId(SUBSCRIBER_ID) + .setReceiptCredentialRequest(ByteString.copyFrom(TestRandomUtil.nextBytes(97))) + .build()); + assertEquals(GetReceiptCredentialsResponse.ResponseCase.SUCCESS, response.getResponseCase()); + assertArrayEquals(responseBytes, response.getSuccess().getReceiptCredentialResponse().toByteArray()); + } + + static Stream getReceiptCredentialsExceptions() { + return Stream.of( + Arguments.of(new SubscriptionReceiptRequestedForOpenPaymentException(), + GetReceiptCredentialsResponse.ResponseCase.NO_PAID_INVOICE), + Arguments.of(new SubscriptionPaymentRequiredException(), + GetReceiptCredentialsResponse.ResponseCase.PAYMENT_REQUIRED), + Arguments.of(new SubscriptionReceiptAlreadyRedeemedException(), + GetReceiptCredentialsResponse.ResponseCase.ALREADY_REDEEMED) + ); + } + + @ParameterizedTest + @MethodSource + void getReceiptCredentialsExceptions(final SubscriptionException exception, + final GetReceiptCredentialsResponse.ResponseCase expectedCase) throws Exception { + doThrow(exception).when(subscriptionManager).createReceiptCredentials(any(), any(), any()); + final GetReceiptCredentialsResponse response = unauthenticatedServiceStub().getReceiptCredentials( + GetReceiptCredentialsRequest.newBuilder() + .setSubscriberId(SUBSCRIBER_ID) + .setReceiptCredentialRequest(ByteString.copyFrom(TestRandomUtil.nextBytes(97))) + .build()); + assertEquals(expectedCase, response.getResponseCase()); + } + + @Test + void getReceiptCredentialsChargeFailure() throws Exception { + doThrow(new SubscriptionChargeFailurePaymentRequiredException(PaymentProvider.STRIPE, + new ChargeFailure("card_declined", "Insufficient funds", null, null, null))) + .when(subscriptionManager).createReceiptCredentials(any(), any(), any()); + final GetReceiptCredentialsResponse response = unauthenticatedServiceStub().getReceiptCredentials( + GetReceiptCredentialsRequest.newBuilder() + .setSubscriberId(SUBSCRIBER_ID) + .setReceiptCredentialRequest(ByteString.copyFrom(TestRandomUtil.nextBytes(97))) + .build()); + assertEquals(GetReceiptCredentialsResponse.ResponseCase.PAYMENT_REQUIRED, response.getResponseCase()); + assertEquals(org.signal.chat.subscriptions.PaymentProvider.PAYMENT_PROVIDER_STRIPE, + response.getPaymentRequired().getChargeFailure().getProcessor()); + assertEquals("card_declined", response.getPaymentRequired().getChargeFailure().getCode()); + } + + @ParameterizedTest + @EnumSource(value = SetIapSubscriptionRequest.RequestCase.class, names = {"APP_STORE", "PLAY_BILLING"}) + void setIapSubscription(final SetIapSubscriptionRequest.RequestCase requestCase) + throws SubscriptionException, RateLimitExceededException { + when(subscriptionManager.updateAppStoreTransactionId(any(), any(), any())).thenReturn(LEVEL); + when(subscriptionManager.updatePlayBillingPurchaseToken(any(), any(), any())).thenReturn(LEVEL); + final SetIapSubscriptionRequest.Builder builder = SetIapSubscriptionRequest.newBuilder() + .setSubscriberId(SUBSCRIBER_ID); + switch (requestCase) { + case APP_STORE -> builder.setAppStore(SetIapSubscriptionRequest.AppStorePurchase.newBuilder() + .setOriginalTransactionId("test-transaction-id").build()); + case PLAY_BILLING -> builder.setPlayBilling(SetIapSubscriptionRequest.PlayBillingPurchase.newBuilder() + .setPurchaseToken("test-purchase-token").build()); + default -> throw new IllegalArgumentException("Unexpected case: " + requestCase); + } + final SetIapSubscriptionResponse response = + unauthenticatedServiceStub().setIapSubscription(builder.build()); + assertEquals(SetIapSubscriptionResponse.ResponseCase.SUCCESS, response.getResponseCase()); + assertEquals(LEVEL, response.getSuccess().getLevel()); + } + + @Test + void setIapSubscriptionNoRequest() { + GrpcTestUtils.assertStatusInvalidArgument( + () -> unauthenticatedServiceStub().setIapSubscription( + SetIapSubscriptionRequest.newBuilder() + .setSubscriberId(SUBSCRIBER_ID) + .build())); + } + + static Stream setIapSubscriptionExceptions() { + return Stream.of( + Arguments.of(new SubscriptionNotFoundException(), + SetIapSubscriptionResponse.ResponseCase.SUBSCRIBER_NOT_FOUND), + Arguments.of(new SubscriptionProcessorConflictException(), + SetIapSubscriptionResponse.ResponseCase.SUBSCRIPTION_PROCESSOR_CONFLICT), + Arguments.of(new SubscriptionPaymentRequiredException(), + SetIapSubscriptionResponse.ResponseCase.PAYMENT_REQUIRED), + Arguments.of(new SubscriptionInvalidArgumentsException("invalid"), + SetIapSubscriptionResponse.ResponseCase.INVALID_TRANSACTION) + ); + } + + @ParameterizedTest + @MethodSource + void setIapSubscriptionExceptions(final SubscriptionException exception, + final SetIapSubscriptionResponse.ResponseCase expectedCase) + throws SubscriptionException, RateLimitExceededException { + doThrow(exception).when(subscriptionManager).updateAppStoreTransactionId(any(), any(), any()); + final SetIapSubscriptionResponse response = unauthenticatedServiceStub().setIapSubscription( + SetIapSubscriptionRequest.newBuilder() + .setSubscriberId(SUBSCRIBER_ID) + .setAppStore(SetIapSubscriptionRequest.AppStorePurchase.newBuilder() + .setOriginalTransactionId("test-transaction-id").build()) + .build()); + assertEquals(expectedCase, response.getResponseCase()); + } + + @Test + void getConfiguration() { + final DynamicConfiguration dynamicConfiguration = mock(DynamicConfiguration.class); + when(dynamicConfigurationManager.getConfiguration()).thenReturn(dynamicConfiguration); + when(dynamicConfiguration.getBackupConfiguration()) + .thenReturn(new DynamicBackupConfiguration(null, null, null, null, 1234L)); + + when(stripeManager.supportsPaymentMethod(any())).thenCallRealMethod(); + when(stripeManager.getSupportedCurrenciesForPaymentMethod( + org.whispersystems.textsecuregcm.subscriptions.PaymentMethod.CARD)) + .thenReturn(Set.of("usd", "jpy", "bif", "eur")); + when(stripeManager.getSupportedCurrenciesForPaymentMethod( + org.whispersystems.textsecuregcm.subscriptions.PaymentMethod.SEPA_DEBIT)) + .thenReturn(Set.of("eur")); + when(stripeManager.getSupportedCurrenciesForPaymentMethod( + org.whispersystems.textsecuregcm.subscriptions.PaymentMethod.IDEAL)) + .thenReturn(Set.of("eur")); + when(braintreeManager.supportsPaymentMethod(any())).thenCallRealMethod(); + when(braintreeManager.getSupportedCurrenciesForPaymentMethod( + org.whispersystems.textsecuregcm.subscriptions.PaymentMethod.PAYPAL)) + .thenReturn(Set.of("usd", "jpy")); + + when(badgeTranslator.translate(any(), eq("B1"))).thenReturn(new Badge("B1", "cat1", "name1", "desc1", + List.of("l", "m", "h", "x", "xx", "xxx"), "SVG", List.of(new BadgeSvg("sl", "sd")))); + when(badgeTranslator.translate(any(), eq("B2"))).thenReturn(new Badge("B2", "cat2", "name2", "desc2", + List.of("l", "m", "h", "x", "xx", "xxx"), "SVG", List.of(new BadgeSvg("sl", "sd")))); + when(badgeTranslator.translate(any(), eq("B3"))).thenReturn(new Badge("B3", "cat3", "name3", "desc3", + List.of("l", "m", "h", "x", "xx", "xxx"), "SVG", List.of(new BadgeSvg("sl", "sd")))); + when(badgeTranslator.translate(any(), eq("BOOST"))).thenReturn(new Badge("BOOST", "boost1", "boost1", "boost1", + List.of("l", "m", "h", "x", "xx", "xxx"), "SVG", List.of(new BadgeSvg("sl", "sd")))); + when(badgeTranslator.translate(any(), eq("GIFT"))).thenReturn(new Badge("GIFT", "gift1", "gift1", "gift1", + List.of("l", "m", "h", "x", "xx", "xxx"), "SVG", List.of(new BadgeSvg("sl", "sd")))); + + final GetConfigurationResponse response = unauthenticatedServiceStub() + .getConfiguration(GetConfigurationRequest.newBuilder().build()); + + assertEquals("10000", response.getSepaMaximumEuros()); + + assertEquals(30L, response.getBackup().getFreeTierMediaDays()); + final GetConfigurationResponse.BackupLevelConfiguration backupLevel = + response.getBackup().getLevelsOrThrow(201L); + assertEquals(1234L, backupLevel.getStorageAllowanceBytes()); + assertEquals("testPlayProductId", backupLevel.getPlayProductId()); + assertEquals(40L, backupLevel.getMediaTtlDays()); + + final GetConfigurationResponse.CurrencyConfiguration usd = response.getCurrenciesOrThrow("usd"); + assertEquals("2.50", usd.getMinimum()); + assertEquals(List.of(PaymentMethod.PAYMENT_METHOD_CARD, PaymentMethod.PAYMENT_METHOD_PAYPAL), + usd.getSupportedPaymentMethodsList()); + assertEquals(List.of("5.50", "6", "7", "8", "9", "10"), usd.getOneTimeOrThrow(1L).getAmountsList()); + assertEquals(List.of("20"), usd.getOneTimeOrThrow(100L).getAmountsList()); + assertEquals(Map.of(5L, "5", 15L, "15", 35L, "35"), usd.getSubscriptionMap()); + assertEquals(Map.of(201L, "5"), usd.getBackupSubscriptionMap()); + + final GetConfigurationResponse.CurrencyConfiguration jpy = response.getCurrenciesOrThrow("jpy"); + assertEquals("250", jpy.getMinimum()); + assertEquals(List.of(PaymentMethod.PAYMENT_METHOD_CARD, PaymentMethod.PAYMENT_METHOD_PAYPAL), + jpy.getSupportedPaymentMethodsList()); + assertEquals(List.of("550", "600", "700", "800", "900", "1000"), jpy.getOneTimeOrThrow(1L).getAmountsList()); + assertEquals(List.of("2000"), jpy.getOneTimeOrThrow(100L).getAmountsList()); + assertEquals(Map.of(5L, "500", 15L, "1500", 35L, "3500"), jpy.getSubscriptionMap()); + assertEquals(Map.of(201L, "500"), jpy.getBackupSubscriptionMap()); + + final GetConfigurationResponse.CurrencyConfiguration bif = response.getCurrenciesOrThrow("bif"); + assertEquals("2500", bif.getMinimum()); + assertEquals(List.of(PaymentMethod.PAYMENT_METHOD_CARD), bif.getSupportedPaymentMethodsList()); + assertEquals(List.of("5500", "6000", "7000", "8000", "9000", "10000"), bif.getOneTimeOrThrow(1L).getAmountsList()); + assertEquals(List.of("20000"), bif.getOneTimeOrThrow(100L).getAmountsList()); + assertEquals(Map.of(5L, "5000", 15L, "15000", 35L, "35000"), bif.getSubscriptionMap()); + assertEquals(Map.of(201L, "5000"), bif.getBackupSubscriptionMap()); + + final GetConfigurationResponse.CurrencyConfiguration eur = response.getCurrenciesOrThrow("eur"); + assertEquals("3", eur.getMinimum()); + assertEquals( + List.of(PaymentMethod.PAYMENT_METHOD_CARD, PaymentMethod.PAYMENT_METHOD_SEPA_DEBIT, + PaymentMethod.PAYMENT_METHOD_IDEAL), + eur.getSupportedPaymentMethodsList()); + assertEquals(List.of("5", "10", "20", "30", "50", "100"), eur.getOneTimeOrThrow(1L).getAmountsList()); + assertEquals(List.of("5"), eur.getOneTimeOrThrow(100L).getAmountsList()); + assertEquals(Map.of(5L, "5", 15L, "15", 35L, "35"), eur.getSubscriptionMap()); + assertEquals(Map.of(201L, "5"), eur.getBackupSubscriptionMap()); + + assertEquals("B1", response.getLevelsOrThrow(5L).getBadge().getBadge().getId()); + assertEquals(0L, response.getLevelsOrThrow(5L).getBadge().getDurationSeconds()); + assertEquals("B2", response.getLevelsOrThrow(15L).getBadge().getBadge().getId()); + assertEquals("B3", response.getLevelsOrThrow(35L).getBadge().getBadge().getId()); + assertEquals("BOOST", response.getLevelsOrThrow(1L).getBadge().getBadge().getId()); + assertTrue(response.getLevelsOrThrow(1L).getBadge().getDurationSeconds() > 0); + assertEquals("GIFT", response.getLevelsOrThrow(100L).getBadge().getBadge().getId()); + assertTrue(response.getLevelsOrThrow(100L).getBadge().getDurationSeconds() > 0); + } + + @Test + void getBankMandate() { + when(bankMandateTranslator.translate(any(), eq(BankTransferType.SEPA_DEBIT))).thenReturn("test-mandate"); + final GetBankMandateResponse response = unauthenticatedServiceStub().getBankMandate( + GetBankMandateRequest.newBuilder() + .setBankTransferType(org.signal.chat.subscriptions.BankTransferType.BANK_TRANSFER_TYPE_SEPA_DEBIT) + .build()); + assertEquals("test-mandate", response.getMandate()); + } + +} diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/tests/util/SubscriptionConfigTestHelper.java b/service/src/test/java/org/whispersystems/textsecuregcm/tests/util/SubscriptionConfigTestHelper.java new file mode 100644 index 000000000..d01475143 --- /dev/null +++ b/service/src/test/java/org/whispersystems/textsecuregcm/tests/util/SubscriptionConfigTestHelper.java @@ -0,0 +1,190 @@ +/* + * Copyright 2026 Signal Messenger, LLC + * SPDX-License-Identifier: AGPL-3.0-only + */ + +package org.whispersystems.textsecuregcm.tests.util; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfiguration; +import org.whispersystems.textsecuregcm.configuration.SubscriptionConfiguration; +import org.whispersystems.textsecuregcm.util.SystemMapper; + +public final class SubscriptionConfigTestHelper { + + private static final ObjectMapper YAML_MAPPER = SystemMapper.yamlMapper(); + + public static SubscriptionConfiguration getSubscriptionConfig() { + return readValue(SUBSCRIPTION_CONFIG_YAML, SubscriptionConfiguration.class); + } + + public static OneTimeDonationConfiguration getOneTimeConfig() { + return readValue(ONETIME_CONFIG_YAML, OneTimeDonationConfiguration.class); + } + + private static T readValue(final String yaml, final Class type) { + try { + return YAML_MAPPER.readValue(yaml, type); + } catch (final Exception e) { + throw new RuntimeException(e); + } + } + + private static final String SUBSCRIPTION_CONFIG_YAML = """ + badgeExpiration: P30D + badgeGracePeriod: P15D + backupExpiration: P3D + backupGracePeriod: P10D + backupFreeTierMediaDuration: P30D + backupLevels: + 201: + playProductId: testPlayProductId + mediaTtl: P40D + prices: + usd: + amount: '5' + processorIds: + STRIPE: R4 + BRAINTREE: M4 + jpy: + amount: '500' + processorIds: + STRIPE: Q4 + BRAINTREE: N4 + bif: + amount: '5000' + processorIds: + STRIPE: S4 + BRAINTREE: O4 + eur: + amount: '5' + processorIds: + STRIPE: A4 + BRAINTREE: B4 + levels: + 5: + badge: B1 + prices: + usd: + amount: '5' + processorIds: + STRIPE: R1 + BRAINTREE: M1 + jpy: + amount: '500' + processorIds: + STRIPE: Q1 + BRAINTREE: N1 + bif: + amount: '5000' + processorIds: + STRIPE: S1 + BRAINTREE: O1 + eur: + amount: '5' + processorIds: + STRIPE: A1 + BRAINTREE: B1 + 15: + badge: B2 + prices: + usd: + amount: '15' + processorIds: + STRIPE: R2 + BRAINTREE: M2 + jpy: + amount: '1500' + processorIds: + STRIPE: Q2 + BRAINTREE: N2 + bif: + amount: '15000' + processorIds: + STRIPE: S2 + BRAINTREE: O2 + eur: + amount: '15' + processorIds: + STRIPE: A2 + BRAINTREE: B2 + 35: + badge: B3 + prices: + usd: + amount: '35' + processorIds: + STRIPE: R3 + BRAINTREE: M3 + jpy: + amount: '3500' + processorIds: + STRIPE: Q3 + BRAINTREE: N3 + bif: + amount: '35000' + processorIds: + STRIPE: S3 + BRAINTREE: O3 + eur: + amount: '35' + processorIds: + STRIPE: A3 + BRAINTREE: B3 + """; + + private static final String ONETIME_CONFIG_YAML = """ + boost: + level: 1 + expiration: P45D + badge: BOOST + gift: + level: 100 + expiration: P60D + badge: GIFT + currencies: + usd: + minimum: '2.50' # fractional to test BigDecimal conversion + gift: '20' + boosts: + - '5.50' + - '6' + - '7' + - '8' + - '9' + - '10' + eur: + minimum: '3' + gift: '5' + boosts: + - '5' + - '10' + - '20' + - '30' + - '50' + - '100' + jpy: + minimum: '250' + gift: '2000' + boosts: + - '550' + - '600' + - '700' + - '800' + - '900' + - '1000' + bif: + minimum: '2500' + gift: '20000' + boosts: + - '5500' + - '6000' + - '7000' + - '8000' + - '9000' + - '10000' + sepaMaximumEuros: '10000' + """; + + private SubscriptionConfigTestHelper() {} +}