From 78b31474916cf2113e82bc38a5cdabc9e75cb249 Mon Sep 17 00:00:00 2001 From: Chris Eager <79161849+eager-signal@users.noreply.github.com> Date: Wed, 24 Jun 2026 12:13:21 -0500 Subject: [PATCH] Implement donation permit spending --- service/config/sample.yml | 3 + .../textsecuregcm/WhisperServerService.java | 20 +- .../auth/DonationPermitHeader.java | 24 ++ .../configuration/DynamoDbTables.java | 9 + .../controllers/DonationController.java | 14 +- .../OneTimeDonationController.java | 48 ++- .../controllers/SubscriptionController.java | 83 +++-- .../grpc/DonationsGrpcService.java | 34 +- .../grpc/SubscriptionsGrpcService.java | 66 +++- .../textsecuregcm/grpc/SubscriptionsUtil.java | 38 ++- .../storage/DonationPermits.java | 56 ++++ .../storage/DonationPermitsManager.java | 51 +++ .../storage/SubscriptionManager.java | 21 +- ...criberIdCreationNotPermittedException.java | 13 + .../textsecuregcm/util/HeaderUtils.java | 2 + .../proto/org/signal/chat/donations.proto | 14 + .../proto/org/signal/chat/subscriptions.proto | 15 +- .../AbstractV1SubscriptionControllerTest.java | 41 +++ .../controllers/DonationControllerTest.java | 8 +- .../OneTimeDonationControllerTest.java | 158 ++++++---- .../SubscriptionControllerTest.java | 297 ++++++++++-------- .../grpc/DonationsGrpcServiceTest.java | 81 ++++- .../grpc/SubscriptionsGrpcServiceTest.java | 115 ++++++- .../storage/DonationPermitsTest.java | 68 ++++ .../storage/DynamoDbExtensionSchema.java | 8 + .../storage/SubscriptionManagerTest.java | 108 +++++++ service/src/test/resources/config/test.yml | 3 + 27 files changed, 1117 insertions(+), 281 deletions(-) create mode 100644 service/src/main/java/org/whispersystems/textsecuregcm/auth/DonationPermitHeader.java create mode 100644 service/src/main/java/org/whispersystems/textsecuregcm/storage/DonationPermits.java create mode 100644 service/src/main/java/org/whispersystems/textsecuregcm/storage/DonationPermitsManager.java create mode 100644 service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/SubscriberIdCreationNotPermittedException.java create mode 100644 service/src/test/java/org/whispersystems/textsecuregcm/storage/DonationPermitsTest.java create mode 100644 service/src/test/java/org/whispersystems/textsecuregcm/storage/SubscriptionManagerTest.java diff --git a/service/config/sample.yml b/service/config/sample.yml index 1f507db64..fe46b11d4 100644 --- a/service/config/sample.yml +++ b/service/config/sample.yml @@ -100,6 +100,9 @@ dynamoDbTables: tableName: Example_DeletedAccounts deletedAccountsLock: tableName: Example_DeletedAccountsLock + donationPermits: + tableName: Example_DonationPermits + expiration: P7D # Duration of time until rows expire issuedReceipts: tableName: Example_IssuedReceipts expiration: P30D # Duration of time until rows expire diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerService.java b/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerService.java index 305ec8e6c..7c966e25d 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerService.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerService.java @@ -251,6 +251,8 @@ import org.whispersystems.textsecuregcm.storage.ChangeNumberWaitingPeriodManager import org.whispersystems.textsecuregcm.storage.ChangeNumberWaitingPeriods; import org.whispersystems.textsecuregcm.storage.ClientReleaseManager; import org.whispersystems.textsecuregcm.storage.ClientReleases; +import org.whispersystems.textsecuregcm.storage.DonationPermits; +import org.whispersystems.textsecuregcm.storage.DonationPermitsManager; import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager; import org.whispersystems.textsecuregcm.storage.FoundationDbVersion; import org.whispersystems.textsecuregcm.storage.IssuedReceiptsManager; @@ -785,6 +787,8 @@ 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! @@ -1087,8 +1094,8 @@ 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! @@ -1219,7 +1226,7 @@ public class WhisperServerService extends Application createBoostPaymentIntent( @Auth Optional authenticatedAccount, + + @Parameter(description="A base64-encoded donation permit retrieved from POST /v1/donation/permit") + @HeaderParam(HeaderUtils.DONATION_PERMIT) + final Optional donationPermitHeader, + @NotNull @Valid CreateBoostRequest request, @HeaderParam(HttpHeaders.USER_AGENT) final String userAgent) { @@ -172,6 +184,20 @@ public class OneTimeDonationController { throw new ForbiddenException("must not use authenticated connection for one-time donation operations"); } + SubscriptionsUtil.recordDonationPermitPresent(donationPermitHeader.isPresent(), "boostCreate", userAgent); + final boolean spendSuccessful = donationPermitHeader.map( + permitHeader -> { + try { + return SubscriptionsUtil.verifyAndSpendDonationPermit(permitHeader.permit(), donationPermitsManager, clock); + } catch (VerificationFailedException e) { + return false; + } + }) + .orElse(true); + if (!spendSuccessful) { + throw new WebApplicationException(Response.Status.UNAUTHORIZED); + } + return CompletableFuture.runAsync(() -> validateRequestCurrencyAmount(request, BigDecimal.valueOf(request.amount), stripeManager)) .thenCompose(_ -> stripeManager.createPaymentIntent(request.currency, request.amount, request.level, diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/controllers/SubscriptionController.java b/service/src/main/java/org/whispersystems/textsecuregcm/controllers/SubscriptionController.java index 934a74e2e..4b43cec6b 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/controllers/SubscriptionController.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/controllers/SubscriptionController.java @@ -5,6 +5,10 @@ package org.whispersystems.textsecuregcm.controllers; +import static org.whispersystems.textsecuregcm.grpc.SubscriptionsUtil.buildCurrencyConfiguration; +import static org.whispersystems.textsecuregcm.grpc.SubscriptionsUtil.buildDonationLevelsConfiguration; +import static org.whispersystems.textsecuregcm.grpc.SubscriptionsUtil.getClientPlatform; + import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.google.common.annotations.VisibleForTesting; @@ -15,6 +19,7 @@ import io.micrometer.core.instrument.Tag; import io.micrometer.core.instrument.Tags; import io.swagger.v3.oas.annotations.ExternalDocumentation; import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.headers.Header; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; @@ -36,6 +41,7 @@ import jakarta.ws.rs.Path; import jakarta.ws.rs.PathParam; import jakarta.ws.rs.Produces; import jakarta.ws.rs.QueryParam; +import jakarta.ws.rs.WebApplicationException; import jakarta.ws.rs.container.ContainerRequestContext; import jakarta.ws.rs.core.Context; import jakarta.ws.rs.core.MediaType; @@ -50,11 +56,12 @@ import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.stream.Collectors; -import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.glassfish.jersey.server.ManagedAsync; +import org.signal.libsignal.zkgroup.VerificationFailedException; import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialResponse; import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice; +import org.whispersystems.textsecuregcm.auth.DonationPermitHeader; import org.whispersystems.textsecuregcm.badges.BadgeTranslator; import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfiguration; import org.whispersystems.textsecuregcm.configuration.SubscriptionConfiguration; @@ -66,6 +73,7 @@ import org.whispersystems.textsecuregcm.limits.RateLimiters; import org.whispersystems.textsecuregcm.mappers.SubscriptionExceptionMapper; import org.whispersystems.textsecuregcm.metrics.MetricsUtil; import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil; +import org.whispersystems.textsecuregcm.storage.DonationPermitsManager; import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager; import org.whispersystems.textsecuregcm.storage.SubscriberCredentials; import org.whispersystems.textsecuregcm.storage.SubscriptionManager; @@ -90,10 +98,6 @@ import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPaymentRequire import org.whispersystems.textsecuregcm.subscriptions.SubscriptionReceiptRequestedForOpenPaymentException; import org.whispersystems.textsecuregcm.util.HeaderUtils; -import static org.whispersystems.textsecuregcm.grpc.SubscriptionsUtil.buildCurrencyConfiguration; -import static org.whispersystems.textsecuregcm.grpc.SubscriptionsUtil.buildDonationLevelsConfiguration; -import static org.whispersystems.textsecuregcm.grpc.SubscriptionsUtil.getClientPlatform; - @Path("/v1/subscription") @io.swagger.v3.oas.annotations.tags.Tag(name = "Subscriptions") public class SubscriptionController { @@ -108,6 +112,7 @@ public class SubscriptionController { private final AppleAppStoreManager appleAppStoreManager; private final BadgeTranslator badgeTranslator; private final BankMandateTranslator bankMandateTranslator; + private final DonationPermitsManager donationPermitsManager; private final DynamicConfigurationManager dynamicConfigurationManager; static final String RECEIPT_ISSUED_COUNTER_NAME = MetricsUtil.name(SubscriptionController.class, "receiptIssued"); static final String PROCESSOR_TAG_NAME = "processor"; @@ -115,17 +120,18 @@ public class SubscriptionController { private static final String SUBSCRIPTION_TYPE_TAG_NAME = "subscriptionType"; public SubscriptionController( - @Nonnull Clock clock, - @Nonnull SubscriptionConfiguration subscriptionConfiguration, - @Nonnull OneTimeDonationConfiguration oneTimeDonationConfiguration, - @Nonnull SubscriptionManager subscriptionManager, - @Nonnull StripeManager stripeManager, - @Nonnull BraintreeManager braintreeManager, - @Nonnull GooglePlayBillingManager googlePlayBillingManager, - @Nonnull AppleAppStoreManager appleAppStoreManager, - @Nonnull BadgeTranslator badgeTranslator, - @Nonnull BankMandateTranslator bankMandateTranslator, - @NotNull DynamicConfigurationManager dynamicConfigurationManager) { + Clock clock, + SubscriptionConfiguration subscriptionConfiguration, + OneTimeDonationConfiguration oneTimeDonationConfiguration, + SubscriptionManager subscriptionManager, + StripeManager stripeManager, + BraintreeManager braintreeManager, + GooglePlayBillingManager googlePlayBillingManager, + AppleAppStoreManager appleAppStoreManager, + BadgeTranslator badgeTranslator, + BankMandateTranslator bankMandateTranslator, + DonationPermitsManager donationPermitsManager, + DynamicConfigurationManager dynamicConfigurationManager) { this.subscriptionManager = subscriptionManager; this.clock = Objects.requireNonNull(clock); this.subscriptionConfiguration = Objects.requireNonNull(subscriptionConfiguration); @@ -136,7 +142,8 @@ public class SubscriptionController { this.appleAppStoreManager = appleAppStoreManager; this.badgeTranslator = Objects.requireNonNull(badgeTranslator); this.bankMandateTranslator = Objects.requireNonNull(bankMandateTranslator); - this.dynamicConfigurationManager = dynamicConfigurationManager; + this.donationPermitsManager = donationPermitsManager; + this.dynamicConfigurationManager = Objects.requireNonNull(dynamicConfigurationManager); } @@ -202,15 +209,35 @@ public class SubscriptionController { period of time will result in the subscription being canceled. """) @ApiResponse(responseCode = "200", description = "The subscriber was successfully created or refreshed") + @ApiResponse(responseCode = "401", description = "Donation permit was invalid or already spent") @ApiResponse(responseCode = "403", description = "subscriberId authentication failure OR account authentication is present") @ApiResponse(responseCode = "404", description = "subscriberId is malformed") @ManagedAsync public Response updateSubscriber( @Auth Optional authenticatedAccount, + + @Parameter(description="A base64-encoded donation permit retrieved from POST /v1/donation/permit") + @HeaderParam(HeaderUtils.DONATION_PERMIT) + final Optional donationPermitHeader, + + @HeaderParam(HttpHeaders.USER_AGENT) @Nullable final String userAgent, + @PathParam("subscriberId") String subscriberId) throws SubscriptionException { SubscriberCredentials subscriberCredentials = SubscriberCredentials.process(authenticatedAccount, subscriberId, clock); - subscriptionManager.updateSubscriber(subscriberCredentials); + + SubscriptionsUtil.recordDonationPermitPresent(donationPermitHeader.isPresent(), "putSubscriber", userAgent); + final boolean creationPermitted = donationPermitHeader.map( + permitHeader -> { + try { + return SubscriptionsUtil.verifyAndSpendDonationPermit(permitHeader.permit(), donationPermitsManager, clock); + } catch (VerificationFailedException e) { + return false; + } + }) + .orElse(true); + + subscriptionManager.updateSubscriber(subscriberCredentials, creationPermitted); return Response.ok().build(); } @@ -226,6 +253,11 @@ public class SubscriptionController { @RateLimitedByIp(RateLimiters.For.ADD_SUBSCRIPTION_PAYMENT_METHOD) public CreatePaymentMethodResponse createPaymentMethod( @Auth Optional authenticatedAccount, + + @Parameter(description="A base64-encoded donation permit retrieved from POST /v1/donation/permit") + @HeaderParam(HeaderUtils.DONATION_PERMIT) + final Optional donationPermitHeader, + @PathParam("subscriberId") String subscriberId, @QueryParam("type") @DefaultValue("CARD") PaymentMethod paymentMethodType, @HeaderParam(HttpHeaders.USER_AGENT) @Nullable final String userAgentString) throws SubscriptionException { @@ -243,6 +275,21 @@ public class SubscriptionController { case UNKNOWN -> throw new BadRequestException("Invalid payment method"); }; + SubscriptionsUtil.recordDonationPermitPresent(donationPermitHeader.isPresent(), "createPaymentMethod", userAgentString); + final boolean spendSuccessful = donationPermitHeader.map( + permitHeader -> { + try { + return SubscriptionsUtil.verifyAndSpendDonationPermit(permitHeader.permit(), donationPermitsManager, clock); + } catch (VerificationFailedException e) { + return false; + } + }) + .orElse(true); + + if (!spendSuccessful) { + throw new WebApplicationException(Response.Status.UNAUTHORIZED); + } + final String token = subscriptionManager.addPaymentMethodToCustomer( subscriberCredentials, customerAwareSubscriptionPaymentProcessor, diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/DonationsGrpcService.java b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/DonationsGrpcService.java index 126867994..79088fca8 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/DonationsGrpcService.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/DonationsGrpcService.java @@ -1,8 +1,11 @@ package org.whispersystems.textsecuregcm.grpc; +import com.google.protobuf.ByteString; import com.google.protobuf.Empty; import java.time.Clock; import java.time.Instant; +import org.signal.chat.donations.CreateDonationPermitRequest; +import org.signal.chat.donations.CreateDonationPermitResponse; import org.signal.chat.donations.RedeemReceiptRequest; import org.signal.chat.donations.RedeemReceiptResponse; import org.signal.chat.donations.SimpleDonationsGrpc; @@ -10,6 +13,8 @@ import org.signal.chat.errors.FailedPrecondition; import org.signal.chat.errors.FailedZkAuthentication; import org.signal.libsignal.zkgroup.InvalidInputException; import org.signal.libsignal.zkgroup.VerificationFailedException; +import org.signal.libsignal.zkgroup.donation.DonationPermitRequest; +import org.signal.libsignal.zkgroup.donation.DonationPermitResponse; import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialPresentation; import org.signal.libsignal.zkgroup.receipts.ReceiptSerial; import org.signal.libsignal.zkgroup.receipts.ServerZkReceiptOperations; @@ -18,8 +23,10 @@ import org.slf4j.LoggerFactory; import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice; import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil; import org.whispersystems.textsecuregcm.configuration.BadgesConfiguration; +import org.whispersystems.textsecuregcm.limits.RateLimiters; import org.whispersystems.textsecuregcm.storage.AccountBadge; import org.whispersystems.textsecuregcm.storage.AccountsManager; +import org.whispersystems.textsecuregcm.storage.DonationPermitsManager; import org.whispersystems.textsecuregcm.storage.RedeemedReceiptsManager; import org.whispersystems.textsecuregcm.subscriptions.ReceiptCredentialPresentationFactory; @@ -31,6 +38,8 @@ public class DonationsGrpcService extends SimpleDonationsGrpc.DonationsImplBase private final AccountsManager accountsManager; private final BadgesConfiguration badgesConfiguration; private final ReceiptCredentialPresentationFactory receiptCredentialPresentationFactory; + private final DonationPermitsManager donationPermitsManager; + private final RateLimiters rateLimiters; private static final Logger LOGGER = LoggerFactory.getLogger(DonationsGrpcService.class); @@ -40,7 +49,9 @@ public class DonationsGrpcService extends SimpleDonationsGrpc.DonationsImplBase final RedeemedReceiptsManager redeemedReceiptsManager, final AccountsManager accountsManager, final BadgesConfiguration badgesConfiguration, - final ReceiptCredentialPresentationFactory receiptCredentialPresentationFactory) { + final ReceiptCredentialPresentationFactory receiptCredentialPresentationFactory, + final DonationPermitsManager donationPermitsManager, + final RateLimiters rateLimiters) { this.clock = clock; this.serverZkReceiptOperations = serverZkReceiptOperations; @@ -48,6 +59,8 @@ public class DonationsGrpcService extends SimpleDonationsGrpc.DonationsImplBase this.accountsManager = accountsManager; this.badgesConfiguration = badgesConfiguration; this.receiptCredentialPresentationFactory = receiptCredentialPresentationFactory; + this.donationPermitsManager = donationPermitsManager; + this.rateLimiters = rateLimiters; } @Override @@ -101,4 +114,23 @@ public class DonationsGrpcService extends SimpleDonationsGrpc.DonationsImplBase .build(); } } + + @Override + public CreateDonationPermitResponse createDonationPermit(final CreateDonationPermitRequest request) throws Exception { + final DonationPermitRequest permitRequest; + try { + permitRequest = new DonationPermitRequest(request.getDonationPermitRequest().toByteArray()); + } catch (InvalidInputException e) { + throw GrpcExceptions.invalidArguments("invalid permit request"); + } + + final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice(); + rateLimiters.getCreateDonationPermitLimiter().validate(authenticatedDevice.accountIdentifier(), permitRequest.getPermitCount()); + + final DonationPermitResponse permitResponse = donationPermitsManager.issue(permitRequest); + + return CreateDonationPermitResponse.newBuilder() + .setDonationPermitResponse(ByteString.copyFrom(permitResponse.serialize())) + .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 43a2350a1..91569d829 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/SubscriptionsGrpcService.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/SubscriptionsGrpcService.java @@ -13,6 +13,7 @@ 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.FailedZkAuthentication; import org.signal.chat.errors.NotFound; import org.signal.chat.subscriptions.CreatePayPalPaymentMethodRequest; import org.signal.chat.subscriptions.CreatePayPalPaymentMethodResponse; @@ -38,6 +39,9 @@ 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.signal.libsignal.zkgroup.InvalidInputException; +import org.signal.libsignal.zkgroup.VerificationFailedException; +import org.signal.libsignal.zkgroup.donation.DonationPermit; import org.whispersystems.textsecuregcm.badges.BadgeTranslator; import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfiguration; import org.whispersystems.textsecuregcm.configuration.SubscriptionConfiguration; @@ -46,6 +50,7 @@ import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfigurati import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException; import org.whispersystems.textsecuregcm.entities.Badge; import org.whispersystems.textsecuregcm.entities.PurchasableBadge; +import org.whispersystems.textsecuregcm.storage.DonationPermitsManager; import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager; import org.whispersystems.textsecuregcm.storage.SubscriberCredentials; import org.whispersystems.textsecuregcm.storage.SubscriptionManager; @@ -61,6 +66,7 @@ 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.SubscriberIdCreationNotPermittedException; import org.whispersystems.textsecuregcm.subscriptions.SubscriptionChargeFailurePaymentRequiredException; import org.whispersystems.textsecuregcm.subscriptions.SubscriptionForbiddenException; import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInformation; @@ -82,6 +88,7 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti private final SubscriptionConfiguration subscriptionConfiguration; private final OneTimeDonationConfiguration oneTimeDonationConfiguration; private final SubscriptionManager subscriptionManager; + private final DonationPermitsManager donationPermitsManager; private final StripeManager stripeManager; private final BraintreeManager braintreeManager; private final GooglePlayBillingManager googlePlayBillingManager; @@ -92,14 +99,16 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti 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 DonationPermitsManager donationPermitsManager, 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.donationPermitsManager = donationPermitsManager; this.stripeManager = stripeManager; this.braintreeManager = braintreeManager; this.googlePlayBillingManager = googlePlayBillingManager; @@ -115,11 +124,41 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti try { final SubscriberCredentials subscriberCredentials = SubscriberCredentials.process( request.getSubscriberId().toByteArray(), clock); - subscriptionManager.updateSubscriber(subscriberCredentials); + + final boolean creationPermitted; + try { + if (request.getDonationPermit().isEmpty()) { + creationPermitted = false; + } else { + final DonationPermit permit = new DonationPermit(request.getDonationPermit().toByteArray()); + + creationPermitted = SubscriptionsUtil.verifyAndSpendDonationPermit(permit, donationPermitsManager, clock); + } + } catch (final InvalidInputException _) { + throw GrpcExceptions.invalidArguments("invalid donation permit"); + } catch (final VerificationFailedException _ ) { + return UpdateSubscriberResponse.newBuilder() + .setPermitRejected(FailedZkAuthentication.newBuilder() + .setDescription("donation permit failed verification") + .build()) + .build(); + } + + subscriptionManager.updateSubscriber(subscriberCredentials, creationPermitted); return UpdateSubscriberResponse.newBuilder().setSuccess(Empty.getDefaultInstance()).build(); } catch (final SubscriptionForbiddenException e) { return UpdateSubscriberResponse.newBuilder().setSubscriberIdMismatch( FailedUnidentifiedAuthorization.newBuilder().setDescription(e.errorDetail().orElse("")).build()).build(); + } catch (SubscriberIdCreationNotPermittedException _) { + if (request.getDonationPermit().isEmpty()) { + throw GrpcExceptions.invalidArguments("donation permit is required to create a subscriber ID"); + } + + return UpdateSubscriberResponse.newBuilder() + .setPermitRejected(FailedZkAuthentication.newBuilder() + .setDescription("donation permit was not valid") + .build()) + .build(); } } @@ -144,12 +183,27 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti 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 DonationPermit permit = new DonationPermit(request.getDonationPermit().toByteArray()); + + if (!SubscriptionsUtil.verifyAndSpendDonationPermit(permit, donationPermitsManager, clock)) { + return CreatePaymentMethodResponse.newBuilder() + .setPermitRejected(FailedZkAuthentication.getDefaultInstance()) + .build(); + } + } catch (final InvalidInputException _) { + throw GrpcExceptions.invalidArguments("invalid donation permit"); + } catch (final VerificationFailedException _ ) { + return CreatePaymentMethodResponse.newBuilder() + .setPermitRejected(FailedZkAuthentication.getDefaultInstance()) + .build(); + } + try { final String token = subscriptionManager.addPaymentMethodToCustomer(subscriberCredentials, customerAwareSubscriptionPaymentProcessor, @@ -178,7 +232,7 @@ public class SubscriptionsGrpcService extends SimpleSubscriptionsGrpc.Subscripti try { final BraintreeManager.PayPalBillingAgreementApprovalDetails details = subscriptionManager.addPaymentMethodToCustomer( subscriberCredentials, braintreeManager, getClientPlatform(RequestAttributesUtil.getUserAgent().orElse(null)), - (mgr, customerId) -> mgr.createPayPalBillingAgreement(request.getReturnUrl(), request.getCancelUrl(), + (mgr, _) -> mgr.createPayPalBillingAgreement(request.getReturnUrl(), request.getCancelUrl(), locale.toLanguageTag())).join(); return CreatePayPalPaymentMethodResponse.newBuilder().setResult( CreatePayPalPaymentMethodResponse.CreatePayPalPaymentMethodResult.newBuilder() diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/SubscriptionsUtil.java b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/SubscriptionsUtil.java index c5cdd9565..e13a01dc2 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/SubscriptionsUtil.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/SubscriptionsUtil.java @@ -1,9 +1,11 @@ package org.whispersystems.textsecuregcm.grpc; +import io.micrometer.core.instrument.Metrics; +import io.micrometer.core.instrument.Tags; import java.math.BigDecimal; +import java.time.Clock; import java.time.Instant; import java.util.Arrays; -import java.util.EnumSet; import java.util.HashMap; import java.util.List; import java.util.Locale; @@ -11,6 +13,8 @@ import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; import javax.annotation.Nullable; +import org.signal.libsignal.zkgroup.VerificationFailedException; +import org.signal.libsignal.zkgroup.donation.DonationPermit; import org.whispersystems.textsecuregcm.badges.BadgeTranslator; import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfiguration; import org.whispersystems.textsecuregcm.configuration.OneTimeDonationCurrencyConfiguration; @@ -18,6 +22,9 @@ 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.metrics.MetricsUtil; +import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil; +import org.whispersystems.textsecuregcm.storage.DonationPermitsManager; import org.whispersystems.textsecuregcm.subscriptions.CurrencyConfiguration; import org.whispersystems.textsecuregcm.subscriptions.CustomerAwareSubscriptionPaymentProcessor; import org.whispersystems.textsecuregcm.subscriptions.LevelConfiguration; @@ -27,6 +34,13 @@ import org.whispersystems.textsecuregcm.util.ua.UnrecognizedUserAgentException; import org.whispersystems.textsecuregcm.util.ua.UserAgentUtil; public class SubscriptionsUtil { + + private static final String DONATION_PERMIT_PRESENT_COUNTER_NAME = MetricsUtil.name(SubscriptionsUtil.class, + "donationPermitPresent"); + + private static final String DONATION_PERMIT_SPEND_COUNTER_NAME = MetricsUtil.name(SubscriptionsUtil.class, + "donationPermitSpend"); + @Nullable public static ClientPlatform getClientPlatform(@Nullable final String userAgentString) { try { @@ -124,4 +138,26 @@ public class SubscriptionsUtil { oneTimeDonationConfiguration.gift().expiration()))); return donationLevels; } + + /// Verifies the permit and spends it + /// + /// @return `true` if the spend was accepted, otherwise `false` + /// @throws VerificationFailedException if the permit is invalid + public static boolean verifyAndSpendDonationPermit(final DonationPermit permit, final DonationPermitsManager donationPermitsManager, final Clock clock) throws VerificationFailedException { + + final boolean spent = donationPermitsManager.spend(permit); + + Metrics.counter(DONATION_PERMIT_SPEND_COUNTER_NAME, "outcome", spent ? "success" : "failure").increment(); + + return spent; + } + + public static void recordDonationPermitPresent(final boolean present, final String context, final String userAgent) { + Metrics.counter(DONATION_PERMIT_PRESENT_COUNTER_NAME, + Tags.of("present", String.valueOf(present), + "context", context) + .and(UserAgentTagUtil.getPlatformTag(userAgent))) + .increment(); + } + } diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/storage/DonationPermits.java b/service/src/main/java/org/whispersystems/textsecuregcm/storage/DonationPermits.java new file mode 100644 index 000000000..6de2cb67e --- /dev/null +++ b/service/src/main/java/org/whispersystems/textsecuregcm/storage/DonationPermits.java @@ -0,0 +1,56 @@ +/* + * Copyright 2026 Signal Messenger, LLC + * SPDX-License-Identifier: AGPL-3.0-only + */ + +package org.whispersystems.textsecuregcm.storage; + +import static org.whispersystems.textsecuregcm.util.AttributeValues.b; +import static org.whispersystems.textsecuregcm.util.AttributeValues.n; + +import java.time.Duration; +import java.time.Instant; +import java.util.Map; +import software.amazon.awssdk.services.dynamodb.DynamoDbClient; +import software.amazon.awssdk.services.dynamodb.model.ConditionalCheckFailedException; +import software.amazon.awssdk.services.dynamodb.model.ReturnValue; +import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest; + +public class DonationPermits { + + public static final String KEY_SPEND_ID = "I"; // B (HashKey) + public static final String KEY_EXPIRATION = "E"; // N + + private final String table; + private final Duration expiration; + private final DynamoDbClient dynamoDbClient; + + public DonationPermits(String tableName, Duration expiration, + DynamoDbClient dynamoDbClient) { + this.table = tableName; + this.expiration = expiration; + this.dynamoDbClient = dynamoDbClient; + } + + public boolean spend(final byte[] spendId, final Instant now) { + final UpdateItemRequest updateItemRequest = UpdateItemRequest.builder() + .tableName(table) + .key(Map.of(KEY_SPEND_ID, b(spendId))) + .conditionExpression("attribute_not_exists(#id)") + .returnValues(ReturnValue.NONE) + .updateExpression("SET #exp = :exp") + .expressionAttributeNames(Map.of( + "#id", KEY_SPEND_ID, + "#exp", KEY_EXPIRATION)) + .expressionAttributeValues(Map.of( + ":exp", n(now.plus(expiration).getEpochSecond()))) + .build(); + try { + dynamoDbClient.updateItem(updateItemRequest); + + return true; + } catch (final ConditionalCheckFailedException _) { + return false; + } + } +} diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/storage/DonationPermitsManager.java b/service/src/main/java/org/whispersystems/textsecuregcm/storage/DonationPermitsManager.java new file mode 100644 index 000000000..662358019 --- /dev/null +++ b/service/src/main/java/org/whispersystems/textsecuregcm/storage/DonationPermitsManager.java @@ -0,0 +1,51 @@ +/* + * Copyright 2026 Signal Messenger, LLC + * SPDX-License-Identifier: AGPL-3.0-only + */ + +package org.whispersystems.textsecuregcm.storage; + +import java.time.Clock; +import org.signal.libsignal.zkgroup.ServerSecretParams; +import org.signal.libsignal.zkgroup.VerificationFailedException; +import org.signal.libsignal.zkgroup.donation.DonationPermit; +import org.signal.libsignal.zkgroup.donation.DonationPermitDerivedKeyPair; +import org.signal.libsignal.zkgroup.donation.DonationPermitRequest; +import org.signal.libsignal.zkgroup.donation.DonationPermitResponse; + +public class DonationPermitsManager { + + private final DonationPermits donationPermits; + private final ServerSecretParams serverSecretParams; + private final Clock clock; + + public DonationPermitsManager(final DonationPermits donationPermits, final ServerSecretParams serverSecretParams, + final Clock clock) { + this.donationPermits = donationPermits; + this.serverSecretParams = serverSecretParams; + this.clock = clock; + } + + /// Verifies and then spends the given {@link DonationPermit} + /// + /// @throws VerificationFailedException if the permit was not valid (expired or otherwise) + public boolean spend(final DonationPermit donationPermit) throws VerificationFailedException { + // Permits must be verified with the key pair that issued them, which can be re-derived from the embedded expiration + final DonationPermitDerivedKeyPair issuingKeyPair = DonationPermitDerivedKeyPair.forExpiration( + donationPermit.getExpiration(), serverSecretParams); + + donationPermit.verify(issuingKeyPair, clock.instant()); + + return donationPermits.spend(donationPermit.getSpendId(), clock.instant()); + } + + /// Issues {@link DonationPermitResponse} with an expiration derived from the current time + public DonationPermitResponse issue(final DonationPermitRequest permitRequest) { + final DonationPermitDerivedKeyPair currentDerivedKeyPair = DonationPermitDerivedKeyPair.forExpiration( + DonationPermitResponse.defaultExpiration(clock.instant()), + serverSecretParams); + + return permitRequest.issue(currentDerivedKeyPair); + } + +} 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 539193ead..41f6a0963 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/storage/SubscriptionManager.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/storage/SubscriptionManager.java @@ -12,7 +12,6 @@ import java.util.List; import java.util.Locale; import java.util.Objects; import java.util.Optional; -import java.util.concurrent.CompletionException; import java.util.function.BiFunction; import java.util.function.Function; import java.util.stream.Collectors; @@ -23,26 +22,25 @@ import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialRequest; import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialResponse; import org.signal.libsignal.zkgroup.receipts.ServerZkReceiptOperations; import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException; -import org.whispersystems.textsecuregcm.controllers.SubscriptionController; import org.whispersystems.textsecuregcm.subscriptions.AppleAppStoreManager; 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.SubscriptionInformation; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidIdempotencyKeyException; -import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPaymentProcessor; +import org.whispersystems.textsecuregcm.subscriptions.SubscriberIdCreationNotPermittedException; 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.SubscriptionPaymentProcessor; 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.util.ExceptionUtils; import org.whispersystems.textsecuregcm.util.ua.ClientPlatform; /** @@ -105,16 +103,23 @@ public class SubscriptionManager { * already exists, its last access time will be updated. * * @param subscriberCredentials Subscriber credentials derived from the subscriberId + * @param createPermitted Whether creating a new subscriber is permitted if one does not exist * @throws SubscriptionForbiddenException if the subscriber credentials were incorrect + * @throws SubscriberIdCreationNotPermittedException if a new subscriber ID would be created, but the caller does not permit it */ - public void updateSubscriber(final SubscriberCredentials subscriberCredentials) - throws SubscriptionForbiddenException { + public void updateSubscriber(final SubscriberCredentials subscriberCredentials, final boolean createPermitted) + throws SubscriptionForbiddenException, SubscriberIdCreationNotPermittedException { final Subscriptions.GetResult getResult = subscriptions.get(subscriberCredentials.subscriberUser(), subscriberCredentials.hmac()); if (getResult == Subscriptions.GetResult.PASSWORD_MISMATCH) { throw new SubscriptionForbiddenException("subscriberId mismatch"); } else if (getResult == Subscriptions.GetResult.NOT_STORED) { + + if (!createPermitted) { + throw new SubscriberIdCreationNotPermittedException(); + } + // create a customer and write it to ddb final Subscriptions.Record updatedRecord = subscriptions.create(subscriberCredentials.subscriberUser(), subscriberCredentials.hmac(), diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/SubscriberIdCreationNotPermittedException.java b/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/SubscriberIdCreationNotPermittedException.java new file mode 100644 index 000000000..457ea5778 --- /dev/null +++ b/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/SubscriberIdCreationNotPermittedException.java @@ -0,0 +1,13 @@ +/* + * Copyright 2026 Signal Messenger, LLC + * SPDX-License-Identifier: AGPL-3.0-only + */ + +package org.whispersystems.textsecuregcm.subscriptions; + +public class SubscriberIdCreationNotPermittedException extends SubscriptionException { + + public SubscriberIdCreationNotPermittedException() { + super(null); + } +} diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/util/HeaderUtils.java b/service/src/main/java/org/whispersystems/textsecuregcm/util/HeaderUtils.java index 87f5bac1a..876b0496c 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/util/HeaderUtils.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/util/HeaderUtils.java @@ -38,6 +38,8 @@ public final class HeaderUtils { public static final String GROUP_SEND_TOKEN = "Group-Send-Token"; + public static final String DONATION_PERMIT = "Donation-Permit"; + private static final String INVALID_ACCEPT_LANGUAGE_COUNTER_NAME = MetricsUtil.name(HeaderUtils.class, "invalidAcceptLanguage"); diff --git a/service/src/main/proto/org/signal/chat/donations.proto b/service/src/main/proto/org/signal/chat/donations.proto index 9af7fd390..0ea30226c 100644 --- a/service/src/main/proto/org/signal/chat/donations.proto +++ b/service/src/main/proto/org/signal/chat/donations.proto @@ -21,6 +21,11 @@ service Donations { // responses will include the corresponding badge (if configured as visible) // until the expiration time on the receipt. rpc RedeemReceipt(RedeemReceiptRequest) returns (RedeemReceiptResponse) {} + + // Generate a set of anonymous, single-use, permits for use with /v1/subscription endpoints. + // + // If rate limited, reduce requested permit count and/or try again after the prescribed delay. + rpc CreateDonationPermit(CreateDonationPermitRequest) returns (CreateDonationPermitResponse) {} } message RedeemReceiptRequest { @@ -41,5 +46,14 @@ message RedeemReceiptResponse { // The receipt was already redeemed for a different account errors.FailedPrecondition already_redeemed = 3 [(tag.reason) = "already_redeemed"]; } +} +message CreateDonationPermitRequest { + // a serialized libsignal DonationPermitRequest + bytes donation_permit_request = 1 [(require.nonEmpty) = true]; +} + +message CreateDonationPermitResponse { + // a serialized libsignal DonationPermitResponse + bytes donation_permit_response = 1; } diff --git a/service/src/main/proto/org/signal/chat/subscriptions.proto b/service/src/main/proto/org/signal/chat/subscriptions.proto index 63c06ee36..4570dbc33 100644 --- a/service/src/main/proto/org/signal/chat/subscriptions.proto +++ b/service/src/main/proto/org/signal/chat/subscriptions.proto @@ -108,7 +108,10 @@ service Subscriptions { } message UpdateSubscriberRequest { - bytes subscriberId = 1 [(require.exactlySize) = 32]; + bytes subscriber_id = 1 [(require.exactlySize) = 32]; + // A libsignal DonationPermit from rpc Donations.CreateDonationPermit, + // required if the subscriber ID is new + bytes donation_permit = 2; } message UpdateSubscriberResponse { @@ -116,6 +119,8 @@ message UpdateSubscriberResponse { google.protobuf.Empty success = 1; // subscriberId authentication failure errors.FailedUnidentifiedAuthorization subscriber_id_mismatch = 2 [(tag.reason) = "subscriber_id_mismatch"]; + // The donation permit was expired or already spent + errors.FailedZkAuthentication permit_rejected = 3 [(tag.reason) = "permit_rejected"]; } } @@ -171,8 +176,10 @@ enum SubscriptionStatus { 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]; + bytes subscriber_id = 1 [(require.exactlySize) = 32]; + PaymentMethod payment_method = 2 [(require.specified) = true]; + // a libsignal DonationPermit from rpc Donations.CreateDonationPermit + bytes donation_permit = 3 [(require.nonEmpty) = true]; } message CreatePaymentMethodResponse { @@ -188,6 +195,8 @@ message CreatePaymentMethodResponse { 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"]; + // The donation permit was expired or already spent + errors.FailedZkAuthentication permit_rejected = 5 [(tag.reason) = "permit_rejected"]; } } 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 6642366e0..52a164d58 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/controllers/AbstractV1SubscriptionControllerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/controllers/AbstractV1SubscriptionControllerTest.java @@ -5,12 +5,26 @@ package org.whispersystems.textsecuregcm.controllers; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.time.Clock; +import java.time.Instant; +import java.util.Base64; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import org.signal.libsignal.zkgroup.ServerSecretParams; +import org.signal.libsignal.zkgroup.VerificationFailedException; +import org.signal.libsignal.zkgroup.donation.DonationPermit; +import org.signal.libsignal.zkgroup.donation.DonationPermitRequest; +import org.signal.libsignal.zkgroup.donation.DonationPermitRequestContext; +import org.signal.libsignal.zkgroup.donation.DonationPermitResponse; import org.signal.libsignal.zkgroup.receipts.ServerZkReceiptOperations; import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfiguration; +import org.whispersystems.textsecuregcm.storage.DonationPermits; +import org.whispersystems.textsecuregcm.storage.DonationPermitsManager; import org.whispersystems.textsecuregcm.storage.IssuedReceiptsManager; import org.whispersystems.textsecuregcm.subscriptions.BraintreeManager; import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider; @@ -31,5 +45,32 @@ class AbstractV1SubscriptionControllerTest { static final ServerZkReceiptOperations ZK_OPS = mock(ServerZkReceiptOperations.class); + private static final ServerSecretParams DONATION_PERMITS_SECRET_PARAMS = ServerSecretParams.generate(); + static final DonationPermits DONATION_PERMITS = mock(DonationPermits.class); + static final DonationPermitsManager DONATION_PERMITS_MANAGER = new DonationPermitsManager(DONATION_PERMITS, DONATION_PERMITS_SECRET_PARAMS, CLOCK); + + String getDonationPermitHeader() { + final DonationPermitRequestContext context = DonationPermitRequestContext.forCount(1); + final DonationPermitRequest permitRequest = context.request(); + + final DonationPermitResponse permitResponse = DONATION_PERMITS_MANAGER.issue(permitRequest); + + try { + final List donationPermits = context.receive(permitResponse, + DONATION_PERMITS_SECRET_PARAMS.getPublicParams(), CLOCK.instant()); + + return Base64.getEncoder().encodeToString(donationPermits.getFirst().serialize()); + } catch (final VerificationFailedException e) { + throw new RuntimeException(e); + } + } + + /// Sets up stubbing so that spendIds are spend-once + protected void setUpDonationPermitsSpendStubbing(final DonationPermits donationPermits) { + final Set spent = new HashSet<>(); + when(donationPermits.spend(any(byte[].class), any(Instant.class))) + .thenAnswer(answer -> spent.add(new String(answer.getArgument(0, byte[].class)))); + } + } diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/controllers/DonationControllerTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/controllers/DonationControllerTest.java index cf51ec20b..f20d21247 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/controllers/DonationControllerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/controllers/DonationControllerTest.java @@ -51,6 +51,8 @@ import org.whispersystems.textsecuregcm.limits.RateLimiters; import org.whispersystems.textsecuregcm.mappers.RateLimitExceededExceptionMapper; import org.whispersystems.textsecuregcm.storage.AccountBadge; import org.whispersystems.textsecuregcm.storage.AccountsManager; +import org.whispersystems.textsecuregcm.storage.DonationPermits; +import org.whispersystems.textsecuregcm.storage.DonationPermitsManager; import org.whispersystems.textsecuregcm.storage.RedeemedReceiptsManager; import org.whispersystems.textsecuregcm.subscriptions.ReceiptCredentialPresentationFactory; import org.whispersystems.textsecuregcm.tests.util.AccountsHelper; @@ -78,7 +80,9 @@ class DonationControllerTest { } private final TestClock clock = TestClock.pinned(Instant.ofEpochSecond(nowEpochSeconds)); - private final ServerSecretParams serverSecretParams = ServerSecretParams.generate(); + + final ServerSecretParams serverSecretParams = ServerSecretParams.generate(); + private final DonationPermitsManager donationPermitsManager = new DonationPermitsManager(mock(DonationPermits.class), serverSecretParams, clock); private RedeemedReceiptsManager redeemedReceiptsManager; private AccountsManager accountsManager; @@ -117,7 +121,7 @@ class DonationControllerTest { .addProvider(RateLimitExceededExceptionMapper.class) .setTestContainerFactory(new GrizzlyWebTestContainerFactory()) .addResource(new DonationController(clock, mock(ServerZkReceiptOperations.class), redeemedReceiptsManager, accountsManager, - getBadgesConfiguration(), receiptCredentialPresentationFactory, serverSecretParams, rateLimiters)) + getBadgesConfiguration(), receiptCredentialPresentationFactory, donationPermitsManager, rateLimiters)) .build(); resources.before(); } 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 3a3068b00..dbc2626e6 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/controllers/OneTimeDonationControllerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/controllers/OneTimeDonationControllerTest.java @@ -28,10 +28,6 @@ import java.util.Map; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.stream.Stream; -import org.signal.libsignal.zkgroup.ServerSecretParams; -import org.signal.libsignal.zkgroup.receipts.ClientZkReceiptOperations; -import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialRequest; -import org.signal.libsignal.zkgroup.receipts.ReceiptSerial; import org.assertj.core.api.InstanceOfAssertFactories; import org.glassfish.jersey.server.ServerProperties; import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory; @@ -41,10 +37,16 @@ import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.ValueSource; +import org.signal.libsignal.zkgroup.ServerSecretParams; +import org.signal.libsignal.zkgroup.receipts.ClientZkReceiptOperations; +import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialRequest; +import org.signal.libsignal.zkgroup.receipts.ReceiptSerial; import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice; import org.whispersystems.textsecuregcm.mappers.CompletionExceptionMapper; import org.whispersystems.textsecuregcm.mappers.SubscriptionExceptionMapper; import org.whispersystems.textsecuregcm.storage.OneTimeDonationsManager; +import org.whispersystems.textsecuregcm.storage.WriteConflictException; import org.whispersystems.textsecuregcm.subscriptions.BraintreeManager; import org.whispersystems.textsecuregcm.subscriptions.ChargeFailure; import org.whispersystems.textsecuregcm.subscriptions.PayPalDonationsTranslator; @@ -54,7 +56,7 @@ import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider; import org.whispersystems.textsecuregcm.subscriptions.PaymentStatus; import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorException; import org.whispersystems.textsecuregcm.tests.util.AuthHelper; -import org.whispersystems.textsecuregcm.storage.WriteConflictException; +import org.whispersystems.textsecuregcm.util.HeaderUtils; import org.whispersystems.textsecuregcm.util.SystemMapper; @ExtendWith(DropwizardExtensionsSupport.class) @@ -67,7 +69,7 @@ class OneTimeDonationControllerTest extends AbstractV1SubscriptionControllerTest private static final OneTimeDonationController ONE_TIME_CONTROLLER = new OneTimeDonationController(CLOCK, ONETIME_CONFIG, STRIPE_MANAGER, BRAINTREE_MANAGER, PAYPAL_ONE_TIME_DONATION_LINE_ITEM_TRANSLATOR, - ZK_OPS, ISSUED_RECEIPTS_MANAGER, ONE_TIME_DONATIONS_MANAGER); + ZK_OPS, ISSUED_RECEIPTS_MANAGER, ONE_TIME_DONATIONS_MANAGER, DONATION_PERMITS_MANAGER); private static final ResourceExtension RESOURCE_EXTENSION = ResourceExtension.builder() .addProperty(ServerProperties.UNWRAP_COMPLETION_STAGE_IN_WRITER_ENABLE, Boolean.TRUE) @@ -82,7 +84,11 @@ class OneTimeDonationControllerTest extends AbstractV1SubscriptionControllerTest @BeforeEach void setUp() { - reset(CLOCK, STRIPE_MANAGER, BRAINTREE_MANAGER, ZK_OPS, PAYPAL_ONE_TIME_DONATION_LINE_ITEM_TRANSLATOR); + reset(CLOCK, DONATION_PERMITS, STRIPE_MANAGER, BRAINTREE_MANAGER, ZK_OPS, PAYPAL_ONE_TIME_DONATION_LINE_ITEM_TRANSLATOR); + + setUpDonationPermitsSpendStubbing(DONATION_PERMITS); + + when(CLOCK.instant()).thenReturn(Instant.now()); when(STRIPE_MANAGER.getProvider()).thenReturn(PaymentProvider.STRIPE); when(BRAINTREE_MANAGER.getProvider()).thenReturn(PaymentProvider.BRAINTREE); @@ -101,69 +107,80 @@ class OneTimeDonationControllerTest extends AbstractV1SubscriptionControllerTest .thenReturn(Set.of("usd", "jpy")); } - @Test void testCreateBoostPaymentIntentAmountBelowCurrencyMinimum() { when(STRIPE_MANAGER.getSupportedCurrenciesForPaymentMethod(PaymentMethod.CARD)) .thenReturn(Set.of("usd", "jpy", "bif", "eur")); - final Response response = RESOURCE_EXTENSION.target("/v1/subscription/boost/create") + + try (Response response = RESOURCE_EXTENSION.target("/v1/subscription/boost/create") .request() + .header(HeaderUtils.DONATION_PERMIT, getDonationPermitHeader()) .post(Entity.json(""" { "currency": "USD", "amount": 249 } - """)); - assertThat(response.getStatus()).isEqualTo(400); - assertThat(response.hasEntity()).isTrue(); - final Map responseMap = response.readEntity(Map.class); - assertThat(responseMap.get("error")).isEqualTo("amount_below_currency_minimum"); - assertThat(responseMap.get("minimum")).isEqualTo("2.50"); + """))) { + assertThat(response.getStatus()).isEqualTo(400); + assertThat(response.hasEntity()).isTrue(); + final Map responseMap = response.readEntity(Map.class); + assertThat(responseMap.get("error")).isEqualTo("amount_below_currency_minimum"); + assertThat(responseMap.get("minimum")).isEqualTo("2.50"); + } } @Test void testCreateBoostPaymentIntentAmountAboveSepaLimit() { when(STRIPE_MANAGER.getSupportedCurrenciesForPaymentMethod(PaymentMethod.SEPA_DEBIT)) .thenReturn(Set.of("eur")); - final Response response = RESOURCE_EXTENSION.target("/v1/subscription/boost/create") + + try (Response response = RESOURCE_EXTENSION.target("/v1/subscription/boost/create") .request() + .header(HeaderUtils.DONATION_PERMIT, getDonationPermitHeader()) .post(Entity.json(""" { "currency": "EUR", "amount": 1000001, "paymentMethod": "SEPA_DEBIT" } - """)); - assertThat(response.getStatus()).isEqualTo(400); - assertThat(response.hasEntity()).isTrue(); + """))) { + assertThat(response.getStatus()).isEqualTo(400); + assertThat(response.hasEntity()).isTrue(); - final Map responseMap = response.readEntity(Map.class); - assertThat(responseMap.get("error")).isEqualTo("amount_above_sepa_limit"); - assertThat(responseMap.get("maximum")).isEqualTo("10000"); + final Map responseMap = response.readEntity(Map.class); + assertThat(responseMap.get("error")).isEqualTo("amount_above_sepa_limit"); + assertThat(responseMap.get("maximum")).isEqualTo("10000"); + } } @Test void testCreateBoostPaymentIntentUnsupportedCurrency() { when(STRIPE_MANAGER.getSupportedCurrenciesForPaymentMethod(PaymentMethod.SEPA_DEBIT)) .thenReturn(Set.of("eur")); - final Response response = RESOURCE_EXTENSION.target("/v1/subscription/boost/create") + + try (Response response = RESOURCE_EXTENSION.target("/v1/subscription/boost/create") .request() + .header(HeaderUtils.DONATION_PERMIT, getDonationPermitHeader()) .post(Entity.json(""" { "currency": "USD", "amount": 3000, "paymentMethod": "SEPA_DEBIT" } - """)); - assertThat(response.getStatus()).isEqualTo(400); - assertThat(response.hasEntity()).isTrue(); + """))) { + assertThat(response.getStatus()).isEqualTo(400); + assertThat(response.hasEntity()).isTrue(); - final Map responseMap = response.readEntity(Map.class); - assertThat(responseMap.get("error")).isEqualTo("unsupported_currency"); + final Map responseMap = response.readEntity(Map.class); + assertThat(responseMap.get("error")).isEqualTo("unsupported_currency"); + } } - @Test - void testCreateBoostPaymentIntent() { + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void testCreateBoostPaymentIntent(final boolean donationPermitSpendOk) { + when(DONATION_PERMITS.spend(any(byte[].class), any(Instant.class))).thenReturn(donationPermitSpendOk); + when(STRIPE_MANAGER.getSupportedCurrenciesForPaymentMethod(PaymentMethod.CARD)) .thenReturn(Set.of("usd", "jpy", "bif", "eur")); when(STRIPE_MANAGER.createPaymentIntent(anyString(), anyLong(), anyLong(), any())) @@ -172,13 +189,15 @@ class OneTimeDonationControllerTest extends AbstractV1SubscriptionControllerTest String clientSecret = "some_client_secret"; when(PAYMENT_INTENT.getClientSecret()).thenReturn(clientSecret); - final Response response = RESOURCE_EXTENSION.target("/v1/subscription/boost/create") + try (Response response = RESOURCE_EXTENSION.target("/v1/subscription/boost/create") .request() + .header(HeaderUtils.DONATION_PERMIT, getDonationPermitHeader()) .post(Entity.json(""" {"currency": "USD", "amount": 300} """ - )); - assertThat(response.getStatus()).isEqualTo(200); + ))) { + assertThat(response.getStatus()).isEqualTo(donationPermitSpendOk ? 200 : 401); + } } @Test @@ -192,7 +211,7 @@ class OneTimeDonationControllerTest extends AbstractV1SubscriptionControllerTest when(payPalOneTimePaymentApprovalDetails.approvalUrl()).thenReturn("approvalUrl"); when(payPalOneTimePaymentApprovalDetails.paymentId()).thenReturn("someId"); - final Response response = RESOURCE_EXTENSION.target("/v1/subscription/boost/paypal/create") + try (Response response = RESOURCE_EXTENSION.target("/v1/subscription/boost/paypal/create") .request() .post(Entity.json(""" { @@ -202,17 +221,19 @@ class OneTimeDonationControllerTest extends AbstractV1SubscriptionControllerTest "returnUrl": "returnUrl" } """ - )); - assertThat(response.getStatus()).isEqualTo(200); + ))) { + assertThat(response.getStatus()).isEqualTo(200); + } } @Test void createBoostReceiptInvalid() { - final Response response = RESOURCE_EXTENSION.target("/v1/subscription/boost/receipt_credentials") + try (Response response = RESOURCE_EXTENSION.target("/v1/subscription/boost/receipt_credentials") .request() // invalid, request body should have receiptCredentialRequest - .post(Entity.json("{\"paymentIntentId\": \"foo\"}")); - assertThat(response.getStatus()).isEqualTo(422); + .post(Entity.json("{\"paymentIntentId\": \"foo\"}"))) { + assertThat(response.getStatus()).isEqualTo(422); + } } @ParameterizedTest @@ -225,21 +246,23 @@ class OneTimeDonationControllerTest extends AbstractV1SubscriptionControllerTest Instant.now(), chargeFailure) )); - Response response = RESOURCE_EXTENSION.target("/v1/subscription/boost/receipt_credentials") + try (Response response = RESOURCE_EXTENSION.target("/v1/subscription/boost/receipt_credentials") .request() .post(Entity.json(""" - { - "paymentIntentId": "foo", - "receiptCredentialRequest": "abcd", - "processor": "STRIPE" - } - """)); - assertThat(response.getStatus()).isEqualTo(402); + { + "paymentIntentId": "foo", + "receiptCredentialRequest": "abcd", + "processor": "STRIPE" + } + """))) { + assertThat(response.getStatus()).isEqualTo(402); - if (expectChargeFailure) { - assertThat(response.readEntity(OneTimeDonationController.CreateBoostReceiptCredentialsErrorResponse.class).chargeFailure()).isEqualTo(chargeFailure); - } else { - assertThat(response.readEntity(String.class)).isEqualTo("{}"); + if (expectChargeFailure) { + assertThat(response.readEntity(OneTimeDonationController.CreateBoostReceiptCredentialsErrorResponse.class) + .chargeFailure()).isEqualTo(chargeFailure); + } else { + assertThat(response.readEntity(String.class)).isEqualTo("{}"); + } } } @@ -265,30 +288,32 @@ class OneTimeDonationControllerTest extends AbstractV1SubscriptionControllerTest .thenReturn(CompletableFuture.failedFuture(new SubscriptionProcessorException(PaymentProvider.BRAINTREE, new ChargeFailure("2046", "Declined", null, null, null)))); - final Response response = RESOURCE_EXTENSION.target("/v1/subscription/boost/paypal/confirm") + try (Response response = RESOURCE_EXTENSION.target("/v1/subscription/boost/paypal/confirm") .request() .post(Entity.json(Map.of("payerId", "payer123", "paymentId", "PAYID-456", "paymentToken", "EC-789", "currency", "usd", - "amount", 300))); + "amount", 300)))) { - assertThat(response.getStatus()).isEqualTo(SubscriptionExceptionMapper.PROCESSOR_ERROR_STATUS_CODE); + assertThat(response.getStatus()).isEqualTo(SubscriptionExceptionMapper.PROCESSOR_ERROR_STATUS_CODE); - final Map responseMap = response.readEntity(Map.class); - assertThat(responseMap.get("processor")).isEqualTo("BRAINTREE"); - assertThat(responseMap.get("chargeFailure")).asInstanceOf( - InstanceOfAssertFactories.map(String.class, Object.class)) - .extracting("code") - .isEqualTo("2046"); + final Map responseMap = response.readEntity(Map.class); + assertThat(responseMap.get("processor")).isEqualTo("BRAINTREE"); + assertThat(responseMap.get("chargeFailure")).asInstanceOf( + InstanceOfAssertFactories.map(String.class, Object.class)) + .extracting("code") + .isEqualTo("2046"); + } } @Test void createBoostReceiptNoRequest() { - final Response response = RESOURCE_EXTENSION.target("/v1/subscription/boost/receipt_credentials") + try (Response response = RESOURCE_EXTENSION.target("/v1/subscription/boost/receipt_credentials") .request() - .post(Entity.json("")); - assertThat(response.getStatus()).isEqualTo(422); + .post(Entity.json(""))) { + assertThat(response.getStatus()).isEqualTo(422); + } } @Test @@ -305,14 +330,15 @@ class OneTimeDonationControllerTest extends AbstractV1SubscriptionControllerTest null))); doThrow(WriteConflictException.class).when(ISSUED_RECEIPTS_MANAGER).recordIssuance(any(), any(), any(), any()); - final Response response = RESOURCE_EXTENSION.target("/v1/subscription/boost/receipt_credentials") + try (Response response = RESOURCE_EXTENSION.target("/v1/subscription/boost/receipt_credentials") .request() .post(Entity.json(Map.of( "paymentIntentId", "foo", "receiptCredentialRequest", Base64.getEncoder().encodeToString(receiptCredentialRequest.serialize()), "processor", "STRIPE" - ))); - assertThat(response.getStatus()).isEqualTo(409); + )))) { + assertThat(response.getStatus()).isEqualTo(409); + } } } diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/controllers/SubscriptionControllerTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/controllers/SubscriptionControllerTest.java index e1123e5ca..0f05e8ad8 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/controllers/SubscriptionControllerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/controllers/SubscriptionControllerTest.java @@ -92,9 +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.HeaderUtils; import org.whispersystems.textsecuregcm.util.MockUtils; import org.whispersystems.textsecuregcm.util.SystemMapper; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; @@ -117,7 +117,7 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest { SUBSCRIPTION_CONFIG, ONETIME_CONFIG, new SubscriptionManager(SUBSCRIPTIONS, List.of(STRIPE_MANAGER, BRAINTREE_MANAGER, PLAY_MANAGER, APPSTORE_MANAGER), ZK_OPS, ISSUED_RECEIPTS_MANAGER), STRIPE_MANAGER, BRAINTREE_MANAGER, PLAY_MANAGER, APPSTORE_MANAGER, - BADGE_TRANSLATOR, BANK_MANDATE_TRANSLATOR, DYNAMIC_CONFIGURATION_MANAGER); + BADGE_TRANSLATOR, BANK_MANDATE_TRANSLATOR, DONATION_PERMITS_MANAGER, DYNAMIC_CONFIGURATION_MANAGER); private static final ResourceExtension RESOURCE_EXTENSION = ResourceExtension.builder() .addProperty(ServerProperties.UNWRAP_COMPLETION_STAGE_IN_WRITER_ENABLE, Boolean.TRUE) .addProvider(AuthHelper.getAuthFilter()) @@ -131,7 +131,11 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest { @BeforeEach void setUp() { - reset(CLOCK, SUBSCRIPTIONS, STRIPE_MANAGER, BRAINTREE_MANAGER, ZK_OPS, ISSUED_RECEIPTS_MANAGER, BADGE_TRANSLATOR); + reset(CLOCK, DONATION_PERMITS, SUBSCRIPTIONS, STRIPE_MANAGER, BRAINTREE_MANAGER, ZK_OPS, ISSUED_RECEIPTS_MANAGER, BADGE_TRANSLATOR); + + setUpDonationPermitsSpendStubbing(DONATION_PERMITS); + + when(CLOCK.instant()).thenReturn(Instant.now()); when(STRIPE_MANAGER.getProvider()).thenReturn(PaymentProvider.STRIPE); when(BRAINTREE_MANAGER.getProvider()).thenReturn(PaymentProvider.BRAINTREE); @@ -163,8 +167,6 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest { @BeforeEach void setUp() { - when(CLOCK.instant()).thenReturn(Instant.now()); - final byte[] subscriberUserAndKey = new byte[32]; Arrays.fill(subscriberUserAndKey, (byte) 1); subscriberId = Base64.getEncoder().encodeToString(subscriberUserAndKey); @@ -189,12 +191,13 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest { final String level = String.valueOf(levelId); final String idempotencyKey = UUID.randomUUID().toString(); - final Response response = RESOURCE_EXTENSION.target( + try (Response response = RESOURCE_EXTENSION.target( String.format("/v1/subscription/%s/level/%s/%s/%s", subscriberId, level, currency, idempotencyKey)) .request() - .put(Entity.json("")); + .put(Entity.json(""))) { - assertThat(response.getStatus()).isEqualTo(200); + assertThat(response.getStatus()).isEqualTo(200); + } } @Test @@ -205,14 +208,16 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest { final String level = String.valueOf(levelId); final String idempotencyKey = UUID.randomUUID().toString(); - final Response response = RESOURCE_EXTENSION.target( + final Map responseMap; + try (Response response = RESOURCE_EXTENSION.target( String.format("/v1/subscription/%s/level/%s/%s/%s", subscriberId, level, currency, idempotencyKey)) .request() - .put(Entity.json("")); + .put(Entity.json(""))) { - assertThat(response.getStatus()).isEqualTo(SubscriptionExceptionMapper.PROCESSOR_ERROR_STATUS_CODE); + assertThat(response.getStatus()).isEqualTo(SubscriptionExceptionMapper.PROCESSOR_ERROR_STATUS_CODE); - final Map responseMap = response.readEntity(Map.class); + responseMap = response.readEntity(Map.class); + } assertThat(responseMap.get("processor")).isEqualTo("STRIPE"); assertThat(responseMap.get("chargeFailure")).asInstanceOf( InstanceOfAssertFactories.map(String.class, Object.class)) @@ -238,12 +243,13 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest { final String level = String.valueOf(levelId); final String idempotencyKey = UUID.randomUUID().toString(); - final Response response = RESOURCE_EXTENSION.target( + try (Response response = RESOURCE_EXTENSION.target( String.format("/v1/subscription/%s/level/%s/%s/%s", subscriberId, level, currency, idempotencyKey)) .request() - .put(Entity.json("")); - assertThat(response.getStatus()).isEqualTo(409); - assertThat(response.readEntity(Map.class)).containsOnlyKeys("code", "message"); + .put(Entity.json(""))) { + assertThat(response.getStatus()).isEqualTo(409); + assertThat(response.readEntity(Map.class)).containsOnlyKeys("code", "message"); + } } @Test @@ -263,13 +269,15 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest { when(SUBSCRIPTIONS.get(eq(Arrays.copyOfRange(subscriberUserAndKey, 0, 16)), any())) .thenReturn(Subscriptions.GetResult.found(record)); - final Response response = RESOURCE_EXTENSION + try (Response response = RESOURCE_EXTENSION .target(String.format("/v1/subscription/%s/create_payment_method", subscriberId)) .request() - .post(Entity.json("")); + .header(HeaderUtils.DONATION_PERMIT, getDonationPermitHeader()) + .post(Entity.json(""))) { - assertThat(response.getStatus()).isEqualTo(409); - assertThat(response.readEntity(Map.class)).containsOnlyKeys("code", "message"); + assertThat(response.getStatus()).isEqualTo(409); + assertThat(response.readEntity(Map.class)).containsOnlyKeys("code", "message"); + } } @Test @@ -280,27 +288,26 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest { final String level = String.valueOf(levelId); final String idempotencyKey = UUID.randomUUID().toString(); - final Response response = RESOURCE_EXTENSION.target( + try (Response response = RESOURCE_EXTENSION.target( String.format("/v1/subscription/%s/level/%s/%s/%s", subscriberId, level, currency, idempotencyKey)) .request() - .put(Entity.json("")); + .put(Entity.json(""))) { - assertThat(response.getStatus()).isEqualTo(400); + assertThat(response.getStatus()).isEqualTo(400); - assertThat(response.readEntity(SubscriptionController.SetSubscriptionLevelErrorResponse.class)) - .satisfies(errorResponse -> - assertThat(errorResponse.errors()) - .anySatisfy(error -> - assertThat(error.type()) - .isEqualTo( - SubscriptionController.SetSubscriptionLevelErrorResponse.Error.Type.PAYMENT_REQUIRES_ACTION))); + assertThat(response.readEntity(SubscriptionController.SetSubscriptionLevelErrorResponse.class)) + .satisfies(errorResponse -> + assertThat(errorResponse.errors()) + .anySatisfy(error -> + assertThat(error.type()) + .isEqualTo( + SubscriptionController.SetSubscriptionLevelErrorResponse.Error.Type.PAYMENT_REQUIRES_ACTION))); + } } } @Test void createSubscriber() { - when(CLOCK.instant()).thenReturn(Instant.now()); - // basic create final byte[] subscriberUserAndKey = new byte[32]; Arrays.fill(subscriberUserAndKey, (byte) 1); @@ -316,30 +323,34 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest { Arrays.copyOfRange(subscriberUserAndKey, 0, 16), dynamoItem); when(SUBSCRIPTIONS.create(any(), any(), any())).thenReturn(record); - final Response createResponse = RESOURCE_EXTENSION.target(String.format("/v1/subscription/%s", subscriberId)) + try (Response createResponse = RESOURCE_EXTENSION.target(String.format("/v1/subscription/%s", subscriberId)) .request() - .put(Entity.json("")); - assertThat(createResponse.getStatus()).isEqualTo(200); + .header(HeaderUtils.DONATION_PERMIT, getDonationPermitHeader()) + .put(Entity.json(""))) { + assertThat(createResponse.getStatus()).isEqualTo(200); + } // creating should be idempotent when(SUBSCRIPTIONS.get(any(), any())).thenReturn(Subscriptions.GetResult.found(record)); - final Response idempotentCreateResponse = RESOURCE_EXTENSION.target( + try (Response idempotentCreateResponse = RESOURCE_EXTENSION.target( String.format("/v1/subscription/%s", subscriberId)) .request() - .put(Entity.json("")); - assertThat(idempotentCreateResponse.getStatus()).isEqualTo(200); + .put(Entity.json(""))) { + assertThat(idempotentCreateResponse.getStatus()).isEqualTo(200); + } // when the manager returns `null`, it means there was a password mismatch from the storage layer `create`. // this could happen if there is a race between two concurrent `create` requests for the same user ID when(SUBSCRIPTIONS.get(any(), any())).thenReturn(Subscriptions.GetResult.NOT_STORED); when(SUBSCRIPTIONS.create(any(), any(), any())).thenReturn(null); - final Response managerCreateNullResponse = RESOURCE_EXTENSION.target( + try (Response managerCreateNullResponse = RESOURCE_EXTENSION.target( String.format("/v1/subscription/%s", subscriberId)) .request() - .put(Entity.json("")); - assertThat(managerCreateNullResponse.getStatus()).isEqualTo(403); + .put(Entity.json(""))) { + assertThat(managerCreateNullResponse.getStatus()).isEqualTo(403); + } final byte[] subscriberUserAndMismatchedKey = new byte[32]; Arrays.fill(subscriberUserAndMismatchedKey, 0, 16, (byte) 1); @@ -349,24 +360,26 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest { // a password mismatch for an existing record when(SUBSCRIPTIONS.get(any(), any())).thenReturn(Subscriptions.GetResult.PASSWORD_MISMATCH); - final Response passwordMismatchResponse = RESOURCE_EXTENSION.target( + try (Response passwordMismatchResponse = RESOURCE_EXTENSION.target( String.format("/v1/subscription/%s", mismatchedSubscriberId)) .request() - .put(Entity.json("")); + .put(Entity.json(""))) { - assertThat(passwordMismatchResponse.getStatus()).isEqualTo(403); + assertThat(passwordMismatchResponse.getStatus()).isEqualTo(403); + } // invalid request data is a 404 final byte[] malformedUserAndKey = new byte[16]; Arrays.fill(malformedUserAndKey, (byte) 1); final String malformedUserId = Base64.getEncoder().encodeToString(malformedUserAndKey); - final Response malformedUserAndKeyResponse = RESOURCE_EXTENSION.target( + try (Response malformedUserAndKeyResponse = RESOURCE_EXTENSION.target( String.format("/v1/subscription/%s", malformedUserId)) .request() - .put(Entity.json("")); + .put(Entity.json(""))) { - assertThat(malformedUserAndKeyResponse.getStatus()).isEqualTo(404); + assertThat(malformedUserAndKeyResponse.getStatus()).isEqualTo(404); + } } @Test @@ -375,7 +388,6 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest { Arrays.fill(subscriberUserAndKey, (byte) 1); final String subscriberId = Base64.getEncoder().encodeToString(subscriberUserAndKey); - when(CLOCK.instant()).thenReturn(Instant.now()); when(SUBSCRIPTIONS.get(any(), any())).thenReturn(Subscriptions.GetResult.NOT_STORED); final Map dynamoItem = Map.of(Subscriptions.KEY_PASSWORD, b(new byte[16]), @@ -386,12 +398,14 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest { Arrays.copyOfRange(subscriberUserAndKey, 0, 16), dynamoItem); when(SUBSCRIPTIONS.create(any(), any(), any(Instant.class))).thenReturn(record); - final Response createSubscriberResponse = RESOURCE_EXTENSION + try (Response createSubscriberResponse = RESOURCE_EXTENSION .target(String.format("/v1/subscription/%s", subscriberId)) .request() - .put(Entity.json("")); + .header(HeaderUtils.DONATION_PERMIT, getDonationPermitHeader()) + .put(Entity.json(""))) { - assertThat(createSubscriberResponse.getStatus()).isEqualTo(200); + assertThat(createSubscriberResponse.getStatus()).isEqualTo(200); + } when(SUBSCRIPTIONS.get(any(), any())) .thenReturn(Subscriptions.GetResult.found(record)); @@ -415,15 +429,17 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest { when(STRIPE_MANAGER.createPaymentMethodSetupToken(customerId)) .thenReturn(clientSecret); - final SubscriptionController.CreatePaymentMethodResponse createPaymentMethodResponse = RESOURCE_EXTENSION + try (Response response = RESOURCE_EXTENSION .target(String.format("/v1/subscription/%s/create_payment_method", subscriberId)) .request() - .post(Entity.json("")) - .readEntity(SubscriptionController.CreatePaymentMethodResponse.class); - - assertThat(createPaymentMethodResponse.processor()).isEqualTo(PaymentProvider.STRIPE); - assertThat(createPaymentMethodResponse.clientSecret()).isEqualTo(clientSecret); + .header(HeaderUtils.DONATION_PERMIT, getDonationPermitHeader()) + .post(Entity.json(""))) { + final SubscriptionController.CreatePaymentMethodResponse createPaymentMethodResponse = + response.readEntity(SubscriptionController.CreatePaymentMethodResponse.class); + assertThat(createPaymentMethodResponse.processor()).isEqualTo(PaymentProvider.STRIPE); + assertThat(createPaymentMethodResponse.clientSecret()).isEqualTo(clientSecret); + } } @Test @@ -443,16 +459,16 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest { .thenReturn(record); // set up mocks - when(CLOCK.instant()).thenReturn(Instant.now()); when(SUBSCRIPTIONS.get(any(), any())) .thenReturn(Subscriptions.GetResult.found(record)); - final Response response = RESOURCE_EXTENSION + try (Response response = RESOURCE_EXTENSION .target(String.format("/v1/subscription/%s/level/%d/%s/%s", subscriberId, 5, "usd", "abcd")) .request() - .put(Entity.json("")); + .put(Entity.json(""))) { - assertThat(response.getStatus()).isEqualTo(409); + assertThat(response.getStatus()).isEqualTo(409); + } } @ParameterizedTest @@ -482,26 +498,26 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest { .thenReturn(record); // set up mocks - when(CLOCK.instant()).thenReturn(Instant.now()); when(SUBSCRIPTIONS.get(any(), any())) .thenReturn(Subscriptions.GetResult.found(record)); when(BRAINTREE_MANAGER.createSubscription(any(), any(), anyLong(), anyLong())) .thenReturn(new CustomerAwareSubscriptionPaymentProcessor.SubscriptionId("subscription")); - final Response response = RESOURCE_EXTENSION + try (Response response = RESOURCE_EXTENSION .target(String.format("/v1/subscription/%s/level/%d/%s/%s", subscriberId, levelId, "usd", "abcd")) .request() - .put(Entity.json("")); + .put(Entity.json(""))) { - verify(BRAINTREE_MANAGER).createSubscription(eq(customerId), eq(expectedProcessorId), eq(levelId), eq(0L)); - verifyNoMoreInteractions(BRAINTREE_MANAGER); + verify(BRAINTREE_MANAGER).createSubscription(eq(customerId), eq(expectedProcessorId), eq(levelId), eq(0L)); + verifyNoMoreInteractions(BRAINTREE_MANAGER); - assertThat(response.getStatus()).isEqualTo(200); + assertThat(response.getStatus()).isEqualTo(200); - assertThat(response.readEntity(SubscriptionController.SetSubscriptionLevelSuccessResponse.class)) - .extracting(SubscriptionController.SetSubscriptionLevelSuccessResponse::level) - .isEqualTo(levelId); + assertThat(response.readEntity(SubscriptionController.SetSubscriptionLevelSuccessResponse.class)) + .extracting(SubscriptionController.SetSubscriptionLevelSuccessResponse::level) + .isEqualTo(levelId); + } } @ParameterizedTest @@ -530,7 +546,6 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest { .thenReturn(record); // set up mocks - when(CLOCK.instant()).thenReturn(Instant.now()); when(SUBSCRIPTIONS.get(any(), any())) .thenReturn(Subscriptions.GetResult.found(record)); @@ -546,27 +561,28 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest { } final String idempotencyKey = "abcd"; - final Response response = RESOURCE_EXTENSION + try (Response response = RESOURCE_EXTENSION .target(String.format("/v1/subscription/%s/level/%d/%s/%s", subscriberId, requestLevel, requestCurrency, idempotencyKey)) .request() - .put(Entity.json("")); + .put(Entity.json(""))) { - verify(BRAINTREE_MANAGER).getSubscription(any()); - verify(BRAINTREE_MANAGER).getLevelAndCurrencyForSubscription(any()); + verify(BRAINTREE_MANAGER).getSubscription(any()); + verify(BRAINTREE_MANAGER).getLevelAndCurrencyForSubscription(any()); - if (expectUpdate) { - verify(BRAINTREE_MANAGER).updateSubscription(any(), any(), eq(requestLevel), eq(idempotencyKey)); - verify(SUBSCRIPTIONS).subscriptionLevelChanged(any(), any(), eq(requestLevel), eq(updatedSubscriptionId)); + if (expectUpdate) { + verify(BRAINTREE_MANAGER).updateSubscription(any(), any(), eq(requestLevel), eq(idempotencyKey)); + verify(SUBSCRIPTIONS).subscriptionLevelChanged(any(), any(), eq(requestLevel), eq(updatedSubscriptionId)); + } + + verifyNoMoreInteractions(BRAINTREE_MANAGER); + + assertThat(response.getStatus()).isEqualTo(200); + + assertThat(response.readEntity(SubscriptionController.SetSubscriptionLevelSuccessResponse.class)) + .extracting(SubscriptionController.SetSubscriptionLevelSuccessResponse::level) + .isEqualTo(requestLevel); } - - verifyNoMoreInteractions(BRAINTREE_MANAGER); - - assertThat(response.getStatus()).isEqualTo(200); - - assertThat(response.readEntity(SubscriptionController.SetSubscriptionLevelSuccessResponse.class)) - .extracting(SubscriptionController.SetSubscriptionLevelSuccessResponse::level) - .isEqualTo(requestLevel); } static Stream setSubscriptionLevelExistingSubscription() { @@ -600,7 +616,6 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest { when(SUBSCRIPTIONS.create(any(), any(), any(Instant.class))) .thenReturn(record); - when(CLOCK.instant()).thenReturn(Instant.now()); when(SUBSCRIPTIONS.get(any(), any())) .thenReturn(Subscriptions.GetResult.found(record)); @@ -610,17 +625,19 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest { .thenReturn(new CustomerAwareSubscriptionPaymentProcessor.LevelAndCurrency(201, "usd")); // Try to change from a backup subscription (201) to a donation subscription (5) - final Response response = RESOURCE_EXTENSION + try (Response response = RESOURCE_EXTENSION .target(String.format("/v1/subscription/%s/level/%d/%s/%s", subscriberId, 5, "usd", "abcd")) .request() - .put(Entity.json("")); - assertThat(response.getStatus()).isEqualTo(400); - assertThat(response.readEntity(SubscriptionController.SetSubscriptionLevelErrorResponse.class)) - .extracting(resp -> resp.errors()) - .asInstanceOf(InstanceOfAssertFactories.list(SubscriptionController.SetSubscriptionLevelErrorResponse.Error.class)) - .hasSize(1).first() - .extracting(error -> error.type()) - .isEqualTo(SubscriptionController.SetSubscriptionLevelErrorResponse.Error.Type.UNSUPPORTED_LEVEL); + .put(Entity.json(""))) { + assertThat(response.getStatus()).isEqualTo(400); + assertThat(response.readEntity(SubscriptionController.SetSubscriptionLevelErrorResponse.class)) + .extracting(SubscriptionController.SetSubscriptionLevelErrorResponse::errors) + .asInstanceOf( + InstanceOfAssertFactories.list(SubscriptionController.SetSubscriptionLevelErrorResponse.Error.class)) + .hasSize(1).first() + .extracting(SubscriptionController.SetSubscriptionLevelErrorResponse.Error::type) + .isEqualTo(SubscriptionController.SetSubscriptionLevelErrorResponse.Error.Type.UNSUPPORTED_LEVEL); + } } @Test @@ -646,14 +663,15 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest { when(APPSTORE_MANAGER.validateTransaction(eq(originalTxId))) .thenReturn(99L); - - final Response response = RESOURCE_EXTENSION + + try (Response response = RESOURCE_EXTENSION .target(String.format("/v1/subscription/%s/appstore/%s", subscriberId, originalTxId)) .request() - .post(Entity.json("")); - assertThat(response.getStatus()).isEqualTo(200); - assertThat(response.readEntity(SubscriptionController.SetSubscriptionLevelSuccessResponse.class).level()) - .isEqualTo(99L); + .post(Entity.json(""))) { + assertThat(response.getStatus()).isEqualTo(200); + assertThat(response.readEntity(SubscriptionController.SetSubscriptionLevelSuccessResponse.class).level()) + .isEqualTo(99L); + } verify(SUBSCRIPTIONS, times(1)).setIapPurchase( any(), @@ -687,13 +705,14 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest { when(validatedToken.getLevel()).thenReturn(99L); when(PLAY_MANAGER.validateToken(eq(purchaseToken))).thenReturn(validatedToken); - final Response response = RESOURCE_EXTENSION + try (Response response = RESOURCE_EXTENSION .target(String.format("/v1/subscription/%s/playbilling/%s", subscriberId, purchaseToken)) .request() - .post(Entity.json("")); - assertThat(response.getStatus()).isEqualTo(200); - assertThat(response.readEntity(SubscriptionController.SetSubscriptionLevelSuccessResponse.class).level()) - .isEqualTo(99L); + .post(Entity.json(""))) { + assertThat(response.getStatus()).isEqualTo(200); + assertThat(response.readEntity(SubscriptionController.SetSubscriptionLevelSuccessResponse.class).level()) + .isEqualTo(99L); + } verify(SUBSCRIPTIONS, times(1)).setIapPurchase( any(), @@ -729,13 +748,14 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest { when(PLAY_MANAGER.validateToken(eq(newPurchaseToken))).thenReturn(validatedToken); - final Response response = RESOURCE_EXTENSION + try (Response response = RESOURCE_EXTENSION .target(String.format("/v1/subscription/%s/playbilling/%s", subscriberId, newPurchaseToken)) .request() - .post(Entity.json("")); - assertThat(response.getStatus()).isEqualTo(200); - assertThat(response.readEntity(SubscriptionController.SetSubscriptionLevelSuccessResponse.class).level()) - .isEqualTo(99L); + .post(Entity.json(""))) { + assertThat(response.getStatus()).isEqualTo(200); + assertThat(response.readEntity(SubscriptionController.SetSubscriptionLevelSuccessResponse.class).level()) + .isEqualTo(99L); + } verify(SUBSCRIPTIONS, times(1)).setIapPurchase( any(), @@ -754,7 +774,6 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest { Arrays.fill(subscriberUserAndKey, (byte) 1); final String subscriberId = Base64.getEncoder().encodeToString(subscriberUserAndKey); - when(CLOCK.instant()).thenReturn(Instant.now()); when(SUBSCRIPTIONS.get(any(), any())) .thenReturn(Subscriptions.GetResult.found(Subscriptions.Record.from( Arrays.copyOfRange(subscriberUserAndKey, 0, 16), @@ -772,13 +791,15 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest { final ReceiptCredentialRequest receiptRequest = new ClientZkReceiptOperations( ServerSecretParams.generate().getPublicParams()).createReceiptCredentialRequestContext( new ReceiptSerial(new byte[ReceiptSerial.SIZE])).getRequest(); - final Response response = RESOURCE_EXTENSION + final Map responseMap; + try (Response response = RESOURCE_EXTENSION .target(String.format("/v1/subscription/%s/receipt_credentials", subscriberId)) .request() - .post(Entity.json(new SubscriptionController.GetReceiptCredentialsRequest(receiptRequest.serialize()))); + .post(Entity.json(new SubscriptionController.GetReceiptCredentialsRequest(receiptRequest.serialize())))) { - assertThat(response.getStatus()).isEqualTo(402); - final Map responseMap = response.readEntity(Map.class); + assertThat(response.getStatus()).isEqualTo(402); + responseMap = response.readEntity(Map.class); + } assertThat(responseMap.get("processor")).isEqualTo("STRIPE"); assertThat(responseMap.get("chargeFailure")).asInstanceOf( InstanceOfAssertFactories.map(String.class, Object.class)) @@ -793,7 +814,6 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest { Arrays.fill(subscriberUserAndKey, (byte) 1); final String subscriberId = Base64.getEncoder().encodeToString(subscriberUserAndKey); - when(CLOCK.instant()).thenReturn(Instant.now()); when(SUBSCRIPTIONS.get(any(), any())) .thenReturn(Subscriptions.GetResult.found(Subscriptions.Record.from( Arrays.copyOfRange(subscriberUserAndKey, 0, 16), @@ -813,12 +833,13 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest { final ReceiptCredentialRequest receiptRequest = new ClientZkReceiptOperations( ServerSecretParams.generate().getPublicParams()).createReceiptCredentialRequestContext( new ReceiptSerial(new byte[ReceiptSerial.SIZE])).getRequest(); - final Response response = RESOURCE_EXTENSION + try (Response response = RESOURCE_EXTENSION .target(String.format("/v1/subscription/%s/receipt_credentials", subscriberId)) .request() - .post(Entity.json(new SubscriptionController.GetReceiptCredentialsRequest(receiptRequest.serialize()))); + .post(Entity.json(new SubscriptionController.GetReceiptCredentialsRequest(receiptRequest.serialize())))) { - assertThat(response.getStatus()).isEqualTo(409); + assertThat(response.getStatus()).isEqualTo(409); + } } @ParameterizedTest @@ -844,7 +865,6 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest { new ReceiptSerial(new byte[ReceiptSerial.SIZE])).getRequest(); final ReceiptCredentialResponse receiptCredentialResponse = mock(ReceiptCredentialResponse.class); - when(CLOCK.instant()).thenReturn(Instant.now()); when(SUBSCRIPTIONS.get(any(), any())) .thenReturn(Subscriptions.GetResult.found(record)); when(BRAINTREE_MANAGER.getReceiptItem(subscriptionId)).thenReturn( @@ -854,11 +874,12 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest { level)); when(ZK_OPS.issueReceiptCredential(any(), anyLong(), eq(level))).thenReturn(receiptCredentialResponse); when(receiptCredentialResponse.serialize()).thenReturn(new byte[0]); - final Response response = RESOURCE_EXTENSION + try (Response response = RESOURCE_EXTENSION .target(String.format("/v1/subscription/%s/receipt_credentials", subscriberId)) .request() - .post(Entity.json(new SubscriptionController.GetReceiptCredentialsRequest(receiptRequest.serialize()))); - assertThat(response.getStatus()).isEqualTo(200); + .post(Entity.json(new SubscriptionController.GetReceiptCredentialsRequest(receiptRequest.serialize())))) { + assertThat(response.getStatus()).isEqualTo(200); + } long expectedExpiration = Instant.EPOCH // Truncated current time is day 1 @@ -988,13 +1009,12 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest { assertThat(badge.getName()).isEqualTo("gift1"); })); - 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(5L).satisfies(level -> + assertThat(level).extracting(LevelConfiguration::badge) + .satisfies(badge -> { + assertThat(badge.getId()).isEqualTo("B1"); + assertThat(badge.getName()).isEqualTo("name1"); + })); assertThat(levelsMap).extractingByKey(15L).satisfies(level -> assertThat(level).extracting(LevelConfiguration::badge) @@ -1003,13 +1023,12 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest { assertThat(badge.getName()).isEqualTo("name2"); })); - assertThat(levelsMap).extractingByKey(35L).satisfies(level -> { - assertThat(level).extracting(LevelConfiguration::badge) - .satisfies(badge -> { - assertThat(badge.getId()).isEqualTo("B3"); - assertThat(badge.getName()).isEqualTo("name3"); - }); - }); + assertThat(levelsMap).extractingByKey(35L).satisfies(level -> + assertThat(level).extracting(LevelConfiguration::badge) + .satisfies(badge -> { + assertThat(badge.getId()).isEqualTo("B3"); + assertThat(badge.getName()).isEqualTo("name3"); + })); }); assertThat(response.backup().levels()).containsOnlyKeys("201").extractingByKey("201").satisfies(configuration -> { diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/grpc/DonationsGrpcServiceTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/DonationsGrpcServiceTest.java index af09d5276..066f015e7 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/grpc/DonationsGrpcServiceTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/DonationsGrpcServiceTest.java @@ -3,6 +3,7 @@ package org.whispersystems.textsecuregcm.grpc; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; @@ -11,27 +12,40 @@ import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import com.google.protobuf.ByteString; -import java.time.Clock; +import java.time.Duration; import java.time.Instant; +import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.UUID; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import org.junitpioneer.jupiter.cartesian.CartesianTest; import org.mockito.Mock; +import org.signal.chat.donations.CreateDonationPermitRequest; +import org.signal.chat.donations.CreateDonationPermitResponse; import org.signal.chat.donations.DonationsGrpc; import org.signal.chat.donations.RedeemReceiptRequest; import org.signal.chat.donations.RedeemReceiptResponse; import org.signal.libsignal.zkgroup.InvalidInputException; +import org.signal.libsignal.zkgroup.ServerSecretParams; import org.signal.libsignal.zkgroup.VerificationFailedException; +import org.signal.libsignal.zkgroup.donation.DonationPermit; +import org.signal.libsignal.zkgroup.donation.DonationPermitRequestContext; +import org.signal.libsignal.zkgroup.donation.DonationPermitResponse; import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialPresentation; import org.signal.libsignal.zkgroup.receipts.ReceiptSerial; import org.signal.libsignal.zkgroup.receipts.ServerZkReceiptOperations; import org.whispersystems.textsecuregcm.configuration.BadgesConfiguration; +import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException; +import org.whispersystems.textsecuregcm.limits.RateLimiter; +import org.whispersystems.textsecuregcm.limits.RateLimiters; import org.whispersystems.textsecuregcm.storage.Account; import org.whispersystems.textsecuregcm.storage.AccountBadge; import org.whispersystems.textsecuregcm.storage.AccountsManager; +import org.whispersystems.textsecuregcm.storage.DonationPermits; +import org.whispersystems.textsecuregcm.storage.DonationPermitsManager; import org.whispersystems.textsecuregcm.storage.RedeemedReceiptsManager; import org.whispersystems.textsecuregcm.subscriptions.ReceiptCredentialPresentationFactory; import org.whispersystems.textsecuregcm.tests.util.AccountsHelper; @@ -61,7 +75,13 @@ class DonationsGrpcServiceTest extends SimpleBaseGrpcTest donationPermits = context.receive(donationPermitResponse, + donationsPermitSecretParams.getPublicParams(), + clock.instant()); + + assertEquals(permitCount, donationPermits.size()); + } + + @Test + void createDonationPermitInvalid() throws Exception { + final int permitCount = 10; + final DonationPermitRequestContext context = DonationPermitRequestContext.forCount(permitCount); + + GrpcTestUtils.assertStatusInvalidArgument(() -> + authenticatedServiceStub().createDonationPermit(CreateDonationPermitRequest.newBuilder() + .setDonationPermitRequest(ByteString.copyFrom(new byte[]{1, 2, 3})) + .build())); + } + + @Test + void createDonationPermitRateLimited() throws Exception{ + final Duration retryDuration = Duration.ofHours(3); + doThrow(new RateLimitExceededException(retryDuration)) + .when(createDonationPermitLimiter).validate(any(UUID.class), anyLong()); + + final int permitCount = 10; + final DonationPermitRequestContext context = DonationPermitRequestContext.forCount(permitCount); + + GrpcTestUtils.assertRateLimitExceeded(retryDuration, () -> + authenticatedServiceStub().createDonationPermit(CreateDonationPermitRequest.newBuilder() + .setDonationPermitRequest(ByteString.copyFrom(context.request().serialize())) + .build())); + + } + } 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 09396a054..4f6c6bc9d 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/grpc/SubscriptionsGrpcServiceTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/SubscriptionsGrpcServiceTest.java @@ -10,6 +10,7 @@ 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.anyBoolean; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doThrow; @@ -19,8 +20,9 @@ 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.Duration; import java.time.Instant; +import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; @@ -33,10 +35,10 @@ 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.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; @@ -57,6 +59,12 @@ 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.ServerSecretParams; +import org.signal.libsignal.zkgroup.VerificationFailedException; +import org.signal.libsignal.zkgroup.donation.DonationPermit; +import org.signal.libsignal.zkgroup.donation.DonationPermitRequest; +import org.signal.libsignal.zkgroup.donation.DonationPermitRequestContext; +import org.signal.libsignal.zkgroup.donation.DonationPermitResponse; import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialResponse; import org.whispersystems.textsecuregcm.badges.BadgeTranslator; import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfiguration; @@ -66,6 +74,8 @@ import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfigurati import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException; import org.whispersystems.textsecuregcm.entities.Badge; import org.whispersystems.textsecuregcm.entities.BadgeSvg; +import org.whispersystems.textsecuregcm.storage.DonationPermits; +import org.whispersystems.textsecuregcm.storage.DonationPermitsManager; import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager; import org.whispersystems.textsecuregcm.storage.SubscriptionManager; import org.whispersystems.textsecuregcm.storage.Subscriptions; @@ -78,6 +88,7 @@ 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.SubscriberIdCreationNotPermittedException; import org.whispersystems.textsecuregcm.subscriptions.SubscriptionChargeFailurePaymentRequiredException; import org.whispersystems.textsecuregcm.subscriptions.SubscriptionException; import org.whispersystems.textsecuregcm.subscriptions.SubscriptionForbiddenException; @@ -101,7 +112,7 @@ import org.whispersystems.textsecuregcm.util.TestRandomUtil; public class SubscriptionsGrpcServiceTest extends SimpleBaseGrpcTest { - private final Clock clock = TestClock.pinned(Instant.ofEpochSecond(100)); + private final TestClock clock = TestClock.pinned(Instant.now()); private final SubscriptionConfiguration subscriptionConfiguration = SubscriptionConfigTestHelper.getSubscriptionConfig(); @@ -109,6 +120,12 @@ public class SubscriptionsGrpcServiceTest extends private final OneTimeDonationConfiguration oneTimeDonationConfiguration = SubscriptionConfigTestHelper.getOneTimeConfig(); + @Mock + private DonationPermits donationPermits; + + private static final ServerSecretParams DONATION_PERMITS_SECRET_PARAMS = ServerSecretParams.generate(); + private DonationPermitsManager donationPermitsManager; + @Mock private SubscriptionManager subscriptionManager; @@ -141,9 +158,17 @@ public class SubscriptionsGrpcServiceTest extends protected SubscriptionsGrpcService createServiceBeforeEachTest() { getMockRequestAttributesInterceptor().setRequestAttributes( new RequestAttributes(InetAddresses.forString("127.0.0.1"), null, "en-us")); + + donationPermitsManager = new DonationPermitsManager(donationPermits, DONATION_PERMITS_SECRET_PARAMS, clock); + + // spendIds are spend-once + final Set spent = new HashSet<>(); + when(donationPermits.spend(any(byte[].class), any(Instant.class))) + .thenAnswer(answer -> spent.add(new String(answer.getArgument(0, byte[].class)))); + return new SubscriptionsGrpcService(clock, subscriptionConfiguration, oneTimeDonationConfiguration, - subscriptionManager, stripeManager, braintreeManager, googlePlayBillingManager, appleAppStoreManager, - badgeTranslator, bankMandateTranslator, dynamicConfigurationManager); + subscriptionManager, donationPermitsManager, stripeManager, braintreeManager, googlePlayBillingManager, + appleAppStoreManager, badgeTranslator, bankMandateTranslator, dynamicConfigurationManager); } @Test @@ -156,9 +181,36 @@ public class SubscriptionsGrpcServiceTest extends } @Test - void updateSubscriberIdMismatch() throws SubscriptionForbiddenException { + void updateSubscriberCreationNotPermittedPermitRejected() throws SubscriptionException { + doThrow(new SubscriberIdCreationNotPermittedException()) + .when(subscriptionManager).updateSubscriber(any(), eq(false)); + + final DonationPermit donationPermit = getDonationPermit(); + clock.pin(clock.instant().plus(Duration.ofDays(14))); + + final UpdateSubscriberResponse response = unauthenticatedServiceStub().updateSubscriber( + UpdateSubscriberRequest.newBuilder() + .setSubscriberId(SUBSCRIBER_ID) + .setDonationPermit(ByteString.copyFrom(donationPermit.serialize())) + .build()); + + assertTrue(response.hasPermitRejected()); + } + + @Test + void updateSubscriberCreationNotPermittedMissingPermit() throws SubscriptionException { + doThrow(new SubscriberIdCreationNotPermittedException()) + .when(subscriptionManager).updateSubscriber(any(), eq(false)); + GrpcTestUtils.assertStatusInvalidArgument(() -> unauthenticatedServiceStub().updateSubscriber( + UpdateSubscriberRequest.newBuilder() + .setSubscriberId(SUBSCRIBER_ID) + .build())); + } + + @Test + void updateSubscriberIdMismatch() throws SubscriptionException { doThrow(new SubscriptionForbiddenException("subscriberId mismatch")) - .when(subscriptionManager).updateSubscriber(any()); + .when(subscriptionManager).updateSubscriber(any(), anyBoolean()); final UpdateSubscriberResponse response = unauthenticatedServiceStub().updateSubscriber( UpdateSubscriberRequest.newBuilder() .setSubscriberId(SUBSCRIBER_ID) @@ -206,8 +258,10 @@ public class SubscriptionsGrpcServiceTest extends 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) + .setDonationPermit(ByteString.copyFrom(getDonationPermit().serialize())) .setPaymentMethod(paymentMethod); final CreatePaymentMethodResponse response = unauthenticatedServiceStub().createPaymentMethod(builder.build()); assertEquals(CreatePaymentMethodResponse.ResponseCase.RESULT, response.getResponseCase()); @@ -227,6 +281,34 @@ public class SubscriptionsGrpcServiceTest extends .build())); } + @Test + void createPaymentMethodInvalidDonationPermit() { + GrpcTestUtils.assertStatusInvalidArgument( + () -> unauthenticatedServiceStub().createPaymentMethod( + CreatePaymentMethodRequest.newBuilder() + .setSubscriberId(SUBSCRIBER_ID) + .setDonationPermit(ByteString.copyFrom(new byte[]{1})) + .setPaymentMethod(PaymentMethod.PAYMENT_METHOD_CARD) + .build())); + } + + @Test + void createPaymentMethodExpiredDonationPermit() { + when(stripeManager.getProvider()).thenReturn(PaymentProvider.STRIPE); + + final DonationPermit donationPermit = getDonationPermit(); + clock.pin(clock.instant().plus(Duration.ofDays(30))); + + final CreatePaymentMethodResponse createPaymentMethodResponse = unauthenticatedServiceStub().createPaymentMethod( + CreatePaymentMethodRequest.newBuilder() + .setSubscriberId(SUBSCRIBER_ID) + .setDonationPermit(ByteString.copyFrom(donationPermit.serialize())) + .setPaymentMethod(PaymentMethod.PAYMENT_METHOD_CARD) + .build()); + + assertTrue(createPaymentMethodResponse.hasPermitRejected()); + } + @Test void createPaymentMethodProcessorConflict() throws SubscriptionForbiddenException, SubscriptionNotFoundException, SubscriptionProcessorConflictException { @@ -235,6 +317,7 @@ public class SubscriptionsGrpcServiceTest extends final CreatePaymentMethodResponse response = unauthenticatedServiceStub().createPaymentMethod( CreatePaymentMethodRequest.newBuilder() .setSubscriberId(SUBSCRIBER_ID) + .setDonationPermit(ByteString.copyFrom(getDonationPermit().serialize())) .setPaymentMethod(PaymentMethod.PAYMENT_METHOD_CARD) .build()); assertEquals(CreatePaymentMethodResponse.ResponseCase.SUBSCRIPTION_PROCESSOR_CONFLICT, response.getResponseCase()); @@ -721,4 +804,20 @@ public class SubscriptionsGrpcServiceTest extends assertEquals("test-mandate", response.getMandate()); } + private DonationPermit getDonationPermit() { + final DonationPermitRequestContext context = DonationPermitRequestContext.forCount(1); + final DonationPermitRequest permitRequest = context.request(); + + final DonationPermitResponse permitResponse = donationPermitsManager.issue(permitRequest); + + try { + final List donationPermits = context.receive(permitResponse, + DONATION_PERMITS_SECRET_PARAMS.getPublicParams(), clock.instant()); + + return donationPermits.getFirst(); + } catch (final VerificationFailedException e) { + throw new AssertionError("The permit was correctly requested and issued in this method", e); + } + } + } diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/storage/DonationPermitsTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/storage/DonationPermitsTest.java new file mode 100644 index 000000000..86b1d1d6e --- /dev/null +++ b/service/src/test/java/org/whispersystems/textsecuregcm/storage/DonationPermitsTest.java @@ -0,0 +1,68 @@ +/* + * Copyright 2026 Signal Messenger, LLC + * SPDX-License-Identifier: AGPL-3.0-only + */ + +package org.whispersystems.textsecuregcm.storage; + +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.whispersystems.textsecuregcm.util.AttributeValues.b; + +import java.time.Duration; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.Map; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.whispersystems.textsecuregcm.util.TestRandomUtil; +import software.amazon.awssdk.services.dynamodb.model.GetItemRequest; +import software.amazon.awssdk.services.dynamodb.model.GetItemResponse; + +class DonationPermitsTest { + + @RegisterExtension + static final DynamoDbExtension DYNAMO_DB_EXTENSION = new DynamoDbExtension(DynamoDbExtensionSchema.Tables.DONATION_PERMITS); + + private static final Duration EXPIRATION = Duration.ofDays(7); + + private DonationPermits donationPermits; + + @BeforeEach + void beforeEach() { + + donationPermits = new DonationPermits( + DynamoDbExtensionSchema.Tables.DONATION_PERMITS.tableName(), + EXPIRATION, + DYNAMO_DB_EXTENSION.getDynamoDbClient()); + } + + @Test + void testSpend() { + + final byte[] spendId1 = TestRandomUtil.nextBytes(16); + + final Instant now = Instant.now().truncatedTo(ChronoUnit.SECONDS); + assertTrue(donationPermits.spend(spendId1, now), "first spend should succeed"); + assertFalse(donationPermits.spend(spendId1, now), "second spend should fail"); + + final GetItemResponse getItemResponse = DYNAMO_DB_EXTENSION.getDynamoDbClient() + .getItem(GetItemRequest.builder() + .tableName(DynamoDbExtensionSchema.Tables.DONATION_PERMITS.tableName()) + .key(Map.of(DonationPermits.KEY_SPEND_ID, b(spendId1))) + .build()); + + final Instant expiration = Instant.ofEpochSecond( + Long.parseLong(getItemResponse.item().get(DonationPermits.KEY_EXPIRATION) + .n())); + + assertEquals(now.plus(EXPIRATION), expiration); + + final byte[] spendId2 = TestRandomUtil.nextBytes(16); + + assertTrue(donationPermits.spend(spendId2, now), "spending a second ID should succeed"); + } + +} diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/storage/DynamoDbExtensionSchema.java b/service/src/test/java/org/whispersystems/textsecuregcm/storage/DynamoDbExtensionSchema.java index 767536f11..05cf9ecf7 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/storage/DynamoDbExtensionSchema.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/storage/DynamoDbExtensionSchema.java @@ -115,6 +115,14 @@ public final class DynamoDbExtensionSchema { .attributeType(ScalarAttributeType.S).build()), List.of(), List.of()), + DONATION_PERMITS("donation_permits_test", + DonationPermits.KEY_SPEND_ID, + null, + List.of(AttributeDefinition.builder() + .attributeName(DonationPermits.KEY_SPEND_ID) + .attributeType(ScalarAttributeType.B) + .build()), List.of(), List.of()), + NUMBERS("numbers_test", Accounts.ATTR_ACCOUNT_E164, null, diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/storage/SubscriptionManagerTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/storage/SubscriptionManagerTest.java new file mode 100644 index 000000000..4b1f6cbcd --- /dev/null +++ b/service/src/test/java/org/whispersystems/textsecuregcm/storage/SubscriptionManagerTest.java @@ -0,0 +1,108 @@ +/* + * Copyright 2026 Signal Messenger, LLC + * SPDX-License-Identifier: AGPL-3.0-only + */ + +package org.whispersystems.textsecuregcm.storage; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.AdditionalMatchers.aryEq; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.time.Instant; +import java.util.List; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.signal.libsignal.zkgroup.receipts.ServerZkReceiptOperations; +import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider; +import org.whispersystems.textsecuregcm.subscriptions.SubscriberIdCreationNotPermittedException; +import org.whispersystems.textsecuregcm.subscriptions.SubscriptionForbiddenException; +import org.whispersystems.textsecuregcm.subscriptions.SubscriptionPaymentProcessor; +import org.whispersystems.textsecuregcm.util.TestRandomUtil; + +class SubscriptionManagerTest { + + private static final Subscriptions SUBSCRIPTIONS = mock(Subscriptions.class); + private SubscriptionManager subscriptionManager; + + @BeforeEach + void setUp() { + reset(SUBSCRIPTIONS); + + final SubscriptionPaymentProcessor testProcessor = mock(SubscriptionPaymentProcessor.class); + when(testProcessor.getProvider()).thenReturn(PaymentProvider.STRIPE); + + subscriptionManager = new SubscriptionManager(SUBSCRIPTIONS, List.of(testProcessor), mock(ServerZkReceiptOperations.class), mock( + IssuedReceiptsManager.class)); + } + + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void updateSubscriberCreate(final boolean createPermitted) { + final byte[] user = TestRandomUtil.nextBytes(16); + final SubscriberCredentials credentials = new SubscriberCredentials(TestRandomUtil.nextBytes(32), + user, + TestRandomUtil.nextBytes(16), + TestRandomUtil.nextBytes(16), + Instant.now()); + + when(SUBSCRIPTIONS.get(any(byte[].class), any(byte[].class))).thenReturn(Subscriptions.GetResult.NOT_STORED); + when(SUBSCRIPTIONS.create(any(byte[].class), any(byte[].class), any(Instant.class))) + .thenReturn(mock(Subscriptions.Record.class)); + + if (createPermitted) { + assertDoesNotThrow(() -> subscriptionManager.updateSubscriber(credentials, createPermitted)); + verify(SUBSCRIPTIONS).create(aryEq(user), any(byte[].class), any(Instant.class)); + } else { + assertThrows(SubscriberIdCreationNotPermittedException.class, + () -> subscriptionManager.updateSubscriber(credentials, createPermitted)); + verify(SUBSCRIPTIONS, never()).create(any(byte[].class), any(byte[].class), any(Instant.class)); + } + + } + + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void updateSubscriberExists(final boolean createPermitted) { + final byte[] user = TestRandomUtil.nextBytes(16); + final SubscriberCredentials credentials = new SubscriberCredentials(TestRandomUtil.nextBytes(32), + user, + TestRandomUtil.nextBytes(16), + TestRandomUtil.nextBytes(16), + Instant.now()); + + when(SUBSCRIPTIONS.get(any(byte[].class), any(byte[].class))).thenReturn(Subscriptions.GetResult.found(mock( + Subscriptions.Record.class))); + when(SUBSCRIPTIONS.create(any(byte[].class), any(byte[].class), any(Instant.class))) + .thenReturn(mock(Subscriptions.Record.class)); + + assertDoesNotThrow(() -> subscriptionManager.updateSubscriber(credentials, createPermitted)); + verify(SUBSCRIPTIONS, never()).create(any(byte[].class), any(byte[].class), any(Instant.class)); + verify(SUBSCRIPTIONS).accessedAt(aryEq(user), any(Instant.class)); + } + + @Test + void updateSubscriberMismatch() { + final byte[] user = TestRandomUtil.nextBytes(16); + final SubscriberCredentials credentials = new SubscriberCredentials(TestRandomUtil.nextBytes(32), + user, + TestRandomUtil.nextBytes(16), + TestRandomUtil.nextBytes(16), + Instant.now()); + + when(SUBSCRIPTIONS.get(any(byte[].class), any(byte[].class))).thenReturn(Subscriptions.GetResult.PASSWORD_MISMATCH); + + assertThrows(SubscriptionForbiddenException.class, + () -> subscriptionManager.updateSubscriber(credentials, true)); + verify(SUBSCRIPTIONS, never()).create(any(byte[].class), any(byte[].class), any(Instant.class)); + } + +} diff --git a/service/src/test/resources/config/test.yml b/service/src/test/resources/config/test.yml index 03d81dd16..85067dcf2 100644 --- a/service/src/test/resources/config/test.yml +++ b/service/src/test/resources/config/test.yml @@ -106,6 +106,9 @@ dynamoDbTables: tableName: deleted_accounts_test deletedAccountsLock: tableName: deleted_accounts_lock_test + donationPermits: + tableName: donation_permits_test + expiration: P7D # Duration of time until rows expire issuedReceipts: tableName: issued_receipts_test expiration: P30D # Duration of time until rows expire