diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/auth/RedemptionRange.java b/service/src/main/java/org/whispersystems/textsecuregcm/auth/RedemptionRange.java new file mode 100644 index 000000000..08a3b0376 --- /dev/null +++ b/service/src/main/java/org/whispersystems/textsecuregcm/auth/RedemptionRange.java @@ -0,0 +1,103 @@ +/* + * Copyright 2025 Signal Messenger, LLC + * SPDX-License-Identifier: AGPL-3.0-only + */ +package org.whispersystems.textsecuregcm.auth; + +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.LocalDate; +import java.time.ZoneOffset; +import java.time.temporal.ChronoUnit; +import java.util.Iterator; +import java.util.Objects; +import java.util.stream.Stream; +import org.jetbrains.annotations.NotNull; + +/// A validated range of days for which a credential may be issued. +public class RedemptionRange implements Iterable { + + public static final Duration MAX_REDEMPTION_DURATION = Duration.ofDays(7); + + /// The first day for which a credential should be issued + private final LocalDate from; + + /// The last day for which a credential should be issued + private final LocalDate end; + + private RedemptionRange(final LocalDate from, final LocalDate end) { + this.from = from; + this.end = end; + } + + /// Construct a {@link RedemptionRange} if the provided day bounds are valid. + /// + /// The redemption bounds must satisfy: + /// - `redemptionEnd` >= `redemptionStart` + /// - `redemptionStart` and `redemptionEnd` are day-aligned + /// - `redemptionStart` is yesterday or later + /// - `redemptionEnd` is tomorrow + `MAX_REDEMPTION_DURATION` or earlier + /// - The number of days requested is less than `MAX_REDEMPTION_DURATION` + /// + /// @param clock Clock to use to get current day + /// @param redemptionStart The first day included in the range + /// @param redemptionEnd The last day included in the range + /// @return A {@link RedemptionRange} that can be used to iterate each day between `redemptionStart` and + /// `redemptionEnd` + /// @throws IllegalArgumentException if the redemption bounds were not valid + public static RedemptionRange inclusive(Clock clock, Instant redemptionStart, Instant redemptionEnd) + throws IllegalArgumentException { + final Instant today = clock.instant().truncatedTo(ChronoUnit.DAYS); + final Instant yesterday = today.minus(Duration.ofDays(1)); + + if (redemptionStart.isAfter(redemptionEnd)) { + throw new IllegalArgumentException("end of range must be after start of range"); + } + + if (!redemptionStart.truncatedTo(ChronoUnit.DAYS).equals(redemptionStart) + || !redemptionEnd.truncatedTo(ChronoUnit.DAYS).equals(redemptionEnd)) { + throw new IllegalArgumentException("timestamps must be day aligned"); + } + + if (redemptionStart.isBefore(yesterday)) { + throw new IllegalArgumentException("start of range too far in the past"); + } + + if (redemptionEnd.isAfter(today.plus(MAX_REDEMPTION_DURATION).plus(Duration.ofDays(1)))) { + throw new IllegalArgumentException("end of range too far in the future"); + } + + if (redemptionEnd.isAfter(redemptionStart.plus(MAX_REDEMPTION_DURATION))) { + throw new IllegalArgumentException("redemption window too large"); + } + + return new RedemptionRange( + LocalDate.ofInstant(redemptionStart, ZoneOffset.UTC), + LocalDate.ofInstant(redemptionEnd, ZoneOffset.UTC)); + } + + @Override + public @NotNull Iterator iterator() { + final Instant fromInstant = from.atStartOfDay(ZoneOffset.UTC).toInstant(); + final Instant endInstant = end.atStartOfDay(ZoneOffset.UTC).toInstant(); + return Stream + .iterate(fromInstant, redemptionTime -> redemptionTime.plus(Duration.ofDays(1))) + .takeWhile(redemptionTime -> !redemptionTime.isAfter(endInstant)) + .iterator(); + } + + @Override + public boolean equals(final Object o) { + if (o == null || getClass() != o.getClass()) { + return false; + } + RedemptionRange that = (RedemptionRange) o; + return Objects.equals(from, that.from) && Objects.equals(end, that.end); + } + + @Override + public int hashCode() { + return Objects.hash(from, end); + } +} diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/backup/BackupAuthManager.java b/service/src/main/java/org/whispersystems/textsecuregcm/backup/BackupAuthManager.java index b3a829c2e..cd8b6d5ea 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/backup/BackupAuthManager.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/backup/BackupAuthManager.java @@ -18,6 +18,7 @@ import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.stream.Stream; +import java.util.stream.StreamSupport; import javax.annotation.Nullable; import org.signal.libsignal.zkgroup.GenericServerSecretParams; import org.signal.libsignal.zkgroup.InvalidInputException; @@ -31,6 +32,7 @@ import org.signal.libsignal.zkgroup.receipts.ReceiptSerial; import org.signal.libsignal.zkgroup.receipts.ServerZkReceiptOperations; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.whispersystems.textsecuregcm.auth.RedemptionRange; import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException; import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager; import org.whispersystems.textsecuregcm.limits.RateLimiter; @@ -177,15 +179,13 @@ public class BackupAuthManager { * * @param account The account to create the credentials for * @param credentialType The type of backup credentials to create - * @param redemptionStart The day (must be truncated to a day boundary) the first credential should be valid - * @param redemptionEnd The day (must be truncated to a day boundary) the last credential should be valid + * @param redemptionRange The time range to return credentials for * @return Credentials and the day on which they may be redeemed */ public CompletableFuture> getBackupAuthCredentials( final Account account, final BackupCredentialType credentialType, - final Instant redemptionStart, - final Instant redemptionEnd) { + final RedemptionRange redemptionRange) { // If the account has an expired payment, clear it before continuing if (hasExpiredVoucher(account)) { @@ -194,17 +194,7 @@ public class BackupAuthManager { if (hasExpiredVoucher(a)) { a.setBackupVoucher(null); } - }).thenCompose(updated -> getBackupAuthCredentials(updated, credentialType, redemptionStart, redemptionEnd)); - } - - final Instant startOfDay = clock.instant().truncatedTo(ChronoUnit.DAYS); - if (redemptionStart.isAfter(redemptionEnd) || - redemptionStart.isBefore(startOfDay) || - redemptionEnd.isAfter(startOfDay.plus(MAX_REDEMPTION_DURATION)) || - !redemptionStart.equals(redemptionStart.truncatedTo(ChronoUnit.DAYS)) || - !redemptionEnd.equals(redemptionEnd.truncatedTo(ChronoUnit.DAYS))) { - - throw Status.INVALID_ARGUMENT.withDescription("invalid redemption window").asRuntimeException(); + }).thenCompose(updated -> getBackupAuthCredentials(updated, credentialType, redemptionRange)); } // fetch the blinded backup-id the account should have previously committed to @@ -216,8 +206,7 @@ public class BackupAuthManager { // create a credential for every day in the requested period final BackupAuthCredentialRequest credentialReq = new BackupAuthCredentialRequest(committedBytes); - return CompletableFuture.completedFuture(Stream - .iterate(redemptionStart, redemptionTime -> !redemptionTime.isAfter(redemptionEnd), curr -> curr.plus(Duration.ofDays(1))) + return CompletableFuture.completedFuture(StreamSupport.stream(redemptionRange.spliterator(), false) .map(redemptionTime -> { // Check if the account has a voucher that's good for a certain receiptLevel at redemption time, otherwise // use the default receipt level diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/controllers/ArchiveController.java b/service/src/main/java/org/whispersystems/textsecuregcm/controllers/ArchiveController.java index a1f7a4ed2..a2db99376 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/controllers/ArchiveController.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/controllers/ArchiveController.java @@ -45,6 +45,7 @@ import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +import java.time.Clock; import java.time.Instant; import java.util.Arrays; import java.util.Base64; @@ -65,6 +66,7 @@ import org.signal.libsignal.zkgroup.backups.BackupCredentialType; import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialPresentation; import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice; import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials; +import org.whispersystems.textsecuregcm.auth.RedemptionRange; import org.whispersystems.textsecuregcm.backup.BackupAuthManager; import org.whispersystems.textsecuregcm.backup.BackupManager; import org.whispersystems.textsecuregcm.backup.CopyParameters; @@ -309,6 +311,13 @@ public class ArchiveController { final Map> credentialsByType = new ConcurrentHashMap<>(); + final RedemptionRange redemptionRange; + try { + redemptionRange = RedemptionRange.inclusive(Clock.systemUTC(), Instant.ofEpochSecond(startSeconds), Instant.ofEpochSecond(endSeconds)); + } catch (IllegalArgumentException e) { + throw new BadRequestException(e.getMessage()); + } + return accountsManager.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier()) .thenCompose(maybeAccount -> { final Account account = maybeAccount @@ -318,7 +327,7 @@ public class ArchiveController { .map(credentialType -> this.backupAuthManager.getBackupAuthCredentials( account, credentialType, - Instant.ofEpochSecond(startSeconds), Instant.ofEpochSecond(endSeconds)) + redemptionRange) .thenAccept(credentials -> { backupMetrics.updateGetCredentialCounter( UserAgentTagUtil.getPlatformTag(userAgent), diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/controllers/CertificateController.java b/service/src/main/java/org/whispersystems/textsecuregcm/controllers/CertificateController.java index 6e44b0222..3f4e91d15 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/controllers/CertificateController.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/controllers/CertificateController.java @@ -24,7 +24,6 @@ import java.security.InvalidKeyException; import java.time.Clock; import java.time.Duration; import java.time.Instant; -import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.List; import java.util.Objects; @@ -36,6 +35,7 @@ import org.signal.libsignal.zkgroup.auth.ServerZkAuthOperations; import org.signal.libsignal.zkgroup.calllinks.CallLinkAuthCredentialResponse; import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice; import org.whispersystems.textsecuregcm.auth.CertificateGenerator; +import org.whispersystems.textsecuregcm.auth.RedemptionRange; import org.whispersystems.textsecuregcm.entities.DeliveryCertificate; import org.whispersystems.textsecuregcm.entities.GroupCredentials; import org.whispersystems.textsecuregcm.identity.IdentityType; @@ -97,17 +97,13 @@ public class CertificateController { @QueryParam("redemptionStartSeconds") long startSeconds, @QueryParam("redemptionEndSeconds") long endSeconds) { - final Instant startOfDay = clock.instant().truncatedTo(ChronoUnit.DAYS); - final Instant redemptionStart = Instant.ofEpochSecond(startSeconds); - final Instant redemptionEnd = Instant.ofEpochSecond(endSeconds); - - if (redemptionStart.isAfter(redemptionEnd) || - redemptionStart.isBefore(startOfDay) || - redemptionEnd.isAfter(startOfDay.plus(MAX_REDEMPTION_DURATION)) || - !redemptionStart.equals(redemptionStart.truncatedTo(ChronoUnit.DAYS)) || - !redemptionEnd.equals(redemptionEnd.truncatedTo(ChronoUnit.DAYS))) { - - throw new BadRequestException(); + final RedemptionRange redemptionRange; + try { + final Instant redemptionStart = Instant.ofEpochSecond(startSeconds); + final Instant redemptionEnd = Instant.ofEpochSecond(endSeconds); + redemptionRange = RedemptionRange.inclusive(clock, redemptionStart, redemptionEnd); + } catch (IllegalArgumentException e) { + throw new BadRequestException(e.getCause()); } final Account account = accountsManager.getByAccountIdentifier(auth.accountIdentifier()) @@ -116,12 +112,10 @@ public class CertificateController { final List credentials = new ArrayList<>(); final List callLinkAuthCredentials = new ArrayList<>(); - Instant redemption = redemptionStart; - final ServiceId.Aci aci = new ServiceId.Aci(account.getIdentifier(IdentityType.ACI)); final ServiceId.Pni pni = new ServiceId.Pni(account.getIdentifier(IdentityType.PNI)); - while (!redemption.isAfter(redemptionEnd)) { + for (Instant redemption : redemptionRange) { AuthCredentialWithPniResponse authCredentialWithPni = serverZkAuthOperations.issueAuthCredentialWithPniZkc(aci, pni, redemption); credentials.add(new GroupCredentials.GroupCredential( authCredentialWithPni.serialize(), @@ -130,8 +124,6 @@ public class CertificateController { callLinkAuthCredentials.add(new GroupCredentials.CallLinkAuthCredential( CallLinkAuthCredentialResponse.issueCredential(aci, redemption, genericServerSecretParams).serialize(), redemption.getEpochSecond())); - - redemption = redemption.plus(Duration.ofDays(1)); } return new GroupCredentials(credentials, callLinkAuthCredentials, pni.getRawUUID()); diff --git a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/BackupsGrpcService.java b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/BackupsGrpcService.java index 9b8716ed9..d7446008f 100644 --- a/service/src/main/java/org/whispersystems/textsecuregcm/grpc/BackupsGrpcService.java +++ b/service/src/main/java/org/whispersystems/textsecuregcm/grpc/BackupsGrpcService.java @@ -6,12 +6,11 @@ package org.whispersystems.textsecuregcm.grpc; import com.google.protobuf.ByteString; import io.grpc.Status; +import io.micrometer.core.instrument.Tag; +import java.time.Clock; import java.time.Instant; import java.util.List; import java.util.stream.Collectors; -import io.micrometer.core.instrument.Metrics; -import io.micrometer.core.instrument.Tag; -import io.micrometer.core.instrument.Tags; import org.signal.chat.backup.GetBackupAuthCredentialsRequest; import org.signal.chat.backup.GetBackupAuthCredentialsResponse; import org.signal.chat.backup.ReactorBackupsGrpc; @@ -24,10 +23,10 @@ import org.signal.libsignal.zkgroup.InvalidInputException; import org.signal.libsignal.zkgroup.backups.BackupAuthCredentialRequest; import org.signal.libsignal.zkgroup.backups.BackupCredentialType; import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialPresentation; +import org.whispersystems.textsecuregcm.auth.RedemptionRange; import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice; import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil; import org.whispersystems.textsecuregcm.backup.BackupAuthManager; -import org.whispersystems.textsecuregcm.controllers.ArchiveController; import org.whispersystems.textsecuregcm.metrics.BackupMetrics; import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil; import org.whispersystems.textsecuregcm.storage.Account; @@ -35,8 +34,6 @@ import org.whispersystems.textsecuregcm.storage.AccountsManager; import org.whispersystems.textsecuregcm.storage.Device; import reactor.core.publisher.Mono; -import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name; - public class BackupsGrpcService extends ReactorBackupsGrpc.BackupsImplBase { private final AccountsManager accountManager; @@ -85,14 +82,20 @@ public class BackupsGrpcService extends ReactorBackupsGrpc.BackupsImplBase { @Override public Mono getBackupAuthCredentials(GetBackupAuthCredentialsRequest request) { final Tag platformTag = UserAgentTagUtil.getPlatformTag(RequestAttributesUtil.getUserAgent().orElse(null)); + final RedemptionRange redemptionRange; + try { + redemptionRange = RedemptionRange.inclusive(Clock.systemUTC(), + Instant.ofEpochSecond(request.getRedemptionStart()), + Instant.ofEpochSecond(request.getRedemptionStop())); + } catch (IllegalArgumentException e) { + throw Status.INVALID_ARGUMENT.withDescription(e.getMessage()).asRuntimeException(); + } return authenticatedAccount().flatMap(account -> { - final Mono> messageCredentials = Mono.fromCompletionStage(() -> backupAuthManager.getBackupAuthCredentials( account, BackupCredentialType.MESSAGES, - Instant.ofEpochSecond(request.getRedemptionStart()), - Instant.ofEpochSecond(request.getRedemptionStop()))) + redemptionRange)) .doOnSuccess(credentials -> backupMetrics.updateGetCredentialCounter(platformTag, BackupCredentialType.MESSAGES, credentials.size())); @@ -100,8 +103,7 @@ public class BackupsGrpcService extends ReactorBackupsGrpc.BackupsImplBase { backupAuthManager.getBackupAuthCredentials( account, BackupCredentialType.MEDIA, - Instant.ofEpochSecond(request.getRedemptionStart()), - Instant.ofEpochSecond(request.getRedemptionStop()))) + redemptionRange)) .doOnSuccess(credentials -> backupMetrics.updateGetCredentialCounter(platformTag, BackupCredentialType.MEDIA, credentials.size())); diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/auth/RedemptionRangeTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/auth/RedemptionRangeTest.java new file mode 100644 index 000000000..8d0ee951b --- /dev/null +++ b/service/src/test/java/org/whispersystems/textsecuregcm/auth/RedemptionRangeTest.java @@ -0,0 +1,95 @@ +/* + * Copyright 2025 Signal Messenger, LLC + * SPDX-License-Identifier: AGPL-3.0-only + */ +package org.whispersystems.textsecuregcm.auth; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.AssertionsForClassTypes.assertThatNoException; + +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.StreamSupport; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.whispersystems.textsecuregcm.util.TestClock; + + +class RedemptionRangeTest { + + static List invalidCredentialTimeWindows() { + final Duration max = RedemptionRange.MAX_REDEMPTION_DURATION; + final Instant day0 = Instant.EPOCH; + final Instant day1 = Instant.EPOCH.plus(Duration.ofDays(1)); + final Instant day2 = Instant.EPOCH.plus(Duration.ofDays(2)); + return List.of( + Arguments.argumentSet("non-truncated start", Instant.ofEpochSecond(100), day0.plus(max), + Instant.ofEpochSecond(100)), + Arguments.argumentSet("non-truncated end", day0, Instant.ofEpochSecond(1).plus(max), + Instant.ofEpochSecond(100)), + Arguments.argumentSet("start too old", day0, day0.plus(max), day2), + Arguments.argumentSet("end too far in the future", day2, day2.plus(max), day0), + Arguments.argumentSet("end before start", day1, day0, day1), + Arguments.argumentSet("window too big", day0, day0.plus(max).plus(Duration.ofDays(1)), day1) + ); + } + + @ParameterizedTest + @MethodSource + void invalidCredentialTimeWindows(final Instant requestRedemptionStart, final Instant requestRedemptionEnd, + final Instant now) { + final Clock clock = TestClock.pinned(now); + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> RedemptionRange.inclusive(clock, requestRedemptionStart, requestRedemptionEnd)); + } + + @Test + void allowUpToMax() { + final Instant now = Instant.EPOCH.plus(Duration.ofDays(1)).plus(Duration.ofSeconds(100)); + final Instant today = now.truncatedTo(ChronoUnit.DAYS); + final Clock clock = TestClock.pinned(now); + for (Duration d = Duration.ofDays(0); + d.compareTo(RedemptionRange.MAX_REDEMPTION_DURATION) <= 0; + d = d.plus(Duration.ofDays(1))) { + final Duration fd = d; + assertThatNoException().isThrownBy(() -> RedemptionRange.inclusive(clock, today, today.plus(fd))); + } + } + + @Test + void allowBackwardsSkew() { + final Instant now = Instant.EPOCH.plus(Duration.ofDays(1)).plus(Duration.ofSeconds(100)); + final Instant yesterday = now.minus(Duration.ofDays(1)).truncatedTo(ChronoUnit.DAYS); + final Clock clock = TestClock.pinned(now); + assertThatNoException().isThrownBy(() -> + RedemptionRange.inclusive(clock, yesterday, yesterday.plus(RedemptionRange.MAX_REDEMPTION_DURATION))); + } + + @Test + void allowForwardsSkew() { + final Instant now = Instant.EPOCH.plus(Duration.ofDays(1)).plus(Duration.ofSeconds(100)); + final Instant tomorrow = now.plus(Duration.ofDays(1)).truncatedTo(ChronoUnit.DAYS); + final Clock clock = TestClock.pinned(now); + assertThatNoException().isThrownBy(() -> + RedemptionRange.inclusive(clock, tomorrow, tomorrow.plus(RedemptionRange.MAX_REDEMPTION_DURATION))); + } + + @Test + void inclusiveRange() { + final Instant now = Instant.EPOCH.plus(Duration.ofDays(1)).plus(Duration.ofSeconds(100)); + final Instant today = now.truncatedTo(ChronoUnit.DAYS); + final Clock clock = TestClock.pinned(now); + for (int numDays = 0; numDays < 7; numDays++) { + final RedemptionRange range = RedemptionRange.inclusive(clock, today, today.plus(Duration.ofDays(numDays))); + final List instants = StreamSupport.stream(range.spliterator(), false).toList(); + assertThat(instants.size()).isEqualTo(numDays + 1); + } + } +} diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/backup/BackupAuthManagerTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/backup/BackupAuthManagerTest.java index 66cef5836..3d79bee40 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/backup/BackupAuthManagerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/backup/BackupAuthManagerTest.java @@ -29,15 +29,12 @@ import java.util.Optional; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.function.Consumer; -import java.util.stream.Stream; import org.assertj.core.api.Assertions; import org.assertj.core.api.ThrowableAssert; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.EnumSource; -import org.junit.jupiter.params.provider.MethodSource; import org.junit.jupiter.params.provider.ValueSource; import org.junitpioneer.jupiter.cartesian.CartesianTest; import org.mockito.ArgumentCaptor; @@ -55,6 +52,7 @@ import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialRequestContext; import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialResponse; import org.signal.libsignal.zkgroup.receipts.ReceiptSerial; import org.signal.libsignal.zkgroup.receipts.ServerZkReceiptOperations; +import org.whispersystems.textsecuregcm.auth.RedemptionRange; import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException; import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager; import org.whispersystems.textsecuregcm.limits.RateLimiter; @@ -71,18 +69,20 @@ import org.whispersystems.textsecuregcm.util.TestRandomUtil; public class BackupAuthManagerTest { + private static final Instant NOW = Instant.now(); + private final UUID aci = UUID.randomUUID(); private final byte[] messagesBackupKey = TestRandomUtil.nextBytes(32); private final byte[] mediaBackupKey = TestRandomUtil.nextBytes(32); private final ServerSecretParams receiptParams = ServerSecretParams.generate(); - private final TestClock clock = TestClock.now(); + private final TestClock clock = TestClock.pinned(NOW); private final BackupAuthTestUtil backupAuthTestUtil = new BackupAuthTestUtil(clock); private final AccountsManager accountsManager = mock(AccountsManager.class); private final RedeemedReceiptsManager redeemedReceiptsManager = mock(RedeemedReceiptsManager.class); @BeforeEach void setUp() { - clock.unpin(); + clock.pin(NOW); reset(accountsManager); reset(redeemedReceiptsManager); } @@ -181,13 +181,13 @@ public class BackupAuthManagerTest { final BackupAuthCredentialRequestContext requestContext = BackupAuthCredentialRequestContext.create(backupKey, aci); - final Instant start = clock.instant().truncatedTo(ChronoUnit.DAYS); - final List creds = authManager.getBackupAuthCredentials(account, - credentialType, start, start.plus(Duration.ofDays(1))).join(); + final RedemptionRange range = range(Duration.ofDays(1)); + final List creds = + authManager.getBackupAuthCredentials(account, credentialType, range(Duration.ofDays(1))).join(); assertThat(creds).hasSize(2); assertThat(requestContext - .receiveResponse(creds.getFirst().credential(), start, backupAuthTestUtil.params.getPublicParams()) + .receiveResponse(creds.getFirst().credential(), range.iterator().next(), backupAuthTestUtil.params.getPublicParams()) .getBackupLevel()) .isEqualTo(BackupLevel.PAID); } @@ -204,10 +204,7 @@ public class BackupAuthManagerTest { .mediaCredential(backupAuthTestUtil.getRequest(mediaBackupKey, aci)) .build(); - assertThat(authManager.getBackupAuthCredentials(account, - credentialType, - clock.instant().truncatedTo(ChronoUnit.DAYS), - clock.instant().plus(Duration.ofDays(1)).truncatedTo(ChronoUnit.DAYS)).join()) + assertThat(authManager.getBackupAuthCredentials(account, credentialType, range(Duration.ofDays(1))).join()) .hasSize(2); } @@ -219,10 +216,8 @@ public class BackupAuthManagerTest { final Account account = new MockAccountBuilder().build(); assertThatExceptionOfType(StatusRuntimeException.class) - .isThrownBy(() -> authManager.getBackupAuthCredentials(account, - credentialType, - clock.instant().truncatedTo(ChronoUnit.DAYS), - clock.instant().plus(Duration.ofDays(1)).truncatedTo(ChronoUnit.DAYS)).join()) + .isThrownBy(() -> + authManager.getBackupAuthCredentials(account, credentialType, range(Duration.ofDays(1))).join()) .extracting(ex -> ex.getStatus().getCode()) .isEqualTo(Status.Code.NOT_FOUND); } @@ -246,12 +241,11 @@ public class BackupAuthManagerTest { .messagesCredential(backupAuthTestUtil.getRequest(messagesBackupKey, aci)) .build(); - final Instant start = clock.instant().truncatedTo(ChronoUnit.DAYS); final List creds = authManager.getBackupAuthCredentials(account, - credentialType, start, start.plus(Duration.ofDays(7))).join(); + credentialType, range(Duration.ofDays(7))).join(); assertThat(creds).hasSize(8); - Instant redemptionTime = start; + Instant redemptionTime = clock.instant().truncatedTo(ChronoUnit.DAYS); for (BackupAuthManager.Credential cred : creds) { assertThat(requestContext .receiveResponse(cred.credential(), redemptionTime, backupAuthTestUtil.params.getPublicParams()) @@ -262,51 +256,10 @@ public class BackupAuthManagerTest { } } - static Stream invalidCredentialTimeWindows() { - final Duration max = Duration.ofDays(7); - final Instant day0 = Instant.EPOCH; - final Instant day1 = Instant.EPOCH.plus(Duration.ofDays(1)); - return Stream.of( - // non-truncated start - Arguments.of(Instant.ofEpochSecond(100), day0.plus(max), Instant.ofEpochSecond(100)), - // non-truncated end - Arguments.of(day0, Instant.ofEpochSecond(1).plus(max), Instant.ofEpochSecond(100)), - // start to old - Arguments.of(day0, day0.plus(max), day1), - // end to new - Arguments.of(day1, day1.plus(max), day0), - // end before start - Arguments.of(day1, day0, day1), - // window too big - Arguments.of(day0, day0.plus(max).plus(Duration.ofDays(1)), Instant.ofEpochSecond(100)) - ); - } - - @ParameterizedTest - @MethodSource - void invalidCredentialTimeWindows(final Instant requestRedemptionStart, final Instant requestRedemptionEnd, - final Instant now) { - final BackupAuthManager authManager = create(); - - final Account account = new MockAccountBuilder() - .messagesCredential(backupAuthTestUtil.getRequest(messagesBackupKey, aci)) - .mediaCredential(backupAuthTestUtil.getRequest(mediaBackupKey, aci)) - .build(); - - clock.pin(now); - assertThatExceptionOfType(StatusRuntimeException.class) - .isThrownBy( - () -> authManager.getBackupAuthCredentials(account, BackupCredentialType.MESSAGES, requestRedemptionStart, requestRedemptionEnd).join()) - .extracting(ex -> ex.getStatus().getCode()) - .isEqualTo(Status.Code.INVALID_ARGUMENT); - } - @Test void expiringBackupPayment() throws VerificationFailedException { clock.pin(Instant.ofEpochSecond(1)); - final Instant day0 = Instant.EPOCH; final Instant day4 = Instant.EPOCH.plus(Duration.ofDays(4)); - final Instant dayMax = day0.plus(BackupAuthManager.MAX_REDEMPTION_DURATION); final BackupAuthManager authManager = create(); @@ -316,8 +269,11 @@ public class BackupAuthManagerTest { .backupVoucher(new Account.BackupVoucher(201, day4)) .build(); - final List creds = authManager.getBackupAuthCredentials(account, BackupCredentialType.MESSAGES, day0, dayMax).join(); - Instant redemptionTime = day0; + final List creds = authManager.getBackupAuthCredentials( + account, + BackupCredentialType.MESSAGES, + range(RedemptionRange.MAX_REDEMPTION_DURATION)).join(); + Instant redemptionTime = Instant.EPOCH; final BackupAuthCredentialRequestContext requestContext = BackupAuthCredentialRequestContext.create( messagesBackupKey, aci); for (int i = 0; i < creds.size(); i++) { @@ -355,7 +311,7 @@ public class BackupAuthManagerTest { when(accountsManager.updateAsync(any(), any())).thenReturn(CompletableFuture.completedFuture(updated)); clock.pin(day2.plus(Duration.ofSeconds(1))); - assertThat(authManager.getBackupAuthCredentials(account, BackupCredentialType.MESSAGES, day2, day2.plus(Duration.ofDays(7))).join()) + assertThat(authManager.getBackupAuthCredentials(account, BackupCredentialType.MESSAGES, range(Duration.ofDays(7))).join()) .hasSize(8); @SuppressWarnings("unchecked") final ArgumentCaptor> accountUpdater = ArgumentCaptor.forClass( @@ -620,7 +576,7 @@ public class BackupAuthManagerTest { private class MockAccountBuilder { - private Account account = mock(Account.class); + private final Account account = mock(Account.class); MockAccountBuilder() { when(account.getUuid()).thenReturn(aci); @@ -681,4 +637,9 @@ public class BackupAuthManagerTest { .thenReturn(rateLimitPaidMediaBackupId ? denyLimiter : allowLimiter); return limiters; } + + private RedemptionRange range(Duration length) { + final Instant start = clock.instant().truncatedTo(ChronoUnit.DAYS); + return RedemptionRange.inclusive(clock, start, start.plus(length)); + } } diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/backup/BackupAuthTestUtil.java b/service/src/test/java/org/whispersystems/textsecuregcm/backup/BackupAuthTestUtil.java index 070cd05a6..e8b919b62 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/backup/BackupAuthTestUtil.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/backup/BackupAuthTestUtil.java @@ -21,6 +21,7 @@ import org.signal.libsignal.zkgroup.backups.BackupAuthCredentialRequest; import org.signal.libsignal.zkgroup.backups.BackupAuthCredentialRequestContext; import org.signal.libsignal.zkgroup.backups.BackupCredentialType; import org.signal.libsignal.zkgroup.backups.BackupLevel; +import org.whispersystems.textsecuregcm.auth.RedemptionRange; import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager; import org.whispersystems.textsecuregcm.storage.Account; @@ -73,6 +74,8 @@ public class BackupAuthTestUtil { case FREE -> null; case PAID -> new Account.BackupVoucher(201L, redemptionEnd.plus(1, ChronoUnit.SECONDS)); }); - return issuer.getBackupAuthCredentials(account, credentialType, redemptionStart, redemptionEnd).join(); + final RedemptionRange redemptionRange; + redemptionRange = RedemptionRange.inclusive(clock, redemptionStart, redemptionEnd); + return issuer.getBackupAuthCredentials(account, credentialType, redemptionRange).join(); } } diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/controllers/ArchiveControllerTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/controllers/ArchiveControllerTest.java index fe95dadce..610d84bdc 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/controllers/ArchiveControllerTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/controllers/ArchiveControllerTest.java @@ -64,6 +64,7 @@ import org.signal.libsignal.zkgroup.receipts.ServerZkReceiptOperations; import org.whispersystems.textsecuregcm.auth.AuthenticatedBackupUser; import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice; import org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials; +import org.whispersystems.textsecuregcm.auth.RedemptionRange; import org.whispersystems.textsecuregcm.backup.BackupAuthManager; import org.whispersystems.textsecuregcm.backup.BackupAuthTestUtil; import org.whispersystems.textsecuregcm.backup.BackupManager; @@ -322,14 +323,15 @@ public class ArchiveControllerTest { public void getCredentials() { final Instant start = Instant.now().truncatedTo(ChronoUnit.DAYS); final Instant end = start.plus(Duration.ofDays(1)); + final RedemptionRange expectedRange = RedemptionRange.inclusive(Clock.systemUTC(), start, end); final Map> expectedCredentialsByType = EnumMapUtil.toEnumMap(BackupCredentialType.class, credentialType -> backupAuthTestUtil.getCredentials( BackupLevel.PAID, backupAuthTestUtil.getRequest(messagesBackupKey, aci), credentialType, start, end)); expectedCredentialsByType.forEach((credentialType, expectedCredentials) -> - when(backupAuthManager.getBackupAuthCredentials(any(), eq(credentialType), eq(start), eq(end))).thenReturn( - CompletableFuture.completedFuture(expectedCredentials))); + when(backupAuthManager.getBackupAuthCredentials(any(), eq(credentialType), eq(expectedRange))) + .thenReturn(CompletableFuture.completedFuture(expectedCredentials))); final ArchiveController.BackupAuthCredentialsResponse credentialResponse = resources.getJerseyTest() .target("v1/archives/auth") diff --git a/service/src/test/java/org/whispersystems/textsecuregcm/grpc/BackupsGrpcServiceTest.java b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/BackupsGrpcServiceTest.java index 0a5f1a8d6..4db25687b 100644 --- a/service/src/test/java/org/whispersystems/textsecuregcm/grpc/BackupsGrpcServiceTest.java +++ b/service/src/test/java/org/whispersystems/textsecuregcm/grpc/BackupsGrpcServiceTest.java @@ -28,9 +28,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.CsvSource; -import org.junit.jupiter.params.provider.EnumSource; import org.junit.jupiter.params.provider.MethodSource; -import org.junitpioneer.jupiter.cartesian.CartesianTest; import org.mockito.Mock; import org.signal.chat.backup.BackupsGrpc; import org.signal.chat.backup.GetBackupAuthCredentialsRequest; @@ -51,6 +49,7 @@ import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialRequestContext; import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialResponse; import org.signal.libsignal.zkgroup.receipts.ReceiptSerial; import org.signal.libsignal.zkgroup.receipts.ServerZkReceiptOperations; +import org.whispersystems.textsecuregcm.auth.RedemptionRange; import org.whispersystems.textsecuregcm.backup.BackupAuthManager; import org.whispersystems.textsecuregcm.backup.BackupAuthTestUtil; import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException; @@ -193,6 +192,7 @@ class BackupsGrpcServiceTest extends SimpleBaseGrpcTest> expectedCredentialsByType = EnumMapUtil.toEnumMap(BackupCredentialType.class, credentialType -> backupAuthTestUtil.getCredentials( @@ -200,7 +200,7 @@ class BackupsGrpcServiceTest extends SimpleBaseGrpcTest - when(backupAuthManager.getBackupAuthCredentials(any(), eq(credentialType), eq(start), eq(end))) + when(backupAuthManager.getBackupAuthCredentials(any(), eq(credentialType), eq(expectedRange))) .thenReturn(CompletableFuture.completedFuture(expectedCredentials))); final GetBackupAuthCredentialsResponse credentialResponse = authenticatedServiceStub().getBackupAuthCredentials(