Implement donation permit spending

This commit is contained in:
Chris Eager authored and GitHub committed 2026-06-24 12:13:21 -05:00
1 parent 8b617b64f8
commit 78b3147491
27 files changed
+1117 -281

No files matched your search

@@ -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<DonationPermit> 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<String> spent = new HashSet<>();
when(donationPermits.spend(any(byte[].class), any(Instant.class)))
.thenAnswer(answer -> spent.add(new String(answer.getArgument(0, byte[].class))));
}
}
@@ -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();
}
@@ -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);
}
}
}
@@ -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<String, AttributeValue> 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<Arguments> 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 -> {
@@ -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<DonationsGrpcService,
@Mock
private ReceiptSerial receiptSerial;
private final Clock clock = TestClock.pinned(Instant.ofEpochSecond(100));
private final ServerSecretParams donationsPermitSecretParams = ServerSecretParams.generate();
private RateLimiter createDonationPermitLimiter;
private DonationPermitsManager donationPermitsManager;
private final TestClock clock = TestClock.pinned(Instant.ofEpochSecond(100));
private static final long EXPIRATION_TIME_EPOCH_SECONDS = 200;
@@ -79,13 +99,22 @@ class DonationsGrpcServiceTest extends SimpleBaseGrpcTest<DonationsGrpcService,
when(badgesConfiguration.getReceiptLevels()).thenReturn(Map.of(1L, "testBadge"));
when(receiptCredentialPresentation.getReceiptExpirationTime()).thenReturn(EXPIRATION_TIME_EPOCH_SECONDS);
when(receiptCredentialPresentation.getReceiptSerial()).thenReturn(receiptSerial);
donationPermitsManager = new DonationPermitsManager(mock(DonationPermits.class), donationsPermitSecretParams,
clock);
final RateLimiters rateLimiters = mock(RateLimiters.class);
createDonationPermitLimiter = mock(RateLimiter.class);
when(rateLimiters.getCreateDonationPermitLimiter()).thenReturn(createDonationPermitLimiter);
return new DonationsGrpcService(
clock,
zkReceiptOperations,
redeemedReceiptsManager,
accountsManager,
badgesConfiguration,
receiptCredentialPresentationFactory
receiptCredentialPresentationFactory,
donationPermitsManager,
rateLimiters
);
}
@@ -146,4 +175,50 @@ class DonationsGrpcServiceTest extends SimpleBaseGrpcTest<DonationsGrpcService,
assertEquals(RedeemReceiptResponse.ResponseCase.FAILED_AUTHENTICATION, response.getResponseCase());
verifyNoInteractions(account);
}
@Test
void createDonationPermit() throws Exception {
final int permitCount = 10;
final DonationPermitRequestContext context = DonationPermitRequestContext.forCount(permitCount);
final CreateDonationPermitResponse response = authenticatedServiceStub().createDonationPermit(
CreateDonationPermitRequest.newBuilder()
.setDonationPermitRequest(ByteString.copyFrom(context.request().serialize()))
.build());
final DonationPermitResponse donationPermitResponse = new DonationPermitResponse(response.getDonationPermitResponse().toByteArray());
final List<DonationPermit> 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()));
}
}
@@ -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<SubscriptionsGrpcService, SubscriptionsGrpc.SubscriptionsBlockingStub> {
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<String> 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<DonationPermit> 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);
}
}
}
@@ -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");
}
}
@@ -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,
@@ -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));
}
}