diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/controllers/OneTimeDonationController.java b/service/src/main/java/org/whispersystems/textsecuregcm/controllers/OneTimeDonationController.java index c705409cd..bee0ec8ee 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/controllers/OneTimeDonationController.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/controllers/OneTimeDonationController.java @@ -36,14 +36,11 @@ import jakarta.ws.rs.core.Context; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response; import java.io.IOException; -import java.math.BigDecimal; import java.time.Clock; import java.time.Instant; import java.time.temporal.ChronoUnit; -import java.util.Collections; import java.util.List; import java.util.Locale; -import java.util.Map; import java.util.Objects; import java.util.Optional; import org.glassfish.jersey.server.ManagedAsync; @@ -69,7 +66,7 @@ import org.whispersystems.textsecuregcm.purchases.PayPalDonationsTranslator; import org.whispersystems.textsecuregcm.purchases.PaymentDetails; import org.whispersystems.textsecuregcm.purchases.PaymentMethod; import org.whispersystems.textsecuregcm.purchases.PaymentProvider; -import org.whispersystems.textsecuregcm.purchases.PurchaseInvalidAmountException; +import org.whispersystems.textsecuregcm.purchases.PurchaseAmountTooLargeException; import org.whispersystems.textsecuregcm.purchases.PurchaseNotFoundException; import org.whispersystems.textsecuregcm.purchases.PurchasePaymentRequiredException; import org.whispersystems.textsecuregcm.purchases.PurchaseProcessorException; @@ -181,7 +178,7 @@ public class OneTimeDonationController { @HeaderParam(HeaderUtils.DONATION_PERMIT) final Optional donationPermitHeader, @NotNull @Valid final CreateBoostRequest request, - @HeaderParam(HttpHeaders.USER_AGENT) final String userAgent) throws PurchaseInvalidAmountException { + @HeaderParam(HttpHeaders.USER_AGENT) final String userAgent) throws PurchaseAmountTooLargeException { if (authenticatedAccount.isPresent()) { throw new ForbiddenException("must not use authenticated connection for one-time donation operations"); @@ -217,24 +214,13 @@ public class OneTimeDonationController { private void validateRequestCurrencyAmount(final CreateBoostRequest request, final long amount, final CustomerAwareSubscriptionPaymentProcessor manager) { - final Map errorBody = switch (OneTimeDonationUtil.validateOneTimeDonationRequest(request.currency, - amount, request.level, request.paymentMethod, oneTimeDonationConfiguration, manager)) { - case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.UnsupportedLevel _ -> - Map.of("error", "invalid_level"); - case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.UnsupportedCurrency _ -> - Map.of("error", "unsupported_currency"); - case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.AmountBelowMinimum(final BigDecimal min) -> - Map.of("error", "amount_below_currency_minimum", "minimum", min.toString()); - case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.AmountAboveSepaLimit(final BigDecimal max) -> - Map.of("error", "amount_above_sepa_limit", "maximum", max.toString()); - case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.Success _ -> Collections.emptyMap(); - }; - - if (!errorBody.isEmpty()) { + try { + OneTimeDonationUtil.validateOneTimeDonationRequest(request.currency, amount, request.level, request.paymentMethod, + oneTimeDonationConfiguration, manager); + } catch (OneTimeDonationUtil.ValidationException e) { throw new BadRequestException( - Response.status(Response.Status.BAD_REQUEST).entity(errorBody).build()); + Response.status(Response.Status.BAD_REQUEST).entity(e.getErrorBody()).build()); } - } public static class CreatePayPalBoostRequest extends CreateBoostRequest { diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/OneTimeDonationUtil.java b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/OneTimeDonationUtil.java index 8009894c3..71ccbfa37 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/OneTimeDonationUtil.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/OneTimeDonationUtil.java @@ -4,6 +4,8 @@ import java.math.BigDecimal; import java.time.Duration; import java.util.List; import java.util.Locale; +import java.util.Map; +import java.util.Optional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfiguration; @@ -31,59 +33,72 @@ public class OneTimeDonationUtil { public record LocalizedPayPalDonationLineItem(Locale locale, String itemName){} public record DonationLevelDetails(ReceiptLevel level, Duration levelExpiration){} - public sealed interface OneTimeDonationRequestValidationResult permits OneTimeDonationRequestValidationResult.Success, - OneTimeDonationRequestValidationResult.UnsupportedCurrency, - OneTimeDonationRequestValidationResult.UnsupportedLevel, - OneTimeDonationRequestValidationResult.AmountBelowMinimum, - OneTimeDonationRequestValidationResult.AmountAboveSepaLimit { + /// Thrown when a one-time donation request that failed validation + public static class ValidationException extends Exception { + /// A human-readable description of the failure, suitable for logging + private final String description; + /// The fields of the REST error response body + private final Map errorBody; - record Success() implements OneTimeDonationRequestValidationResult {} + public ValidationException(final String description, final Map errorBody) { + this.description = description; + this.errorBody = errorBody; + } - record UnsupportedCurrency() implements OneTimeDonationRequestValidationResult {} + public String getDescription() { + return description; + } - record UnsupportedLevel() implements OneTimeDonationRequestValidationResult {} - - record AmountBelowMinimum(BigDecimal minimum) implements OneTimeDonationRequestValidationResult {} - - record AmountAboveSepaLimit(BigDecimal maximum) implements OneTimeDonationRequestValidationResult {} + public Map getErrorBody() { + return errorBody; + } + } + private static boolean isOneTimeDonationLevel(final long level) { + return ReceiptLevel.lookupLevel(level) + .map(rl -> rl == ReceiptLevel.ONE_TIME_DONATION || rl == ReceiptLevel.ONE_TIME_GIFT_DONATION) + .orElse(false); } /// Validates a request is for a valid one-time donation level and is at least the configured minimum for the currency /// and payment method. - public static OneTimeDonationRequestValidationResult validateOneTimeDonationRequest( + /// + /// @return the validation error, or empty if the request is valid + public static void validateOneTimeDonationRequest( final String currency, final long amount, final long level, final PaymentMethod paymentMethod, final OneTimeDonationConfiguration oneTimeDonationConfiguration, final CustomerAwareSubscriptionPaymentProcessor manager - ) { + ) throws ValidationException { - if (ReceiptLevel.lookupLevel(level) - .map(rl -> rl != ReceiptLevel.ONE_TIME_DONATION && rl != ReceiptLevel.ONE_TIME_GIFT_DONATION) - .orElse(true)) { - return new OneTimeDonationRequestValidationResult.UnsupportedLevel(); + if (!isOneTimeDonationLevel(level)) { + throw new ValidationException("Not a one-time donation level", Map.of("error", "invalid_level")); } if (!manager.getSupportedCurrenciesForPaymentMethod(paymentMethod) .contains(currency.toLowerCase(Locale.ROOT))) { - return new OneTimeDonationRequestValidationResult.UnsupportedCurrency(); + throw new ValidationException( + "Currency '" + currency + "' is not supported for payment method " + paymentMethod, + Map.of("error", "unsupported_currency")); } final BigDecimal minCurrencyAmount = oneTimeDonationConfiguration.currencies().get(currency.toLowerCase(Locale.ROOT)).minimum(); if (SubscriptionCurrencyUtil.convertPrimaryToMinorUnits(currency, minCurrencyAmount) > amount) { - return new OneTimeDonationRequestValidationResult.AmountBelowMinimum(minCurrencyAmount); + throw new ValidationException( + "Amount is below the minimum for currency '" + currency + "'", + Map.of("error", "amount_below_currency_minimum", "minimum", minCurrencyAmount.toString())); } if (paymentMethod == PaymentMethod.SEPA_DEBIT) { final BigDecimal sepaMaximumEuros = oneTimeDonationConfiguration.sepaMaximumEuros(); if (amount > SubscriptionCurrencyUtil.convertPrimaryToMinorUnits(EURO_CURRENCY_CODE, sepaMaximumEuros)) { - return new OneTimeDonationRequestValidationResult.AmountAboveSepaLimit(sepaMaximumEuros); + throw new ValidationException("Amount is above the SEPA Direct Debit maximum", + Map.of("error", "amount_above_sepa_limit", "maximum", sepaMaximumEuros.toString())); } } - return new OneTimeDonationRequestValidationResult.Success(); } public static LocalizedPayPalDonationLineItem localizePayPalDonationLineItem( diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/OneTimeDonationsGrpcService.java b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/OneTimeDonationsGrpcService.java index 264c006b5..5f46171a6 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/OneTimeDonationsGrpcService.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/OneTimeDonationsGrpcService.java @@ -5,7 +5,6 @@ package org.whispersystems.textsecuregcm.grpc; import static org.whispersystems.textsecuregcm.grpc.SubscriptionsUtil.getClientPlatform; -import static org.whispersystems.textsecuregcm.grpc.SubscriptionsUtil.toChargeFailure; import com.google.protobuf.ByteString; import io.micrometer.core.instrument.Metrics; @@ -17,19 +16,19 @@ import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.List; import java.util.Locale; +import java.util.Optional; import org.signal.chat.errors.FailedPrecondition; import org.signal.chat.errors.FailedZkAuthentication; import org.signal.chat.errors.NotFound; -import org.signal.chat.purchase.AmountAboveSepaLimitError; -import org.signal.chat.purchase.AmountBelowMinimumError; import org.signal.chat.purchase.ConfirmPayPalBoostRequest; import org.signal.chat.purchase.ConfirmPayPalBoostResponse; import org.signal.chat.purchase.CreateBoostReceiptCredentialRequest; import org.signal.chat.purchase.CreateBoostReceiptCredentialResponse; -import org.signal.chat.purchase.CreateBoostRequest; -import org.signal.chat.purchase.CreateBoostResponse; +import org.signal.chat.purchase.CreateStripeBoostRequest; +import org.signal.chat.purchase.CreateStripeBoostResponse; import org.signal.chat.purchase.CreatePayPalBoostRequest; import org.signal.chat.purchase.CreatePayPalBoostResponse; +import org.signal.chat.purchase.PaymentRequired; import org.signal.chat.purchase.SimpleOneTimeDonationsGrpc; import org.signal.libsignal.zkgroup.InvalidInputException; import org.signal.libsignal.zkgroup.VerificationFailedException; @@ -42,16 +41,16 @@ import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException; import org.whispersystems.textsecuregcm.limits.RateLimiters; import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil; import org.whispersystems.textsecuregcm.purchases.BraintreeManager; +import org.whispersystems.textsecuregcm.purchases.CustomerAwareSubscriptionPaymentProcessor; import org.whispersystems.textsecuregcm.purchases.PayPalDonationsTranslator; import org.whispersystems.textsecuregcm.purchases.PaymentDetails; import org.whispersystems.textsecuregcm.purchases.PaymentProvider; -import org.whispersystems.textsecuregcm.purchases.PurchaseInvalidAmountException; +import org.whispersystems.textsecuregcm.purchases.PurchaseAmountTooLargeException; import org.whispersystems.textsecuregcm.purchases.PurchaseNotFoundException; import org.whispersystems.textsecuregcm.purchases.PurchasePaymentRequiredException; import org.whispersystems.textsecuregcm.purchases.PurchaseProcessorException; import org.whispersystems.textsecuregcm.purchases.PurchaseReceiptRequestedForOpenPaymentException; import org.whispersystems.textsecuregcm.purchases.StripeManager; -import org.whispersystems.textsecuregcm.purchases.SubscriptionCurrencyUtil; import org.whispersystems.textsecuregcm.storage.DonationPermitsManager; import org.whispersystems.textsecuregcm.storage.IssuedReceiptsManager; import org.whispersystems.textsecuregcm.storage.OneTimeDonationsManager; @@ -94,121 +93,77 @@ public class OneTimeDonationsGrpcService extends SimpleOneTimeDonationsGrpc.OneT } @Override - public CreateBoostResponse createBoost(final CreateBoostRequest request) + public CreateStripeBoostResponse createStripeBoost(final CreateStripeBoostRequest request) throws RateLimitExceededException { RateLimitUtil.rateLimitByRemoteAddress(rateLimiters.forDescriptor(RateLimiters.For.ONE_TIME_DONATION)); - try { - final DonationPermit donationPermit = new DonationPermit(request.getDonationPermit().toByteArray()); - if (!donationPermitsManager.spend(donationPermit)) { - return CreateBoostResponse.newBuilder() - .setPermitRejected(FailedZkAuthentication.newBuilder() - .setDescription("donation permit rejected") - .build()) - .build(); - } - } catch (InvalidInputException | VerificationFailedException _) { - return CreateBoostResponse.newBuilder() - .setPermitRejected(FailedZkAuthentication.newBuilder() - .setDescription("donation permit rejected") - .build()) - .build(); - } - final org.whispersystems.textsecuregcm.purchases.PaymentMethod paymentMethod = switch (request.getPaymentMethod()) { case PAYMENT_METHOD_CARD -> org.whispersystems.textsecuregcm.purchases.PaymentMethod.CARD; case PAYMENT_METHOD_SEPA_DEBIT -> org.whispersystems.textsecuregcm.purchases.PaymentMethod.SEPA_DEBIT; case PAYMENT_METHOD_IDEAL -> org.whispersystems.textsecuregcm.purchases.PaymentMethod.IDEAL; - default -> throw GrpcExceptions.fieldViolation("payment_method", "Unsupported payment method"); + default -> throw new IllegalStateException("payment_method should already have been validated"); }; - final OneTimeDonationUtil.OneTimeDonationRequestValidationResult validationResult = - OneTimeDonationUtil.validateOneTimeDonationRequest( - request.getCurrency(), - request.getAmount(), - request.getLevel(), - paymentMethod, - oneTimeDonationConfiguration, - stripeManager); - - return switch (validationResult) { - case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.UnsupportedLevel _ -> - CreateBoostResponse.newBuilder() - .setUnsupportedLevel(FailedPrecondition.getDefaultInstance()).build(); - case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.UnsupportedCurrency _ -> - CreateBoostResponse.newBuilder() - .setUnsupportedCurrency(FailedPrecondition.getDefaultInstance()).build(); - case final OneTimeDonationUtil.OneTimeDonationRequestValidationResult.AmountBelowMinimum r -> - CreateBoostResponse.newBuilder() - .setAmountBelowMinimum(AmountBelowMinimumError.newBuilder() - .setMinimum(SubscriptionCurrencyUtil.convertPrimaryToMinorUnits(request.getCurrency(), - r.minimum())) - .build()).build(); - case final OneTimeDonationUtil.OneTimeDonationRequestValidationResult.AmountAboveSepaLimit r -> - CreateBoostResponse.newBuilder() - .setAmountAboveSepaLimit(AmountAboveSepaLimitError.newBuilder() - .setMaximum(SubscriptionCurrencyUtil.convertPrimaryToMinorUnits( - OneTimeDonationUtil.EURO_CURRENCY_CODE, r.maximum())) - .build()).build(); - case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.Success _ -> { - try { - final com.stripe.model.PaymentIntent paymentIntent = stripeManager.createPaymentIntent( - request.getCurrency(), request.getAmount(), request.getLevel(), - getClientPlatform(RequestAttributesUtil.getUserAgent().orElse(null))); - yield CreateBoostResponse.newBuilder().setClientSecret(paymentIntent.getClientSecret()).build(); - } catch (final PurchaseInvalidAmountException e) { - yield CreateBoostResponse.newBuilder() - .setInvalidAmount(FailedPrecondition.newBuilder() - .setDescription(e.getErrorCode()).build()) - .build(); - } + try { + OneTimeDonationUtil.validateOneTimeDonationRequest( + request.getCurrency(), request.getAmount(), request.getLevel(), paymentMethod, oneTimeDonationConfiguration, stripeManager); + final DonationPermit donationPermit = new DonationPermit(request.getDonationPermit().toByteArray()); + if (!donationPermitsManager.spend(donationPermit)) { + return CreateStripeBoostResponse.newBuilder() + .setPermitRejected(FailedZkAuthentication.newBuilder() + .setDescription("donation permit rejected") + .build()) + .build(); } - }; + } catch (InvalidInputException | VerificationFailedException _) { + return CreateStripeBoostResponse.newBuilder() + .setPermitRejected(FailedZkAuthentication.newBuilder() + .setDescription("donation permit rejected") + .build()) + .build(); + } catch (OneTimeDonationUtil.ValidationException e) { + return CreateStripeBoostResponse.newBuilder() + .setInvalidSelection(FailedPrecondition.newBuilder().setDescription(e.getDescription()).build()) + .build(); + } + + try { + final com.stripe.model.PaymentIntent paymentIntent = stripeManager.createPaymentIntent( + request.getCurrency(), request.getAmount(), request.getLevel(), + getClientPlatform(RequestAttributesUtil.getUserAgent().orElse(null))); + return CreateStripeBoostResponse.newBuilder().setClientSecret(paymentIntent.getClientSecret()).build(); + } catch (final PurchaseAmountTooLargeException e) { + return CreateStripeBoostResponse.newBuilder() + .setInvalidSelection(FailedPrecondition.newBuilder() + .setDescription("Amount exceeds the payment processor's maximum for currency " + request.getCurrency())) + .build(); + } } @Override public CreatePayPalBoostResponse createPayPalBoost(final CreatePayPalBoostRequest request) throws IOException { - final OneTimeDonationUtil.OneTimeDonationRequestValidationResult validationResult = - OneTimeDonationUtil.validateOneTimeDonationRequest( - request.getCurrency(), - request.getAmount(), - request.getLevel(), - org.whispersystems.textsecuregcm.purchases.PaymentMethod.PAYPAL, - oneTimeDonationConfiguration, - braintreeManager); + try { + OneTimeDonationUtil.validateOneTimeDonationRequest(request.getCurrency(), request.getAmount(), request.getLevel(), org.whispersystems.textsecuregcm.purchases.PaymentMethod.PAYPAL, oneTimeDonationConfiguration, braintreeManager); + } catch (OneTimeDonationUtil.ValidationException e) { + return CreatePayPalBoostResponse.newBuilder() + .setInvalidSelection(FailedPrecondition.newBuilder().setDescription(e.getDescription()).build()) + .build(); + } - return switch (validationResult) { - case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.UnsupportedLevel _ -> - CreatePayPalBoostResponse.newBuilder() - .setUnsupportedLevel(FailedPrecondition.getDefaultInstance()).build(); - case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.UnsupportedCurrency _ -> - CreatePayPalBoostResponse.newBuilder() - .setUnsupportedCurrency(FailedPrecondition.getDefaultInstance()).build(); - case final OneTimeDonationUtil.OneTimeDonationRequestValidationResult.AmountBelowMinimum r -> - CreatePayPalBoostResponse.newBuilder() - .setAmountBelowMinimum(AmountBelowMinimumError.newBuilder() - .setMinimum(SubscriptionCurrencyUtil.convertPrimaryToMinorUnits(request.getCurrency(), - r.minimum())) - .build()).build(); - case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.AmountAboveSepaLimit _ -> - throw new IllegalStateException("SEPA limit should not trigger for PayPal"); - case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.Success _ -> { - final List acceptableLocales = RequestAttributesUtil.getAvailableAcceptedLocales(); - final OneTimeDonationUtil.LocalizedPayPalDonationLineItem localizedLineItem = OneTimeDonationUtil.localizePayPalDonationLineItem( - payPalDonationsTranslator, acceptableLocales); - final BraintreeManager.PayPalOneTimePaymentApprovalDetails approvalDetails = - braintreeManager.createOneTimePayment( - request.getCurrency().toUpperCase(Locale.ROOT), request.getAmount(), - localizedLineItem.locale().toLanguageTag(), request.getReturnUrl(), request.getCancelUrl(), - localizedLineItem.itemName()); - yield CreatePayPalBoostResponse.newBuilder() - .setResult(CreatePayPalBoostResponse.CreatePayPalBoostResult.newBuilder() - .setApprovalUrl(approvalDetails.approvalUrl()) - .setPaymentId(approvalDetails.paymentId()).build()).build(); - } - }; + final List acceptableLocales = RequestAttributesUtil.getAvailableAcceptedLocales(); + final OneTimeDonationUtil.LocalizedPayPalDonationLineItem localizedLineItem = OneTimeDonationUtil.localizePayPalDonationLineItem( + payPalDonationsTranslator, acceptableLocales); + final BraintreeManager.PayPalOneTimePaymentApprovalDetails approvalDetails = + braintreeManager.createOneTimePayment( + request.getCurrency().toUpperCase(Locale.ROOT), request.getAmount(), + localizedLineItem.locale().toLanguageTag(), request.getReturnUrl(), request.getCancelUrl(), + localizedLineItem.itemName()); + return CreatePayPalBoostResponse.newBuilder() + .setResult(CreatePayPalBoostResponse.CreatePayPalBoostResult.newBuilder() + .setApprovalUrl(approvalDetails.approvalUrl()) + .setPaymentId(approvalDetails.paymentId()).build()).build(); } @Override @@ -216,48 +171,28 @@ public class OneTimeDonationsGrpcService extends SimpleOneTimeDonationsGrpc.OneT throws RateLimitExceededException, IOException { RateLimitUtil.rateLimitByRemoteAddress(rateLimiters.forDescriptor(RateLimiters.For.ONE_TIME_DONATION)); - final OneTimeDonationUtil.OneTimeDonationRequestValidationResult validationResult = - OneTimeDonationUtil.validateOneTimeDonationRequest( - request.getCurrency(), - request.getAmount(), - request.getLevel(), - org.whispersystems.textsecuregcm.purchases.PaymentMethod.PAYPAL, - oneTimeDonationConfiguration, - braintreeManager); - - return switch (validationResult) { - case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.UnsupportedLevel _ -> - ConfirmPayPalBoostResponse.newBuilder() - .setUnsupportedLevel(FailedPrecondition.getDefaultInstance()).build(); - case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.UnsupportedCurrency _ -> - ConfirmPayPalBoostResponse.newBuilder() - .setUnsupportedCurrency(FailedPrecondition.getDefaultInstance()).build(); - case final OneTimeDonationUtil.OneTimeDonationRequestValidationResult.AmountBelowMinimum r -> - ConfirmPayPalBoostResponse.newBuilder() - .setAmountBelowMinimum(AmountBelowMinimumError.newBuilder() - .setMinimum(SubscriptionCurrencyUtil.convertPrimaryToMinorUnits(request.getCurrency(), - r.minimum())) - .build()).build(); - case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.AmountAboveSepaLimit _ -> - throw new IllegalStateException("SEPA limit should not trigger for PayPal"); - case OneTimeDonationUtil.OneTimeDonationRequestValidationResult.Success _ -> { - final BraintreeManager.PayPalChargeSuccessDetails chargeSuccessDetails; - try { - chargeSuccessDetails = braintreeManager.captureOneTimePayment( - request.getPayerId(), request.getPaymentId(), request.getPaymentToken(), - request.getCurrency(), request.getAmount(), request.getLevel(), - SubscriptionsUtil.getClientPlatform(RequestAttributesUtil.getUserAgent().orElse(null))); - oneTimeDonationsManager.putPaidAt(chargeSuccessDetails.paymentId(), clock.instant()); - yield ConfirmPayPalBoostResponse.newBuilder() - .setResult(ConfirmPayPalBoostResponse.ConfirmPayPalBoostResult.newBuilder() - .setPaymentId(chargeSuccessDetails.paymentId()).build()).build(); - } catch (final PurchaseProcessorException e) { - yield ConfirmPayPalBoostResponse.newBuilder() - .setChargeFailure(SubscriptionsUtil.toChargeFailure(e.getProcessor(), e.getChargeFailure())) - .build(); - } - } - }; + try { + OneTimeDonationUtil.validateOneTimeDonationRequest(request.getCurrency(), request.getAmount(), request.getLevel(), + org.whispersystems.textsecuregcm.purchases.PaymentMethod.PAYPAL, oneTimeDonationConfiguration, + braintreeManager); + final BraintreeManager.PayPalChargeSuccessDetails chargeSuccessDetails = braintreeManager.captureOneTimePayment( + request.getPayerId(), request.getPaymentId(), request.getPaymentToken(), + request.getCurrency(), request.getAmount(), request.getLevel(), + SubscriptionsUtil.getClientPlatform(RequestAttributesUtil.getUserAgent().orElse(null))); + oneTimeDonationsManager.putPaidAt(chargeSuccessDetails.paymentId(), clock.instant()); + return ConfirmPayPalBoostResponse.newBuilder() + .setResult(ConfirmPayPalBoostResponse.ConfirmPayPalBoostResult.newBuilder() + .setPaymentId(chargeSuccessDetails.paymentId()).build()).build(); + } catch (OneTimeDonationUtil.ValidationException e) { + return ConfirmPayPalBoostResponse.newBuilder() + .setInvalidSelection(FailedPrecondition.newBuilder().setDescription(e.getDescription()).build()) + .build(); + } catch (final PurchaseProcessorException e) { + return ConfirmPayPalBoostResponse.newBuilder() + .setPaymentRequired(PaymentRequired.newBuilder() + .setChargeFailure(SubscriptionsUtil.toChargeFailure(e.getProcessor(), e.getChargeFailure()))) + .build(); + } } @Override diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/ProductConfigurationGrpcService.java b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/ProductConfigurationGrpcService.java index 26955e532..2157fd865 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/ProductConfigurationGrpcService.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/ProductConfigurationGrpcService.java @@ -67,11 +67,13 @@ public class ProductConfigurationGrpcService extends SimpleProductConfigurationG donationLevels.put(ReceiptLevel.ONE_TIME_DONATION.getValue(), LevelConfiguration.newBuilder() .setBadgeId(oneTimeDonationConfiguration.boost().badge()) - .setBadgeDurationSeconds(oneTimeDonationConfiguration.boost().expiration().toSeconds()).build()); + .setBadgeDurationSeconds(Math.toIntExact(oneTimeDonationConfiguration.boost().expiration().toSeconds())) + .build()); donationLevels.put(ReceiptLevel.ONE_TIME_GIFT_DONATION.getValue(), LevelConfiguration.newBuilder() .setBadgeId(oneTimeDonationConfiguration.gift().badge()) - .setBadgeDurationSeconds(oneTimeDonationConfiguration.gift().expiration().toSeconds()).build()); + .setBadgeDurationSeconds(Math.toIntExact(oneTimeDonationConfiguration.gift().expiration().toSeconds())) + .build()); return donationLevels; } @@ -83,11 +85,11 @@ public class ProductConfigurationGrpcService extends SimpleProductConfigurationG e -> BackupLevelConfiguration.newBuilder() .setStorageAllowanceBytes(backupMediaStorageAllowanceBytes) .setPlayProductId(e.getValue().playProductId()) - .setMediaTtlDays(e.getValue().mediaTtl().toDays()) + .setMediaTtlDays(Math.toIntExact(e.getValue().mediaTtl().toDays())) .build())); return BackupConfiguration.newBuilder() .putAllLevels(backupLevels) - .setFreeTierMediaDays(subscriptionConfiguration.getbackupFreeTierMediaDuration().toDays()) + .setFreeTierMediaDays(Math.toIntExact(subscriptionConfiguration.getbackupFreeTierMediaDuration().toDays())) .build(); } diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/SubscriptionsGrpcService.java b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/SubscriptionsGrpcService.java index d3c8e4ec5..18489583c 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/SubscriptionsGrpcService.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/SubscriptionsGrpcService.java @@ -18,8 +18,8 @@ import org.signal.chat.errors.FailedZkAuthentication; import org.signal.chat.errors.NotFound; import org.signal.chat.purchase.CreatePayPalPaymentMethodRequest; import org.signal.chat.purchase.CreatePayPalPaymentMethodResponse; -import org.signal.chat.purchase.CreatePaymentMethodRequest; -import org.signal.chat.purchase.CreatePaymentMethodResponse; +import org.signal.chat.purchase.CreateStripePaymentMethodRequest; +import org.signal.chat.purchase.CreateStripePaymentMethodResponse; import org.signal.chat.purchase.DeleteSubscriberRequest; import org.signal.chat.purchase.DeleteSubscriberResponse; import org.signal.chat.purchase.GetBankMandateRequest; @@ -28,6 +28,7 @@ import org.signal.chat.purchase.GetReceiptCredentialRequest; import org.signal.chat.purchase.GetReceiptCredentialResponse; import org.signal.chat.purchase.GetSubscriptionInformationRequest; import org.signal.chat.purchase.GetSubscriptionInformationResponse; +import org.signal.chat.purchase.PaymentRequired; import org.signal.chat.purchase.SetDefaultPaymentMethodRequest; import org.signal.chat.purchase.SetDefaultPaymentMethodResponse; import org.signal.chat.purchase.SetIapSubscriptionRequest; @@ -170,42 +171,38 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti } @Override - public CreatePaymentMethodResponse createPaymentMethod(final CreatePaymentMethodRequest request) { + public CreateStripePaymentMethodResponse createStripePaymentMethod(final CreateStripePaymentMethodRequest request) { final SubscriberCredentials subscriberCredentials = SubscriberCredentials.process( request.getSubscriberId().toByteArray(), clock); - 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 DonationPermit permit = new DonationPermit(request.getDonationPermit().toByteArray()); if (!SubscriptionsUtil.verifyAndSpendDonationPermit(permit, donationPermitsManager, clock)) { - return CreatePaymentMethodResponse.newBuilder() + return CreateStripePaymentMethodResponse.newBuilder() .setPermitRejected(FailedZkAuthentication.getDefaultInstance()) .build(); } } catch (final InvalidInputException _) { throw GrpcExceptions.invalidArguments("invalid donation permit"); } catch (final VerificationFailedException _) { - return CreatePaymentMethodResponse.newBuilder() + return CreateStripePaymentMethodResponse.newBuilder() .setPermitRejected(FailedZkAuthentication.getDefaultInstance()) .build(); } try { final String token = subscriptionManager.addPaymentMethodToCustomer(subscriberCredentials, - customerAwareSubscriptionPaymentProcessor, + stripeManager, getClientPlatform(RequestAttributesUtil.getUserAgent().orElse(null)), CustomerAwareSubscriptionPaymentProcessor::createPaymentMethodSetupToken); - return CreatePaymentMethodResponse.newBuilder().setResult( - CreatePaymentMethodResponse.CreatePaymentMethodResult.newBuilder().setClientSecret(token) - .setPaymentProvider(customerAwareSubscriptionPaymentProcessor.getProvider().toProto()).build()).build(); + return CreateStripePaymentMethodResponse.newBuilder().setResult( + CreateStripePaymentMethodResponse.CreateStripePaymentMethodResult.newBuilder().setClientSecret(token).build()) + .build(); } catch (final PurchaseNotFoundException | PurchaseForbiddenException _) { - return CreatePaymentMethodResponse.newBuilder().setSubscriberNotFound(NotFound.newBuilder()).build(); + return CreateStripePaymentMethodResponse.newBuilder().setSubscriberNotFound(NotFound.newBuilder()).build(); } catch (final PurchaseProcessorConflictException e) { - return CreatePaymentMethodResponse.newBuilder().setSubscriptionProcessorConflict( + return CreateStripePaymentMethodResponse.newBuilder().setSubscriptionProcessorConflict( FailedPrecondition.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build(); } } @@ -263,13 +260,13 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti // 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 .orElseGet(() -> SetDefaultPaymentMethodResponse.newBuilder() - .setPaymentMethodNotSetUp(FailedPrecondition.newBuilder().build()) + .setFailedPrecondition(FailedPrecondition.newBuilder().build()) .build()); } catch (final PurchaseNotFoundException | PurchaseForbiddenException _) { return SetDefaultPaymentMethodResponse.newBuilder().setSubscriberNotFound(NotFound.newBuilder().build()).build(); } catch (final PurchaseProcessorConflictException _) { return SetDefaultPaymentMethodResponse.newBuilder() - .setPaymentMethodNotSetUp(FailedPrecondition.newBuilder().build()) + .setFailedPrecondition(FailedPrecondition.newBuilder().build()) .build(); } } @@ -284,7 +281,7 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti // 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()) + .setFailedPrecondition(FailedPrecondition.newBuilder().setDescription(e.errorDetail().orElse("")).build()) .build(); } catch (final IOException e) { throw new UncheckedIOException(e); @@ -298,10 +295,11 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti request.getSubscriberId().toByteArray(), clock); try { final Subscriptions.Record record = subscriptionManager.getSubscriber(subscriberCredentials); - return record.getProcessorCustomer().map(processorCustomer -> - setSubscriptionLevelForCustomer(processorCustomer, subscriberCredentials, record, request)) + return record.getProcessorCustomer() + .map(processorCustomer -> setSubscriptionLevelForCustomer(processorCustomer, subscriberCredentials, record, request)) .orElseGet(() -> SetSubscriptionLevelResponse.newBuilder() - .setPaymentMethodNotSetUp(FailedPrecondition.newBuilder().build()) + .setFailedPrecondition(FailedPrecondition.newBuilder() + .setDescription("No payment method has been created for the subscriber")) .build()); } catch (final PurchaseNotFoundException | PurchaseForbiddenException _) { @@ -312,31 +310,35 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti private SetSubscriptionLevelResponse setSubscriptionLevelForCustomer(final ProcessorCustomer processorCustomer, final SubscriberCredentials subscriberCredentials, final Subscriptions.Record subscriptionRecord, final SetSubscriptionLevelRequest request) { + final CustomerAwareSubscriptionPaymentProcessor manager; + switch (processorCustomer.processor()) { + case STRIPE -> manager = stripeManager; + case BRAINTREE -> manager = braintreeManager; + default -> { + return SetSubscriptionLevelResponse.newBuilder() + .setFailedPrecondition(FailedPrecondition.newBuilder() + .setDescription(String.format("Subscription level %s invalid for %s", request.getLevel(), processorCustomer.processor()))) + .build(); + } + } + final SubscriptionLevelConfiguration config = subscriptionConfiguration.getSubscriptionLevel(request.getLevel()); if (config == null) { - return SetSubscriptionLevelResponse.newBuilder().setUnsupportedLevel(FailedPrecondition.newBuilder().build()) + return SetSubscriptionLevelResponse.newBuilder() + .setInvalidSelection(FailedPrecondition.newBuilder() + .setDescription("Unsupported subscription level " + request.getLevel())) .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()) + return SetSubscriptionLevelResponse.newBuilder() + .setInvalidSelection(FailedPrecondition.newBuilder() + .setDescription(String.format("Currency %s is not supported for %s", request.getCurrency(), processorCustomer.processor()))) .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(), @@ -345,22 +347,30 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti .build(); } catch (final PurchaseInvalidIdempotencyKeyException e) { return SetSubscriptionLevelResponse.newBuilder() - .setInvalidIdempotencyKey(FailedPrecondition.newBuilder().setDescription(e.errorDetail().orElse("")).build()) + .setFailedPrecondition(FailedPrecondition.newBuilder() + .setDescription("Idempotency key was reused with a modified request")) .build(); } catch (final PurchaseProcessorException e) { return SetSubscriptionLevelResponse.newBuilder() - .setChargeFailure(SubscriptionsUtil.toChargeFailure(e.getProcessor(), e.getChargeFailure())).build(); + .setPaymentRequired(PaymentRequired.newBuilder() + .setChargeFailure(SubscriptionsUtil.toChargeFailure(e.getProcessor(), e.getChargeFailure()))) + .build(); } catch (final PurchasePaymentRequiresActionException e) { - return SetSubscriptionLevelResponse.newBuilder().setPaymentRequiresAction(FailedPrecondition.newBuilder().build()) + return SetSubscriptionLevelResponse.newBuilder() + .setFailedPrecondition(FailedPrecondition.newBuilder() + .setDescription("Payment processor requires additional customer action before the payment method can be charged")) .build(); } catch (final PurchaseInvalidLevelException e) { return SetSubscriptionLevelResponse.newBuilder() - .setInvalidLevelTransition(FailedPrecondition.newBuilder().build()).build(); + .setFailedPrecondition(FailedPrecondition.newBuilder() + .setDescription("Cannot transition to level " + request.getLevel())) + .build(); } catch (final PurchaseProcessorConflictException e) { - // We just looked up the subscription processor from the database, a conflict is not possible - throw new IllegalStateException(e); + return SetSubscriptionLevelResponse.newBuilder() + .setFailedPrecondition(FailedPrecondition.newBuilder() + .setDescription("No payment method set up")) + .build(); } - } @Override @@ -385,7 +395,7 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti return SetIapSubscriptionResponse.newBuilder().setSubscriptionProcessorConflict( FailedPrecondition.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build(); } catch (final PurchasePaymentRequiredException e) { - return SetIapSubscriptionResponse.newBuilder().setPaymentRequired(FailedPrecondition.newBuilder().build()) + return SetIapSubscriptionResponse.newBuilder().setPaymentRequired(SubscriptionsUtil.toPaymentRequired(e)) .build(); } catch (final PurchaseInvalidArgumentsException e) { return SetIapSubscriptionResponse.newBuilder() diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/ValidatingInterceptor.java b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/ValidatingInterceptor.java index f5f1e02f7..306b8ce91 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/ValidatingInterceptor.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/ValidatingInterceptor.java @@ -19,6 +19,7 @@ import java.util.Map; import org.signal.chat.require.ElementConstraint; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.whispersystems.textsecuregcm.grpc.validators.AllowedValuesFieldValidator; import org.whispersystems.textsecuregcm.grpc.validators.Base64UrlFieldValidator; import org.whispersystems.textsecuregcm.grpc.validators.FieldValidator; import org.whispersystems.textsecuregcm.grpc.validators.E164FieldValidator; @@ -49,7 +50,8 @@ public class ValidatingInterceptor implements ServerInterceptor { "size", new SizeFieldValidator(), "base64url", new Base64UrlFieldValidator(), "identityType", new ServiceIdentifierIdentityTypeValidator(), - "present", new PresentFieldValidator()); + "present", new PresentFieldValidator(), + "allowedValues", new AllowedValuesFieldValidator()); @Override public ServerCall.Listener interceptCall( diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/validators/AllowedValuesFieldValidator.java b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/validators/AllowedValuesFieldValidator.java new file mode 100644 index 000000000..4e4b9a0fc --- /dev/null +++ b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/validators/AllowedValuesFieldValidator.java @@ -0,0 +1,78 @@ +/* + * Copyright 2026 Signal Messenger, LLC + * SPDX-License-Identifier: AGPL-3.0-only + */ + +package org.whispersystems.textsecuregcm.grpc.validators; + +import com.google.protobuf.Descriptors; +import java.util.Set; +import org.signal.chat.require.AllowedValuesConstraint; + +public class AllowedValuesFieldValidator extends FieldValidator { + + public AllowedValuesFieldValidator() { + super("allowedValues", Set.of( + Descriptors.FieldDescriptor.Type.INT32, + Descriptors.FieldDescriptor.Type.INT64, + Descriptors.FieldDescriptor.Type.UINT32, + Descriptors.FieldDescriptor.Type.UINT64, + Descriptors.FieldDescriptor.Type.FIXED32, + Descriptors.FieldDescriptor.Type.FIXED64, + Descriptors.FieldDescriptor.Type.SFIXED32, + Descriptors.FieldDescriptor.Type.SFIXED64, + Descriptors.FieldDescriptor.Type.SINT32, + Descriptors.FieldDescriptor.Type.SINT64, + Descriptors.FieldDescriptor.Type.STRING, + Descriptors.FieldDescriptor.Type.ENUM + ), MissingOptionalAction.SUCCEED, false); + } + + @Override + protected AllowedValuesConstraint resolveExtensionValue(final Object extensionValue) { + return (AllowedValuesConstraint) extensionValue; + } + + @Override + protected void validateIntegerNumber( + final AllowedValuesConstraint constraint, + final long fieldValue, + final Descriptors.FieldDescriptor.Type type) throws FieldValidationException { + if (constraint.getIntsCount() == 0) { + throw new IllegalArgumentException("allowedValues on integer field must specify ints"); + } + if (constraint.getIntsList().contains(fieldValue)) { + return; + } + throw new FieldValidationException("field value is [%d] but expected to be one of %s" + .formatted(fieldValue, constraint.getIntsList())); + } + + @Override + protected void validateStringValue( + final AllowedValuesConstraint constraint, + final String fieldValue) throws FieldValidationException { + if (constraint.getStringsCount() == 0) { + throw new IllegalArgumentException("allowedValues on string field must specify strings"); + } + if (constraint.getStringsList().contains(fieldValue)) { + return; + } + throw new FieldValidationException("field value is [%s] but expected to be one of %s" + .formatted(fieldValue, constraint.getStringsList())); + } + + @Override + protected void validateEnumValue( + final AllowedValuesConstraint constraint, + final Descriptors.EnumValueDescriptor enumValueDescriptor) throws FieldValidationException { + if (constraint.getEnumsCount() == 0) { + throw new IllegalArgumentException("allowedValues on enum field must specify enums"); + } + if (constraint.getEnumsList().contains(enumValueDescriptor.getName())) { + return; + } + throw new FieldValidationException("field value is [%s] but expected to be one of %s" + .formatted(enumValueDescriptor.getName(), constraint.getEnumsList())); + } +} diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/mappers/PurchaseExceptionMapper.java b/service/src/main/java/org/whispersystems/textsecuregcm/mappers/PurchaseExceptionMapper.java index 166b358e8..16191392f 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/mappers/PurchaseExceptionMapper.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/mappers/PurchaseExceptionMapper.java @@ -15,7 +15,7 @@ import java.util.Map; import org.whispersystems.textsecuregcm.purchases.ChargeFailure; import org.whispersystems.textsecuregcm.purchases.PurchaseException; import org.whispersystems.textsecuregcm.purchases.PurchaseForbiddenException; -import org.whispersystems.textsecuregcm.purchases.PurchaseInvalidAmountException; +import org.whispersystems.textsecuregcm.purchases.PurchaseAmountTooLargeException; import org.whispersystems.textsecuregcm.purchases.PurchaseInvalidArgumentsException; import org.whispersystems.textsecuregcm.purchases.PurchaseNotFoundException; import org.whispersystems.textsecuregcm.purchases.PurchasePaymentRequiredException; @@ -34,7 +34,7 @@ public class PurchaseExceptionMapper implements ExceptionMapper throw new PurchaseInvalidAmountException(errorCode); + case "amount_too_large" -> throw new PurchaseAmountTooLargeException(errorCode); + // Callers should validate against configured minimums first + case "amount_too_small" -> throw new IllegalStateException(String.format("Stripe rejected %d %s, the configured minimum is too low", amount, currency), e); default -> throw new RuntimeException(e); } } @@ -319,6 +325,7 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor, throw new PurchaseProcessorException(getProvider(), createChargeFailureFromCardException(e)); } catch (final StripeException e) { if ("subscription_payment_intent_requires_action".equals(e.getCode())) { + Metrics.counter(PAYMENT_REQUIRES_ACTION_COUNTER_NAME).increment(); throw new PurchasePaymentRequiresActionException(); } throw new UncheckedIOException(new IOException(e)); diff --git a/service/src/main/proto/org/signal/chat/login_purchase.proto b/service/src/main/proto/org/signal/chat/login_purchase.proto index 236deb5ca..d99e50d31 100644 --- a/service/src/main/proto/org/signal/chat/login_purchase.proto +++ b/service/src/main/proto/org/signal/chat/login_purchase.proto @@ -25,9 +25,10 @@ service LoginPurchase { } message CreateLoginReceiptCredentialRequest { - // The payment processor. Currently, only GOOGLE_PLAY_BILLING and - // APPLE_APP_STORE are supported. - PaymentProvider processor = 1 [(require.specified) = true]; + // The payment processor + PaymentProvider processor = 1 [(require.allowedValues) = { + enums: ["PAYMENT_PROVIDER_GOOGLE_PLAY_BILLING", "PAYMENT_PROVIDER_APPLE_APP_STORE"] + }]; // The identifier of a completed purchase for a signal login within the // payment provider diff --git a/service/src/main/proto/org/signal/chat/one_time_donations.proto b/service/src/main/proto/org/signal/chat/one_time_donations.proto index 6ad57e03d..0f04f7ae7 100644 --- a/service/src/main/proto/org/signal/chat/one_time_donations.proto +++ b/service/src/main/proto/org/signal/chat/one_time_donations.proto @@ -22,7 +22,7 @@ service OneTimeDonations { // Create a Stripe payment intent and return a client secret that can be used to complete the payment. // Once the payment is complete, the paymentIntentId can be used with CreateBoostReceiptCredential - rpc CreateBoost(CreateBoostRequest) returns (CreateBoostResponse) {} + rpc CreateStripeBoost(CreateStripeBoostRequest) returns (CreateStripeBoostResponse) {} // Create a PayPal one-time payment. // @@ -44,47 +44,34 @@ service OneTimeDonations { rpc CreateBoostReceiptCredential(CreateBoostReceiptCredentialRequest) returns (CreateBoostReceiptCredentialResponse) {} } -// The amount is below the minimum for the currency. -message AmountBelowMinimumError { - // The minimum amount for the currency in the [currency's minor unit](https://docs.stripe.com/currencies#minor-units) - uint64 minimum = 1; -} - -// The SEPA Direct Debit amount exceeds the allowed maximum. -message AmountAboveSepaLimitError { - // The maximum amount for a SEPA transaction in the [currency's minor unit](https://docs.stripe.com/currencies#minor-units) - uint64 maximum = 1; -} - -message CreateBoostRequest { +message CreateStripeBoostRequest { // ISO 4217 currency code, case-insensitive (e.g. "usd", "EUR") string currency = 1 [(require.exactlySize) = 3]; // The amount to pay in the [currency's minor unit](https://docs.stripe.com/currencies#minor-units) uint64 amount = 2 [(require.range).min = 1]; - // The level for the boost payment - uint64 level = 3 [(require.range).min = 1]; - // The payment method - PaymentMethod payment_method = 4 [(require.specified) = true]; + // The level for the boost payment: 1 for a one-time donation, 100 for a gift donation + uint64 level = 3 [(require.allowedValues) = { ints: [1, 100] }]; + // The payment method. Only card, SEPA Direct Debit, and iDEAL are supported. + PaymentMethod payment_method = 4 [(require.allowedValues) = { + enums: ["PAYMENT_METHOD_CARD", "PAYMENT_METHOD_SEPA_DEBIT", "PAYMENT_METHOD_IDEAL"] + }]; // A donation permit retrieved from Donations.createDonationPermit bytes donation_permit = 5 [(require.nonEmpty) = true]; } -message CreateBoostResponse { +message CreateStripeBoostResponse { oneof response { // A client secret that can be used to complete a stripe PaymentIntent string client_secret = 1; - // The amount is below the minimum for the currency - AmountBelowMinimumError amount_below_minimum = 2 [(tag.reason) = "amount_below_minimum"]; - // The amount exceeds the maximum for SEPA Direct Debit - AmountAboveSepaLimitError amount_above_sepa_limit = 3 [(tag.reason) = "amount_above_sepa_limit"]; - // The requested currency is not supported for the given payment method - errors.FailedPrecondition unsupported_currency = 4 [(tag.reason) = "unsupported_currency"]; - // The requested level is not a valid one-time donation level - errors.FailedPrecondition unsupported_level = 5 [(tag.reason) = "unsupported_level"]; + // The currency is not supported for the payment method, or the amount is + // outside the configured limits (e.g. below the currency's minimum, above + // the SEPA Direct Debit maximum, above the processor's currency maximum). + // The violated constraint may be present in the product configuration, + // clients can attempt a refresh of ProductConfiguration/GetConfiguration + // before giving up. + errors.FailedPrecondition invalid_selection = 2 [(tag.reason) = "invalid_selection"]; // Donation permit was invalid or already spent - errors.FailedZkAuthentication permit_rejected = 6 [(tag.reason) = "permit_rejected"]; - // The amount in the specified currency is not supported by the payment provider - errors.FailedPrecondition invalid_amount = 7 [(tag.reason) = "invalid_amount"]; + errors.FailedZkAuthentication permit_rejected = 3 [(tag.reason) = "permit_rejected"]; } } @@ -93,8 +80,8 @@ message CreatePayPalBoostRequest { string currency = 1 [(require.exactlySize) = 3]; // Amount in the currency's minor unit (e.g. cents for USD), must be >= 1 uint64 amount = 2 [(require.range).min = 1]; - // Donation level. - uint64 level = 3 [(require.range).min = 1]; + // Donation level: 1 for a one-time donation, 100 for a gift donation + uint64 level = 3 [(require.allowedValues) = { ints: [1, 100] }]; // URL to redirect the user to after PayPal approval string return_url = 4 [(require.nonEmpty) = true]; // URL to redirect the user to if they cancel @@ -108,12 +95,11 @@ message CreatePayPalBoostResponse { } oneof response { CreatePayPalBoostResult result = 1; - // The amount is below the minimum for the currency - AmountBelowMinimumError amount_below_minimum = 2 [(tag.reason) = "amount_below_minimum"]; - // The requested currency is not supported for PayPal - errors.FailedPrecondition unsupported_currency = 3 [(tag.reason) = "unsupported_currency"]; - // The requested level is not a valid one-time donation level - errors.FailedPrecondition unsupported_level = 4 [(tag.reason) = "unsupported_level"]; + // The currency is not supported for PayPal, or the amount is below the + // currency's minimum. The violated constraint may be present in the product + // configuration, clients can attempt a refresh of + // ProductConfiguration/GetConfiguration before giving up. + errors.FailedPrecondition invalid_selection = 2 [(tag.reason) = "invalid_selection"]; } } @@ -122,8 +108,8 @@ message ConfirmPayPalBoostRequest { string currency = 1 [(require.exactlySize) = 3]; // Amount in the currency's minor unit, must be >= 1 uint64 amount = 2 [(require.range).min = 1]; - // Donation level. - uint64 level = 3 [(require.range).min = 1]; + // Donation level: 1 for a one-time donation, 100 for a gift donation + uint64 level = 3 [(require.allowedValues) = { ints: [1, 100] }]; // PayPal payer ID from the approval redirect string payer_id = 4 [(require.nonEmpty) = true]; // PayPal payment ID (PAYID-…) from CreatePayPalBoost @@ -138,14 +124,13 @@ message ConfirmPayPalBoostResponse { } oneof response { ConfirmPayPalBoostResult result = 1; - // The amount is below the minimum for the currency - AmountBelowMinimumError amount_below_minimum = 2 [(tag.reason) = "amount_below_minimum"]; - // The requested currency is not supported for PayPal - errors.FailedPrecondition unsupported_currency = 3 [(tag.reason) = "unsupported_currency"]; - // The requested level is not a valid one-time donation level - errors.FailedPrecondition unsupported_level = 4 [(tag.reason) = "unsupported_level"]; + // The currency is not supported for PayPal, or the amount is below the + // currency's minimum. The violated constraint may be present in the product + // configuration, clients can attempt a refresh of + // ProductConfiguration/GetConfiguration before giving up. + errors.FailedPrecondition invalid_selection = 2 [(tag.reason) = "invalid_selection"]; // The payment failed; see charge failure details - ChargeFailure charge_failure = 5 [(tag.reason) = "charge_failure"]; + PaymentRequired payment_required = 3 [(tag.reason) = "payment_required"]; } } @@ -155,7 +140,9 @@ message CreateBoostReceiptCredentialRequest { // ZK blind-signature receipt credential request bytes bytes receipt_credential_request = 2 [(require.nonEmpty) = true]; // The processor that handled the payment - PaymentProvider processor = 3 [(require.specified) = true]; + PaymentProvider processor = 3 [(require.allowedValues) = { + enums: ["PAYMENT_PROVIDER_STRIPE", "PAYMENT_PROVIDER_BRAINTREE"] + }]; } message CreateBoostReceiptCredentialResponse { diff --git a/service/src/main/proto/org/signal/chat/product_configuration.proto b/service/src/main/proto/org/signal/chat/product_configuration.proto index 8273261ce..b738d213d 100644 --- a/service/src/main/proto/org/signal/chat/product_configuration.proto +++ b/service/src/main/proto/org/signal/chat/product_configuration.proto @@ -66,7 +66,7 @@ message LevelConfiguration { // The duration for which a badge is valid. Present only for // one-time (boost, gift) badges - optional uint64 badge_duration_seconds = 2; + optional uint32 badge_duration_seconds = 2; } // Configuration for a backup level - use to present appropriate client interfaces @@ -76,14 +76,14 @@ message BackupLevelConfiguration { // 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; + uint32 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; + uint32 free_tier_media_days = 2; } // Configuration for one-time Signal Login purchases diff --git a/service/src/main/proto/org/signal/chat/require.proto b/service/src/main/proto/org/signal/chat/require.proto index 868a3feb9..cb71f3c8a 100644 --- a/service/src/main/proto/org/signal/chat/require.proto +++ b/service/src/main/proto/org/signal/chat/require.proto @@ -200,7 +200,28 @@ extend google.protobuf.FieldOptions { */ optional ElementConstraint each = 70010; - // next 70011 + /* + * Requires a value to be one of a fixed set of values. Use `ints` for integer + * fields, `strings` for string fields, and `enums` (enum value names) for enum + * fields. + * + * If the field is `optional`, this check allows a value to be not set. + * + * ``` + * import "org/signal/chat/require.proto"; + * + * message Data { + * uint64 level = 1 [(require.allowedValues) = { ints: [1, 100] }]; + * string kind = 2 [(require.allowedValues) = { strings: ["boost", "gift"] }]; + * Color color = 3 [(require.allowedValues) = { enums: ["COLOR_RED", "COLOR_BLUE"] }]; + * } + * ``` + * + * Applicable to integer, string, and enum fields. + */ + optional AllowedValuesConstraint allowedValues = 70011; + + // next 70012 } message ElementConstraint { @@ -219,6 +240,15 @@ message SizeConstraint { optional uint32 max = 2; } +message AllowedValuesConstraint { + // Permitted values for integer fields + repeated int64 ints = 1; + // Permitted values for string fields + repeated string strings = 2; + // Permitted value names for enum fields + repeated string enums = 3; +} + message ValueRangeConstraint { optional int64 min = 1; optional int64 max = 2; diff --git a/service/src/main/proto/org/signal/chat/subscriptions.proto b/service/src/main/proto/org/signal/chat/subscriptions.proto index eaecbece2..7068ab8aa 100644 --- a/service/src/main/proto/org/signal/chat/subscriptions.proto +++ b/service/src/main/proto/org/signal/chat/subscriptions.proto @@ -33,8 +33,8 @@ service Subscriptions { // 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 Stripe client secret that can be used to set up a new payment method with Stripe. + rpc CreateStripePaymentMethod(CreateStripePaymentMethodRequest) returns (CreateStripePaymentMethodResponse) {} // Returns a PayPal billing agreement approval URL and token that can be used to set up PayPal as a payment method. // @@ -49,7 +49,7 @@ service Subscriptions { // 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. + // Returns information about the current subscription associated with the provided subscriber_id 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 @@ -98,11 +98,11 @@ service Subscriptions { // 4. Obtain a receipt via GetReceiptCredential 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 + // After calling this method, the payment is confirmed. Callers must durably store their subscriber_id 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 + // Once a purchaseToken to is posted to a subscriber_id, the same subscriber_id must not be used with another payment + // method. A different playbilling purchaseToken can be posted to the same subscriber_id, in this case the subscription // associated with the old purchaseToken will be cancelled. rpc SetIapSubscription(SetIapSubscriptionRequest) returns (SetIapSubscriptionResponse) {} @@ -131,7 +131,7 @@ message UpdateSubscriberResponse { } message DeleteSubscriberRequest { - bytes subscriberId = 1 [(require.exactlySize) = 32]; + bytes subscriber_id = 1 [(require.exactlySize) = 32]; } message DeleteSubscriberResponse { @@ -180,23 +180,23 @@ enum SubscriptionStatus { 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. +message CreateStripePaymentMethodRequest { bytes subscriber_id = 1 [(require.exactlySize) = 32]; - PaymentMethod payment_method = 2 [(require.specified) = true]; + // The payment method. Only card, SEPA Direct Debit, and iDEAL are supported. + PaymentMethod payment_method = 2 [(require.allowedValues) = { + enums: ["PAYMENT_METHOD_CARD", "PAYMENT_METHOD_SEPA_DEBIT", "PAYMENT_METHOD_IDEAL"] + }]; // a libsignal DonationPermit from rpc Donations.CreateDonationPermits bytes donation_permit = 3 [(require.nonEmpty) = true]; } -message CreatePaymentMethodResponse { - message CreatePaymentMethodResult { - string clientSecret = 1; - PaymentProvider paymentProvider = 2; +message CreateStripePaymentMethodResponse { + message CreateStripePaymentMethodResult { + string client_secret = 1; } oneof response { - CreatePaymentMethodResult result = 1; + CreateStripePaymentMethodResult result = 1; // The subscriber did not exist errors.NotFound subscriber_not_found = 2 [(tag.reason) = "subscriber_not_found"]; // New payment processor does not match existing processor associated with @@ -208,17 +208,17 @@ message CreatePaymentMethodResponse { } message CreatePayPalPaymentMethodRequest { - bytes subscriberId = 1 [(require.exactlySize) = 32]; + bytes subscriber_id = 1 [(require.exactlySize) = 32]; // a callback URL (e.g. an in-client URL handler) for when the user approved the payment - string returnUrl = 2; + string return_url = 2; // a callback URL (e.g. an in-client URL handler) for when the user did not approve the payment - string cancelUrl = 3; + string cancel_url = 3; } message CreatePayPalPaymentMethodResponse { message CreatePayPalPaymentMethodResult { // a URL to open where the user may approve the payment - string approvalUrl = 1; + string approval_url = 1; // an opaque PayPal payment identifier to use with SetDefaultPaymentMethodRequest string token = 2; } @@ -235,16 +235,16 @@ message CreatePayPalPaymentMethodResponse { message SetDefaultPaymentMethodRequest { message StripePaymentMethod { - string paymentMethodToken = 1 [(require.nonEmpty) = true]; + string payment_method_token = 1 [(require.nonEmpty) = true]; } message BraintreePaymentMethod { - string paymentMethodToken = 1 [(require.nonEmpty) = true]; + string payment_method_token = 1 [(require.nonEmpty) = true]; } message SepaPaymentMethod { - string setupIntentId = 1 [(require.nonEmpty) = true]; + string setup_intent_id = 1 [(require.nonEmpty) = true]; } - bytes subscriberId = 1 [(require.exactlySize) = 32]; + bytes subscriber_id = 1 [(require.exactlySize) = 32]; oneof request { StripePaymentMethod stripe = 2; BraintreePaymentMethod braintree = 3; @@ -257,17 +257,20 @@ message SetDefaultPaymentMethodResponse { google.protobuf.Empty success = 1; // The subscriber did not exist, or the referenced setup intent was not found errors.NotFound subscriber_not_found = 2 [(tag.reason) = "subscriber_not_found"]; - // No payment method has been created for the subscriber, or the provided - // payment method has not finished being set up with the processor - errors.FailedPrecondition payment_method_not_set_up = 3 [(tag.reason) = "payment_method_not_set_up"]; + // The request could not be applied in the subscriber's current state. This + // typically indicates a client bug or an out-of-date client. Either + // - No payment method has been created for the subscriber + // - The provided payment method has not finished being set up with the + // processor + errors.FailedPrecondition failed_precondition = 3 [(tag.reason) = "failed_precondition"]; } } message SetSubscriptionLevelRequest { - bytes subscriberId = 1 [(require.exactlySize) = 32]; + bytes subscriber_id = 1 [(require.exactlySize) = 32]; uint64 level = 2; string currency = 3; - string idempotencyKey = 4; + string idempotency_key = 4; } // Information about a charge failure. @@ -312,22 +315,21 @@ message SetSubscriptionLevelResponse { google.protobuf.Empty success = 1; // The subscriber did not exist errors.NotFound subscriber_not_found = 2 [(tag.reason) = "subscriber_not_found"]; - // No payment method has been created for the subscriber - errors.FailedPrecondition payment_method_not_set_up = 3 [(tag.reason) = "payment_method_not_set_up"]; - // The payment processor does not support this operation - errors.FailedPrecondition unsupported_operation = 4 [(tag.reason) = "unsupported_operation"]; - // The requested level was invalid - errors.FailedPrecondition unsupported_level = 5 [(tag.reason) = "unsupported_level"]; - // The requested currency was invalid - errors.FailedPrecondition unsupported_currency = 6 [(tag.reason) = "unsupported_currency"]; - // The card could not be charged - errors.FailedPrecondition payment_requires_action = 7 [(tag.reason) = "payment_requires_action"]; - // Cannot transition from existing level to the requested level - errors.FailedPrecondition invalid_level_transition = 8 [(tag.reason) = "invalid_level_transition"]; - // The idempotency key was invalid or re-used with a modified request - errors.FailedPrecondition invalid_idempotency_key = 9 [(tag.reason) = "invalid_idempotency_key"]; - // The payment failed; see charge failure details - ChargeFailure charge_failure = 10 [(tag.reason) = "charge_failure"]; + // The request could not be applied in the subscriber's current state. This + // typically indicates a client bug or an out-of-date client. Some examples: + // - the client failed to first set up a payment method + // - the requested level cannot be transitioned to from the existing level + // - the payment needs additional authorization before processing + // The FailedPrecondition will contain the specific reason for the failure. + errors.FailedPrecondition failed_precondition = 3 [(tag.reason) = "failed_precondition"]; + // The request contained a currency or level that is not supported. The + // violated constraint may be present in the product configuration, clients + // can attempt a refresh of ProductConfiguration/GetConfiguration before + // giving up. + errors.FailedPrecondition invalid_selection = 4 [(tag.reason) = "invalid_selection"]; + // The payment method could not be charged. If the processor declined the + // charge, charge_failure will be present. + PaymentRequired payment_required = 5 [(tag.reason) = "payment_required"]; } } @@ -339,7 +341,7 @@ message SetIapSubscriptionRequest { string purchase_token = 1 [(require.nonEmpty) = true]; } - bytes subscriberId = 1 [(require.exactlySize) = 32]; + bytes subscriber_id = 1 [(require.exactlySize) = 32]; oneof request { AppStorePurchase app_store = 2; PlayBillingPurchase play_billing = 3; @@ -360,7 +362,7 @@ message SetIapSubscriptionResponse { errors.FailedPrecondition subscription_processor_conflict = 3 [(tag.reason) = "subscription_processor_conflict"]; // The subscription is not in a purchase state that grants the user an // entitlement - errors.FailedPrecondition payment_required = 4 [(tag.reason) = "payment_required"]; + PaymentRequired payment_required = 4 [(tag.reason) = "payment_required"]; // The provided purchase identifier is malformed or the identified // transaction is not supported for use at this endpoint errors.FailedPrecondition invalid_transaction = 5 [(tag.reason) = "invalid_transaction"]; @@ -368,13 +370,13 @@ message SetIapSubscriptionResponse { } message GetReceiptCredentialRequest { - bytes subscriberId = 1 [(require.exactlySize) = 32]; - bytes receiptCredentialRequest = 2 [(require.exactlySize) = 97]; + bytes subscriber_id = 1 [(require.exactlySize) = 32]; + bytes receipt_credential_request = 2 [(require.exactlySize) = 97]; } message GetReceiptCredentialResponse { message GetReceiptCredentialResult { - bytes receiptCredentialResponse = 1; + bytes receipt_credential_response = 1; } oneof response { @@ -391,7 +393,7 @@ message GetReceiptCredentialResponse { } message GetSubscriptionInformationRequest { - bytes subscriberId = 1 [(require.exactlySize) = 32]; + bytes subscriber_id = 1 [(require.exactlySize) = 32]; } message GetSubscriptionInformationResponse { diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/controllers/OneTimeDonationControllerTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/controllers/OneTimeDonationControllerTest.java index 6b400b48c..b9ff97afd 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/controllers/OneTimeDonationControllerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/controllers/OneTimeDonationControllerTest.java @@ -51,7 +51,7 @@ import org.whispersystems.textsecuregcm.purchases.PaymentDetails; import org.whispersystems.textsecuregcm.purchases.PaymentMethod; import org.whispersystems.textsecuregcm.purchases.PaymentProvider; import org.whispersystems.textsecuregcm.purchases.PurchaseException; -import org.whispersystems.textsecuregcm.purchases.PurchaseInvalidAmountException; +import org.whispersystems.textsecuregcm.purchases.PurchaseAmountTooLargeException; import org.whispersystems.textsecuregcm.purchases.PurchasePaymentRequiredException; import org.whispersystems.textsecuregcm.purchases.PurchaseProcessorException; import org.whispersystems.textsecuregcm.purchases.ReceiptLevel; @@ -180,7 +180,7 @@ class OneTimeDonationControllerTest extends AbstractV1SubscriptionControllerTest @ParameterizedTest @ValueSource(booleans = {true, false}) - void testCreateBoostPaymentIntent(final boolean donationPermitSpendOk) throws PurchaseInvalidAmountException { + void testCreateBoostPaymentIntent(final boolean donationPermitSpendOk) throws PurchaseAmountTooLargeException { when(DONATION_PERMITS.spend(any(byte[].class), any(Instant.class))).thenReturn(donationPermitSpendOk); when(STRIPE_MANAGER.getSupportedCurrenciesForPaymentMethod(PaymentMethod.CARD)) diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/grpc/OneTimeDonationsGrpcServiceTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/OneTimeDonationsGrpcServiceTest.java index 49cc6d2a0..01c8af10f 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/grpc/OneTimeDonationsGrpcServiceTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/OneTimeDonationsGrpcServiceTest.java @@ -33,8 +33,8 @@ import org.signal.chat.purchase.ConfirmPayPalBoostRequest; import org.signal.chat.purchase.ConfirmPayPalBoostResponse; import org.signal.chat.purchase.CreateBoostReceiptCredentialRequest; import org.signal.chat.purchase.CreateBoostReceiptCredentialResponse; -import org.signal.chat.purchase.CreateBoostRequest; -import org.signal.chat.purchase.CreateBoostResponse; +import org.signal.chat.purchase.CreateStripeBoostRequest; +import org.signal.chat.purchase.CreateStripeBoostResponse; import org.signal.chat.purchase.CreatePayPalBoostRequest; import org.signal.chat.purchase.CreatePayPalBoostResponse; import org.signal.chat.purchase.OneTimeDonationsGrpc; @@ -58,7 +58,7 @@ import org.whispersystems.textsecuregcm.purchases.ChargeFailure; import org.whispersystems.textsecuregcm.purchases.PayPalDonationsTranslator; import org.whispersystems.textsecuregcm.purchases.PaymentDetails; import org.whispersystems.textsecuregcm.purchases.PurchaseException; -import org.whispersystems.textsecuregcm.purchases.PurchaseInvalidAmountException; +import org.whispersystems.textsecuregcm.purchases.PurchaseAmountTooLargeException; import org.whispersystems.textsecuregcm.purchases.PurchasePaymentRequiredException; import org.whispersystems.textsecuregcm.purchases.PurchaseProcessorException; import org.whispersystems.textsecuregcm.purchases.ReceiptLevel; @@ -137,7 +137,7 @@ public class OneTimeDonationsGrpcServiceTest extends } @Test - void createBoost() throws PurchaseInvalidAmountException { + void createStripeBoost() throws PurchaseAmountTooLargeException { final PaymentIntent paymentIntent = mock(PaymentIntent.class); when(paymentIntent.getClientSecret()).thenReturn("test-client-secret"); when(stripeManager.getSupportedCurrenciesForPaymentMethod( @@ -146,8 +146,8 @@ public class OneTimeDonationsGrpcServiceTest extends when(stripeManager.createPaymentIntent(any(), anyLong(), anyLong(), any())) .thenReturn(paymentIntent); - final CreateBoostResponse response = unauthenticatedServiceStub().createBoost( - CreateBoostRequest.newBuilder() + final CreateStripeBoostResponse response = unauthenticatedServiceStub().createStripeBoost( + CreateStripeBoostRequest.newBuilder() .setCurrency("usd") .setAmount(500) .setLevel(1) @@ -155,16 +155,20 @@ public class OneTimeDonationsGrpcServiceTest extends .setDonationPermit(ByteString.copyFrom(getDonationPermit().serialize())) .build()); - assertEquals(CreateBoostResponse.ResponseCase.CLIENT_SECRET, response.getResponseCase()); + assertEquals(CreateStripeBoostResponse.ResponseCase.CLIENT_SECRET, response.getResponseCase()); assertEquals("test-client-secret", response.getClientSecret()); } @Test - void createBoostPermitAlreadySpent() { - when(donationPermits.spend(any(byte[].class), any(Instant.class))).thenReturn(false); + void createBoostAmountTooLarge() throws PurchaseAmountTooLargeException { + when(stripeManager.getSupportedCurrenciesForPaymentMethod( + org.whispersystems.textsecuregcm.purchases.PaymentMethod.CARD)) + .thenReturn(Set.of("usd")); + when(stripeManager.createPaymentIntent(any(), anyLong(), anyLong(), any())) + .thenThrow(new PurchaseAmountTooLargeException("amount_too_large")); - final CreateBoostResponse response = unauthenticatedServiceStub().createBoost( - CreateBoostRequest.newBuilder() + final CreateStripeBoostResponse response = unauthenticatedServiceStub().createStripeBoost( + CreateStripeBoostRequest.newBuilder() .setCurrency("usd") .setAmount(500) .setLevel(1) @@ -172,7 +176,26 @@ public class OneTimeDonationsGrpcServiceTest extends .setDonationPermit(ByteString.copyFrom(getDonationPermit().serialize())) .build()); - assertEquals(CreateBoostResponse.ResponseCase.PERMIT_REJECTED, response.getResponseCase()); + assertEquals(CreateStripeBoostResponse.ResponseCase.INVALID_SELECTION, response.getResponseCase()); + } + + @Test + void createBoostPermitAlreadySpent() { + when(stripeManager.getSupportedCurrenciesForPaymentMethod( + org.whispersystems.textsecuregcm.purchases.PaymentMethod.CARD)) + .thenReturn(Set.of("usd")); + when(donationPermits.spend(any(byte[].class), any(Instant.class))).thenReturn(false); + + final CreateStripeBoostResponse response = unauthenticatedServiceStub().createStripeBoost( + CreateStripeBoostRequest.newBuilder() + .setCurrency("usd") + .setAmount(500) + .setLevel(1) + .setPaymentMethod(PaymentMethod.PAYMENT_METHOD_CARD) + .setDonationPermit(ByteString.copyFrom(getDonationPermit().serialize())) + .build()); + + assertEquals(CreateStripeBoostResponse.ResponseCase.PERMIT_REJECTED, response.getResponseCase()); } @ParameterizedTest @@ -180,8 +203,7 @@ public class OneTimeDonationsGrpcServiceTest extends void createBoostValidationErrors( final String currency, final long amount, - final PaymentMethod paymentMethod, - final CreateBoostResponse.ResponseCase expectedResponseCase) { + final PaymentMethod paymentMethod) { when(stripeManager.getSupportedCurrenciesForPaymentMethod( org.whispersystems.textsecuregcm.purchases.PaymentMethod.CARD)) .thenReturn(Set.of("usd")); @@ -189,8 +211,8 @@ public class OneTimeDonationsGrpcServiceTest extends org.whispersystems.textsecuregcm.purchases.PaymentMethod.SEPA_DEBIT)) .thenReturn(Set.of("eur")); - final CreateBoostResponse response = unauthenticatedServiceStub().createBoost( - CreateBoostRequest.newBuilder() + final CreateStripeBoostResponse response = unauthenticatedServiceStub().createStripeBoost( + CreateStripeBoostRequest.newBuilder() .setCurrency(currency) .setAmount(amount) .setLevel(1) @@ -198,21 +220,32 @@ public class OneTimeDonationsGrpcServiceTest extends .setDonationPermit(ByteString.copyFrom(getDonationPermit().serialize())) .build()); - assertEquals(expectedResponseCase, response.getResponseCase()); + assertEquals(CreateStripeBoostResponse.ResponseCase.INVALID_SELECTION, response.getResponseCase()); } static Stream createBoostValidationErrors() { return Stream.of( - Arguments.of("usd", 249L, PaymentMethod.PAYMENT_METHOD_CARD, - CreateBoostResponse.ResponseCase.AMOUNT_BELOW_MINIMUM), - Arguments.of("eur", 1000001L, PaymentMethod.PAYMENT_METHOD_SEPA_DEBIT, - CreateBoostResponse.ResponseCase.AMOUNT_ABOVE_SEPA_LIMIT), + // Below the USD minimum + Arguments.of("usd", 249L, PaymentMethod.PAYMENT_METHOD_CARD), + // Above the SEPA maximum + Arguments.of("eur", 1000001L, PaymentMethod.PAYMENT_METHOD_SEPA_DEBIT), // USD is not supported for SEPA_DEBIT - Arguments.of("usd", 3000L, PaymentMethod.PAYMENT_METHOD_SEPA_DEBIT, - CreateBoostResponse.ResponseCase.UNSUPPORTED_CURRENCY) + Arguments.of("usd", 3000L, PaymentMethod.PAYMENT_METHOD_SEPA_DEBIT) ); } + @Test + void createBoostUnsupportedLevel() { + GrpcTestUtils.assertStatusInvalidArgument(() -> unauthenticatedServiceStub().createStripeBoost( + CreateStripeBoostRequest.newBuilder() + .setCurrency("usd") + .setAmount(3000L) + .setLevel(500) + .setPaymentMethod(PaymentMethod.PAYMENT_METHOD_CARD) + .setDonationPermit(ByteString.copyFrom(getDonationPermit().serialize())) + .build())); + } + @Test void createPayPalBoost() throws IOException { final BraintreeManager.PayPalOneTimePaymentApprovalDetails approvalDetails = diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/grpc/SubscriptionsGrpcServiceTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/SubscriptionsGrpcServiceTest.java index 0bcddb329..4342329f8 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/grpc/SubscriptionsGrpcServiceTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/SubscriptionsGrpcServiceTest.java @@ -36,8 +36,8 @@ import org.junit.jupiter.params.provider.MethodSource; import org.mockito.Mock; import org.signal.chat.purchase.CreatePayPalPaymentMethodRequest; import org.signal.chat.purchase.CreatePayPalPaymentMethodResponse; -import org.signal.chat.purchase.CreatePaymentMethodRequest; -import org.signal.chat.purchase.CreatePaymentMethodResponse; +import org.signal.chat.purchase.CreateStripePaymentMethodRequest; +import org.signal.chat.purchase.CreateStripePaymentMethodResponse; import org.signal.chat.purchase.DeleteSubscriberRequest; import org.signal.chat.purchase.DeleteSubscriberResponse; import org.signal.chat.purchase.GetBankMandateRequest; @@ -233,28 +233,24 @@ public class SubscriptionsGrpcServiceTest extends @ParameterizedTest @EnumSource(value = PaymentMethod.class, names = {"PAYMENT_METHOD_CARD", "PAYMENT_METHOD_SEPA_DEBIT", "PAYMENT_METHOD_IDEAL"}) - void createPaymentMethod(final PaymentMethod paymentMethod) + void createStripePaymentMethod(final PaymentMethod paymentMethod) throws PurchaseForbiddenException, PurchaseNotFoundException, PurchaseProcessorConflictException { when(subscriptionManager.addPaymentMethodToCustomer(any(), any(), any(), any())).thenReturn("test-client-secret"); - when(stripeManager.getProvider()).thenReturn(PaymentProvider.STRIPE); - final CreatePaymentMethodRequest.Builder builder = CreatePaymentMethodRequest.newBuilder() + final CreateStripePaymentMethodRequest.Builder builder = CreateStripePaymentMethodRequest.newBuilder() .setSubscriberId(SUBSCRIBER_ID) .setDonationPermit(ByteString.copyFrom(getDonationPermit().serialize())) .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.purchase.PaymentProvider.PAYMENT_PROVIDER_STRIPE, - response.getResult().getPaymentProvider()); + final CreateStripePaymentMethodResponse response = unauthenticatedServiceStub().createStripePaymentMethod(builder.build()); + assertEquals(CreateStripePaymentMethodResponse.ResponseCase.RESULT, response.getResponseCase()); assertEquals("test-client-secret", response.getResult().getClientSecret()); } @Test void createPaymentMethodUnsupportedPaymentMethod() { GrpcTestUtils.assertStatusInvalidArgument( - () -> unauthenticatedServiceStub().createPaymentMethod( - CreatePaymentMethodRequest.newBuilder() + () -> unauthenticatedServiceStub().createStripePaymentMethod( + CreateStripePaymentMethodRequest.newBuilder() .setSubscriberId(SUBSCRIBER_ID) .setPaymentMethod(PaymentMethod.PAYMENT_METHOD_PAYPAL) .build())); @@ -263,8 +259,8 @@ public class SubscriptionsGrpcServiceTest extends @Test void createPaymentMethodInvalidDonationPermit() { GrpcTestUtils.assertStatusInvalidArgument( - () -> unauthenticatedServiceStub().createPaymentMethod( - CreatePaymentMethodRequest.newBuilder() + () -> unauthenticatedServiceStub().createStripePaymentMethod( + CreateStripePaymentMethodRequest.newBuilder() .setSubscriberId(SUBSCRIBER_ID) .setDonationPermit(ByteString.copyFrom(new byte[]{1})) .setPaymentMethod(PaymentMethod.PAYMENT_METHOD_CARD) @@ -278,8 +274,8 @@ public class SubscriptionsGrpcServiceTest extends final DonationPermit donationPermit = getDonationPermit(); clock.pin(clock.instant().plus(Duration.ofDays(30))); - final CreatePaymentMethodResponse createPaymentMethodResponse = unauthenticatedServiceStub().createPaymentMethod( - CreatePaymentMethodRequest.newBuilder() + final CreateStripePaymentMethodResponse createPaymentMethodResponse = unauthenticatedServiceStub().createStripePaymentMethod( + CreateStripePaymentMethodRequest.newBuilder() .setSubscriberId(SUBSCRIBER_ID) .setDonationPermit(ByteString.copyFrom(donationPermit.serialize())) .setPaymentMethod(PaymentMethod.PAYMENT_METHOD_CARD) @@ -293,13 +289,13 @@ public class SubscriptionsGrpcServiceTest extends throws PurchaseForbiddenException, PurchaseNotFoundException, PurchaseProcessorConflictException { doThrow(new PurchaseProcessorConflictException()) .when(subscriptionManager).addPaymentMethodToCustomer(any(), any(), any(), any()); - final CreatePaymentMethodResponse response = unauthenticatedServiceStub().createPaymentMethod( - CreatePaymentMethodRequest.newBuilder() + final CreateStripePaymentMethodResponse response = unauthenticatedServiceStub().createStripePaymentMethod( + CreateStripePaymentMethodRequest.newBuilder() .setSubscriberId(SUBSCRIBER_ID) .setDonationPermit(ByteString.copyFrom(getDonationPermit().serialize())) .setPaymentMethod(PaymentMethod.PAYMENT_METHOD_CARD) .build()); - assertEquals(CreatePaymentMethodResponse.ResponseCase.SUBSCRIPTION_PROCESSOR_CONFLICT, response.getResponseCase()); + assertEquals(CreateStripePaymentMethodResponse.ResponseCase.SUBSCRIPTION_PROCESSOR_CONFLICT, response.getResponseCase()); } @Test @@ -398,7 +394,7 @@ public class SubscriptionsGrpcServiceTest extends .setStripe(SetDefaultPaymentMethodRequest.StripePaymentMethod.newBuilder() .setPaymentMethodToken("test-token").build()) .build()); - assertEquals(SetDefaultPaymentMethodResponse.ResponseCase.PAYMENT_METHOD_NOT_SET_UP, response.getResponseCase()); + assertEquals(SetDefaultPaymentMethodResponse.ResponseCase.FAILED_PRECONDITION, response.getResponseCase()); } private void mockValidSubscription() throws PurchaseNotFoundException, PurchaseForbiddenException { @@ -443,7 +439,7 @@ public class SubscriptionsGrpcServiceTest extends .setSubscriberId(SUBSCRIBER_ID) .setLevel(LEVEL).setCurrency(CURRENCY).setIdempotencyKey("test-idempotency-key") .build()); - assertEquals(SetSubscriptionLevelResponse.ResponseCase.PAYMENT_METHOD_NOT_SET_UP, response.getResponseCase()); + assertEquals(SetSubscriptionLevelResponse.ResponseCase.FAILED_PRECONDITION, response.getResponseCase()); } @Test @@ -457,7 +453,7 @@ public class SubscriptionsGrpcServiceTest extends .setSubscriberId(SUBSCRIBER_ID) .setLevel(999L).setCurrency(CURRENCY).setIdempotencyKey("test-idempotency-key") .build()); - assertEquals(SetSubscriptionLevelResponse.ResponseCase.UNSUPPORTED_LEVEL, response.getResponseCase()); + assertEquals(SetSubscriptionLevelResponse.ResponseCase.INVALID_SELECTION, response.getResponseCase()); } @Test @@ -471,13 +467,12 @@ public class SubscriptionsGrpcServiceTest extends .setSubscriberId(SUBSCRIBER_ID) .setLevel(LEVEL).setCurrency("xyz").setIdempotencyKey("test-idempotency-key") .build()); - assertEquals(SetSubscriptionLevelResponse.ResponseCase.UNSUPPORTED_CURRENCY, response.getResponseCase()); + assertEquals(SetSubscriptionLevelResponse.ResponseCase.INVALID_SELECTION, response.getResponseCase()); } @ParameterizedTest @MethodSource - void setSubscriptionLevelUpdateExceptions(final PurchaseException exception, - final SetSubscriptionLevelResponse.ResponseCase expectedCase) + void setSubscriptionLevelUpdateFailedPreconditionExceptions(final PurchaseException exception) throws PurchaseException { mockValidSubscription(); doThrow(exception).when(subscriptionManager).updateSubscriptionLevelForCustomer( @@ -487,17 +482,15 @@ public class SubscriptionsGrpcServiceTest extends .setSubscriberId(SUBSCRIBER_ID) .setLevel(LEVEL).setCurrency(CURRENCY).setIdempotencyKey("test-idempotency-key") .build()); - assertEquals(expectedCase, response.getResponseCase()); + assertEquals(SetSubscriptionLevelResponse.ResponseCase.FAILED_PRECONDITION, response.getResponseCase()); } - static Stream setSubscriptionLevelUpdateExceptions() { + static Stream setSubscriptionLevelUpdateFailedPreconditionExceptions() { return Stream.of( - Arguments.of(new PurchaseInvalidIdempotencyKeyException("bad key"), - SetSubscriptionLevelResponse.ResponseCase.INVALID_IDEMPOTENCY_KEY), - Arguments.of(new PurchasePaymentRequiresActionException(), - SetSubscriptionLevelResponse.ResponseCase.PAYMENT_REQUIRES_ACTION), - Arguments.of(new PurchaseInvalidLevelException(), - SetSubscriptionLevelResponse.ResponseCase.INVALID_LEVEL_TRANSITION) + Arguments.of(new PurchaseInvalidIdempotencyKeyException("bad key")), + Arguments.of(new PurchasePaymentRequiresActionException()), + Arguments.of(new PurchaseInvalidLevelException()), + Arguments.of(new PurchaseProcessorConflictException()) ); } @@ -514,11 +507,11 @@ public class SubscriptionsGrpcServiceTest extends .setSubscriberId(SUBSCRIBER_ID) .setLevel(LEVEL).setCurrency(CURRENCY).setIdempotencyKey("test-idempotency-key") .build()); - assertEquals(SetSubscriptionLevelResponse.ResponseCase.CHARGE_FAILURE, response.getResponseCase()); + assertEquals(SetSubscriptionLevelResponse.ResponseCase.PAYMENT_REQUIRED, response.getResponseCase()); assertEquals(org.signal.chat.purchase.PaymentProvider.PAYMENT_PROVIDER_STRIPE, - response.getChargeFailure().getProcessor()); - assertEquals("card_declined", response.getChargeFailure().getCode()); - assertEquals("Insufficient funds", response.getChargeFailure().getMessage()); + response.getPaymentRequired().getChargeFailure().getProcessor()); + assertEquals("card_declined", response.getPaymentRequired().getChargeFailure().getCode()); + assertEquals("Insufficient funds", response.getPaymentRequired().getChargeFailure().getMessage()); } @Test diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/grpc/ValidatingInterceptorTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/ValidatingInterceptorTest.java index 6aad25f5c..fd3d0ee14 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/grpc/ValidatingInterceptorTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/ValidatingInterceptorTest.java @@ -423,6 +423,78 @@ public class ValidatingInterceptorTest { )); } + @Test + public void testAllowedValues() throws Exception { + GrpcTestUtils.assertStatusException(Status.INVALID_ARGUMENT, () -> stub.validationsEndpoint( + builderWithValidDefaults() + .setAllowedValues(2) + .build() + )); + GrpcTestUtils.assertStatusException(Status.INVALID_ARGUMENT, () -> stub.validationsEndpoint( + builderWithValidDefaults() + .clearAllowedValues() + .build() + )); + GrpcTestUtils.assertStatusException(Status.INVALID_ARGUMENT, () -> stub.validationsEndpoint( + builderWithValidDefaults() + .setAllowedValuesOptional(0) + .build() + )); + stub.validationsEndpoint( + builderWithValidDefaults() + .setAllowedValues(100) + .build() + ); + stub.validationsEndpoint( + builderWithValidDefaults() + .setAllowedValuesOptional(-1) + .build() + ); + stub.validationsEndpoint( + builderWithValidDefaults() + .clearAllowedValuesOptional() + .build() + ); + } + + @Test + public void testAllowedValuesString() throws Exception { + GrpcTestUtils.assertStatusException(Status.INVALID_ARGUMENT, () -> stub.validationsEndpoint( + builderWithValidDefaults() + .setAllowedValuesString("subscription") + .build() + )); + GrpcTestUtils.assertStatusException(Status.INVALID_ARGUMENT, () -> stub.validationsEndpoint( + builderWithValidDefaults() + .setAllowedValuesString("") + .build() + )); + stub.validationsEndpoint( + builderWithValidDefaults() + .setAllowedValuesString("gift") + .build() + ); + } + + @Test + public void testAllowedValuesEnum() throws Exception { + GrpcTestUtils.assertStatusException(Status.INVALID_ARGUMENT, () -> stub.validationsEndpoint( + builderWithValidDefaults() + .setAllowedValuesEnum(Color.COLOR_GREEN) + .build() + )); + GrpcTestUtils.assertStatusException(Status.INVALID_ARGUMENT, () -> stub.validationsEndpoint( + builderWithValidDefaults() + .setAllowedValuesEnum(Color.COLOR_UNSPECIFIED) + .build() + )); + stub.validationsEndpoint( + builderWithValidDefaults() + .setAllowedValuesEnum(Color.COLOR_BLUE) + .build() + ); + } + @Test public void testPresent() throws Exception { GrpcTestUtils.assertStatusException(Status.INVALID_ARGUMENT, () -> stub.validationsEndpoint( @@ -588,6 +660,7 @@ public class ValidatingInterceptorTest { .addAllFixedSizeList(List.of("a", "b", "c", "d", "e")) .addAllRangeSizeList(List.of("a", "b", "c", "d", "e")) .setI32Range(15) + .setAllowedValues(1) .setNested(NestedMessage.getDefaultInstance()) .addRepeatedNested(NestedMessage.getDefaultInstance()) .putMapNested("test", NestedMessage.getDefaultInstance()) diff --git a/service/src/test/proto/validation_test.proto b/service/src/test/proto/validation_test.proto index 8e46bef60..b581ff512 100644 --- a/service/src/test/proto/validation_test.proto +++ b/service/src/test/proto/validation_test.proto @@ -93,7 +93,12 @@ message ValidationsRequest { (require.each) = { exactlySize: 4 } ]; - // next 40 + uint64 allowedValues = 40 [(require.allowedValues) = { ints: [1, 100] }]; + optional int32 allowedValuesOptional = 41 [(require.allowedValues) = { ints: [-1, 5] }]; + optional string allowedValuesString = 42 [(require.allowedValues) = { strings: ["boost", "gift"] }]; + optional Color allowedValuesEnum = 43 [(require.allowedValues) = { enums: ["COLOR_RED", "COLOR_BLUE"] }]; + + // next 44 } message NestedMessage {