diff --git a/service/config/sample.yml b/service/config/sample.yml index 9b6d1d20d..954b2a56b 100644 --- a/service/config/sample.yml +++ b/service/config/sample.yml @@ -74,7 +74,6 @@ appleDeviceCheck: deviceCheck: backupRedemptionDuration: P30D - backupRedemptionLevel: 201 dynamoDbClient: region: us-west-2 # AWS Region @@ -365,7 +364,7 @@ badges: - light: example-light.svg dark: example-dark.svg receiptLevels: - '1': TEST + ONE_TIME_DONATION: TEST subscription: # configuration for Stripe subscriptions badgeExpiration: P30D @@ -385,18 +384,15 @@ subscription: # configuration for Stripe subscriptions BRAINTREE: plan_example # braintree Plan ID loginPurchase: - level: 300 playProductId: login_example appStoreProductId: login_example oneTimeDonations: sepaMaximumEuros: '10000' boost: - level: 1 expiration: P90D badge: EXAMPLE gift: - level: 10 expiration: P90D badge: EXAMPLE currencies: diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerService.java b/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerService.java index 3f659fa95..c2b5a2ab7 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerService.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/WhisperServerService.java @@ -994,8 +994,7 @@ public class WhisperServerService extends Application spamFilters = ServiceLoader.load(SpamFilter.class) .stream() @@ -1270,7 +1269,6 @@ public class WhisperServerService extends Application productIdToLevel, + @NotNull Map productIdToLevel, @NotNull List<@NotBlank String> appleRootCerts, @Nullable String retryConfigurationName) { } diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/configuration/BadgesConfiguration.java b/service/src/main/java/org/whispersystems/textsecuregcm/configuration/BadgesConfiguration.java index 75f775378..abc5b135b 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/configuration/BadgesConfiguration.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/configuration/BadgesConfiguration.java @@ -13,6 +13,7 @@ import com.fasterxml.jackson.annotation.Nulls; import io.dropwizard.validation.ValidationMethod; import jakarta.validation.Valid; import jakarta.validation.constraints.NotNull; +import org.whispersystems.textsecuregcm.subscriptions.ReceiptLevel; import java.util.List; import java.util.Map; import java.util.Objects; @@ -21,12 +22,12 @@ import java.util.stream.Collectors; public class BadgesConfiguration { private final List badges; - private final Map receiptLevels; + private final Map receiptLevels; @JsonCreator public BadgesConfiguration( @JsonProperty("badges") @JsonSetter(nulls = Nulls.AS_EMPTY) final List badges, - @JsonProperty("receiptLevels") @JsonSetter(nulls = Nulls.AS_EMPTY) final Map receiptLevels) { + @JsonProperty("receiptLevels") @JsonSetter(nulls = Nulls.AS_EMPTY) final Map receiptLevels) { this.badges = Objects.requireNonNull(badges); this.receiptLevels = Objects.requireNonNull(receiptLevels); } @@ -39,7 +40,7 @@ public class BadgesConfiguration { @Valid @NotNull - public Map getReceiptLevels() { + public Map getReceiptLevels() { return receiptLevels; } diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/configuration/DeviceCheckConfiguration.java b/service/src/main/java/org/whispersystems/textsecuregcm/configuration/DeviceCheckConfiguration.java index 42ebdfb1f..5d50db49f 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/configuration/DeviceCheckConfiguration.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/configuration/DeviceCheckConfiguration.java @@ -10,6 +10,5 @@ import java.time.Duration; * Configuration for Device Check operations * * @param backupRedemptionDuration How long to grant backup access for redemptions via device check - * @param backupRedemptionLevel What backup level to grant redemptions via device check */ -public record DeviceCheckConfiguration(Duration backupRedemptionDuration, long backupRedemptionLevel) {} +public record DeviceCheckConfiguration(Duration backupRedemptionDuration) {} diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/configuration/GooglePlayBillingConfiguration.java b/service/src/main/java/org/whispersystems/textsecuregcm/configuration/GooglePlayBillingConfiguration.java index e70a17035..c0a449c0e 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/configuration/GooglePlayBillingConfiguration.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/configuration/GooglePlayBillingConfiguration.java @@ -9,6 +9,7 @@ import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotNull; import java.util.Map; import org.whispersystems.textsecuregcm.configuration.secrets.SecretString; +import org.whispersystems.textsecuregcm.subscriptions.ReceiptLevel; /** * @param credentialsJson Service account credentials for Play Billing API @@ -21,4 +22,4 @@ public record GooglePlayBillingConfiguration( @NotBlank String credentialsJson, @NotNull String packageName, @NotBlank String applicationName, - @NotNull Map productIdToLevel) {} + @NotNull Map productIdToLevel) {} diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/configuration/LoginPurchaseConfiguration.java b/service/src/main/java/org/whispersystems/textsecuregcm/configuration/LoginPurchaseConfiguration.java index cdbd30542..08cfa9d47 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/configuration/LoginPurchaseConfiguration.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/configuration/LoginPurchaseConfiguration.java @@ -11,10 +11,8 @@ import java.time.Duration; /// Configuration for one-time Signal Login purchases /// -/// @param level the receipt level that identifies a purchase as a Signal Login. /// @param playProductId the Google Play Billing productId clients should purchase to obtain a Signal Login /// @param appStoreProductId the App Store productId clients should purchase to obtain a Signal Login public record LoginPurchaseConfiguration( - @Positive long level, @NotEmpty String playProductId, @NotEmpty String appStoreProductId) {} diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/configuration/OneTimeDonationConfiguration.java b/service/src/main/java/org/whispersystems/textsecuregcm/configuration/OneTimeDonationConfiguration.java index 552ebc05a..df5b79011 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/configuration/OneTimeDonationConfiguration.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/configuration/OneTimeDonationConfiguration.java @@ -24,10 +24,9 @@ public record OneTimeDonationConfiguration(@Valid ExpiringLevelConfiguration boo /** * @param badge the numeric donation level ID - * @param level the badge ID associated with the level * @param expiration the duration after which the level expires */ - public record ExpiringLevelConfiguration(@NotEmpty String badge, @Positive long level, Duration expiration) { + public record ExpiringLevelConfiguration(@NotEmpty String badge, Duration expiration) { } } diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/controllers/DeviceCheckController.java b/service/src/main/java/org/whispersystems/textsecuregcm/controllers/DeviceCheckController.java index b67fc98b6..1d4533be2 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/controllers/DeviceCheckController.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/controllers/DeviceCheckController.java @@ -29,6 +29,7 @@ import java.time.Duration; import java.util.Base64; import java.util.Locale; import org.glassfish.jersey.server.ManagedAsync; +import org.signal.libsignal.zkgroup.backups.BackupLevel; import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice; import org.whispersystems.textsecuregcm.backup.BackupAuthManager; import org.whispersystems.textsecuregcm.limits.RateLimiters; @@ -59,7 +60,6 @@ public class DeviceCheckController { private final BackupAuthManager backupAuthManager; private final AppleDeviceCheckManager deviceCheckManager; private final RateLimiters rateLimiters; - private final long backupRedemptionLevel; private final Duration backupRedemptionDuration; public DeviceCheckController( @@ -68,13 +68,11 @@ public class DeviceCheckController { final BackupAuthManager backupAuthManager, final AppleDeviceCheckManager deviceCheckManager, final RateLimiters rateLimiters, - final long backupRedemptionLevel, final Duration backupRedemptionDuration) { this.clock = clock; this.accountsManager = accountsManager; this.backupAuthManager = backupAuthManager; this.deviceCheckManager = deviceCheckManager; - this.backupRedemptionLevel = backupRedemptionLevel; this.backupRedemptionDuration = backupRedemptionDuration; this.rateLimiters = rateLimiters; } @@ -252,7 +250,7 @@ public class DeviceCheckController { switch (request.assertionRequest().action()) { case BACKUP -> backupAuthManager.extendBackupVoucher( account, - new Account.BackupVoucher(backupRedemptionLevel, clock.instant().plus(backupRedemptionDuration))); + new Account.BackupVoucher(BackupLevel.PAID.getValue(), clock.instant().plus(backupRedemptionDuration))); } } diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/controllers/DonationController.java b/service/src/main/java/org/whispersystems/textsecuregcm/controllers/DonationController.java index 4c4f310e4..456f8bdcd 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/controllers/DonationController.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/controllers/DonationController.java @@ -41,6 +41,7 @@ import org.whispersystems.textsecuregcm.storage.AccountsManager; import org.whispersystems.textsecuregcm.storage.DonationPermitsManager; import org.whispersystems.textsecuregcm.storage.RedeemedReceiptsManager; import org.whispersystems.textsecuregcm.subscriptions.ReceiptCredentialPresentationFactory; +import org.whispersystems.textsecuregcm.subscriptions.ReceiptLevel; @Path("/v1/donation") @Tag(name = "Donations") @@ -117,7 +118,10 @@ public class DonationController { final ReceiptSerial receiptSerial = receiptCredentialPresentation.getReceiptSerial(); final Instant receiptExpiration = Instant.ofEpochSecond(receiptCredentialPresentation.getReceiptExpirationTime()); final long receiptLevel = receiptCredentialPresentation.getReceiptLevel(); - final String badgeId = badgesConfiguration.getReceiptLevels().get(receiptLevel); + final String badgeId = ReceiptLevel + .lookupLevel(receiptLevel) + .map(badgesConfiguration.getReceiptLevels()::get) + .orElse(null); if (badgeId == null) { return Response.serverError() .entity("server does not recognize the requested receipt level") diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/controllers/OneTimeDonationController.java b/service/src/main/java/org/whispersystems/textsecuregcm/controllers/OneTimeDonationController.java index 4f78f5641..2a1f570ae 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/controllers/OneTimeDonationController.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/controllers/OneTimeDonationController.java @@ -397,7 +397,7 @@ public class OneTimeDonationController { final ReceiptCredentialResponse receiptCredentialResponse; try { receiptCredentialResponse = zkReceiptOperations.issueReceiptCredential( - receiptCredentialRequest, expiration.getEpochSecond(), levelDetails.level()); + receiptCredentialRequest, expiration.getEpochSecond(), levelDetails.level().getValue()); } catch (final VerificationFailedException e) { throw new BadRequestException("receipt credential request failed verification", e); } 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 3c0fc774b..cbb545a1f 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/controllers/SubscriptionController.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/controllers/SubscriptionController.java @@ -49,7 +49,6 @@ import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response; import jakarta.ws.rs.core.Response.Status; import java.io.IOException; -import java.io.UncheckedIOException; import java.math.BigDecimal; import java.time.Clock; import java.time.Instant; @@ -92,6 +91,7 @@ import org.whispersystems.textsecuregcm.subscriptions.LevelConfiguration; import org.whispersystems.textsecuregcm.subscriptions.PaymentMethod; import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider; import org.whispersystems.textsecuregcm.subscriptions.ProcessorCustomer; +import org.whispersystems.textsecuregcm.subscriptions.ReceiptLevel; import org.whispersystems.textsecuregcm.subscriptions.StripeManager; import org.whispersystems.textsecuregcm.subscriptions.SubscriptionException; import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidArgumentsException; @@ -171,7 +171,7 @@ public class SubscriptionController { buildDonationLevelsConfiguration(subscriptionConfiguration, oneTimeDonationConfiguration, badgeTranslator, acceptableLanguages), new BackupConfiguration(backupLevels, subscriptionConfiguration.getbackupFreeTierMediaDuration().toDays()), - new LoginConfiguration(loginPurchaseConfiguration.level(), loginPurchaseConfiguration.playProductId(), + new LoginConfiguration(ReceiptLevel.LOGIN.getValue(), loginPurchaseConfiguration.playProductId(), loginPurchaseConfiguration.appStoreProductId()), oneTimeDonationConfiguration.sepaMaximumEuros()); } 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 79088fca8..afb0c7e43 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/DonationsGrpcService.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/DonationsGrpcService.java @@ -29,6 +29,7 @@ import org.whispersystems.textsecuregcm.storage.AccountsManager; import org.whispersystems.textsecuregcm.storage.DonationPermitsManager; import org.whispersystems.textsecuregcm.storage.RedeemedReceiptsManager; import org.whispersystems.textsecuregcm.subscriptions.ReceiptCredentialPresentationFactory; +import org.whispersystems.textsecuregcm.subscriptions.ReceiptLevel; public class DonationsGrpcService extends SimpleDonationsGrpc.DonationsImplBase { @@ -73,7 +74,10 @@ public class DonationsGrpcService extends SimpleDonationsGrpc.DonationsImplBase final ReceiptSerial receiptSerial = receiptCredentialPresentation.getReceiptSerial(); final Instant receiptExpiration = Instant.ofEpochSecond(receiptCredentialPresentation.getReceiptExpirationTime()); final long receiptLevel = receiptCredentialPresentation.getReceiptLevel(); - final String badgeId = badgesConfiguration.getReceiptLevels().get(receiptLevel); + final String badgeId = ReceiptLevel + .lookupLevel(receiptLevel) + .map(badgesConfiguration.getReceiptLevels()::get) + .orElse(null); if (badgeId == null) { // Since the receipt presentation checked out, the server messed up because it doesn't recognize a receipt level it previously issued. LOGGER.error("Server doesn't recognize previously issued receipt level; please check badgesConfiguration for issues"); diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/OneTimeDonationUtil.java b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/OneTimeDonationUtil.java index 58e23643e..001082d4f 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/OneTimeDonationUtil.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/OneTimeDonationUtil.java @@ -1,7 +1,5 @@ package org.whispersystems.textsecuregcm.grpc; -import io.micrometer.core.instrument.Counter; -import io.micrometer.core.instrument.Metrics; import java.math.BigDecimal; import java.time.Duration; import java.util.List; @@ -9,11 +7,11 @@ import java.util.Locale; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfiguration; -import org.whispersystems.textsecuregcm.metrics.MetricsUtil; import org.whispersystems.textsecuregcm.subscriptions.CustomerAwareSubscriptionPaymentProcessor; import org.whispersystems.textsecuregcm.subscriptions.PayPalDonationsTranslator; import org.whispersystems.textsecuregcm.subscriptions.PaymentDetails; import org.whispersystems.textsecuregcm.subscriptions.PaymentMethod; +import org.whispersystems.textsecuregcm.subscriptions.ReceiptLevel; import org.whispersystems.textsecuregcm.subscriptions.SubscriptionCurrencyUtil; public class OneTimeDonationUtil { @@ -22,9 +20,6 @@ public class OneTimeDonationUtil { private static final Logger LOGGER = LoggerFactory.getLogger(OneTimeDonationUtil.class); - private static final Counter MISSING_LEVEL_COUNTER = - Metrics.counter(MetricsUtil.name(OneTimeDonationUtil.class, "missingLevelMetadata")); - /// Thrown if a one time donation level cannot be parsed or if it is not found in configuration public static class InvalidLevelException extends Exception { @@ -34,7 +29,7 @@ public class OneTimeDonationUtil { } public record LocalizedPayPalDonationLineItem(Locale locale, String itemName){} - public record DonationLevelDetails(long level, Duration levelExpiration){} + public record DonationLevelDetails(ReceiptLevel level, Duration levelExpiration){} public sealed interface OneTimeDonationRequestValidationResult permits OneTimeDonationRequestValidationResult.Success, OneTimeDonationRequestValidationResult.UnsupportedCurrency, @@ -63,8 +58,9 @@ public class OneTimeDonationUtil { final CustomerAwareSubscriptionPaymentProcessor manager ) { - if (!(level == oneTimeDonationConfiguration.gift().level() - || level == oneTimeDonationConfiguration.boost().level())) { + if (ReceiptLevel.lookupLevel(level) + .map(rl -> rl != ReceiptLevel.ONE_TIME_DONATION && rl != ReceiptLevel.ONE_TIME_GIFT_DONATION) + .orElse(true)) { return new OneTimeDonationRequestValidationResult.UnsupportedLevel(); } @@ -108,25 +104,15 @@ public class OneTimeDonationUtil { final OneTimeDonationConfiguration oneTimeDonationConfiguration) throws InvalidLevelException { - Long level = paymentDetails.level(); - if (level == null) { - LOGGER.warn("paymentId {} did not have attached level metadata", paymentDetails.id()); - MISSING_LEVEL_COUNTER.increment(); - - // Default to boost if the level was not encoded in the metadata - level = oneTimeDonationConfiguration.boost().level(); - } - - final Duration levelExpiration; - if (level == oneTimeDonationConfiguration.boost().level()) { - levelExpiration = oneTimeDonationConfiguration.boost().expiration(); - } else if (level == oneTimeDonationConfiguration.gift().level()) { - levelExpiration = oneTimeDonationConfiguration.gift().expiration(); - } else { - LOGGER.error("level ({}) returned from payment intent that is unknown to the server", level); - throw new InvalidLevelException("unrecognized level"); - } - return new DonationLevelDetails(level, levelExpiration); + final Duration levelExpiration = switch (paymentDetails.level()) { + case ONE_TIME_DONATION -> oneTimeDonationConfiguration.boost().expiration(); + case ONE_TIME_GIFT_DONATION -> oneTimeDonationConfiguration.gift().expiration(); + default -> { + LOGGER.error("level ({}) returned from payment intent that is unknown to the server", paymentDetails.level()); + throw new InvalidLevelException("unrecognized level"); + } + }; + return new DonationLevelDetails(paymentDetails.level(), levelExpiration); } } diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/OneTimeDonationsGrpcService.java b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/OneTimeDonationsGrpcService.java index 4375b5f05..6e4ca6373 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/OneTimeDonationsGrpcService.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/OneTimeDonationsGrpcService.java @@ -320,7 +320,7 @@ public class OneTimeDonationsGrpcService extends SimpleOneTimeDonationsGrpc.OneT final ReceiptCredentialResponse receiptCredentialResponse; try { receiptCredentialResponse = zkReceiptOperations.issueReceiptCredential( - receiptCredentialRequest, expiration.getEpochSecond(), levelDetails.level()); + receiptCredentialRequest, expiration.getEpochSecond(), levelDetails.level().getValue()); } catch (final VerificationFailedException e) { throw GrpcExceptions.fieldViolation("receipt_credential_request", "receipt credential request failed verification"); diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/ProductConfigurationGrpcService.java b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/ProductConfigurationGrpcService.java index 74b7c905e..8c87296f9 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/ProductConfigurationGrpcService.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/ProductConfigurationGrpcService.java @@ -19,6 +19,7 @@ import org.whispersystems.textsecuregcm.configuration.OneTimeDonationConfigurati import org.whispersystems.textsecuregcm.configuration.SubscriptionConfiguration; import org.whispersystems.textsecuregcm.subscriptions.CustomerAwareSubscriptionPaymentProcessor; import org.whispersystems.textsecuregcm.subscriptions.PaymentMethod; +import org.whispersystems.textsecuregcm.subscriptions.ReceiptLevel; public class ProductConfigurationGrpcService extends SimpleProductConfigurationGrpc.ProductConfigurationImplBase { private final GetConfigurationResponse configurationResponse; @@ -62,11 +63,11 @@ public class ProductConfigurationGrpcService extends SimpleProductConfigurationG subscriptionConfiguration.getDonationLevels().forEach((levelId, levelConfig) -> { donationLevels.put(levelId, LevelConfiguration.newBuilder().setBadgeId(levelConfig.badge()).build()); }); - donationLevels.put(oneTimeDonationConfiguration.boost().level(), + donationLevels.put(ReceiptLevel.ONE_TIME_DONATION.getValue(), LevelConfiguration.newBuilder() .setBadgeId(oneTimeDonationConfiguration.boost().badge()) .setBadgeDurationSeconds(oneTimeDonationConfiguration.boost().expiration().toSeconds()).build()); - donationLevels.put(oneTimeDonationConfiguration.gift().level(), + donationLevels.put(ReceiptLevel.ONE_TIME_GIFT_DONATION.getValue(), LevelConfiguration.newBuilder() .setBadgeId(oneTimeDonationConfiguration.gift().badge()) .setBadgeDurationSeconds(oneTimeDonationConfiguration.gift().expiration().toSeconds()).build()); @@ -92,7 +93,7 @@ public class ProductConfigurationGrpcService extends SimpleProductConfigurationG private static LoginConfiguration buildLoginConfiguration( final LoginPurchaseConfiguration loginPurchaseConfiguration) { return LoginConfiguration.newBuilder() - .setLevel(loginPurchaseConfiguration.level()) + .setLevel(ReceiptLevel.LOGIN.getValue()) .setPlayProductId(loginPurchaseConfiguration.playProductId()) .setAppStoreProductId(loginPurchaseConfiguration.appStoreProductId()) .build(); diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/SubscriptionsUtil.java b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/SubscriptionsUtil.java index b8de29c74..896b3824d 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/SubscriptionsUtil.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/SubscriptionsUtil.java @@ -31,6 +31,7 @@ import org.whispersystems.textsecuregcm.subscriptions.CustomerAwareSubscriptionP import org.whispersystems.textsecuregcm.subscriptions.LevelConfiguration; import org.whispersystems.textsecuregcm.subscriptions.PaymentMethod; import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider; +import org.whispersystems.textsecuregcm.subscriptions.ReceiptLevel; import org.whispersystems.textsecuregcm.util.ua.ClientPlatform; import org.whispersystems.textsecuregcm.util.ua.UnrecognizedUserAgentException; import org.whispersystems.textsecuregcm.util.ua.UserAgentUtil; @@ -80,8 +81,8 @@ public class SubscriptionsUtil { final OneTimeDonationCurrencyConfiguration currencyConfig = currencyAndConfig.getValue(); final Map> oneTimeLevelsToSuggestedAmounts = Map.of( - oneTimeDonationConfiguration.boost().level(), currencyConfig.boosts(), - oneTimeDonationConfiguration.gift().level(), List.of(currencyConfig.gift()) + ReceiptLevel.ONE_TIME_DONATION.getValue(), currencyConfig.boosts(), + ReceiptLevel.ONE_TIME_GIFT_DONATION.getValue(), List.of(currencyConfig.gift()) ); final Function, Map> extractSubscriptionAmounts = levels -> @@ -125,7 +126,7 @@ public class SubscriptionsUtil { final Badge boostBadge = badgeTranslator.translate(acceptableLanguages, oneTimeDonationConfiguration.boost().badge()); - donationLevels.put(oneTimeDonationConfiguration.boost().level(), + donationLevels.put(ReceiptLevel.ONE_TIME_DONATION.getValue(), new LevelConfiguration( // NB: the one-time badges are PurchasableBadge, which has a `duration` field new PurchasableBadge( @@ -133,7 +134,7 @@ public class SubscriptionsUtil { oneTimeDonationConfiguration.boost().expiration()))); final Badge giftBadge = badgeTranslator.translate(acceptableLanguages, oneTimeDonationConfiguration.gift().badge()); - donationLevels.put(oneTimeDonationConfiguration.gift().level(), + donationLevels.put(ReceiptLevel.ONE_TIME_GIFT_DONATION.getValue(), new LevelConfiguration( new PurchasableBadge( giftBadge, diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/AppleAppStoreManager.java b/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/AppleAppStoreManager.java index 57d3148d0..f2c16dcfc 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/AppleAppStoreManager.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/AppleAppStoreManager.java @@ -44,13 +44,13 @@ public class AppleAppStoreManager implements SubscriptionPaymentProcessor, OneTi private static final String LOOKUP_TYPE_TAG = "lookup_type"; private final AppleAppStoreClient appleAppStoreClient; - private final Map productIdToLevel; + private final Map productIdToLevel; private final String subscriptionGroupId; public AppleAppStoreManager( - AppleAppStoreClient appleAppStoreClient, + final AppleAppStoreClient appleAppStoreClient, final String subscriptionGroupId, - final Map productIdToLevel) { + final Map productIdToLevel) { this.appleAppStoreClient = appleAppStoreClient; this.subscriptionGroupId = subscriptionGroupId; this.productIdToLevel = productIdToLevel; @@ -78,7 +78,7 @@ public class AppleAppStoreManager implements SubscriptionPaymentProcessor, OneTi if (!isSubscriptionActive(tx)) { throw new SubscriptionPaymentRequiredException(); } - return getLevel(tx.transaction()); + return getLevel(tx.transaction()).getValue(); } @@ -123,7 +123,7 @@ public class AppleAppStoreManager implements SubscriptionPaymentProcessor, OneTi return new SubscriptionInformation( getSubscriptionPrice(tx), - getLevel(tx.transaction()), + getLevel(tx.transaction()).getValue(), Instant.ofEpochMilli(tx.transaction().getOriginalPurchaseDate()), Instant.ofEpochMilli(tx.transaction().getExpiresDate()), isSubscriptionActive(tx), @@ -150,7 +150,7 @@ public class AppleAppStoreManager implements SubscriptionPaymentProcessor, OneTi final String itemId = tx.transaction().getWebOrderLineItemId(); final PaymentTime paymentTime = PaymentTime.periodEnds(Instant.ofEpochMilli(tx.transaction().getExpiresDate())); - return new ReceiptItem(itemId, paymentTime, getLevel(tx.transaction())); + return new ReceiptItem(itemId, paymentTime, getLevel(tx.transaction()).getValue()); } @@ -225,8 +225,8 @@ public class AppleAppStoreManager implements SubscriptionPaymentProcessor, OneTi SubscriptionCurrencyUtil.convertConfiguredAmountToApiAmount(tx.transaction().getCurrency(), amount)); } - private long getLevel(final JWSTransactionDecodedPayload tx) { - final Long level = productIdToLevel.get(tx.getProductId()); + private ReceiptLevel getLevel(final JWSTransactionDecodedPayload tx) { + final ReceiptLevel level = productIdToLevel.get(tx.getProductId()); if (level == null) { throw new UncheckedIOException(new IOException( "Transaction for unknown productId " + tx.getProductId())); diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/BraintreeManager.java b/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/BraintreeManager.java index 49cc58d36..f2b9aac07 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/BraintreeManager.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/BraintreeManager.java @@ -139,15 +139,12 @@ public class BraintreeManager implements CustomerAwareSubscriptionPaymentProcess chargeFailure = createChargeFailure(transaction); } - final Long level; - try { - level = Optional.ofNullable(transaction.getCustomFields()) - .map(m -> m.get(BraintreeGraphqlClient.LEVEL_METADATA_NAME)) - .map(Long::parseLong) - .orElse(null); - } catch (final NumberFormatException e) { - throw new IllegalStateException("failed to parse level metadata on payment intent %s".formatted(paymentId), e); - } + final ReceiptLevel level = Optional.ofNullable(transaction.getCustomFields()) + .map(m -> m.get(BraintreeGraphqlClient.LEVEL_METADATA_NAME)) + .map(Long::parseLong) + .flatMap(ReceiptLevel::lookupLevel) + .orElseThrow(() -> new IllegalStateException( + "failed to retrieve level metadata from payment intent %s".formatted(paymentId))); return Optional.of(new PaymentDetails(transaction.getGraphQLId(), level, diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/GooglePlayBillingManager.java b/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/GooglePlayBillingManager.java index 1179bbb70..518b119a4 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/GooglePlayBillingManager.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/GooglePlayBillingManager.java @@ -65,7 +65,7 @@ public class GooglePlayBillingManager implements SubscriptionPaymentProcessor, O private final AndroidPublisher androidPublisher; private final String packageName; - private final Map productIdToLevel; + private final Map productIdToLevel; private final Clock clock; private static final String VALIDATE_COUNTER_NAME = MetricsUtil.name(GooglePlayBillingManager.class, "validate"); @@ -77,7 +77,7 @@ public class GooglePlayBillingManager implements SubscriptionPaymentProcessor, O final InputStream credentialsStream, final String packageName, final String applicationName, - final Map productIdToLevel) + final Map productIdToLevel) throws GeneralSecurityException, IOException { this(new AndroidPublisher.Builder( GoogleNetHttpTransport.newTrustedTransport(), @@ -95,7 +95,7 @@ public class GooglePlayBillingManager implements SubscriptionPaymentProcessor, O final AndroidPublisher androidPublisher, final Clock clock, final String packageName, - final Map productIdToLevel) { + final Map productIdToLevel) { this.clock = clock; this.androidPublisher = androidPublisher; this.productIdToLevel = productIdToLevel; @@ -189,9 +189,9 @@ public class GooglePlayBillingManager implements SubscriptionPaymentProcessor, O }; final SubscriptionPurchaseLineItem purchase = getLineItem(subscription); - final long level = productIdToLevel(purchase.getProductId()); + final ReceiptLevel level = productIdToLevel(purchase.getProductId()); - return new ValidatedToken(level, purchase.getProductId(), purchaseToken, requiresAck); + return new ValidatedToken(level.getValue(), purchase.getProductId(), purchaseToken, requiresAck); } @@ -255,7 +255,7 @@ public class GooglePlayBillingManager implements SubscriptionPaymentProcessor, O .orElse(false); return new SubscriptionInformation( price, - productIdToLevel(lineItem.getProductId()), + productIdToLevel(lineItem.getProductId()).getValue(), billingCycleAnchor.orElse(null), expiration.orElse(null), expiration.map(clock.instant()::isBefore).orElse(false), @@ -308,7 +308,7 @@ public class GooglePlayBillingManager implements SubscriptionPaymentProcessor, O return new ReceiptItem( subscription.getLatestOrderId(), PaymentTime.periodEnds(expiration), - productIdToLevel(purchase.getProductId())); + productIdToLevel(purchase.getProductId()).getValue()); } @@ -337,7 +337,7 @@ public class GooglePlayBillingManager implements SubscriptionPaymentProcessor, O final ProductLineItem lineItem = getLineItem(productPurchaseV2); final String productId = lineItem.getProductId(); - final long level = productIdToLevel(productId); + final ReceiptLevel level = productIdToLevel(productId); Instant purchaseTime = null; if (paymentStatus == PaymentStatus.SUCCEEDED) { @@ -421,8 +421,8 @@ public class GooglePlayBillingManager implements SubscriptionPaymentProcessor, O return executeTokenOperation(publisher -> publisher.purchases().subscriptionsv2().get(packageName, purchaseToken)); } - private long productIdToLevel(final String productId) { - final Long level = this.productIdToLevel.get(productId); + private ReceiptLevel productIdToLevel(final String productId) { + final ReceiptLevel level = this.productIdToLevel.get(productId); if (level == null) { logger.error("productId={} had no associated level", productId); // This was a productId a user was able to successfully purchase from our catalog, diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/LoginPurchaseManager.java b/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/LoginPurchaseManager.java index a277a4035..53417a48e 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/LoginPurchaseManager.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/LoginPurchaseManager.java @@ -24,7 +24,6 @@ public class LoginPurchaseManager { private final Map oneTimePaymentProcessors; private final IssuedReceiptsManager issuedReceiptsManager; private final ServerZkReceiptOperations zkReceiptOperations; - private final long loginLevel; // Signal Login receipt credentials expire after 5 years @VisibleForTesting @@ -35,17 +34,13 @@ public class LoginPurchaseManager { /// @param oneTimePaymentProcessors The processor to use for each supported [PaymentProvider] /// @param issuedReceiptsManager Tracks which purchases have already had receipt credentials issued for them /// @param zkReceiptOperations Used to issue receipt credentials - /// @param loginLevel The receipt level that identifies a Signal Login purchase. Purchases for any other - /// level are rejected. public LoginPurchaseManager( final Map oneTimePaymentProcessors, final IssuedReceiptsManager issuedReceiptsManager, - final ServerZkReceiptOperations zkReceiptOperations, - final long loginLevel) { + final ServerZkReceiptOperations zkReceiptOperations) { this.oneTimePaymentProcessors = oneTimePaymentProcessors; this.issuedReceiptsManager = issuedReceiptsManager; this.zkReceiptOperations = zkReceiptOperations; - this.loginLevel = loginLevel; } /// Verify a completed one-time purchase and issue a receipt credential for it. @@ -80,7 +75,7 @@ public class LoginPurchaseManager { .map( cf -> new SubscriptionChargeFailurePaymentRequiredException(paymentProvider, cf)) .orElseGet(SubscriptionPaymentRequiredException::new); - } else if (paymentDetails.level() == null || paymentDetails.level() != loginLevel) { + } else if (paymentDetails.level() != ReceiptLevel.LOGIN) { throw new SubscriptionInvalidArgumentsException("purchase was for an unexpected product"); } @@ -97,6 +92,6 @@ public class LoginPurchaseManager { } return zkReceiptOperations.issueReceiptCredential(receiptCredentialRequest, expiration.getEpochSecond(), - loginLevel); + ReceiptLevel.LOGIN.getValue()); } } diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/PaymentDetails.java b/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/PaymentDetails.java index 4169cb155..06c8e0e51 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/PaymentDetails.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/PaymentDetails.java @@ -11,14 +11,14 @@ import javax.annotation.Nullable; * Payment details for a one-time payment specified by id * * @param id The id of the payment in the payment processor - * @param level The level identifier of purchase, if it could be identified from the processor. + * @param level The level identifier of purchase * @param status The status of the payment in the payment processor * @param created When the payment was created * @param chargeFailure If present, additional information about why the payment failed. Will not be set if the status * is not {@link PaymentStatus#SUCCEEDED} */ public record PaymentDetails(String id, - @Nullable Long level, + ReceiptLevel level, PaymentStatus status, @Nullable Instant created, @Nullable ChargeFailure chargeFailure) {} diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/ReceiptLevel.java b/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/ReceiptLevel.java new file mode 100644 index 000000000..706e0c454 --- /dev/null +++ b/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/ReceiptLevel.java @@ -0,0 +1,41 @@ +/* + * Copyright 2026 Signal Messenger, LLC + * SPDX-License-Identifier: AGPL-3.0-only + */ +package org.whispersystems.textsecuregcm.subscriptions; + +import java.util.Arrays; +import java.util.Optional; + +/// This enum represents all supported purchasable items. Purchases of these items are encoded into a zero-knowledge +/// [org.signal.libsignal.zkgroup.receipts.ReceiptCredential], and the long `value` on these items map to the `level` +/// field of these credentials. +/// +/// Note: the numeric `level` now mostly serves as a unique identifier for specific item-type, rather than +/// representing a comparable/ordinal value (which mostly only applies to the donation subscription levels) +public enum ReceiptLevel { + ONE_TIME_DONATION(1L), + ONE_TIME_GIFT_DONATION(100L), + BACKUP_FREE(200L), + BACKUP_PAID(201L), + LOGIN(300L), + SUBSCRIPTION_LOW(500), + SUBSCRIPTION_MEDIUM(1000), + SUBSCRIPTION_HIGH(2000); + + private static final ReceiptLevel[] VALUES = ReceiptLevel.values(); + + private final long value; + + private ReceiptLevel(long value) { + this.value = value; + } + + public long getValue() { + return value; + } + + public static Optional lookupLevel(final long level) { + return Arrays.stream(VALUES).filter(r -> r.value == level).findFirst(); + } +} diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/StripeManager.java b/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/StripeManager.java index 600192154..e1d568158 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/StripeManager.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/subscriptions/StripeManager.java @@ -253,15 +253,12 @@ public class StripeManager implements CustomerAwareSubscriptionPaymentProcessor, } } - final Long level; - try { - level = Optional.ofNullable(paymentIntent.getMetadata()) - .map(m -> m.get(METADATA_KEY_LEVEL)) - .map(Long::parseLong) - .orElse(null); - } catch (final NumberFormatException e) { - throw new IllegalStateException("failed to parse level metadata on payment intent %s".formatted(paymentIntentId), e); - } + final ReceiptLevel level = Optional.ofNullable(paymentIntent.getMetadata()) + .map(m -> m.get(METADATA_KEY_LEVEL)) + .map(Long::parseLong) + .flatMap(ReceiptLevel::lookupLevel) + .orElseThrow(() -> new IllegalStateException( + "failed to retrieve level metadata from payment intent %s".formatted(paymentIntentId))); return Optional.of(new PaymentDetails(paymentIntent.getId(), level, diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/controllers/DeviceCheckControllerTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/controllers/DeviceCheckControllerTest.java index cc8d5909b..328a25347 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/controllers/DeviceCheckControllerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/controllers/DeviceCheckControllerTest.java @@ -61,7 +61,6 @@ import org.whispersystems.textsecuregcm.util.TestRandomUtil; class DeviceCheckControllerTest { private final static Duration REDEMPTION_DURATION = Duration.ofDays(5); - private final static long REDEMPTION_LEVEL = 201L; private static final AccountsManager accountsManager = mock(AccountsManager.class); private final static BackupAuthManager backupAuthManager = mock(BackupAuthManager.class); private final static AppleDeviceCheckManager appleDeviceCheckManager = mock(AppleDeviceCheckManager.class); @@ -78,7 +77,7 @@ class DeviceCheckControllerTest { .setMapper(SystemMapper.jsonMapper()) .setTestContainerFactory(new GrizzlyWebTestContainerFactory()) .addResource(new DeviceCheckController(clock, accountsManager, backupAuthManager, appleDeviceCheckManager, rateLimiters, - REDEMPTION_LEVEL, REDEMPTION_DURATION)) + REDEMPTION_DURATION)) .build(); @BeforeEach 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 bcc3e7fc3..0e85a7538 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/controllers/DonationControllerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/controllers/DonationControllerTest.java @@ -55,6 +55,7 @@ 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.subscriptions.ReceiptLevel; import org.whispersystems.textsecuregcm.tests.util.AccountsHelper; import org.whispersystems.textsecuregcm.tests.util.AuthHelper; import org.whispersystems.textsecuregcm.util.TestClock; @@ -75,7 +76,7 @@ class DonationControllerTest { List.of(new BadgeSvg("sl", "sd"), new BadgeSvg("ml", "md"), new BadgeSvg("ll", "ld"))), new BadgeConfiguration("TEST3", "testing", List.of("l", "m", "h", "x", "xx", "xxx"), "SVG", List.of(new BadgeSvg("sl", "sd"), new BadgeSvg("ml", "md"), new BadgeSvg("ll", "ld")))), - Map.of(1L, "TEST1", 2L, "TEST2", 3L, "TEST3")); + Map.of(ReceiptLevel.ONE_TIME_DONATION, "TEST1", ReceiptLevel.ONE_TIME_GIFT_DONATION, "TEST2", ReceiptLevel.SUBSCRIPTION_HIGH, "TEST3")); } private final TestClock clock = TestClock.pinned(Instant.ofEpochSecond(nowEpochSeconds)); 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 37dbe9f3c..7230727ca 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/controllers/OneTimeDonationControllerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/controllers/OneTimeDonationControllerTest.java @@ -54,6 +54,7 @@ import org.whispersystems.textsecuregcm.subscriptions.PaymentDetails; import org.whispersystems.textsecuregcm.subscriptions.PaymentMethod; import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider; import org.whispersystems.textsecuregcm.subscriptions.PaymentStatus; +import org.whispersystems.textsecuregcm.subscriptions.ReceiptLevel; import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidAmountException; import org.whispersystems.textsecuregcm.subscriptions.SubscriptionProcessorException; import org.whispersystems.textsecuregcm.tests.util.AuthHelper; @@ -342,7 +343,7 @@ class OneTimeDonationControllerTest extends AbstractV1SubscriptionControllerTest when(ONE_TIME_DONATIONS_MANAGER.getPaidAt(any(), anyString(), any())).thenReturn(Instant.now()); when(STRIPE_MANAGER.claimOneTimePurchase(any())).thenReturn(Optional.of(new PaymentDetails( "id", - ONETIME_CONFIG.boost().level(), + ReceiptLevel.ONE_TIME_DONATION, PaymentStatus.SUCCEEDED, Instant.now(), null))); diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/controllers/ProfileControllerTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/controllers/ProfileControllerTest.java index 9f9471f3f..7cc5bb37a 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/controllers/ProfileControllerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/controllers/ProfileControllerTest.java @@ -111,6 +111,7 @@ import org.whispersystems.textsecuregcm.storage.DeviceCapability; import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager; import org.whispersystems.textsecuregcm.storage.ProfilesManager; import org.whispersystems.textsecuregcm.storage.VersionedProfileV1; +import org.whispersystems.textsecuregcm.subscriptions.ReceiptLevel; import org.whispersystems.textsecuregcm.tests.util.AccountsHelper; import org.whispersystems.textsecuregcm.tests.util.AuthHelper; import org.whispersystems.textsecuregcm.tests.util.ProfileTestHelper; @@ -186,7 +187,10 @@ class ProfileControllerTest { new BadgeConfiguration("TEST1", "testing", List.of("l", "m", "h", "x", "xx", "xxx"), "SVG", List.of(new BadgeSvg("sl", "sd"), new BadgeSvg("ml", "md"), new BadgeSvg("ll", "ld"))), new BadgeConfiguration("TEST2", "testing", List.of("l", "m", "h", "x", "xx", "xxx"), "SVG", List.of(new BadgeSvg("sl", "sd"), new BadgeSvg("ml", "md"), new BadgeSvg("ll", "ld"))), new BadgeConfiguration("TEST3", "testing", List.of("l", "m", "h", "x", "xx", "xxx"), "SVG", List.of(new BadgeSvg("sl", "sd"), new BadgeSvg("ml", "md"), new BadgeSvg("ll", "ld"))) - ), Map.of(1L, "TEST1", 2L, "TEST2", 3L, "TEST3")), + ), Map.of( + ReceiptLevel.ONE_TIME_DONATION, "TEST1", + ReceiptLevel.SUBSCRIPTION_MEDIUM, "TEST2", + ReceiptLevel.SUBSCRIPTION_HIGH, "TEST3")), postPolicyGenerator, serverSecretParams, zkProfileOperations, 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 0da8679fc..61529dff4 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/controllers/SubscriptionControllerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/controllers/SubscriptionControllerTest.java @@ -81,6 +81,7 @@ import org.whispersystems.textsecuregcm.subscriptions.LevelConfiguration; import org.whispersystems.textsecuregcm.subscriptions.PaymentMethod; import org.whispersystems.textsecuregcm.subscriptions.PaymentProvider; import org.whispersystems.textsecuregcm.subscriptions.ProcessorCustomer; +import org.whispersystems.textsecuregcm.subscriptions.ReceiptLevel; import org.whispersystems.textsecuregcm.subscriptions.SubscriptionChargeFailurePaymentRequiredException; import org.whispersystems.textsecuregcm.subscriptions.SubscriptionException; import org.whispersystems.textsecuregcm.subscriptions.SubscriptionInvalidArgumentsException; @@ -111,7 +112,7 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest { private static final BadgeTranslator BADGE_TRANSLATOR = mock(BadgeTranslator.class); private static final BankMandateTranslator BANK_MANDATE_TRANSLATOR = mock(BankMandateTranslator.class); private static final LoginPurchaseConfiguration LOGIN_PURCHASE_CONFIG = - new LoginPurchaseConfiguration(300L, "testLoginPlayProductId", "testLoginAppStoreProductId"); + new LoginPurchaseConfiguration("testLoginPlayProductId", "testLoginAppStoreProductId"); private final static SubscriptionController SUBSCRIPTION_CONTROLLER = new SubscriptionController(CLOCK, SUBSCRIPTION_CONFIG, ONETIME_CONFIG, LOGIN_PURCHASE_CONFIG, new SubscriptionManager(SUBSCRIPTIONS, List.of(STRIPE_MANAGER, BRAINTREE_MANAGER, PLAY_MANAGER, APPSTORE_MANAGER), @@ -1077,7 +1078,7 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest { }); assertThat(response.backup().freeTierMediaDays()).isEqualTo(30); - assertThat(response.login().level()).isEqualTo(LOGIN_PURCHASE_CONFIG.level()); + assertThat(response.login().level()).isEqualTo(ReceiptLevel.LOGIN.getValue()); assertThat(response.login().playProductId()).isEqualTo(LOGIN_PURCHASE_CONFIG.playProductId()); assertThat(response.login().appStoreProductId()).isEqualTo(LOGIN_PURCHASE_CONFIG.appStoreProductId()); 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 066f015e7..bba0c8029 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/grpc/DonationsGrpcServiceTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/DonationsGrpcServiceTest.java @@ -48,6 +48,7 @@ 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.subscriptions.ReceiptLevel; import org.whispersystems.textsecuregcm.tests.util.AccountsHelper; import org.whispersystems.textsecuregcm.util.TestClock; import org.whispersystems.textsecuregcm.util.TestRandomUtil; @@ -95,8 +96,8 @@ class DonationsGrpcServiceTest extends SimpleBaseGrpcTest 0); - assertEquals(LOGIN_PURCHASE_CONFIGURATION.level(), configuration.getLogin().getLevel()); + assertEquals(ReceiptLevel.LOGIN.getValue(), configuration.getLogin().getLevel()); assertEquals(LOGIN_PURCHASE_CONFIGURATION.playProductId(), configuration.getLogin().getPlayProductId()); assertEquals(LOGIN_PURCHASE_CONFIGURATION.appStoreProductId(), configuration.getLogin().getAppStoreProductId()); } diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/grpc/ProfileGrpcServiceTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/ProfileGrpcServiceTest.java index 498f62aaf..47f101b26 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/grpc/ProfileGrpcServiceTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/ProfileGrpcServiceTest.java @@ -103,6 +103,7 @@ import org.whispersystems.textsecuregcm.storage.ProfilesManager; import org.whispersystems.textsecuregcm.storage.VersionedProfile; import org.whispersystems.textsecuregcm.storage.VersionedProfileV1; import org.whispersystems.textsecuregcm.storage.WriteConflictException; +import org.whispersystems.textsecuregcm.subscriptions.ReceiptLevel; import org.whispersystems.textsecuregcm.tests.util.AuthHelper; import org.whispersystems.textsecuregcm.tests.util.ProfileTestHelper; import org.whispersystems.textsecuregcm.util.MockUtils; @@ -167,7 +168,7 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest products = List.of("otherProduct1", PRODUCT_ID, "otherProduct3"); + final List products = List.of("otherProduct1", SUBSCRIPTION_PRODUCT_ID, "otherProduct3"); when(apiClient.getAllSubscriptionStatuses(ORIGINAL_TX_ID, new Status[]{})) .thenReturn(new StatusResponse().data(List.of(new SubscriptionGroupIdentifierItem() @@ -170,7 +172,8 @@ class AppleAppStoreManagerTest { .signedTransactionInfo(SIGNED_TX_INFO)))) .environment(Environment.PRODUCTION)); mockDecode(AutoRenewStatus.ON); - assertThat(appleAppStoreManager.validateTransaction(ORIGINAL_TX_ID)).isEqualTo(LEVEL); + assertThat(appleAppStoreManager.validateTransaction(ORIGINAL_TX_ID)) + .isEqualTo(ReceiptLevel.BACKUP_PAID.getValue()); } @Test @@ -201,7 +204,7 @@ class AppleAppStoreManagerTest { .thenReturn(new TransactionInfoResponse().signedTransactionInfo(SIGNED_TX_INFO)); final JWSTransactionDecodedPayload payload = new JWSTransactionDecodedPayload() .transactionId(TRANSACTION_ID) - .productId(PRODUCT_ID) + .productId(ONE_TIME_PRODUCT_ID) .type(Type.CONSUMABLE) .inAppOwnershipType(InAppOwnershipType.PURCHASED) .purchaseDate(Instant.EPOCH.plus(Duration.ofDays(1)).toEpochMilli()); @@ -211,7 +214,7 @@ class AppleAppStoreManagerTest { // PURCHASED payment final PaymentDetails paymentDetails = appleAppStoreManager.claimOneTimePurchase(TRANSACTION_ID).orElseThrow(); assertThat(paymentDetails.id()).isEqualTo(TRANSACTION_ID); - assertThat(paymentDetails.level()).isEqualTo(LEVEL); + assertThat(paymentDetails.level()).isEqualTo(ReceiptLevel.LOGIN); assertThat(paymentDetails.created()).isEqualTo(Instant.EPOCH.plus(Duration.ofDays(1))); assertThat(paymentDetails.chargeFailure()).isNull(); assertThat(paymentDetails.status()).isEqualTo(PaymentStatus.SUCCEEDED); @@ -247,7 +250,7 @@ class AppleAppStoreManagerTest { private void mockDecode(final AutoRenewStatus autoRenewStatus) throws VerificationException { when(signedDataVerifier.verifyAndDecodeTransaction(SIGNED_TX_INFO)) .thenReturn(new JWSTransactionDecodedPayload() - .productId(PRODUCT_ID) + .productId(SUBSCRIPTION_PRODUCT_ID) .currency("usd").price(1500L) // $1.50 .originalPurchaseDate(Instant.EPOCH.toEpochMilli()) .expiresDate(Instant.EPOCH.plus(Duration.ofDays(1)).toEpochMilli()) diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/subscriptions/GooglePlayBillingManagerTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/subscriptions/GooglePlayBillingManagerTest.java index af523dd5b..2b1903fbe 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/subscriptions/GooglePlayBillingManagerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/subscriptions/GooglePlayBillingManagerTest.java @@ -49,7 +49,8 @@ import org.whispersystems.textsecuregcm.util.MutableClock; class GooglePlayBillingManagerTest { - private static final String PRODUCT_ID = "productId"; + private static final String SUBSCRIPTION_PRODUCT_ID = "subscriptionProductId"; + private static final String ONE_TIME_PRODUCT_ID = "oneTimeProductId"; private static final String PACKAGE_NAME = "package.name"; private static final String PURCHASE_TOKEN = "purchaseToken"; private static final String ORDER_ID = "orderId"; @@ -96,9 +97,9 @@ class GooglePlayBillingManagerTest { AndroidPublisher.Purchases.Subscriptions subscriptions = mock(AndroidPublisher.Purchases.Subscriptions.class); when(purchases.subscriptions()).thenReturn(subscriptions); - when(subscriptions.acknowledge(eq(PACKAGE_NAME), eq(PRODUCT_ID), eq(PURCHASE_TOKEN), any())) + when(subscriptions.acknowledge(eq(PACKAGE_NAME), any(), eq(PURCHASE_TOKEN), any())) .thenReturn(acknowledge); - when(subscriptions.cancel(PACKAGE_NAME, PRODUCT_ID, PURCHASE_TOKEN)) + when(subscriptions.cancel(eq(PACKAGE_NAME), any(), eq(PURCHASE_TOKEN))) .thenReturn(cancel); AndroidPublisher.Purchases.Productsv2 productsv2 = mock(AndroidPublisher.Purchases.Productsv2.class); @@ -107,10 +108,11 @@ class GooglePlayBillingManagerTest { AndroidPublisher.Purchases.Products products = mock(AndroidPublisher.Purchases.Products.class); when(purchases.products()).thenReturn(products); - when(products.consume(PACKAGE_NAME, PRODUCT_ID, PURCHASE_TOKEN)).thenReturn(consume); + when(products.consume(PACKAGE_NAME, ONE_TIME_PRODUCT_ID, PURCHASE_TOKEN)).thenReturn(consume); - googlePlayBillingManager = new GooglePlayBillingManager( - androidPublisher, clock, PACKAGE_NAME, Map.of(PRODUCT_ID, 201L)); + googlePlayBillingManager = new GooglePlayBillingManager(androidPublisher, clock, PACKAGE_NAME, Map.of( + SUBSCRIPTION_PRODUCT_ID, ReceiptLevel.BACKUP_PAID, + ONE_TIME_PRODUCT_ID, ReceiptLevel.LOGIN)); } @Test @@ -120,7 +122,7 @@ class GooglePlayBillingManagerTest { .setSubscriptionState(GooglePlayBillingManager.SubscriptionState.ACTIVE.apiString()) .setLineItems(List.of(new SubscriptionPurchaseLineItem() .setExpiryTime(Instant.now().plus(Duration.ofDays(1)).toString()) - .setProductId(PRODUCT_ID)))); + .setProductId(SUBSCRIPTION_PRODUCT_ID)))); final GooglePlayBillingManager.ValidatedToken result = googlePlayBillingManager.validateToken(PURCHASE_TOKEN); @@ -137,7 +139,7 @@ class GooglePlayBillingManagerTest { .setSubscriptionState(subscriptionState.apiString()) .setLineItems(List.of(new SubscriptionPurchaseLineItem() .setExpiryTime(Instant.now().plus(Duration.ofDays(1)).toString()) - .setProductId(PRODUCT_ID)))); + .setProductId(SUBSCRIPTION_PRODUCT_ID)))); switch (subscriptionState) { case ACTIVE, IN_GRACE_PERIOD, CANCELED -> assertThatNoException() @@ -154,7 +156,7 @@ class GooglePlayBillingManagerTest { .setSubscriptionState(GooglePlayBillingManager.SubscriptionState.ACTIVE.apiString()) .setLineItems(List.of(new SubscriptionPurchaseLineItem() .setExpiryTime(Instant.now().plus(Duration.ofDays(1)).toString()) - .setProductId(PRODUCT_ID)))); + .setProductId(SUBSCRIPTION_PRODUCT_ID)))); final GooglePlayBillingManager.ValidatedToken result = googlePlayBillingManager.validateToken(PURCHASE_TOKEN); @@ -171,7 +173,7 @@ class GooglePlayBillingManagerTest { .setSubscriptionState(subscriptionState.apiString()) .setLineItems(List.of(new SubscriptionPurchaseLineItem() .setExpiryTime(Instant.now().plus(Duration.ofDays(1)).toString()) - .setProductId(PRODUCT_ID)))); + .setProductId(SUBSCRIPTION_PRODUCT_ID)))); assertThatNoException().isThrownBy(() -> googlePlayBillingManager.cancelAllActiveSubscriptions(PURCHASE_TOKEN)); final int wanted = switch (subscriptionState) { @@ -207,7 +209,7 @@ class GooglePlayBillingManagerTest { .setSubscriptionState(GooglePlayBillingManager.SubscriptionState.ACTIVE.apiString()) .setLineItems(List.of(new SubscriptionPurchaseLineItem() .setExpiryTime(Instant.now().plus(Duration.ofDays(1)).toString()) - .setProductId(PRODUCT_ID)))); + .setProductId(SUBSCRIPTION_PRODUCT_ID)))); assertThatExceptionOfType(IllegalStateException.class).isThrownBy(() -> googlePlayBillingManager.getReceiptItem(PURCHASE_TOKEN)); } @@ -224,7 +226,7 @@ class GooglePlayBillingManagerTest { .setLatestOrderId(ORDER_ID) .setLineItems(List.of(new SubscriptionPurchaseLineItem() .setExpiryTime(day10.toString().toString()) - .setProductId(PRODUCT_ID)))); + .setProductId(SUBSCRIPTION_PRODUCT_ID)))); clock.setTimeInstant(day9); SubscriptionPaymentProcessor.ReceiptItem item = googlePlayBillingManager.getReceiptItem(PURCHASE_TOKEN); @@ -260,7 +262,7 @@ class GooglePlayBillingManagerTest { .setAutoRenewingPlan(new AutoRenewingPlan() .setAutoRenewEnabled(null) .setRecurringPrice(new Money().setCurrencyCode("USD").setUnits(1L).setNanos(750_000_000))) - .setProductId(PRODUCT_ID) + .setProductId(SUBSCRIPTION_PRODUCT_ID) .setOfferDetails(new OfferDetails().setBasePlanId(basePlanId))))); final SubscriptionInformation info = googlePlayBillingManager.getSubscriptionInformation(PURCHASE_TOKEN); @@ -300,7 +302,7 @@ class GooglePlayBillingManagerTest { purchaseState.apiString(), consumptionState.apiString(), Instant.EPOCH.plus(Duration.ofDays(3)), - PRODUCT_ID)); + ONE_TIME_PRODUCT_ID)); final PaymentStatus expected = switch (purchaseState) { case PURCHASED -> PaymentStatus.SUCCEEDED; @@ -312,7 +314,7 @@ class GooglePlayBillingManagerTest { assertThat(googlePlayBillingManager.claimOneTimePurchase(PURCHASE_TOKEN)).hasValueSatisfying(details -> { assertThat(details.status()).isEqualTo(expected); assertThat(details.id()).isEqualTo(PURCHASE_TOKEN); - assertThat(details.level()).isEqualTo(201L); + assertThat(details.level()).isEqualTo(ReceiptLevel.LOGIN); }); final boolean expectConsume = purchaseState == GooglePlayBillingManager.PurchaseState.PURCHASED && diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/subscriptions/LoginPurchaseManagerTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/subscriptions/LoginPurchaseManagerTest.java index 8a1f7e271..4dfd35eef 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/subscriptions/LoginPurchaseManagerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/subscriptions/LoginPurchaseManagerTest.java @@ -44,7 +44,6 @@ class LoginPurchaseManagerTest { private static final PaymentProvider PROVIDER = PaymentProvider.APPLE_APP_STORE; private static final String PURCHASE_ID = "purchaseId"; - private static final long LEVEL = 123L; private static final Instant PURCHASED_AT = Instant.now().minus(Duration.ofHours(3)); private static final ChargeFailure CHARGE_FAILURE = new ChargeFailure("generic_decline", "some failure message", null, null, null); @@ -70,14 +69,13 @@ class LoginPurchaseManagerTest { loginPurchaseManager = new LoginPurchaseManager( Map.of(PROVIDER, paymentProcessor), issuedReceiptsManager, - new ServerZkReceiptOperations(SERVER_SECRET_PARAMS), - LEVEL); + new ServerZkReceiptOperations(SERVER_SECRET_PARAMS)); } @Test void generateReceiptSuccess() throws Exception { when(paymentProcessor.claimOneTimePurchase(PURCHASE_ID)) - .thenReturn(Optional.of(new PaymentDetails(PURCHASE_ID, LEVEL, PaymentStatus.SUCCEEDED, PURCHASED_AT, null))); + .thenReturn(Optional.of(new PaymentDetails(PURCHASE_ID, ReceiptLevel.LOGIN, PaymentStatus.SUCCEEDED, PURCHASED_AT, null))); final ReceiptCredentialResponse receipt = loginPurchaseManager.generateReceipt(PROVIDER, PURCHASE_ID, receiptCredentialRequestContext.getRequest()); @@ -88,7 +86,7 @@ class LoginPurchaseManagerTest { .plus(LoginPurchaseManager.LOGIN_EXPIRATION) .truncatedTo(ChronoUnit.DAYS); - assertThat(receiptCredential.getReceiptLevel()).isEqualTo(LEVEL); + assertThat(receiptCredential.getReceiptLevel()).isEqualTo(ReceiptLevel.LOGIN.getValue()); assertThat(receiptCredential.getReceiptExpirationTime()).isEqualTo(expectedExpiration.getEpochSecond()); verify(issuedReceiptsManager).recordOneTimeIssuance( @@ -99,15 +97,15 @@ class LoginPurchaseManagerTest { return Stream.of( Arguments.of(Optional.empty(), SubscriptionNotFoundException.class), Arguments.of( - Optional.of(new PaymentDetails(PURCHASE_ID, LEVEL, PaymentStatus.PROCESSING, PURCHASED_AT, null)), + Optional.of(new PaymentDetails(PURCHASE_ID, ReceiptLevel.LOGIN, PaymentStatus.PROCESSING, PURCHASED_AT, null)), SubscriptionReceiptRequestedForOpenPaymentException.class), Arguments.of( - Optional.of(new PaymentDetails(PURCHASE_ID, LEVEL, PaymentStatus.FAILED, PURCHASED_AT, CHARGE_FAILURE)), + Optional.of(new PaymentDetails(PURCHASE_ID, ReceiptLevel.LOGIN, PaymentStatus.FAILED, PURCHASED_AT, CHARGE_FAILURE)), SubscriptionChargeFailurePaymentRequiredException.class), Arguments.of( - Optional.of(new PaymentDetails(PURCHASE_ID, LEVEL, PaymentStatus.FAILED, PURCHASED_AT, null)), + Optional.of(new PaymentDetails(PURCHASE_ID, ReceiptLevel.LOGIN, PaymentStatus.FAILED, PURCHASED_AT, null)), SubscriptionPaymentRequiredException.class), - Arguments.of(Optional.of(new PaymentDetails(PURCHASE_ID, LEVEL, PaymentStatus.UNKNOWN, PURCHASED_AT, null)), + Arguments.of(Optional.of(new PaymentDetails(PURCHASE_ID, ReceiptLevel.LOGIN, PaymentStatus.UNKNOWN, PURCHASED_AT, null)), SubscriptionPaymentRequiredException.class)); } @@ -132,7 +130,7 @@ class LoginPurchaseManagerTest { @Test void generateReceiptNonLoginLevel() throws Exception { when(paymentProcessor.claimOneTimePurchase(PURCHASE_ID)) - .thenReturn(Optional.of(new PaymentDetails(PURCHASE_ID, LEVEL + 1, PaymentStatus.SUCCEEDED, PURCHASED_AT, null))); + .thenReturn(Optional.of(new PaymentDetails(PURCHASE_ID, ReceiptLevel.ONE_TIME_DONATION, PaymentStatus.SUCCEEDED, PURCHASED_AT, null))); assertThatExceptionOfType(SubscriptionInvalidArgumentsException.class).isThrownBy(() -> loginPurchaseManager.generateReceipt(PROVIDER, PURCHASE_ID, receiptCredentialRequestContext.getRequest())); verifyNoInteractions(issuedReceiptsManager); @@ -141,7 +139,7 @@ class LoginPurchaseManagerTest { @Test void generateReceiptAlreadyRedeemed() throws Exception { when(paymentProcessor.claimOneTimePurchase(PURCHASE_ID)) - .thenReturn(Optional.of(new PaymentDetails(PURCHASE_ID, LEVEL, PaymentStatus.SUCCEEDED, PURCHASED_AT, null))); + .thenReturn(Optional.of(new PaymentDetails(PURCHASE_ID, ReceiptLevel.LOGIN, PaymentStatus.SUCCEEDED, PURCHASED_AT, null))); doThrow(new WriteConflictException()) .when(issuedReceiptsManager).recordOneTimeIssuance(any(), any(), any(), any()); assertThatExceptionOfType(SubscriptionReceiptAlreadyRedeemedException.class).isThrownBy(() -> diff --git a/service/src/test/resources/config/test.yml b/service/src/test/resources/config/test.yml index ec2cdec2b..4b17c2e7b 100644 --- a/service/src/test/resources/config/test.yml +++ b/service/src/test/resources/config/test.yml @@ -80,7 +80,6 @@ appleDeviceCheck: deviceCheck: backupRedemptionDuration: P30D - backupRedemptionLevel: 201 dynamoDbClient: type: local @@ -372,7 +371,7 @@ badges: - light: example-light.svg dark: example-dark.svg receiptLevels: - '1': TEST + ONE_TIME_DONATION: TEST subscription: # configuration for Stripe subscriptions badgeExpiration: P30D @@ -397,18 +396,15 @@ subscription: # configuration for Stripe subscriptions BRAINTREE: plan_example # braintree Plan ID loginPurchase: - level: 300 playProductId: login_example appStoreProductId: login_example oneTimeDonations: sepaMaximumEuros: '10000' boost: - level: 1 expiration: P90D badge: TEST gift: - level: 10 expiration: P90D badge: TEST currencies: