mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-12-01 08:56:47 +00:00
Compare commits
28
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
25fdc95843 | ||
|
|
d3c93dd1a2 | ||
|
|
54ea7a288c | ||
|
|
e2cb484743 | ||
|
|
45f176d5a8 | ||
|
|
450945a9cc | ||
|
|
253671c206 | ||
|
|
cdd461b8f4 | ||
|
|
d9a54a0d42 | ||
|
|
3f3aa89b0f | ||
|
|
55fa60dd4e | ||
|
|
b539df8e48 | ||
|
|
0cd0716eb5 | ||
|
|
6386aada73 | ||
|
|
5c44398bb5 | ||
|
|
54736bb117 | ||
|
|
aed8e60789 | ||
|
|
5fa50e8ad7 | ||
|
|
fdaba751bd | ||
|
|
0eebb58956 | ||
|
|
6bb85d77a7 | ||
|
|
9e3844ee5a | ||
|
|
7ee8e349e2 | ||
|
|
4d9e252697 | ||
|
|
222e5a033b | ||
|
|
8c6fbbfa65 | ||
|
|
b0b2122d8c | ||
|
|
d7711e235b |
No files matched your search
@@ -17,6 +17,7 @@ jobs:
|
||||
permissions:
|
||||
id-token: write
|
||||
contents: read
|
||||
issues: write
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
- uses: actions/setup-java@1bcf9fb12cf4aa7d266a90ae39939e61372fe520 # v5.4.0
|
||||
@@ -35,3 +36,11 @@ jobs:
|
||||
echo "${INTEGRATION_TEST_CONFIG}" > integration-tests/src/main/resources/config.yml
|
||||
- name: Run and verify integration tests
|
||||
run: ./mvnw clean compile test-compile failsafe:integration-test failsafe:verify -P aws-sso
|
||||
- name: Open an issue on failure
|
||||
if: ${{ failure() && github.event_name == 'schedule' }}
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
gh issue create \
|
||||
--title "Failed server integration tests ($(date +'%Y-%m-%d'))" \
|
||||
--body "Workflow **${{ github.workflow }}** failed. See the run: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}"
|
||||
@@ -67,7 +67,7 @@
|
||||
<junit-pioneer.version>2.3.0</junit-pioneer.version>
|
||||
<jsr305.version>3.0.2</jsr305.version>
|
||||
<kotlin.version>2.3.20</kotlin.version>
|
||||
<logback.version>1.5.32</logback.version>
|
||||
<logback.version>1.5.38</logback.version>
|
||||
<logback-access-common.version>2.0.12</logback-access-common.version>
|
||||
<lettuce.version>7.5.1.RELEASE</lettuce.version>
|
||||
<libphonenumber.version>9.0.21</libphonenumber.version>
|
||||
|
||||
@@ -365,8 +365,6 @@ badges:
|
||||
svgs:
|
||||
- light: example-light.svg
|
||||
dark: example-dark.svg
|
||||
badgeIdsEnabledForAll:
|
||||
- TEST
|
||||
receiptLevels:
|
||||
'1': TEST
|
||||
|
||||
|
||||
@@ -178,6 +178,7 @@ import org.whispersystems.textsecuregcm.grpc.MessagesGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.MetricServerInterceptor;
|
||||
import org.whispersystems.textsecuregcm.grpc.OneTimeDonationsGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.PaymentsGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.ProductConfigurationGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.ProfileAnonymousGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.ProfileGrpcService;
|
||||
import org.whispersystems.textsecuregcm.grpc.RequestAttributesInterceptor;
|
||||
@@ -209,6 +210,7 @@ import org.whispersystems.textsecuregcm.mappers.JsonMappingExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.NonNormalizedPhoneNumberExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.ObsoletePhoneNumberFormatExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.RateLimitExceededExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.RegistrationLockFailureExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.RegistrationServiceSenderExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.ServerRejectedExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.mappers.SubscriptionExceptionMapper;
|
||||
@@ -316,6 +318,7 @@ import org.whispersystems.textsecuregcm.workers.BackupMetricsCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.BackupUsageRecalculationCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.CertificateCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.CheckDynamicConfigurationCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.ClearExpiredFoundationDbMessagesCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.ClearIssuedReceiptRedemptionsCommand;
|
||||
import org.whispersystems.textsecuregcm.workers.CopyToS3Command;
|
||||
import org.whispersystems.textsecuregcm.workers.DeleteUserCommand;
|
||||
@@ -391,6 +394,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
bootstrap.addCommand(new NotifyIdleDevicesCommand());
|
||||
bootstrap.addCommand(new ClearIssuedReceiptRedemptionsCommand());
|
||||
bootstrap.addCommand(new CopyToS3Command());
|
||||
bootstrap.addCommand(new ClearExpiredFoundationDbMessagesCommand(Clock.systemUTC()));
|
||||
|
||||
bootstrap.addCommand(new ProcessScheduledJobsServiceCommand("process-idle-device-notification-jobs",
|
||||
"Processes scheduled jobs to send notifications to idle devices",
|
||||
@@ -1066,8 +1070,15 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
config.getDeliveryCertificate().expiresDays(),
|
||||
config.getDeliveryCertificate().embedSigner());
|
||||
|
||||
final PhoneVerificationTokenManager phoneVerificationTokenManager = new PhoneVerificationTokenManager(
|
||||
phoneNumberIdentifiers, registrationServiceClient, registrationRecoveryPasswordsManager, registrationRecoveryChecker);
|
||||
|
||||
final ChangeNumberManager changeNumberManager = new ChangeNumberManager(messageSender, accountsManager,
|
||||
phoneVerificationTokenManager, registrationLockVerificationManager, rateLimiters,
|
||||
changeNumberWaitingPeriodManager, Clock.systemUTC());
|
||||
|
||||
final List<ServerServiceDefinition> authenticatedServices = Stream.of(
|
||||
new AccountsGrpcService(accountsManager, rateLimiters, usernameHashZkProofVerifier, registrationRecoveryPasswordsManager),
|
||||
new AccountsGrpcService(accountsManager, rateLimiters, usernameHashZkProofVerifier, registrationRecoveryPasswordsManager, Clock.systemUTC(), changeNumberManager),
|
||||
new CallingGrpcService(cloudflareTurnCredentialsManager, rateLimiters),
|
||||
new CredentialsGrpcService(accountsManager, certificateGenerator, zkAuthOperations, callingGenericZkSecretParams, rateLimiters, Clock.systemUTC(), ExternalServiceDefinitions.createExternalServiceList(config, Clock.systemUTC())),
|
||||
new KeysGrpcService(accountsManager, keysManager, rateLimiters),
|
||||
@@ -1080,7 +1091,10 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
config.getAttachments().maxAttachmentUploadSizeInBytes(), Clock.systemUTC()),
|
||||
new PaymentsGrpcService(currencyManager),
|
||||
new ChallengeGrpcService(accountsManager, rateLimitChallengeManager, challengeConstraintChecker),
|
||||
new DonationsGrpcService(clock, zkReceiptOperations, redeemedReceiptsManager, accountsManager, config.getBadges(), ReceiptCredentialPresentation::new, donationPermitsManager, rateLimiters))
|
||||
new DonationsGrpcService(clock, zkReceiptOperations, redeemedReceiptsManager, accountsManager, config.getBadges(), ReceiptCredentialPresentation::new, donationPermitsManager, rateLimiters),
|
||||
new ProductConfigurationGrpcService(config.getSubscription(), config.getOneTimeDonations(),
|
||||
List.of(stripeManager, braintreeManager), profileBadgeConverter,
|
||||
config.getBackupConfiguration().maxTotalMediaSize()))
|
||||
.map(bindableService -> ServerInterceptors.intercept(bindableService,
|
||||
// Note: interceptors run in the reverse order they are added; the remote deprecation filter
|
||||
// depends on the user-agent context so it has to come first here!
|
||||
@@ -1211,13 +1225,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
|
||||
final PersistentTimer persistentTimer = new PersistentTimer(rateLimitersCluster, clock);
|
||||
|
||||
final PhoneVerificationTokenManager phoneVerificationTokenManager = new PhoneVerificationTokenManager(
|
||||
phoneNumberIdentifiers, registrationServiceClient, registrationRecoveryPasswordsManager, registrationRecoveryChecker);
|
||||
|
||||
final ChangeNumberManager changeNumberManager = new ChangeNumberManager(messageSender, accountsManager,
|
||||
phoneVerificationTokenManager, registrationLockVerificationManager, rateLimiters,
|
||||
changeNumberWaitingPeriodManager, Clock.systemUTC());
|
||||
|
||||
final List<Object> commonControllers = Lists.newArrayList(
|
||||
new AccountController(accountsManager, rateLimiters, registrationRecoveryPasswordsManager,
|
||||
usernameHashZkProofVerifier),
|
||||
@@ -1334,7 +1341,8 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
new RegistrationServiceSenderExceptionMapper(),
|
||||
new SubscriptionExceptionMapper(),
|
||||
new BackupExceptionMapper(),
|
||||
new JsonMappingExceptionMapper()
|
||||
new JsonMappingExceptionMapper(),
|
||||
new RegistrationLockFailureExceptionMapper()
|
||||
).forEach(exceptionMapper -> {
|
||||
environment.jersey().register(exceptionMapper);
|
||||
webSocketEnvironment.jersey().register(exceptionMapper);
|
||||
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
package org.whispersystems.textsecuregcm.auth;
|
||||
|
||||
import org.whispersystems.textsecuregcm.util.NoStackTraceException;
|
||||
|
||||
public class InvalidRegistrationSessionException extends NoStackTraceException {
|
||||
|
||||
public InvalidRegistrationSessionException(final String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
+29
-25
@@ -7,12 +7,7 @@ package org.whispersystems.textsecuregcm.auth;
|
||||
|
||||
import io.grpc.Status;
|
||||
import io.grpc.StatusRuntimeException;
|
||||
import jakarta.ws.rs.BadRequestException;
|
||||
import jakarta.ws.rs.ForbiddenException;
|
||||
import jakarta.ws.rs.NotAuthorizedException;
|
||||
import jakarta.ws.rs.ServerErrorException;
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import java.io.IOException;
|
||||
import java.security.MessageDigest;
|
||||
import java.time.Duration;
|
||||
import java.util.UUID;
|
||||
@@ -55,23 +50,27 @@ public class PhoneVerificationTokenManager {
|
||||
* Checks if a {@link PhoneVerificationRequest} has a token that verifies the caller has confirmed access to the e164
|
||||
* number
|
||||
*
|
||||
* @param requestContext the container request context
|
||||
* @param number the e164 presented for verification
|
||||
* @param sessionId a verification session ID; exactly one of {@code sessionId} or {@code recoveryPassword} must be
|
||||
* non-null
|
||||
* @param recoveryPassword a registration recovery password; exactly one of {@code sessionId} or
|
||||
* {@code recoveryPassword} must be non-null
|
||||
* @return if verification was successful, returns the verification type
|
||||
* @throws BadRequestException if the number does not match the sessionId’s number, or the remote service rejects
|
||||
* @throws InvalidRegistrationSessionException if the number does not match the sessionId’s number, or the remote service rejects
|
||||
* the session ID as invalid
|
||||
* @throws NotAuthorizedException if the session is not verified
|
||||
* @throws ForbiddenException if the recovery password is not valid
|
||||
* @throws UnverifiedRegistrationSessionException if the session is not verified
|
||||
* @throws RecoveryPasswordVerificationFailedException if the recovery password is not valid
|
||||
* @throws InterruptedException if verification did not complete before a timeout
|
||||
* @throws IOException if there was an error talking to registration service
|
||||
*/
|
||||
public PhoneVerificationRequest.VerificationType verify(final ContainerRequestContext requestContext,
|
||||
public PhoneVerificationRequest.VerificationType verify(
|
||||
final String number,
|
||||
@Nullable final String userAgent,
|
||||
@Nullable final String acceptLanguage,
|
||||
@Nullable final String mostRecentProxy,
|
||||
@Nullable final byte[] sessionId,
|
||||
@Nullable final byte[] recoveryPassword) throws InterruptedException {
|
||||
@Nullable final byte[] recoveryPassword)
|
||||
throws InterruptedException, UnverifiedRegistrationSessionException, InvalidRegistrationSessionException, IOException, RecoveryPasswordVerificationFailedException {
|
||||
|
||||
if ((sessionId == null) == (recoveryPassword == null)) {
|
||||
throw new IllegalArgumentException("Exactly one of session ID or recovery password must non-null");
|
||||
@@ -83,40 +82,45 @@ public class PhoneVerificationTokenManager {
|
||||
|
||||
switch (verificationType) {
|
||||
case SESSION -> verifyBySessionId(number, sessionId);
|
||||
case RECOVERY_PASSWORD -> verifyByRecoveryPassword(requestContext, number, recoveryPassword);
|
||||
case RECOVERY_PASSWORD -> verifyByRecoveryPassword(number, userAgent, acceptLanguage, mostRecentProxy, recoveryPassword);
|
||||
}
|
||||
|
||||
return verificationType;
|
||||
}
|
||||
|
||||
private void verifyBySessionId(final String number, final byte[] sessionId) {
|
||||
private void verifyBySessionId(final String number, final byte[] sessionId)
|
||||
throws UnverifiedRegistrationSessionException, InvalidRegistrationSessionException, IOException {
|
||||
try {
|
||||
final RegistrationServiceSession session = registrationServiceClient
|
||||
.getSession(sessionId, REGISTRATION_RPC_TIMEOUT)
|
||||
.orElseThrow(() -> new NotAuthorizedException("session not verified"));
|
||||
.orElseThrow(UnverifiedRegistrationSessionException::new);
|
||||
|
||||
if (!MessageDigest.isEqual(number.getBytes(), session.number().getBytes())) {
|
||||
throw new BadRequestException("number does not match session");
|
||||
throw new InvalidRegistrationSessionException("number does not match session");
|
||||
}
|
||||
if (!session.verified()) {
|
||||
throw new NotAuthorizedException("session not verified");
|
||||
throw new UnverifiedRegistrationSessionException();
|
||||
}
|
||||
} catch (final StatusRuntimeException e) {
|
||||
if (e.getStatus().getCode() == Status.Code.INVALID_ARGUMENT) {
|
||||
throw new BadRequestException();
|
||||
throw new InvalidRegistrationSessionException(e.getMessage());
|
||||
}
|
||||
|
||||
logger.error("Registration service failure", e);
|
||||
throw new ServerErrorException(Response.Status.SERVICE_UNAVAILABLE);
|
||||
throw new IOException("Registration service failure", e);
|
||||
}
|
||||
}
|
||||
|
||||
private void verifyByRecoveryPassword(final ContainerRequestContext requestContext,
|
||||
private void verifyByRecoveryPassword(
|
||||
final String number,
|
||||
final byte[] recoveryPassword) throws InterruptedException {
|
||||
@Nullable final String userAgent,
|
||||
@Nullable final String acceptLanguage,
|
||||
@Nullable final String mostRecentProxy,
|
||||
final byte[] recoveryPassword)
|
||||
throws InterruptedException, IOException, RecoveryPasswordVerificationFailedException {
|
||||
|
||||
if (!registrationRecoveryChecker.checkRegistrationRecoveryAttempt(requestContext, number)) {
|
||||
throw new ForbiddenException("recoveryPassword couldn't be verified");
|
||||
if (!registrationRecoveryChecker.checkRegistrationRecoveryAttempt(number, userAgent, acceptLanguage, mostRecentProxy)) {
|
||||
throw new RecoveryPasswordVerificationFailedException();
|
||||
}
|
||||
|
||||
try {
|
||||
@@ -126,10 +130,10 @@ public class PhoneVerificationTokenManager {
|
||||
final boolean verified = registrationRecoveryPasswordsManager.verify(phoneNumberIdentifier, recoveryPassword);
|
||||
|
||||
if (!verified) {
|
||||
throw new ForbiddenException("recoveryPassword couldn't be verified");
|
||||
throw new RecoveryPasswordVerificationFailedException();
|
||||
}
|
||||
} catch (final ExecutionException | TimeoutException e) {
|
||||
throw new ServerErrorException(Response.Status.SERVICE_UNAVAILABLE);
|
||||
throw new IOException("registration service unavailable", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
package org.whispersystems.textsecuregcm.auth;
|
||||
|
||||
import org.whispersystems.textsecuregcm.util.NoStackTraceException;
|
||||
|
||||
public class RecoveryPasswordVerificationFailedException extends NoStackTraceException {
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package org.whispersystems.textsecuregcm.auth;
|
||||
|
||||
import org.whispersystems.textsecuregcm.entities.RegistrationLockFailure;
|
||||
import org.whispersystems.textsecuregcm.util.NoStackTraceException;
|
||||
|
||||
public class RegistrationLockFailureException extends NoStackTraceException {
|
||||
|
||||
private final RegistrationLockFailure failure;
|
||||
|
||||
public RegistrationLockFailureException(final RegistrationLockFailure failure) {
|
||||
super();
|
||||
this.failure = failure;
|
||||
}
|
||||
|
||||
public RegistrationLockFailure getFailure() {
|
||||
return failure;
|
||||
}
|
||||
}
|
||||
+6
-9
@@ -12,8 +12,6 @@ import io.micrometer.core.instrument.DistributionSummary;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tag;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import jakarta.ws.rs.WebApplicationException;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
@@ -80,13 +78,13 @@ public class RegistrationLockVerificationManager {
|
||||
* @param account
|
||||
* @param clientRegistrationLock
|
||||
* @throws RateLimitExceededException
|
||||
* @throws WebApplicationException
|
||||
* @throws RegistrationLockFailureException
|
||||
*/
|
||||
public void verifyRegistrationLock(final Account account, @Nullable final String clientRegistrationLock,
|
||||
final String userAgent,
|
||||
@Nullable final String userAgent,
|
||||
final Flow flow,
|
||||
final PhoneVerificationRequest.VerificationType phoneVerificationType
|
||||
) throws RateLimitExceededException, WebApplicationException {
|
||||
) throws RateLimitExceededException, RegistrationLockFailureException {
|
||||
|
||||
final Tags expiredTags = Tags.of(UserAgentTagUtil.getPlatformTag(userAgent),
|
||||
Tag.of(REGISTRATION_LOCK_VERIFICATION_FLOW_TAG_NAME, flow.name()),
|
||||
@@ -165,11 +163,10 @@ public class RegistrationLockVerificationManager {
|
||||
Metrics.counter(CHALLENGED_DEVICE_NOT_PUSH_REGISTERED_COUNTER_NAME).increment();
|
||||
}
|
||||
|
||||
throw new WebApplicationException(Response.status(FAILURE_HTTP_STATUS)
|
||||
.entity(new RegistrationLockFailure(
|
||||
throw new RegistrationLockFailureException(
|
||||
new RegistrationLockFailure(
|
||||
existingRegistrationLock.getTimeRemaining().toMillis(),
|
||||
svr2FailureCredentials(existingRegistrationLock, updatedAccount)))
|
||||
.build());
|
||||
svr2FailureCredentials(existingRegistrationLock, updatedAccount)));
|
||||
}
|
||||
|
||||
rateLimiters.getPinLimiter().clear(phoneNumber);
|
||||
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
package org.whispersystems.textsecuregcm.auth;
|
||||
|
||||
import org.whispersystems.textsecuregcm.util.NoStackTraceException;
|
||||
|
||||
public class UnverifiedRegistrationSessionException extends NoStackTraceException {
|
||||
}
|
||||
+1
-18
@@ -7,7 +7,6 @@ package org.whispersystems.textsecuregcm.badges;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
@@ -31,7 +30,6 @@ public class ConfiguredProfileBadgeConverter implements ProfileBadgeConverter, B
|
||||
|
||||
private final Clock clock;
|
||||
private final Map<String, BadgeConfiguration> knownBadges;
|
||||
private final List<String> badgeIdsEnabledForAll;
|
||||
private final HeaderControlledResourceBundleLookup headerControlledResourceBundleLookup;
|
||||
|
||||
public ConfiguredProfileBadgeConverter(
|
||||
@@ -41,7 +39,6 @@ public class ConfiguredProfileBadgeConverter implements ProfileBadgeConverter, B
|
||||
this.clock = clock;
|
||||
this.knownBadges = badgesConfiguration.getBadges().stream()
|
||||
.collect(Collectors.toMap(BadgeConfiguration::getId, Function.identity()));
|
||||
this.badgeIdsEnabledForAll = badgesConfiguration.getBadgeIdsEnabledForAll();
|
||||
this.headerControlledResourceBundleLookup = headerControlledResourceBundleLookup;
|
||||
}
|
||||
|
||||
@@ -73,7 +70,7 @@ public class ConfiguredProfileBadgeConverter implements ProfileBadgeConverter, B
|
||||
final List<Locale> acceptableLanguages,
|
||||
final List<AccountBadge> accountBadges,
|
||||
final boolean isSelf) {
|
||||
if (accountBadges.isEmpty() && badgeIdsEnabledForAll.isEmpty()) {
|
||||
if (accountBadges.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
@@ -99,20 +96,6 @@ public class ConfiguredProfileBadgeConverter implements ProfileBadgeConverter, B
|
||||
accountBadge.visible());
|
||||
})
|
||||
.collect(Collectors.toCollection(ArrayList::new));
|
||||
badges.addAll(badgeIdsEnabledForAll.stream().filter(knownBadges::containsKey).map(id -> {
|
||||
BadgeConfiguration configuration = knownBadges.get(id);
|
||||
return newBadge(
|
||||
isSelf,
|
||||
id,
|
||||
configuration.getCategory(),
|
||||
resourceBundle.getString(id + "_name"),
|
||||
resourceBundle.getString(id + "_description"),
|
||||
configuration.getSprites(),
|
||||
configuration.getSvg(),
|
||||
configuration.getSvgs(),
|
||||
now.plus(Duration.ofDays(1)),
|
||||
true);
|
||||
}).collect(Collectors.toList()));
|
||||
return badges;
|
||||
}
|
||||
|
||||
|
||||
-9
@@ -21,16 +21,13 @@ import java.util.stream.Collectors;
|
||||
|
||||
public class BadgesConfiguration {
|
||||
private final List<BadgeConfiguration> badges;
|
||||
private final List<String> badgeIdsEnabledForAll;
|
||||
private final Map<Long, String> receiptLevels;
|
||||
|
||||
@JsonCreator
|
||||
public BadgesConfiguration(
|
||||
@JsonProperty("badges") @JsonSetter(nulls = Nulls.AS_EMPTY) final List<BadgeConfiguration> badges,
|
||||
@JsonProperty("badgeIdsEnabledForAll") @JsonSetter(nulls = Nulls.AS_EMPTY) final List<String> badgeIdsEnabledForAll,
|
||||
@JsonProperty("receiptLevels") @JsonSetter(nulls = Nulls.AS_EMPTY) final Map<Long, String> receiptLevels) {
|
||||
this.badges = Objects.requireNonNull(badges);
|
||||
this.badgeIdsEnabledForAll = Objects.requireNonNull(badgeIdsEnabledForAll);
|
||||
this.receiptLevels = Objects.requireNonNull(receiptLevels);
|
||||
}
|
||||
|
||||
@@ -40,12 +37,6 @@ public class BadgesConfiguration {
|
||||
return badges;
|
||||
}
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
public List<String> getBadgeIdsEnabledForAll() {
|
||||
return badgeIdsEnabledForAll;
|
||||
}
|
||||
|
||||
@Valid
|
||||
@NotNull
|
||||
public Map<Long, String> getReceiptLevels() {
|
||||
|
||||
+20
-2
@@ -19,6 +19,7 @@ import jakarta.ws.rs.Consumes;
|
||||
import jakarta.ws.rs.ForbiddenException;
|
||||
import jakarta.ws.rs.GET;
|
||||
import jakarta.ws.rs.HeaderParam;
|
||||
import jakarta.ws.rs.NotAuthorizedException;
|
||||
import jakarta.ws.rs.PUT;
|
||||
import jakarta.ws.rs.Path;
|
||||
import jakarta.ws.rs.Produces;
|
||||
@@ -28,11 +29,16 @@ import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import jakarta.ws.rs.core.Context;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import java.io.IOException;
|
||||
import java.time.Instant;
|
||||
import java.util.UUID;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.ChangesPhoneNumber;
|
||||
import org.whispersystems.textsecuregcm.auth.InvalidRegistrationSessionException;
|
||||
import org.whispersystems.textsecuregcm.auth.RecoveryPasswordVerificationFailedException;
|
||||
import org.whispersystems.textsecuregcm.auth.RegistrationLockFailureException;
|
||||
import org.whispersystems.textsecuregcm.auth.UnverifiedRegistrationSessionException;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountDataReportResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountIdentityResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.ChangeNumberRequest;
|
||||
@@ -40,6 +46,7 @@ import org.whispersystems.textsecuregcm.entities.MismatchedDevicesResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.PhoneNumberDiscoverabilityRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.RegistrationLockFailure;
|
||||
import org.whispersystems.textsecuregcm.entities.StaleDevicesResponse;
|
||||
import org.whispersystems.textsecuregcm.filters.RemoteAddressFilter;
|
||||
import org.whispersystems.textsecuregcm.push.MessageTooLargeException;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
@@ -80,7 +87,8 @@ public class AccountControllerV2 {
|
||||
public AccountIdentityResponse changeNumber(@Auth final AuthenticatedDevice authenticatedDevice,
|
||||
@NotNull @Valid final ChangeNumberRequest request,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgentString,
|
||||
@Context final ContainerRequestContext requestContext) throws RateLimitExceededException, InterruptedException {
|
||||
@Context final ContainerRequestContext requestContext)
|
||||
throws RateLimitExceededException, InterruptedException, RegistrationLockFailureException {
|
||||
|
||||
if (authenticatedDevice.deviceId() != Device.PRIMARY_ID) {
|
||||
throw new ForbiddenException();
|
||||
@@ -102,7 +110,9 @@ public class AccountControllerV2 {
|
||||
request.devicePniPqLastResortPrekeys(),
|
||||
request.deviceMessages(),
|
||||
request.pniRegistrationIds(),
|
||||
requestContext);
|
||||
userAgentString,
|
||||
requestContext.getHeaderString(HttpHeaders.ACCEPT_LANGUAGE),
|
||||
(String) requestContext.getProperty(RemoteAddressFilter.REMOTE_ADDRESS_ATTRIBUTE_NAME));
|
||||
|
||||
return AccountIdentityResponseBuilder.fromAccount(updatedAccount);
|
||||
} catch (final MismatchedDevicesException e) {
|
||||
@@ -124,6 +134,14 @@ public class AccountControllerV2 {
|
||||
throw new WebApplicationException(Response.Status.REQUEST_ENTITY_TOO_LARGE);
|
||||
} catch (final MessageDeliveryNotAllowedException e) {
|
||||
throw new ServiceUnavailableException();
|
||||
} catch (final UnverifiedRegistrationSessionException e) {
|
||||
throw new NotAuthorizedException("registration session is unverified");
|
||||
} catch (final InvalidRegistrationSessionException e) {
|
||||
throw new BadRequestException(e.getMessage());
|
||||
} catch (final IOException e) {
|
||||
throw new ServiceUnavailableException(e.getMessage());
|
||||
} catch (final RecoveryPasswordVerificationFailedException e) {
|
||||
throw new ForbiddenException("recovery password could not be verified");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+30
-6
@@ -19,16 +19,21 @@ import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.ws.rs.BadRequestException;
|
||||
import jakarta.ws.rs.Consumes;
|
||||
import jakarta.ws.rs.ForbiddenException;
|
||||
import jakarta.ws.rs.HeaderParam;
|
||||
import jakarta.ws.rs.NotAuthorizedException;
|
||||
import jakarta.ws.rs.POST;
|
||||
import jakarta.ws.rs.Path;
|
||||
import jakarta.ws.rs.Produces;
|
||||
import jakarta.ws.rs.ServiceUnavailableException;
|
||||
import jakarta.ws.rs.WebApplicationException;
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import jakarta.ws.rs.core.Context;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import java.io.IOException;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
@@ -38,13 +43,18 @@ import org.apache.commons.lang3.StringUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.BasicAuthorizationHeader;
|
||||
import org.whispersystems.textsecuregcm.auth.InvalidRegistrationSessionException;
|
||||
import org.whispersystems.textsecuregcm.auth.PhoneVerificationTokenManager;
|
||||
import org.whispersystems.textsecuregcm.auth.RecoveryPasswordVerificationFailedException;
|
||||
import org.whispersystems.textsecuregcm.auth.RegistrationLockFailureException;
|
||||
import org.whispersystems.textsecuregcm.auth.RegistrationLockVerificationManager;
|
||||
import org.whispersystems.textsecuregcm.auth.UnverifiedRegistrationSessionException;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountCreationResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountIdentityResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.PhoneVerificationRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.RegistrationLockFailure;
|
||||
import org.whispersystems.textsecuregcm.entities.RegistrationRequest;
|
||||
import org.whispersystems.textsecuregcm.filters.RemoteAddressFilter;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.spam.RegistrationFraudChecker;
|
||||
@@ -116,7 +126,8 @@ public class RegistrationController {
|
||||
@HeaderParam(HeaderUtils.X_SIGNAL_AGENT) final String signalAgent,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
|
||||
@NotNull @Valid final RegistrationRequest registrationRequest,
|
||||
@Context final ContainerRequestContext requestContext) throws RateLimitExceededException, InterruptedException {
|
||||
@Context final ContainerRequestContext requestContext)
|
||||
throws RateLimitExceededException, InterruptedException, RegistrationLockFailureException {
|
||||
|
||||
final String number = authorizationHeader.getUsername();
|
||||
final String password = authorizationHeader.getPassword();
|
||||
@@ -134,11 +145,24 @@ public class RegistrationController {
|
||||
|
||||
rateLimiters.getRegistrationLimiter().validate(number);
|
||||
|
||||
final PhoneVerificationRequest.VerificationType verificationType =
|
||||
phoneVerificationTokenManager.verify(requestContext,
|
||||
number,
|
||||
StringUtils.isNotBlank(registrationRequest.sessionId()) ? registrationRequest.decodeSessionId() : null,
|
||||
registrationRequest.recoveryPassword());
|
||||
final PhoneVerificationRequest.VerificationType verificationType;
|
||||
try {
|
||||
verificationType = phoneVerificationTokenManager.verify(
|
||||
number,
|
||||
requestContext.getHeaderString(HttpHeaders.USER_AGENT),
|
||||
requestContext.getHeaderString(HttpHeaders.ACCEPT_LANGUAGE),
|
||||
(String) requestContext.getProperty(RemoteAddressFilter.REMOTE_ADDRESS_ATTRIBUTE_NAME),
|
||||
StringUtils.isNotBlank(registrationRequest.sessionId()) ? registrationRequest.decodeSessionId() : null,
|
||||
registrationRequest.recoveryPassword());
|
||||
} catch (final UnverifiedRegistrationSessionException e) {
|
||||
throw new NotAuthorizedException("registration session is unverified");
|
||||
} catch (final InvalidRegistrationSessionException e) {
|
||||
throw new BadRequestException(e.getMessage());
|
||||
} catch (final IOException e) {
|
||||
throw new ServiceUnavailableException(e.getMessage());
|
||||
} catch (final RecoveryPasswordVerificationFailedException e) {
|
||||
throw new ForbiddenException("recovery password could not be verified");
|
||||
}
|
||||
|
||||
// There can be at most one existing account for a set of numbers in the same equivalence class, so it's sufficient
|
||||
// to find the first one.
|
||||
|
||||
+1
-1
@@ -28,7 +28,7 @@ public record AccountDataReportResponse(UUID reportId,
|
||||
|
||||
@JsonProperty
|
||||
@Schema(description = "A plaintext representation of the data report")
|
||||
String text() {
|
||||
public String text() {
|
||||
|
||||
final StringBuilder builder = new StringBuilder();
|
||||
|
||||
|
||||
+1
-1
@@ -11,7 +11,7 @@ import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import org.whispersystems.textsecuregcm.registration.VerificationSession;
|
||||
|
||||
public record VerificationSessionResponse(
|
||||
@Schema(requiredMode = Schema.RequiredMode.REQUIRED, description = "A URL-safe ID for the session")
|
||||
@Schema(requiredMode = Schema.RequiredMode.REQUIRED, description = "A URL-safe base64-encoded ID for the session")
|
||||
String id,
|
||||
|
||||
@Schema(requiredMode = Schema.RequiredMode.NOT_REQUIRED, description = "Duration in seconds after which next SMS can be requested for this session")
|
||||
|
||||
+259
-16
@@ -6,12 +6,21 @@
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import com.google.protobuf.ByteString;
|
||||
import java.io.IOException;
|
||||
import java.security.SecureRandom;
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
import io.grpc.StatusRuntimeException;
|
||||
import org.signal.chat.account.ChangeNumberRequest;
|
||||
import org.signal.chat.account.ChangeNumberResponse;
|
||||
import org.signal.chat.account.ClearRegistrationLockRequest;
|
||||
import org.signal.chat.account.ClearRegistrationLockResponse;
|
||||
import org.signal.chat.account.ConfigureUnidentifiedAccessRequest;
|
||||
@@ -24,8 +33,14 @@ import org.signal.chat.account.DeleteUsernameHashRequest;
|
||||
import org.signal.chat.account.DeleteUsernameHashResponse;
|
||||
import org.signal.chat.account.DeleteUsernameLinkRequest;
|
||||
import org.signal.chat.account.DeleteUsernameLinkResponse;
|
||||
import org.signal.chat.account.ExternalServiceCredentials;
|
||||
import org.signal.chat.account.GetAccountDataReportRequest;
|
||||
import org.signal.chat.account.GetAccountDataReportResponse;
|
||||
import org.signal.chat.account.GetAccountIdentityRequest;
|
||||
import org.signal.chat.account.GetAccountIdentityResponse;
|
||||
import org.signal.chat.account.GetEntitlementsRequest;
|
||||
import org.signal.chat.account.GetEntitlementsResponse;
|
||||
import org.signal.chat.account.RegistrationLockFailure;
|
||||
import org.signal.chat.account.ReserveUsernameHashRequest;
|
||||
import org.signal.chat.account.ReserveUsernameHashResponse;
|
||||
import org.signal.chat.account.SetDiscoverableByPhoneNumberRequest;
|
||||
@@ -39,26 +54,45 @@ import org.signal.chat.account.SetUsernameLinkResponse;
|
||||
import org.signal.chat.account.SetZkCredentialKeyRequest;
|
||||
import org.signal.chat.account.SetZkCredentialKeyResponse;
|
||||
import org.signal.chat.account.SimpleAccountsGrpc;
|
||||
import org.signal.chat.account.StaleDevices;
|
||||
import org.signal.chat.account.UsernameNotAvailable;
|
||||
import org.signal.chat.common.AccountIdentifiers;
|
||||
import org.signal.chat.errors.FailedPrecondition;
|
||||
import org.signal.chat.messages.SendMessageType;
|
||||
import org.signal.libsignal.protocol.IdentityKey;
|
||||
import org.signal.libsignal.protocol.InvalidKeyException;
|
||||
import org.signal.libsignal.usernames.BaseUsernameException;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.signal.libsignal.zkgroup.ZkCredentialPublicKey;
|
||||
import org.whispersystems.textsecuregcm.auth.InvalidRegistrationSessionException;
|
||||
import org.whispersystems.textsecuregcm.auth.RecoveryPasswordVerificationFailedException;
|
||||
import org.whispersystems.textsecuregcm.auth.RegistrationLockFailureException;
|
||||
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
|
||||
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
|
||||
import org.whispersystems.textsecuregcm.auth.UnverifiedRegistrationSessionException;
|
||||
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
|
||||
import org.whispersystems.textsecuregcm.controllers.MessageDeliveryNotAllowedException;
|
||||
import org.whispersystems.textsecuregcm.controllers.MismatchedDevicesException;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountDataReportResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.IncomingMessage;
|
||||
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.push.MessageTooLargeException;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ChangeNumberManager;
|
||||
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.UsernameHashNotAvailableException;
|
||||
import org.whispersystems.textsecuregcm.storage.UsernameReservationNotFoundException;
|
||||
import org.whispersystems.textsecuregcm.util.RegistrationIdValidator;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
import org.whispersystems.textsecuregcm.util.UsernameHashZkProofVerifier;
|
||||
|
||||
@@ -70,37 +104,55 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
|
||||
private final RateLimiters rateLimiters;
|
||||
private final UsernameHashZkProofVerifier usernameHashZkProofVerifier;
|
||||
private final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager;
|
||||
private final Clock clock;
|
||||
private final ChangeNumberManager changeNumberManager;
|
||||
|
||||
public AccountsGrpcService(final AccountsManager accountsManager,
|
||||
final RateLimiters rateLimiters,
|
||||
final UsernameHashZkProofVerifier usernameHashZkProofVerifier,
|
||||
final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager) {
|
||||
final RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager,
|
||||
final Clock clock,
|
||||
final ChangeNumberManager changeNumberManager) {
|
||||
|
||||
this.accountsManager = accountsManager;
|
||||
this.rateLimiters = rateLimiters;
|
||||
this.usernameHashZkProofVerifier = usernameHashZkProofVerifier;
|
||||
this.registrationRecoveryPasswordsManager = registrationRecoveryPasswordsManager;
|
||||
this.clock = clock;
|
||||
this.changeNumberManager = changeNumberManager;
|
||||
}
|
||||
|
||||
@Override
|
||||
public GetAccountIdentityResponse getAccountIdentity(final GetAccountIdentityRequest request) {
|
||||
return GetAccountIdentityResponse.newBuilder()
|
||||
.setAccountIdentifiers(buildAccountIdentifiers(getAuthenticatedAccount()))
|
||||
.build();
|
||||
}
|
||||
|
||||
@Override
|
||||
public GetEntitlementsResponse getEntitlements(final GetEntitlementsRequest request) {
|
||||
final Account account = getAuthenticatedAccount();
|
||||
final GetEntitlementsResponse.Builder builder = GetEntitlementsResponse.newBuilder();
|
||||
|
||||
final AccountIdentifiers.Builder accountIdentifiersBuilder = AccountIdentifiers.newBuilder()
|
||||
.addServiceIdentifiers(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(new AciServiceIdentifier(account.getUuid())))
|
||||
.addServiceIdentifiers(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(new PniServiceIdentifier(account.getPhoneNumberIdentifier())))
|
||||
.setE164(account.getNumber());
|
||||
final Instant now = clock.instant();
|
||||
|
||||
account.getUsernameHash().ifPresent(usernameHash ->
|
||||
accountIdentifiersBuilder.setUsernameHash(ByteString.copyFrom(usernameHash)));
|
||||
|
||||
if (account.getUsernameLinkHandle() != null) {
|
||||
accountIdentifiersBuilder.setUsernameLinkHandle(UUIDUtil.toByteString(account.getUsernameLinkHandle()));
|
||||
final Account.BackupVoucher backupVoucher = account.getBackupVoucher();
|
||||
if (backupVoucher != null && backupVoucher.expiration().isAfter(now)) {
|
||||
builder.setBackup(GetEntitlementsResponse.BackupEntitlement.newBuilder()
|
||||
.setExpirationEpochSeconds(backupVoucher.expiration().getEpochSecond())
|
||||
.setLevel(backupVoucher.receiptLevel()));
|
||||
}
|
||||
|
||||
return GetAccountIdentityResponse.newBuilder()
|
||||
.setAccountIdentifiers(accountIdentifiersBuilder)
|
||||
.build();
|
||||
builder.addAllBadges(account.getBadges().stream()
|
||||
.filter(badge -> badge.expiration().isAfter(now))
|
||||
.map(badge -> GetEntitlementsResponse.BadgeEntitlement.newBuilder()
|
||||
.setBadgeId(badge.id())
|
||||
.setExpirationEpochSeconds(badge.expiration().getEpochSecond())
|
||||
.setVisible(badge.visible())
|
||||
.build())
|
||||
.toList());
|
||||
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -113,10 +165,8 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
|
||||
|
||||
@Override
|
||||
public SetRegistrationLockResponse setRegistrationLock(final SetRegistrationLockRequest request) {
|
||||
// In the previous REST-based API, clients would send hex strings directly. For backward compatibility, we
|
||||
// convert the registration lock secret to a lowercase hex string before turning it into a salted hash.
|
||||
final SaltedTokenHash credentials =
|
||||
SaltedTokenHash.generateFor(HexFormat.of().withLowerCase().formatHex(request.getRegistrationLock().toByteArray()));
|
||||
SaltedTokenHash.generateFor(formatRegistrationLock(request.getRegistrationLock().toByteArray()));
|
||||
|
||||
accountsManager.update(AuthenticationUtil.requireAuthenticatedPrimaryDevice().accountIdentifier(),
|
||||
account -> account.setRegistrationLock(credentials.hash(), credentials.salt()));
|
||||
@@ -304,6 +354,178 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
|
||||
.build();
|
||||
}
|
||||
|
||||
@Override
|
||||
public ChangeNumberResponse changeNumber(final ChangeNumberRequest request)
|
||||
throws RateLimitExceededException, InterruptedException {
|
||||
|
||||
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedPrimaryDevice();
|
||||
|
||||
final IdentityKey pniIdentityKey;
|
||||
try {
|
||||
pniIdentityKey = new IdentityKey(request.getPniIdentityKey().toByteArray());
|
||||
} catch (final InvalidKeyException e) {
|
||||
throw GrpcExceptions.fieldViolation("pni_identity_key", "invalid identity key");
|
||||
}
|
||||
|
||||
final Map<Byte, ECSignedPreKey> devicePniSignedPreKeys = transformDeviceMap(request.getDevicePniSignedPreKeysMap(),
|
||||
key -> KeysGrpcHelper.checkEcSignedPreKey(key, pniIdentityKey,
|
||||
invalidPublicKeyException("device_pni_signed_pre_keys"),
|
||||
invalidSignatureException("device_pni_signed_pre_keys")));
|
||||
|
||||
final Map<Byte, KEMSignedPreKey> devicePniPqLastResortPreKeys = transformDeviceMap(request.getDevicePniPqLastResortPreKeysMap(),
|
||||
key -> KeysGrpcHelper.checkKemSignedPreKey(key, pniIdentityKey,
|
||||
invalidPublicKeyException("device_pni_pq_last_resort_pre_keys"),
|
||||
invalidSignatureException("device_pni_pq_last_resort_pre_keys")));
|
||||
|
||||
final Map<Byte, Integer> pniRegistrationIds = transformDeviceMap(request.getPniRegistrationIdsMap(), Function.identity());
|
||||
|
||||
if (!pniRegistrationIds.values().stream().allMatch(RegistrationIdValidator::validRegistrationId)) {
|
||||
throw GrpcExceptions.fieldViolation("pni_registration_ids", "invalid registration id");
|
||||
}
|
||||
|
||||
final List<IncomingMessage> deviceMessages = request.getDeviceMessages().getMessagesMap()
|
||||
.entrySet()
|
||||
.stream()
|
||||
.map(entry -> new IncomingMessage(
|
||||
getEnvelopeType(entry.getValue().getType()).getNumber(),
|
||||
(byte) (int) entry.getKey(),
|
||||
entry.getValue().getRegistrationId(),
|
||||
entry.getValue().getPayload().toByteArray()))
|
||||
.toList();
|
||||
|
||||
final byte[] sessionId = request.getVerificationCase() == ChangeNumberRequest.VerificationCase.SESSION_ID
|
||||
? request.getSessionId().toByteArray()
|
||||
: null;
|
||||
|
||||
final byte[] recoveryPassword =
|
||||
request.getVerificationCase() == ChangeNumberRequest.VerificationCase.RECOVERY_PASSWORD
|
||||
? request.getRecoveryPassword().toByteArray()
|
||||
: null;
|
||||
|
||||
final String registrationLock = request.getRegistrationLock().isEmpty() ? null :
|
||||
formatRegistrationLock(request.getRegistrationLock().toByteArray());
|
||||
|
||||
try {
|
||||
final Account updatedAccount = changeNumberManager.changeNumber(
|
||||
authenticatedDevice.accountIdentifier(),
|
||||
sessionId,
|
||||
recoveryPassword,
|
||||
registrationLock,
|
||||
request.getNumber(),
|
||||
pniIdentityKey,
|
||||
devicePniSignedPreKeys,
|
||||
devicePniPqLastResortPreKeys,
|
||||
deviceMessages,
|
||||
pniRegistrationIds,
|
||||
RequestAttributesUtil.getUserAgent().orElse(null),
|
||||
RequestAttributesUtil.getAcceptLanguageRaw(),
|
||||
RequestAttributesUtil.getRemoteAddress().getHostAddress());
|
||||
|
||||
return ChangeNumberResponse.newBuilder()
|
||||
.setAccountIdentifiers(buildAccountIdentifiers(updatedAccount))
|
||||
.build();
|
||||
} catch (final MismatchedDevicesException e) {
|
||||
if (!e.getMismatchedDevices().staleDeviceIds().isEmpty()) {
|
||||
return ChangeNumberResponse.newBuilder()
|
||||
.setStaleDevices(StaleDevices.newBuilder()
|
||||
.addAllStaleDevices(e.getMismatchedDevices().staleDeviceIds().stream().map(Byte::intValue).toList()))
|
||||
.build();
|
||||
}
|
||||
|
||||
return ChangeNumberResponse.newBuilder()
|
||||
.setMismatchedDevices(MessagesGrpcHelper.buildMismatchedDevices(
|
||||
new AciServiceIdentifier(authenticatedDevice.accountIdentifier()), e.getMismatchedDevices()))
|
||||
.build();
|
||||
} catch (final MessageTooLargeException e) {
|
||||
return ChangeNumberResponse.newBuilder()
|
||||
.setMessageTooLarge(FailedPrecondition.newBuilder()
|
||||
.setDescription("one or more device messages was too large"))
|
||||
.build();
|
||||
} catch (final MessageDeliveryNotAllowedException e) {
|
||||
throw GrpcExceptions.unavailable();
|
||||
} catch (final IllegalArgumentException e) {
|
||||
throw GrpcExceptions.invalidArguments(e.getMessage());
|
||||
} catch (final RegistrationLockFailureException e) {
|
||||
final RegistrationLockFailure.Builder failureBuilder = RegistrationLockFailure.newBuilder()
|
||||
.setTimeRemainingMillis(e.getFailure().timeRemaining());
|
||||
|
||||
if (e.getFailure().svr2Credentials() != null) {
|
||||
failureBuilder.setSvr2Credentials(ExternalServiceCredentials.newBuilder()
|
||||
.setUsername(e.getFailure().svr2Credentials().username())
|
||||
.setPassword(e.getFailure().svr2Credentials().password()));
|
||||
}
|
||||
|
||||
return ChangeNumberResponse.newBuilder()
|
||||
.setRegistrationLockFailure(failureBuilder)
|
||||
.build();
|
||||
} catch (final UnverifiedRegistrationSessionException e) {
|
||||
return ChangeNumberResponse.newBuilder()
|
||||
.setUnverifiedRegistrationSession(FailedPrecondition.getDefaultInstance())
|
||||
.build();
|
||||
} catch (final InvalidRegistrationSessionException e) {
|
||||
return ChangeNumberResponse.newBuilder()
|
||||
.setInvalidRegistrationSession(FailedPrecondition.newBuilder().setDescription(e.getMessage()))
|
||||
.build();
|
||||
} catch (final IOException e) {
|
||||
throw GrpcExceptions.unavailable(e.getMessage());
|
||||
} catch (final RecoveryPasswordVerificationFailedException e) {
|
||||
return ChangeNumberResponse.newBuilder()
|
||||
.setRecoveryPasswordVerificationFailed(FailedPrecondition.getDefaultInstance())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public GetAccountDataReportResponse getAccountDataReport(final GetAccountDataReportRequest request)
|
||||
throws IOException {
|
||||
final Account account = getAuthenticatedAccount();
|
||||
|
||||
final AccountDataReportResponse report = new AccountDataReportResponse(UUID.randomUUID(), clock.instant(),
|
||||
new AccountDataReportResponse.AccountAndDevicesDataReport(
|
||||
new AccountDataReportResponse.AccountDataReport(
|
||||
account.getNumber(),
|
||||
account.getBadges().stream().map(AccountDataReportResponse.BadgeDataReport::new).toList(),
|
||||
account.isUnrestrictedUnidentifiedAccess(),
|
||||
account.isDiscoverableByPhoneNumber()),
|
||||
account.getDevices().stream().map(device ->
|
||||
new AccountDataReportResponse.DeviceDataReport(
|
||||
device.getId(),
|
||||
Instant.ofEpochMilli(device.getLastSeen()),
|
||||
Instant.ofEpochMilli(device.getCreated()),
|
||||
device.getUserAgent())).toList()));
|
||||
|
||||
return GetAccountDataReportResponse.newBuilder()
|
||||
.setJson(SystemMapper.jsonMapper().writeValueAsString(report))
|
||||
.setText(report.text())
|
||||
.build();
|
||||
}
|
||||
|
||||
private static AccountIdentifiers buildAccountIdentifiers(final Account account) {
|
||||
final AccountIdentifiers.Builder accountIdentifiersBuilder = AccountIdentifiers.newBuilder()
|
||||
.addServiceIdentifiers(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(new AciServiceIdentifier(account.getUuid())))
|
||||
.addServiceIdentifiers(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(new PniServiceIdentifier(account.getPhoneNumberIdentifier())))
|
||||
.setE164(account.getNumber());
|
||||
|
||||
account.getUsernameHash().ifPresent(usernameHash ->
|
||||
accountIdentifiersBuilder.setUsernameHash(ByteString.copyFrom(usernameHash)));
|
||||
|
||||
if (account.getUsernameLinkHandle() != null) {
|
||||
accountIdentifiersBuilder.setUsernameLinkHandle(UUIDUtil.toByteString(account.getUsernameLinkHandle()));
|
||||
}
|
||||
|
||||
return accountIdentifiersBuilder.build();
|
||||
}
|
||||
|
||||
private static MessageProtos.Envelope.Type getEnvelopeType(final SendMessageType type) {
|
||||
return switch (type) {
|
||||
case DOUBLE_RATCHET -> MessageProtos.Envelope.Type.CIPHERTEXT;
|
||||
case PREKEY_MESSAGE -> MessageProtos.Envelope.Type.PREKEY_BUNDLE;
|
||||
case PLAINTEXT_CONTENT -> MessageProtos.Envelope.Type.PLAINTEXT_CONTENT;
|
||||
case UNIDENTIFIED_SENDER -> throw GrpcExceptions.invalidArguments("illegal envelope type for change-number sync messages");
|
||||
case UNSPECIFIED, UNRECOGNIZED -> throw GrpcExceptions.invalidArguments("unrecognized envelope type");
|
||||
};
|
||||
}
|
||||
|
||||
private Account getAuthenticatedAccount() {
|
||||
return getAuthenticatedAccount(AuthenticationUtil.requireAuthenticatedDevice());
|
||||
}
|
||||
@@ -312,4 +534,25 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
|
||||
return accountsManager.getByAccountIdentifier(authenticatedDevice.accountIdentifier())
|
||||
.orElseThrow(() -> GrpcExceptions.invalidCredentials("invalid credentials"));
|
||||
}
|
||||
|
||||
private static String formatRegistrationLock(final byte[] registrationLock) {
|
||||
// In the previous REST-based API, clients would send hex strings directly. For backward compatibility, we
|
||||
// convert the registration lock secret to a lowercase hex string before turning it into a salted hash.
|
||||
return HexFormat.of().withLowerCase().formatHex(registrationLock);
|
||||
}
|
||||
|
||||
private static StatusRuntimeException invalidPublicKeyException(final String fieldName) {
|
||||
return GrpcExceptions.fieldViolation(fieldName, "invalid public key");
|
||||
}
|
||||
|
||||
private static StatusRuntimeException invalidSignatureException(final String fieldName) {
|
||||
return GrpcExceptions.fieldViolation(fieldName, "pre-key signature did not match PNI identity key");
|
||||
}
|
||||
|
||||
private static <T, U> Map<Byte, U> transformDeviceMap(final Map<Integer, T> byDeviceId, final Function<T, U> f) {
|
||||
return byDeviceId.entrySet()
|
||||
.stream()
|
||||
.collect(Collectors.<Map.Entry<Integer, T>, Byte, U>toMap(entry -> entry.getKey().byteValue(),
|
||||
entry -> f.apply(entry.getValue())));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import org.signal.chat.common.Badge;
|
||||
import org.signal.chat.common.BadgeSvg;
|
||||
|
||||
public class BadgeGrpcHelper {
|
||||
|
||||
public static Badge toGrpcBadge(final org.whispersystems.textsecuregcm.entities.Badge badge) {
|
||||
final Badge.Builder builder = Badge.newBuilder()
|
||||
.setId(badge.getId())
|
||||
.setCategory(badge.getCategory())
|
||||
.setName(badge.getName())
|
||||
.setDescription(badge.getDescription())
|
||||
.addAllSprites6(badge.getSprites6())
|
||||
.setSvg(badge.getSvg());
|
||||
|
||||
badge.getSvgs().stream()
|
||||
.map(badgeSvg -> BadgeSvg.newBuilder()
|
||||
.setDark(badgeSvg.getDark())
|
||||
.setLight(badgeSvg.getLight())
|
||||
.build())
|
||||
.forEach(builder::addSvgs);
|
||||
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -138,7 +138,9 @@ public class DevicesGrpcService extends SimpleDevicesGrpc.DevicesImplBase {
|
||||
final Device device = account.getDevice(authenticatedDevice.deviceId())
|
||||
.orElseThrow(() -> GrpcExceptions.invalidCredentials("invalid credentials"));
|
||||
|
||||
if (!Objects.equals(device.getApnId(), apnsToken) || !Objects.equals(device.getGcmId(), fcmToken)) {
|
||||
// Unlike FCM tokens, we need current "last updated" timestamps for APNs tokens and so update device records
|
||||
// unconditionally if it's an APNS request
|
||||
if (request.hasApnsTokenRequest() || !Objects.equals(device.getGcmId(), fcmToken)) {
|
||||
accountsManager.updateDevice(account.getIdentifier(IdentityType.ACI), authenticatedDevice.deviceId(), d -> {
|
||||
d.setApnId(apnsToken);
|
||||
d.setGcmId(fcmToken);
|
||||
|
||||
@@ -11,11 +11,19 @@ import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
import io.grpc.StatusRuntimeException;
|
||||
import org.signal.chat.common.EcPreKey;
|
||||
import org.signal.chat.common.EcSignedPreKey;
|
||||
import org.signal.chat.common.KemSignedPreKey;
|
||||
import org.signal.chat.keys.AccountPreKeyBundles;
|
||||
import org.signal.chat.keys.DevicePreKeyBundle;
|
||||
import org.signal.libsignal.protocol.IdentityKey;
|
||||
import org.signal.libsignal.protocol.InvalidKeyException;
|
||||
import org.signal.libsignal.protocol.ecc.ECPublicKey;
|
||||
import org.signal.libsignal.protocol.kem.KEMPublicKey;
|
||||
import org.whispersystems.textsecuregcm.entities.ECPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
@@ -89,4 +97,46 @@ class KeysGrpcHelper {
|
||||
|
||||
return Optional.of(preKeyBundlesBuilder.build());
|
||||
}
|
||||
|
||||
public static ECPreKey checkEcPreKey(final EcPreKey preKey, final StatusRuntimeException invalidPublicKeyException) {
|
||||
try {
|
||||
return new ECPreKey(preKey.getKeyId(), new ECPublicKey(preKey.getPublicKey().toByteArray()));
|
||||
} catch (final InvalidKeyException e) {
|
||||
throw invalidPublicKeyException;
|
||||
}
|
||||
}
|
||||
|
||||
public static ECSignedPreKey checkEcSignedPreKey(final EcSignedPreKey preKey, final IdentityKey identityKey,
|
||||
final StatusRuntimeException invalidPublicKeyException, final StatusRuntimeException invalidSignatureException) {
|
||||
try {
|
||||
final ECSignedPreKey ecSignedPreKey = new ECSignedPreKey(preKey.getKeyId(),
|
||||
new ECPublicKey(preKey.getPublicKey().toByteArray()),
|
||||
preKey.getSignature().toByteArray());
|
||||
|
||||
if (ecSignedPreKey.signatureValid(identityKey)) {
|
||||
return ecSignedPreKey;
|
||||
} else {
|
||||
throw invalidSignatureException;
|
||||
}
|
||||
} catch (final InvalidKeyException e) {
|
||||
throw invalidPublicKeyException;
|
||||
}
|
||||
}
|
||||
|
||||
public static KEMSignedPreKey checkKemSignedPreKey(final KemSignedPreKey preKey, final IdentityKey identityKey,
|
||||
final StatusRuntimeException invalidPublicKeyException, final StatusRuntimeException invalidSignatureException) {
|
||||
try {
|
||||
final KEMSignedPreKey kemSignedPreKey = new KEMSignedPreKey(preKey.getKeyId(),
|
||||
new KEMPublicKey(preKey.getPublicKey().toByteArray()),
|
||||
preKey.getSignature().toByteArray());
|
||||
|
||||
if (kemSignedPreKey.signatureValid(identityKey)) {
|
||||
return kemSignedPreKey;
|
||||
} else {
|
||||
throw invalidSignatureException;
|
||||
}
|
||||
} catch (final InvalidKeyException e) {
|
||||
throw invalidPublicKeyException;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -11,9 +11,6 @@ import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.function.BiFunction;
|
||||
import org.signal.chat.common.EcPreKey;
|
||||
import org.signal.chat.common.EcSignedPreKey;
|
||||
import org.signal.chat.common.KemSignedPreKey;
|
||||
import org.signal.chat.errors.NotFound;
|
||||
import org.signal.chat.keys.GetPreKeyCountRequest;
|
||||
import org.signal.chat.keys.GetPreKeyCountResponse;
|
||||
@@ -26,16 +23,10 @@ import org.signal.chat.keys.SetOneTimeKemSignedPreKeysRequest;
|
||||
import org.signal.chat.keys.SetPreKeyResponse;
|
||||
import org.signal.chat.keys.SimpleKeysGrpc;
|
||||
import org.signal.libsignal.protocol.IdentityKey;
|
||||
import org.signal.libsignal.protocol.InvalidKeyException;
|
||||
import org.signal.libsignal.protocol.ecc.ECPublicKey;
|
||||
import org.signal.libsignal.protocol.kem.KEMPublicKey;
|
||||
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitKeys;
|
||||
import org.whispersystems.textsecuregcm.entities.ECPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
@@ -136,7 +127,7 @@ public class KeysGrpcService extends SimpleKeysGrpc.KeysImplBase {
|
||||
storeOneTimePreKeys(authenticatedDevice.accountIdentifier(),
|
||||
request.getPreKeysList(),
|
||||
IdentityTypeUtil.fromGrpcIdentityType(request.getIdentityType()),
|
||||
(requestPreKey, _) -> checkEcPreKey(requestPreKey),
|
||||
(requestPreKey, _) -> KeysGrpcHelper.checkEcPreKey(requestPreKey, INVALID_PUBLIC_KEY_EXCEPTION),
|
||||
(identifier, preKeys) -> keysManager.storeEcOneTimePreKeys(identifier, authenticatedDevice.deviceId(), preKeys));
|
||||
|
||||
return SetPreKeyResponse.getDefaultInstance();
|
||||
@@ -149,7 +140,7 @@ public class KeysGrpcService extends SimpleKeysGrpc.KeysImplBase {
|
||||
storeOneTimePreKeys(authenticatedDevice.accountIdentifier(),
|
||||
request.getPreKeysList(),
|
||||
IdentityTypeUtil.fromGrpcIdentityType(request.getIdentityType()),
|
||||
KeysGrpcService::checkKemSignedPreKey,
|
||||
(preKey, identityKey) -> KeysGrpcHelper.checkKemSignedPreKey(preKey, identityKey, INVALID_PUBLIC_KEY_EXCEPTION, INVALID_SIGNATURE_EXCEPTION),
|
||||
(identifier, preKeys) -> keysManager.storeKemOneTimePreKeys(identifier, authenticatedDevice.deviceId(), preKeys));
|
||||
|
||||
return SetPreKeyResponse.getDefaultInstance();
|
||||
@@ -177,7 +168,7 @@ public class KeysGrpcService extends SimpleKeysGrpc.KeysImplBase {
|
||||
storeRepeatedUseKey(authenticatedDevice.accountIdentifier(),
|
||||
request.getIdentityType(),
|
||||
request.getSignedPreKey(),
|
||||
KeysGrpcService::checkEcSignedPreKey,
|
||||
(preKey, identityKey) -> KeysGrpcHelper.checkEcSignedPreKey(preKey, identityKey, INVALID_PUBLIC_KEY_EXCEPTION, INVALID_SIGNATURE_EXCEPTION),
|
||||
(account, signedPreKey) -> {
|
||||
final IdentityType identityType = IdentityTypeUtil.fromGrpcIdentityType(request.getIdentityType());
|
||||
final UUID identifier = account.getIdentifier(identityType);
|
||||
@@ -195,7 +186,7 @@ public class KeysGrpcService extends SimpleKeysGrpc.KeysImplBase {
|
||||
storeRepeatedUseKey(authenticatedDevice.accountIdentifier(),
|
||||
request.getIdentityType(),
|
||||
request.getSignedPreKey(),
|
||||
KeysGrpcService::checkKemSignedPreKey,
|
||||
(preKey, identityKey) -> KeysGrpcHelper.checkKemSignedPreKey(preKey, identityKey, INVALID_PUBLIC_KEY_EXCEPTION, INVALID_SIGNATURE_EXCEPTION),
|
||||
(account, lastResortKey) -> {
|
||||
final UUID identifier =
|
||||
account.getIdentifier(IdentityTypeUtil.fromGrpcIdentityType(request.getIdentityType()));
|
||||
@@ -220,45 +211,6 @@ public class KeysGrpcService extends SimpleKeysGrpc.KeysImplBase {
|
||||
storeKeyFunction.apply(account, key).join();
|
||||
}
|
||||
|
||||
private static ECPreKey checkEcPreKey(final EcPreKey preKey) {
|
||||
try {
|
||||
return new ECPreKey(preKey.getKeyId(), new ECPublicKey(preKey.getPublicKey().toByteArray()));
|
||||
} catch (final InvalidKeyException e) {
|
||||
throw INVALID_PUBLIC_KEY_EXCEPTION;
|
||||
}
|
||||
}
|
||||
|
||||
private static ECSignedPreKey checkEcSignedPreKey(final EcSignedPreKey preKey, final IdentityKey identityKey) {
|
||||
try {
|
||||
final ECSignedPreKey ecSignedPreKey = new ECSignedPreKey(preKey.getKeyId(),
|
||||
new ECPublicKey(preKey.getPublicKey().toByteArray()),
|
||||
preKey.getSignature().toByteArray());
|
||||
|
||||
if (ecSignedPreKey.signatureValid(identityKey)) {
|
||||
return ecSignedPreKey;
|
||||
} else {
|
||||
throw INVALID_SIGNATURE_EXCEPTION;
|
||||
}
|
||||
} catch (final InvalidKeyException e) {
|
||||
throw INVALID_PUBLIC_KEY_EXCEPTION;
|
||||
}
|
||||
}
|
||||
|
||||
private static KEMSignedPreKey checkKemSignedPreKey(final KemSignedPreKey preKey, final IdentityKey identityKey) {
|
||||
try {
|
||||
final KEMSignedPreKey kemSignedPreKey = new KEMSignedPreKey(preKey.getKeyId(),
|
||||
new KEMPublicKey(preKey.getPublicKey().toByteArray()),
|
||||
preKey.getSignature().toByteArray());
|
||||
|
||||
if (kemSignedPreKey.signatureValid(identityKey)) {
|
||||
return kemSignedPreKey;
|
||||
} else {
|
||||
throw INVALID_SIGNATURE_EXCEPTION;
|
||||
}
|
||||
} catch (final InvalidKeyException e) {
|
||||
throw INVALID_PUBLIC_KEY_EXCEPTION;
|
||||
}
|
||||
}
|
||||
|
||||
private Account getAuthenticatedAccount(final UUID authenticatedAccountId) {
|
||||
return accountsManager.getByAccountIdentifier(authenticatedAccountId)
|
||||
|
||||
+12
@@ -30,6 +30,7 @@ import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.atomic.LongAdder;
|
||||
import javax.annotation.Nullable;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
@@ -65,12 +66,19 @@ public class MetricServerInterceptor implements ServerInterceptor {
|
||||
@VisibleForTesting
|
||||
static final String DURATION_TIMER_NAME = MetricsUtil.name(MetricServerInterceptor.class, "processingDuration");
|
||||
|
||||
private static final String ACTIVE_REQUESTS_GAUGE_NAME =
|
||||
MetricsUtil.name(MetricServerInterceptor.class, "activeRequests");
|
||||
|
||||
private final MeterRegistry meterRegistry;
|
||||
private final ClientReleaseManager clientReleaseManager;
|
||||
|
||||
private final LongAdder activeRequests;
|
||||
|
||||
public MetricServerInterceptor(final MeterRegistry meterRegistry, final ClientReleaseManager clientReleaseManager) {
|
||||
this.meterRegistry = meterRegistry;
|
||||
this.clientReleaseManager = clientReleaseManager;
|
||||
|
||||
this.activeRequests = meterRegistry.gauge(ACTIVE_REQUESTS_GAUGE_NAME, new LongAdder());
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -194,6 +202,8 @@ public class MetricServerInterceptor implements ServerInterceptor {
|
||||
this.requestBytesCounter = meterRegistry.counter(REQUEST_BYTES_COUNTER_NAME, tags);
|
||||
this.responseTimer = meterRegistry.timer(DURATION_TIMER_NAME, tags);
|
||||
this.sample = Timer.start(meterRegistry);
|
||||
|
||||
activeRequests.increment();
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -210,12 +220,14 @@ public class MetricServerInterceptor implements ServerInterceptor {
|
||||
@Override
|
||||
public void onComplete() {
|
||||
this.sample.stop(responseTimer);
|
||||
activeRequests.decrement();
|
||||
super.onComplete();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onCancel() {
|
||||
this.sample.stop(responseTimer);
|
||||
activeRequests.decrement();
|
||||
super.onCancel();
|
||||
}
|
||||
}
|
||||
|
||||
+5
-17
@@ -13,8 +13,6 @@ import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.stream.Collectors;
|
||||
import org.signal.chat.common.Badge;
|
||||
import org.signal.chat.common.BadgeSvg;
|
||||
import org.signal.chat.purchase.AmountList;
|
||||
import org.signal.chat.purchase.BackupConfiguration;
|
||||
import org.signal.chat.purchase.BackupLevelConfiguration;
|
||||
@@ -158,22 +156,12 @@ public class ProductConfigurationGrpcService extends SimpleProductConfigurationG
|
||||
|
||||
private static LevelConfiguration toProtoLevelConfiguration(
|
||||
final org.whispersystems.textsecuregcm.subscriptions.LevelConfiguration levelConfiguration) {
|
||||
final org.whispersystems.textsecuregcm.entities.Badge badge = levelConfiguration.badge();
|
||||
final Badge commonBadge = Badge.newBuilder()
|
||||
.setId(badge.getId())
|
||||
.setCategory(badge.getCategory())
|
||||
.setName(badge.getName())
|
||||
.setDescription(badge.getDescription())
|
||||
.addAllSprites6(badge.getSprites6())
|
||||
.setSvg(badge.getSvg())
|
||||
.addAllSvgs(badge.getSvgs().stream()
|
||||
.map(s -> BadgeSvg.newBuilder().setLight(s.getLight()).setDark(s.getDark()).build())
|
||||
.toList())
|
||||
.build();
|
||||
final LevelConfiguration.Builder builder = LevelConfiguration.newBuilder().setBadge(commonBadge);
|
||||
if (badge instanceof final PurchasableBadge purchasableBadge) {
|
||||
final LevelConfiguration.Builder builder = LevelConfiguration.newBuilder();
|
||||
if (levelConfiguration.badge() instanceof final PurchasableBadge purchasableBadge) {
|
||||
builder.setBadgeDurationSeconds(purchasableBadge.getDuration().toSeconds());
|
||||
}
|
||||
return builder.build();
|
||||
return builder
|
||||
.setBadge(BadgeGrpcHelper.toGrpcBadge(levelConfiguration.badge()))
|
||||
.build();
|
||||
}
|
||||
}
|
||||
+15
-2
@@ -129,7 +129,6 @@ public class ProfileAnonymousGrpcService extends SimpleProfileAnonymousGrpc.Prof
|
||||
return targetAccount.map(account ->
|
||||
GetUnversionedProfileAnonymousResponse.newBuilder()
|
||||
.setResult(ProfileGrpcHelper.buildUnversionedProfileResult(targetIdentifier,
|
||||
null,
|
||||
account,
|
||||
profileBadgeConverter))
|
||||
.build())
|
||||
@@ -142,7 +141,21 @@ public class ProfileAnonymousGrpcService extends SimpleProfileAnonymousGrpc.Prof
|
||||
public GetVersionedProfileAnonymousResponse getVersionedProfile(final GetVersionedProfileAnonymousRequest request) {
|
||||
final ServiceIdentifier targetIdentifier = GrpcServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getRequest().getAccountIdentifier());
|
||||
|
||||
final Optional<Account> targetAccount = getTargetAccountAndValidateUnidentifiedAccess(targetIdentifier, request.getUnidentifiedAccessKey().toByteArray());
|
||||
final Optional<Account> targetAccount = accountsManager.getByServiceIdentifier(targetIdentifier);
|
||||
|
||||
final boolean authorized = switch (request.getAuthenticationCase()) {
|
||||
case GROUP_SEND_TOKEN -> groupSendTokenUtil.checkGroupSendToken(request.getGroupSendToken(), targetIdentifier);
|
||||
case UNIDENTIFIED_ACCESS_KEY ->
|
||||
targetAccount.map(a -> UnidentifiedAccessUtil.checkUnidentifiedAccess(a, request.getUnidentifiedAccessKey().toByteArray()))
|
||||
.orElse(false);
|
||||
default -> throw GrpcExceptions.invalidArguments("invalid authentication");
|
||||
};
|
||||
|
||||
if (!authorized) {
|
||||
return GetVersionedProfileAnonymousResponse.newBuilder()
|
||||
.setFailedUnidentifiedAuthorization(FailedUnidentifiedAuthorization.getDefaultInstance())
|
||||
.build();
|
||||
}
|
||||
|
||||
return targetAccount.flatMap(account ->
|
||||
ProfileGrpcHelper.getVersionedProfile(account,
|
||||
|
||||
@@ -10,14 +10,11 @@ import com.google.protobuf.ByteString;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.time.Clock;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import org.signal.chat.common.Badge;
|
||||
import org.signal.chat.common.BadgeSvg;
|
||||
import org.signal.chat.common.S3UploadForm;
|
||||
import org.signal.chat.profile.DataEtag;
|
||||
import org.signal.chat.profile.GetExpiringProfileKeyCredentialResult;
|
||||
@@ -33,6 +30,7 @@ import org.signal.libsignal.zkgroup.profiles.ProfileKeyCredentialRequest;
|
||||
import org.signal.libsignal.zkgroup.profiles.ServerZkProfileOperations;
|
||||
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessChecksum;
|
||||
import org.whispersystems.textsecuregcm.badges.ProfileBadgeConverter;
|
||||
import org.whispersystems.textsecuregcm.entities.Badge;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
@@ -129,23 +127,6 @@ public class ProfileGrpcHelper {
|
||||
return Optional.of(responseBuilder.build());
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static List<Badge> buildBadges(final List<org.whispersystems.textsecuregcm.entities.Badge> badges) {
|
||||
final ArrayList<Badge> grpcBadges = new ArrayList<>();
|
||||
for (final org.whispersystems.textsecuregcm.entities.Badge badge : badges) {
|
||||
grpcBadges.add(Badge.newBuilder()
|
||||
.setId(badge.getId())
|
||||
.setCategory(badge.getCategory())
|
||||
.setName(badge.getName())
|
||||
.setDescription(badge.getDescription())
|
||||
.addAllSprites6(badge.getSprites6())
|
||||
.setSvg(badge.getSvg())
|
||||
.addAllSvgs(buildBadgeSvgs(badge.getSvgs()))
|
||||
.build());
|
||||
}
|
||||
return grpcBadges;
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static List<org.signal.chat.common.DeviceCapability> buildAccountCapabilities(final Account account) {
|
||||
return Arrays.stream(DeviceCapability.values())
|
||||
@@ -155,20 +136,8 @@ public class ProfileGrpcHelper {
|
||||
.toList();
|
||||
}
|
||||
|
||||
private static List<BadgeSvg> buildBadgeSvgs(final List<org.whispersystems.textsecuregcm.entities.BadgeSvg> badgeSvgs) {
|
||||
ArrayList<BadgeSvg> grpcBadgeSvgs = new ArrayList<>();
|
||||
for (final org.whispersystems.textsecuregcm.entities.BadgeSvg badgeSvg : badgeSvgs) {
|
||||
grpcBadgeSvgs.add(BadgeSvg.newBuilder()
|
||||
.setDark(badgeSvg.getDark())
|
||||
.setLight(badgeSvg.getLight())
|
||||
.build());
|
||||
}
|
||||
return grpcBadgeSvgs;
|
||||
}
|
||||
|
||||
static GetUnversionedProfileResult buildUnversionedProfileResult(
|
||||
final ServiceIdentifier targetIdentifier,
|
||||
final UUID requesterUuid,
|
||||
final Account targetAccount,
|
||||
final ProfileBadgeConverter profileBadgeConverter) {
|
||||
final GetUnversionedProfileResult.Builder resultBuilder = GetUnversionedProfileResult.newBuilder()
|
||||
@@ -177,11 +146,13 @@ public class ProfileGrpcHelper {
|
||||
|
||||
switch (targetIdentifier.identityType()) {
|
||||
case ACI -> {
|
||||
resultBuilder.setUnrestrictedUnidentifiedAccess(targetAccount.isUnrestrictedUnidentifiedAccess())
|
||||
.addAllBadges(
|
||||
buildBadges(profileBadgeConverter.convert(RequestAttributesUtil.getAvailableAcceptedLocales(),
|
||||
targetAccount.getBadges(),
|
||||
ProfileHelper.isSelfProfileRequest(requesterUuid, targetIdentifier))));
|
||||
final List<Locale> acceptedLocales = RequestAttributesUtil.getAvailableAcceptedLocales();
|
||||
final List<Badge> badges =
|
||||
profileBadgeConverter.convert(acceptedLocales, targetAccount.getBadges(), false);
|
||||
|
||||
resultBuilder
|
||||
.setUnrestrictedUnidentifiedAccess(targetAccount.isUnrestrictedUnidentifiedAccess())
|
||||
.addAllBadges(badges.stream().map(BadgeGrpcHelper::toGrpcBadge).toList());
|
||||
|
||||
targetAccount.getUnidentifiedAccessKey()
|
||||
.map(UnidentifiedAccessChecksum::generateFor)
|
||||
|
||||
@@ -260,7 +260,6 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
|
||||
|
||||
return maybeAccount.map(account -> GetUnversionedProfileResponse.newBuilder()
|
||||
.setResult(ProfileGrpcHelper.buildUnversionedProfileResult(targetIdentifier,
|
||||
authenticatedDevice.accountIdentifier(),
|
||||
account,
|
||||
profileBadgeConverter))
|
||||
.build()).orElseGet(() -> GetUnversionedProfileResponse.newBuilder()
|
||||
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
package org.whispersystems.textsecuregcm.mappers;
|
||||
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import jakarta.ws.rs.ext.ExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.auth.RegistrationLockFailureException;
|
||||
import org.whispersystems.textsecuregcm.auth.RegistrationLockVerificationManager;
|
||||
|
||||
public class RegistrationLockFailureExceptionMapper implements ExceptionMapper<RegistrationLockFailureException> {
|
||||
|
||||
@Override
|
||||
public Response toResponse(final RegistrationLockFailureException exception) {
|
||||
return Response.status(RegistrationLockVerificationManager.FAILURE_HTTP_STATUS)
|
||||
.entity(exception.getFailure())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
+15
@@ -16,6 +16,7 @@ import io.micrometer.core.instrument.Tags;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.atomic.LongAdder;
|
||||
import javax.annotation.Nullable;
|
||||
import org.glassfish.jersey.server.ContainerResponse;
|
||||
import org.glassfish.jersey.server.monitoring.RequestEvent;
|
||||
@@ -44,6 +45,8 @@ public class MetricsRequestEventListener implements RequestEventListener {
|
||||
public static final String RESPONSE_BYTES_COUNTER_NAME = name(MetricsRequestEventListener.class, "responseBytes");
|
||||
public static final String REQUEST_BYTES_COUNTER_NAME = name(MetricsRequestEventListener.class, "requestBytes");
|
||||
|
||||
private static final String ACTIVE_REQUESTS_GAUGE_NAME = name(MetricsRequestEventListener.class, "activeRequests");
|
||||
|
||||
@VisibleForTesting
|
||||
static final String PATH_TAG = "path";
|
||||
|
||||
@@ -65,6 +68,8 @@ public class MetricsRequestEventListener implements RequestEventListener {
|
||||
private final TrafficSource trafficSource;
|
||||
private final MeterRegistry meterRegistry;
|
||||
|
||||
private final LongAdder activeRequests;
|
||||
|
||||
public MetricsRequestEventListener(final TrafficSource trafficSource, final ClientReleaseManager clientReleaseManager) {
|
||||
this(trafficSource, Metrics.globalRegistry, clientReleaseManager);
|
||||
|
||||
@@ -81,10 +86,20 @@ public class MetricsRequestEventListener implements RequestEventListener {
|
||||
this.trafficSource = trafficSource;
|
||||
this.meterRegistry = meterRegistry;
|
||||
this.clientReleaseManager = clientReleaseManager;
|
||||
|
||||
this.activeRequests = meterRegistry.gauge(ACTIVE_REQUESTS_GAUGE_NAME, new LongAdder());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onEvent(final RequestEvent event) {
|
||||
if (event.getType() == RequestEvent.Type.RESOURCE_METHOD_START) {
|
||||
activeRequests.increment();
|
||||
}
|
||||
|
||||
if (event.getType() == RequestEvent.Type.RESOURCE_METHOD_FINISHED) {
|
||||
activeRequests.decrement();
|
||||
}
|
||||
|
||||
if (event.getType() == RequestEvent.Type.FINISHED) {
|
||||
if (!event.getUriInfo().getMatchedTemplates().isEmpty()) {
|
||||
@Nullable final UserAgent userAgent;
|
||||
|
||||
+3
-3
@@ -1,6 +1,6 @@
|
||||
package org.whispersystems.textsecuregcm.spam;
|
||||
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import jakarta.annotation.Nullable;
|
||||
|
||||
public interface RegistrationRecoveryChecker {
|
||||
|
||||
@@ -11,9 +11,9 @@ public interface RegistrationRecoveryChecker {
|
||||
* @param e164 The E164 formatted phone number of the requester
|
||||
* @return true if the registration recovery attempt is allowed, false otherwise.
|
||||
*/
|
||||
boolean checkRegistrationRecoveryAttempt(final ContainerRequestContext requestContext, final String e164);
|
||||
boolean checkRegistrationRecoveryAttempt(String e164, @Nullable String userAgent, @Nullable String acceptLanguage, @Nullable String mostRecentProxy);
|
||||
|
||||
static RegistrationRecoveryChecker noop() {
|
||||
return (ignoredCtx, ignoredE164) -> true;
|
||||
return (_, _, _, _) -> true;
|
||||
}
|
||||
}
|
||||
+22
-2
@@ -34,6 +34,9 @@ public class AcknowledgementMirroringMessageStream implements MessageStream {
|
||||
@VisibleForTesting
|
||||
static final int MAX_PENDING_ACKNOWLEDGEMENTS = 8192;
|
||||
|
||||
@VisibleForTesting
|
||||
static final int FOUNDATIONDB_REQUEST_SIZE = 100;
|
||||
|
||||
private static final Counter HIGH_PENDING_ACKNOWLEDGEMENT_COUNT_WARNING_COUNTER =
|
||||
Metrics.counter(MetricsUtil.name(AcknowledgementMirroringMessageStream.class, "highPendingAcknowledgementCount"));
|
||||
|
||||
@@ -44,6 +47,9 @@ public class AcknowledgementMirroringMessageStream implements MessageStream {
|
||||
|
||||
private final BiConsumer<UUID, Long> mirroredMessageHandler;
|
||||
|
||||
private long mirroredEntriesDelivered = 0;
|
||||
private long requested = 0;
|
||||
|
||||
private FoundationDbSubscriber(final BiConsumer<UUID, Long> mirroredMessageHandler) {
|
||||
this.mirroredMessageHandler = mirroredMessageHandler;
|
||||
}
|
||||
@@ -56,8 +62,22 @@ public class AcknowledgementMirroringMessageStream implements MessageStream {
|
||||
case MessageStreamEntry.QueueEmpty _ -> false;
|
||||
};
|
||||
|
||||
if (isMirroredMessage) {
|
||||
request(1);
|
||||
if (!isMirroredMessage) {
|
||||
return;
|
||||
}
|
||||
|
||||
final boolean requestMore;
|
||||
|
||||
synchronized (this) {
|
||||
requestMore = ++mirroredEntriesDelivered > requested;
|
||||
|
||||
if (requestMore) {
|
||||
requested += FOUNDATIONDB_REQUEST_SIZE;
|
||||
}
|
||||
}
|
||||
|
||||
if (requestMore) {
|
||||
request(FOUNDATIONDB_REQUEST_SIZE);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+14
-11
@@ -6,11 +6,10 @@ package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import com.google.common.net.HttpHeaders;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tag;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import java.io.IOException;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
@@ -22,8 +21,12 @@ import javax.annotation.Nullable;
|
||||
import org.signal.libsignal.protocol.IdentityKey;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.InvalidRegistrationSessionException;
|
||||
import org.whispersystems.textsecuregcm.auth.PhoneVerificationTokenManager;
|
||||
import org.whispersystems.textsecuregcm.auth.RecoveryPasswordVerificationFailedException;
|
||||
import org.whispersystems.textsecuregcm.auth.RegistrationLockFailureException;
|
||||
import org.whispersystems.textsecuregcm.auth.RegistrationLockVerificationManager;
|
||||
import org.whispersystems.textsecuregcm.auth.UnverifiedRegistrationSessionException;
|
||||
import org.whispersystems.textsecuregcm.controllers.AccountControllerV2;
|
||||
import org.whispersystems.textsecuregcm.controllers.MessageDeliveryNotAllowedException;
|
||||
import org.whispersystems.textsecuregcm.controllers.MismatchedDevicesException;
|
||||
@@ -88,10 +91,10 @@ public class ChangeNumberManager {
|
||||
final Map<Byte, KEMSignedPreKey> devicePqLastResortPreKeys,
|
||||
final List<IncomingMessage> deviceMessages,
|
||||
final Map<Byte, Integer> pniRegistrationIds,
|
||||
final ContainerRequestContext containerRequestContext)
|
||||
throws InterruptedException, MismatchedDevicesException, MessageTooLargeException, RateLimitExceededException, MessageDeliveryNotAllowedException {
|
||||
|
||||
final String senderUserAgent = containerRequestContext.getHeaderString(HttpHeaders.USER_AGENT);
|
||||
@Nullable final String userAgent,
|
||||
@Nullable final String acceptLanguage,
|
||||
@Nullable final String mostRecentProxy)
|
||||
throws InterruptedException, MismatchedDevicesException, MessageTooLargeException, RateLimitExceededException, MessageDeliveryNotAllowedException, RegistrationLockFailureException, UnverifiedRegistrationSessionException, InvalidRegistrationSessionException, IOException, RecoveryPasswordVerificationFailedException {
|
||||
|
||||
final Pair<Account, Optional<Account>> accountAndMaybeExistingAccount =
|
||||
accountsManager.getAccountsForChangeNumber(accountIdentifier, number);
|
||||
@@ -110,16 +113,16 @@ public class ChangeNumberManager {
|
||||
rateLimiters.getRegistrationLimiter().validate(number);
|
||||
|
||||
final PhoneVerificationRequest.VerificationType verificationType =
|
||||
phoneVerificationTokenManager.verify(containerRequestContext, number, sessionId, recoveryPassword);
|
||||
phoneVerificationTokenManager.verify(number, userAgent, acceptLanguage, mostRecentProxy, sessionId, recoveryPassword);
|
||||
|
||||
final Optional<Account> existingAccount = accountAndMaybeExistingAccount.second();
|
||||
|
||||
if (existingAccount.isPresent()) {
|
||||
registrationLockVerificationManager.verifyRegistrationLock(existingAccount.get(), registrationLock,
|
||||
senderUserAgent, RegistrationLockVerificationManager.Flow.CHANGE_NUMBER, verificationType);
|
||||
userAgent, RegistrationLockVerificationManager.Flow.CHANGE_NUMBER, verificationType);
|
||||
}
|
||||
|
||||
Metrics.counter(CHANGE_NUMBER_COUNTER_NAME, Tags.of(UserAgentTagUtil.getPlatformTag(senderUserAgent),
|
||||
Metrics.counter(CHANGE_NUMBER_COUNTER_NAME, Tags.of(UserAgentTagUtil.getPlatformTag(userAgent),
|
||||
Tag.of(VERIFICATION_TYPE_TAG_NAME, verificationType.name())))
|
||||
.increment();
|
||||
}
|
||||
@@ -152,7 +155,7 @@ public class ChangeNumberManager {
|
||||
messagesByDeviceId,
|
||||
registrationIdsByDeviceId,
|
||||
Optional.of(Device.PRIMARY_ID),
|
||||
senderUserAgent);
|
||||
userAgent);
|
||||
}
|
||||
|
||||
final Account updatedAccount = accountsManager.changeNumber(
|
||||
@@ -170,7 +173,7 @@ public class ChangeNumberManager {
|
||||
messagesByDeviceId,
|
||||
registrationIdsByDeviceId,
|
||||
Optional.of(Device.PRIMARY_ID),
|
||||
senderUserAgent);
|
||||
userAgent);
|
||||
} catch (final RuntimeException e) {
|
||||
logger.warn("Changed number but could not send all device messages for {}",
|
||||
account.getIdentifier(IdentityType.ACI), e);
|
||||
|
||||
+44
-8
@@ -61,12 +61,18 @@ public class MessagesManager {
|
||||
private static final String PRESENCE_MATCH_COUNTER_NAME =
|
||||
MetricsUtil.name(MessagesManager.class, "presenceMatch");
|
||||
|
||||
private static final Counter INSERT_TIMEOUT_COUNTER =
|
||||
Metrics.counter(name(MessagesManager.class, "insertTimeout"));
|
||||
|
||||
@VisibleForTesting
|
||||
static final String MIRROR_INSERTS_EXPERIMENT_NAME = "foundationDbMirrorInserts";
|
||||
|
||||
@VisibleForTesting
|
||||
static final String MIRROR_DELETIONS_EXPERIMENT_NAME = "foundationDbMirrorDeletions";
|
||||
|
||||
@VisibleForTesting
|
||||
static final String MIRROR_READS_EXPERIMENT_NAME = "foundationDbMirrorReads";
|
||||
|
||||
private static final long FOUNDATIONDB_INSERT_TIMEOUT_MILLIS = Duration.ofSeconds(2).toMillis();
|
||||
|
||||
private final MessagesDynamoDb messagesDynamoDb;
|
||||
@@ -129,10 +135,14 @@ public class MessagesManager {
|
||||
foundationDbMessageStore.insert(new AciServiceIdentifier(accountIdentifier), minimizedMessagesByDeviceId)
|
||||
.orTimeout(FOUNDATIONDB_INSERT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)
|
||||
.exceptionally(e -> {
|
||||
logger.warn("Failed to insert {} message(s) for {} into FoundationDB",
|
||||
minimizedMessagesByDeviceId.size(),
|
||||
accountIdentifier,
|
||||
e);
|
||||
if (e instanceof TimeoutException) {
|
||||
INSERT_TIMEOUT_COUNTER.increment();
|
||||
} else {
|
||||
logger.warn("Failed to insert {} message(s) for {} into FoundationDB",
|
||||
minimizedMessagesByDeviceId.size(),
|
||||
accountIdentifier,
|
||||
e);
|
||||
}
|
||||
|
||||
return Collections.emptyMap();
|
||||
});
|
||||
@@ -283,11 +293,12 @@ public class MessagesManager {
|
||||
new RedisDynamoDbMessageStream(messagesDynamoDb, messagesCache, redisMessageAvailabilityManager,
|
||||
destinationUuid, destinationDevice);
|
||||
|
||||
return experimentEnrollmentManager.isEnrolled(destinationUuid, MIRROR_DELETIONS_EXPERIMENT_NAME)
|
||||
? new AcknowledgementMirroringMessageStream(
|
||||
return new MirroringMessageStream(
|
||||
redisDynamoDbMessageStream,
|
||||
foundationDbMessageStore.getMessages(new AciServiceIdentifier(destinationUuid), destinationDevice.getId()))
|
||||
: redisDynamoDbMessageStream;
|
||||
foundationDbMessageStore.getMessages(new AciServiceIdentifier(destinationUuid), destinationDevice.getId()),
|
||||
experimentEnrollmentManager,
|
||||
destinationUuid,
|
||||
destinationDevice.getId());
|
||||
}
|
||||
|
||||
Publisher<Envelope> getMessagesForDevice(final UUID destinationUuid, final Device destinationDevice) {
|
||||
@@ -386,4 +397,29 @@ public class MessagesManager {
|
||||
final SealedSenderMultiRecipientMessage sealedSenderMultiRecipientMessage) {
|
||||
return messagesCache.insertSharedMultiRecipientMessagePayload(sealedSenderMultiRecipientMessage);
|
||||
}
|
||||
|
||||
/// Record versionstamps for the current time in the FoundationDB database(s).
|
||||
public void recordFoundationDbVersionstamps() {
|
||||
foundationDbMessageStore.recordVersionstamps();
|
||||
}
|
||||
|
||||
/// Clean up expired entries in the FoundationDB versionstamp clock.
|
||||
///
|
||||
/// @param oldestRetainedEntryTimestamp the earliest time for which we still want to be able to obtain a versionstamp
|
||||
public void expireOldFoundationDbVersionstamps(final Instant oldestRetainedEntryTimestamp) {
|
||||
foundationDbMessageStore.expireOldVersionstamps(oldestRetainedEntryTimestamp);
|
||||
}
|
||||
|
||||
/// Delete messages in FoundationDB for the given devices that were inserted before the given
|
||||
/// time. (Expiration of messages from Redis and Dynamo is handled automatically and do not
|
||||
/// require any interaction with this class.)
|
||||
///
|
||||
/// @param accountDeviceIdentifiers a map from ACI to the list of device IDs for which expired messages should be
|
||||
/// trimmed.
|
||||
///
|
||||
/// @param cutoffTime the expiration threshold. Messages inserted before this time may be deleted; messages inserted
|
||||
/// after it will not be.
|
||||
public void deleteFoundationDbMessagesBefore(final Map<AciServiceIdentifier, List<Byte>> accountDeviceIdentifiers, final Instant cutoffTime) {
|
||||
foundationDbMessageStore.deleteMessagesBefore(accountDeviceIdentifiers, cutoffTime);
|
||||
}
|
||||
}
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Flow;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStream;
|
||||
import reactor.adapter.JdkFlowAdapter;
|
||||
import reactor.core.Disposable;
|
||||
|
||||
/// A temporary message stream that can mirror message acknowledgements (deletion requests) to FoundationDB
|
||||
public class MirroringMessageStream implements MessageStream {
|
||||
|
||||
private final RedisDynamoDbMessageStream redisDynamoDbMessageStream;
|
||||
private final FoundationDbMessageStream foundationDbMessageStream;
|
||||
private final ExperimentEnrollmentManager experimentEnrollmentManager;
|
||||
|
||||
private final AciServiceIdentifier accountIdentifier;
|
||||
private final byte deviceId;
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(MirroringMessageStream.class);
|
||||
|
||||
public MirroringMessageStream(final RedisDynamoDbMessageStream redisDynamoDbMessageStream,
|
||||
final FoundationDbMessageStream foundationDbMessageStream,
|
||||
final ExperimentEnrollmentManager experimentEnrollmentManager,
|
||||
final UUID accountIdentifier,
|
||||
final byte deviceId) {
|
||||
|
||||
this.redisDynamoDbMessageStream = redisDynamoDbMessageStream;
|
||||
this.foundationDbMessageStream = foundationDbMessageStream;
|
||||
this.experimentEnrollmentManager = experimentEnrollmentManager;
|
||||
|
||||
this.accountIdentifier = new AciServiceIdentifier(accountIdentifier);
|
||||
this.deviceId = deviceId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Flow.Publisher<MessageStreamEntry> getMessages() {
|
||||
if (experimentEnrollmentManager.isEnrolled(accountIdentifier.uuid(), MessagesManager.MIRROR_READS_EXPERIMENT_NAME)) {
|
||||
final Disposable foundationDbDisposable =
|
||||
foundationDbMessageStream.getFiniteMessageStream()
|
||||
.limitRate(100)
|
||||
.subscribe();
|
||||
|
||||
return JdkFlowAdapter.publisherToFlowPublisher(
|
||||
JdkFlowAdapter.flowPublisherToFlux(redisDynamoDbMessageStream.getMessages())
|
||||
.doFinally(_ -> {
|
||||
try {
|
||||
foundationDbDisposable.dispose();
|
||||
} catch (final Exception _) {
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
return redisDynamoDbMessageStream.getMessages();
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Void> acknowledgeMessage(final UUID messageGuid, final long serverTimestamp) {
|
||||
// All messages stored in FoundationDB use version 8 UUIDs; if a message has a version 4 UUID, then it only exists
|
||||
// in Redis/DynamoDB
|
||||
if (messageGuid.version() == 8 &&
|
||||
experimentEnrollmentManager.isEnrolled(accountIdentifier.uuid(), MessagesManager.MIRROR_DELETIONS_EXPERIMENT_NAME)) {
|
||||
|
||||
foundationDbMessageStream.acknowledgeMessage(messageGuid, serverTimestamp)
|
||||
.whenComplete((_, throwable) -> {
|
||||
if (throwable != null) {
|
||||
logger.warn("Failed to delete message {}/{}/{} from FoundationDb", accountIdentifier.uuid(), deviceId,
|
||||
messageGuid, throwable);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return redisDynamoDbMessageStream.acknowledgeMessage(messageGuid, serverTimestamp);
|
||||
}
|
||||
}
|
||||
-113
@@ -1,113 +0,0 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage.foundationdb;
|
||||
|
||||
import com.apple.foundationdb.tuple.Versionstamp;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.NavigableMap;
|
||||
import java.util.TreeMap;
|
||||
|
||||
/// An acknowledged message buffer keeps track of messages that have been sent, whether they have been acknowledged by
|
||||
/// the recipient, and whether those acknowledgements have been flushed to the underlying data store. It also batches
|
||||
/// acknowledgements into contiguous ranges in the interest of efficiency.
|
||||
class AcknowledgedMessageBuffer {
|
||||
|
||||
/// The maximum number of unacknowledged messages we will send before closing the stream with an error
|
||||
private final int maxUnacknowledgedMessages;
|
||||
|
||||
/// Map of versionstamp -> acknowledged? to keep track of acknowledged versionstamp ranges to clear
|
||||
private final NavigableMap<Versionstamp, Boolean> sentVersionstamps = new TreeMap<>();
|
||||
private int unacknowledgedMessages = 0;
|
||||
|
||||
AcknowledgedMessageBuffer(final int maxUnacknowledgedMessages) {
|
||||
this.maxUnacknowledgedMessages = maxUnacknowledgedMessages;
|
||||
}
|
||||
|
||||
public synchronized void addUnacknowledgedMessage(final Versionstamp versionstamp) throws TooManyUnacknowledgedMessagesException {
|
||||
if (++unacknowledgedMessages > maxUnacknowledgedMessages) {
|
||||
throw new TooManyUnacknowledgedMessagesException();
|
||||
}
|
||||
|
||||
sentVersionstamps.put(versionstamp, false);
|
||||
}
|
||||
|
||||
public synchronized void acknowledgeMessage(final Versionstamp versionstamp) {
|
||||
// If we don't know about this versionstamp, or it's already acknowledged, there's nothing to do
|
||||
if (!sentVersionstamps.containsKey(versionstamp) || sentVersionstamps.get(versionstamp)) {
|
||||
return;
|
||||
}
|
||||
|
||||
unacknowledgedMessages--;
|
||||
sentVersionstamps.put(versionstamp, true);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
int getUnacknowledgedMessageCount() {
|
||||
return unacknowledgedMessages;
|
||||
}
|
||||
|
||||
/// Computes a list of acknowledged contiguous versionstamp ranges that can be cleared from the database and removes
|
||||
/// them from ths unacknowledged mesage buffer.
|
||||
///
|
||||
/// @return a list of acknowledged contiguous versionstamp ranges that can be cleared from the database.
|
||||
public synchronized List<Pair<Versionstamp, Versionstamp>> takeFlushableRanges() {
|
||||
final List<Pair<Versionstamp, Versionstamp>> flushableRanges = computeFlushableRanges();
|
||||
flushableRanges.forEach(range -> sentVersionstamps.subMap(range.first(), true, range.second(), true).clear());
|
||||
|
||||
return flushableRanges;
|
||||
}
|
||||
|
||||
/// Computes a list of acknowledged contiguous versionstamp ranges that can be cleared from the database.
|
||||
///
|
||||
/// @return a list of acknowledged contiguous versionstamp ranges that can be cleared from the database.
|
||||
@VisibleForTesting
|
||||
synchronized List<Pair<Versionstamp, Versionstamp>> computeFlushableRanges() {
|
||||
final List<Pair<Versionstamp, Versionstamp>> flushableRanges = new ArrayList<>();
|
||||
Versionstamp startInclusive = null;
|
||||
Versionstamp endInclusive = null;
|
||||
|
||||
for (final Map.Entry<Versionstamp, Boolean> entry : sentVersionstamps.entrySet()) {
|
||||
if (entry.getValue()) {
|
||||
// Message is acknowledged, so we can either start tracking a new range if we aren't already, or extend our
|
||||
// current range
|
||||
if (startInclusive == null) {
|
||||
startInclusive = entry.getKey();
|
||||
}
|
||||
endInclusive = entry.getKey();
|
||||
} else {
|
||||
// Message is un-acknowledged, which means either it is a "range-breaker" or we never started tracking an
|
||||
// acknowledged range. Mark the currently tracked range flushable, if it exists.
|
||||
if (startInclusive != null) {
|
||||
assert endInclusive != null;
|
||||
flushableRanges.add(new Pair<>(startInclusive, endInclusive));
|
||||
startInclusive = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (startInclusive != null) {
|
||||
assert endInclusive != null;
|
||||
flushableRanges.add(new Pair<>(startInclusive, endInclusive));
|
||||
}
|
||||
|
||||
return flushableRanges;
|
||||
}
|
||||
|
||||
|
||||
/// Acknowledges a stale ephemeral message for cleanup from FoundationDB.
|
||||
/// Ephemeral messages are only delivered when the recipient has an active message stream, so any ephemeral message
|
||||
/// read from the finite publisher is stale by definition and can be immediately acknowledged and discarded.
|
||||
///
|
||||
/// @param versionstamp The versionstamp to acknowledge
|
||||
public synchronized void acknowledgeStaleEphemeralMessage(final Versionstamp versionstamp) {
|
||||
sentVersionstamps.put(versionstamp, true);
|
||||
}
|
||||
|
||||
}
|
||||
+52
-90
@@ -10,9 +10,9 @@ import com.google.protobuf.InvalidProtocolBufferException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.time.Clock;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.ScheduledFuture;
|
||||
@@ -20,15 +20,13 @@ import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Supplier;
|
||||
import javax.annotation.Nullable;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.FluxSink;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
/// Publishes a message stream from a device queue in FoundationDB. Capable of publishing both a finite stream for
|
||||
/// catching up to end-of-queue,and an infinite stream for live updates.
|
||||
@@ -60,10 +58,6 @@ class FoundationDbMessagePublisher {
|
||||
/// Listener to watch for state machine transitions; used for testing.
|
||||
private final BiConsumer<State, State> stateChangeListener;
|
||||
|
||||
/// A supplier that returns a function to execute before we begin fetching a page; it is passed the transaction that
|
||||
/// is started for the page fetch operations.
|
||||
private final Supplier<Consumer<Transaction>> beforePageFetch;
|
||||
|
||||
/// Whether the publisher is finite or infinite.
|
||||
private final boolean terminateOnQueueEmpty;
|
||||
|
||||
@@ -131,8 +125,7 @@ class FoundationDbMessagePublisher {
|
||||
@Nullable final byte[] presenceKey,
|
||||
@Nullable final ScheduledExecutorService presenceRenewalExecutorService,
|
||||
@Nullable final byte[] messagesAvailableWatchKey,
|
||||
@Nullable final BiConsumer<State, State> stateChangeListener,
|
||||
final Supplier<Consumer<Transaction>> beforePageFetch) {
|
||||
@Nullable final BiConsumer<State, State> stateChangeListener) {
|
||||
|
||||
this.database = database;
|
||||
this.clock = clock;
|
||||
@@ -143,37 +136,37 @@ class FoundationDbMessagePublisher {
|
||||
this.messagesAvailableWatchKey = messagesAvailableWatchKey;
|
||||
this.terminateOnQueueEmpty = messagesAvailableWatchKey == null;
|
||||
this.stateChangeListener = stateChangeListener != null ? stateChangeListener : (_, _) -> {};
|
||||
this.beforePageFetch = beforePageFetch;
|
||||
|
||||
if (!terminateOnQueueEmpty) {
|
||||
Objects.requireNonNull(presenceKey);
|
||||
Objects.requireNonNull(presenceRenewalExecutorService);
|
||||
}
|
||||
|
||||
this.messagePublisher = Flux.<FoundationDbMessageStreamEntry.Message>create(emitter -> {
|
||||
this.emitter = emitter;
|
||||
emitter.onRequest(n -> {
|
||||
final long totalRequestedCount = totalRequested.addAndGet(n);
|
||||
if (totalRequestedCount > totalEmitted.get()) {
|
||||
transitionStateOnEvent(Event.DEMAND_REQUESTED);
|
||||
}
|
||||
});
|
||||
emitter.onDispose(this::onDispose);
|
||||
}).doOnSubscribe(_ -> {
|
||||
if (!terminateOnQueueEmpty) {
|
||||
// Establish presence immediately and block until we do. We must establish presence for watches to work as
|
||||
// expected. If we fail to establish presence, then this non-terminating stream will never learn about new
|
||||
// messages. If establishing presence throws an exception, then the whole publisher will terminate with that
|
||||
// exception.
|
||||
database.run(transaction -> {
|
||||
setPresence(transaction);
|
||||
return null;
|
||||
});
|
||||
|
||||
// Refresh presence at regular intervals
|
||||
startPresenceRenewal(presenceRenewalExecutorService);
|
||||
}
|
||||
});
|
||||
this.messagePublisher = Mono.fromFuture(() -> {
|
||||
if (!terminateOnQueueEmpty) {
|
||||
// Establish presence before attempting to fetch messages. We must establish presence for watches to work as
|
||||
// expected. If we fail to establish presence, then this non-terminating stream will never learn about new
|
||||
// messages. If establishing presence throws an exception, then the whole publisher will terminate with that
|
||||
// exception.
|
||||
return database.runAsync(transaction -> {
|
||||
setPresence(transaction);
|
||||
return CompletableFuture.completedFuture(null);
|
||||
})
|
||||
.thenRun(() -> startPresenceRenewal(presenceRenewalExecutorService));
|
||||
} else {
|
||||
return CompletableFuture.completedFuture(null);
|
||||
}
|
||||
})
|
||||
.thenMany(Flux.create(emitter -> {
|
||||
this.emitter = emitter;
|
||||
emitter.onRequest(n -> {
|
||||
final long totalRequestedCount = totalRequested.addAndGet(n);
|
||||
if (totalRequestedCount > totalEmitted.get()) {
|
||||
transitionStateOnEvent(Event.DEMAND_REQUESTED);
|
||||
}
|
||||
});
|
||||
emitter.onDispose(this::onDispose);
|
||||
}));
|
||||
}
|
||||
|
||||
/// Creates a [FoundationDbMessagePublisher] that publishes a stream of messages in a queue that terminates when it
|
||||
@@ -185,8 +178,7 @@ class FoundationDbMessagePublisher {
|
||||
final Clock clock,
|
||||
final KeySelector beginKeyInclusive,
|
||||
final KeySelector endKeyExclusive,
|
||||
final int maxMessagesPerScan,
|
||||
final Supplier<Consumer<Transaction>> beforePageFetch) {
|
||||
final int maxMessagesPerScan) {
|
||||
|
||||
return new FoundationDbMessagePublisher(database,
|
||||
clock,
|
||||
@@ -196,8 +188,7 @@ class FoundationDbMessagePublisher {
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
beforePageFetch);
|
||||
null);
|
||||
}
|
||||
|
||||
/// Creates a [FoundationDbMessagePublisher] that publishes a non-terminating stream of messages from a device queue.
|
||||
@@ -211,8 +202,7 @@ class FoundationDbMessagePublisher {
|
||||
final int maxMessagesPerScan,
|
||||
final byte[] presenceKey,
|
||||
final ScheduledExecutorService presenceRenewalExecutorService,
|
||||
final byte[] messagesAvailableWatchKey,
|
||||
final Supplier<Consumer<Transaction>> beforePageFetch) {
|
||||
final byte[] messagesAvailableWatchKey) {
|
||||
|
||||
return new FoundationDbMessagePublisher(database,
|
||||
clock,
|
||||
@@ -222,8 +212,7 @@ class FoundationDbMessagePublisher {
|
||||
presenceKey,
|
||||
presenceRenewalExecutorService,
|
||||
messagesAvailableWatchKey,
|
||||
null,
|
||||
beforePageFetch);
|
||||
null);
|
||||
}
|
||||
|
||||
private synchronized void setState(final State newState, final Event event) {
|
||||
@@ -312,70 +301,43 @@ class FoundationDbMessagePublisher {
|
||||
|
||||
/// Fetch messages using a range query limiting batch size to [#maxMessagesPerScan]. If the query returns fewer than
|
||||
/// [#maxMessagesPerScan], emit [Event#FETCHED_ALL_AVAILABLE_MESSAGES]. In the case of an infinite publisher, also set
|
||||
/// a watch for new messages. Execute the function supplied by [#beforePageFetch] in the context of the transaction.
|
||||
/// Additionally, the cursor is updated so that we begin fetching from the right key on
|
||||
/// subsequent scans
|
||||
/// a watch for new messages. Additionally, the cursor is updated so that we begin fetching from the right key on
|
||||
/// subsequent scans.
|
||||
///
|
||||
/// @return a future of a list of [FoundationDbMessageStreamEntry.Message] with a max size of [#maxMessagesPerScan]
|
||||
private CompletableFuture<List<FoundationDbMessageStreamEntry.Message>> getMessagesBatch() {
|
||||
final Consumer<Transaction> doBeforePageFetch = beforePageFetch.get();
|
||||
return database.runAsync(transaction ->
|
||||
transaction.getRange(beginKeyCursor, endKeyExclusive, maxMessagesPerScan, false, StreamingMode.EXACT).asList()
|
||||
.thenApply(keyValues -> {
|
||||
if (keyValues.size() < maxMessagesPerScan && !terminateOnQueueEmpty) {
|
||||
setWatch(transaction);
|
||||
}
|
||||
|
||||
return database.runAsync(transaction -> {
|
||||
doBeforePageFetch.accept(transaction);
|
||||
|
||||
return getItemsInRange(transaction, beginKeyCursor, endKeyExclusive, maxMessagesPerScan)
|
||||
.thenApply(lastKeyReadAndItems -> {
|
||||
if (lastKeyReadAndItems.second().size() < maxMessagesPerScan && !terminateOnQueueEmpty) {
|
||||
setWatch(transaction);
|
||||
}
|
||||
|
||||
return lastKeyReadAndItems;
|
||||
});
|
||||
})
|
||||
// Defer any state mutations until after the transaction has been committed. The transaction block can
|
||||
// fail/retry, and we don't want to trigger spurious state transitions when that happens.
|
||||
.thenApply(lastKeyReadAndItems -> {
|
||||
// Set our beginning key to just past the last key read so that we're ready for our next fetch
|
||||
lastKeyReadAndItems.first()
|
||||
.ifPresent(lastKeyRead -> beginKeyCursor = KeySelector.firstGreaterThan(lastKeyRead));
|
||||
|
||||
if (lastKeyReadAndItems.second().size() < maxMessagesPerScan) {
|
||||
return keyValues;
|
||||
}))
|
||||
.thenApply(keyValues -> {
|
||||
if (keyValues.size() < maxMessagesPerScan) {
|
||||
transitionStateOnEvent(Event.FETCHED_ALL_AVAILABLE_MESSAGES);
|
||||
}
|
||||
|
||||
return lastKeyReadAndItems.second();
|
||||
});
|
||||
}
|
||||
if (keyValues.isEmpty()) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
/// Fetch messages in the range between `begin` and `end` limited to a batch size of `maxMessagesPerSccan`
|
||||
///
|
||||
/// @param transaction the FoundationDB transaction in which to perform the read query
|
||||
/// @param beginInclusive the range start key (inclusive)
|
||||
/// @param endExclusive the range end key (exclusive)
|
||||
/// @param maxMessagesPerScan maximum number of messages to return in the fetch query
|
||||
/// @return the last key read (if there were non-zero number of messages read) and the list of messages read
|
||||
private CompletableFuture<Pair<Optional<byte[]>, List<FoundationDbMessageStreamEntry.Message>>> getItemsInRange(
|
||||
final Transaction transaction,
|
||||
final KeySelector beginInclusive,
|
||||
final KeySelector endExclusive,
|
||||
final int maxMessagesPerScan) {
|
||||
return transaction.getRange(beginInclusive, endExclusive, maxMessagesPerScan, false, StreamingMode.EXACT).asList()
|
||||
.thenApply(keyValues -> {
|
||||
final Optional<byte[]> lastKeyRead = keyValues.isEmpty()
|
||||
? Optional.empty()
|
||||
: Optional.of(keyValues.getLast().getKey());
|
||||
final List<FoundationDbMessageStreamEntry.Message> messages = keyValues.stream()
|
||||
beginKeyCursor = KeySelector.firstGreaterThan(keyValues.getLast().getKey());
|
||||
|
||||
return keyValues.stream()
|
||||
.map(keyValue -> {
|
||||
final Versionstamp versionstamp = FoundationDbMessageStore.getVersionstamp(keyValue.getKey());
|
||||
|
||||
try {
|
||||
return new FoundationDbMessageStreamEntry.Message(versionstamp, MessageProtos.Envelope.parseFrom(keyValue.getValue()));
|
||||
return new FoundationDbMessageStreamEntry.Message(versionstamp,
|
||||
MessageProtos.Envelope.parseFrom(keyValue.getValue()));
|
||||
} catch (final InvalidProtocolBufferException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
})
|
||||
.toList();
|
||||
return new Pair<>(lastKeyRead, messages);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
+38
-8
@@ -84,6 +84,12 @@ public class FoundationDbMessageStore {
|
||||
private static final Timer INSERT_MESSAGE_BATCH_TIMER =
|
||||
Metrics.timer(MetricsUtil.name(FoundationDbMessageStore.class, "insertMessageBatchTimer"));
|
||||
|
||||
private static final Counter DELETE_MESSAGE_COUNTER =
|
||||
Metrics.counter(MetricsUtil.name(FoundationDbMessageStore.class, "deleteMessage"));
|
||||
|
||||
private static final Timer DELETE_MESSAGE_TIMER =
|
||||
Metrics.timer(MetricsUtil.name(FoundationDbMessageStore.class, "deleteMessageTimer"));
|
||||
|
||||
/// Result of inserting a message for a particular device
|
||||
///
|
||||
/// @param versionstamp the versionstamp of the transaction in which this device's message was inserted, empty
|
||||
@@ -343,6 +349,25 @@ public class FoundationDbMessageStore {
|
||||
});
|
||||
}
|
||||
|
||||
CompletableFuture<Void> delete(final AciServiceIdentifier aci, final byte deviceId, final UUID messageGuid) {
|
||||
return delete(aci, deviceId, versionstampUUIDCipher.decryptVersionstamp(messageGuid, aci.uuid(), deviceId));
|
||||
}
|
||||
|
||||
CompletableFuture<Void> delete(final AciServiceIdentifier aci, final byte deviceId, final Versionstamp versionstamp) {
|
||||
final Timer.Sample sample = Timer.start();
|
||||
|
||||
final byte[] messageKey = getDeviceQueueSubspace(aci, deviceId).pack(Tuple.from(versionstamp));
|
||||
|
||||
return databasesByEpoch[getConfigurationEpoch(versionstamp)][getShardId(versionstamp)].runAsync(transaction -> {
|
||||
transaction.clear(messageKey);
|
||||
return CompletableFuture.completedFuture(null);
|
||||
})
|
||||
.thenRun(() -> {
|
||||
sample.stop(DELETE_MESSAGE_TIMER);
|
||||
DELETE_MESSAGE_COUNTER.increment();
|
||||
});
|
||||
}
|
||||
|
||||
public void clearAll(final AciServiceIdentifier aci) {
|
||||
doForAllDatabasesWithMessages(aci, database -> database.run(transaction -> {
|
||||
transaction.clear(getAccountSubspace(aci).range());
|
||||
@@ -366,15 +391,13 @@ public class FoundationDbMessageStore {
|
||||
}
|
||||
|
||||
public FoundationDbMessageStream getMessages(final AciServiceIdentifier aci, final byte deviceId) {
|
||||
return getMessages(aci, deviceId, FoundationDbMessageStream.DEFAULT_MAX_MESSAGES_PER_SCAN,
|
||||
FoundationDbMessageStream.DEFAULT_MAX_UNACKNOWLEDGED_MESSAGES, Util.NOOP);
|
||||
return getMessages(aci, deviceId, FoundationDbMessageStream.DEFAULT_MAX_MESSAGES_PER_SCAN, Util.NOOP);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
FoundationDbMessageStream getMessages(final AciServiceIdentifier aci,
|
||||
final byte deviceId,
|
||||
final int maxMessagesPerScan,
|
||||
final int maxUnacknowledgedMessages,
|
||||
final Runnable doAfterCleanup) {
|
||||
|
||||
// For each configured database epoch, which database held (or holds) the messages for this ACI/device pair?
|
||||
@@ -384,13 +407,12 @@ public class FoundationDbMessageStore {
|
||||
databasesForQueueByEpoch[epoch] = getShardForAci(aci, epoch);
|
||||
}
|
||||
|
||||
return new FoundationDbMessageStream(getDeviceQueueSubspace(aci, deviceId),
|
||||
getPresenceKey(aci, deviceId),
|
||||
getMessagesAvailableWatchKey(aci),
|
||||
return new FoundationDbMessageStream(this,
|
||||
aci,
|
||||
deviceId,
|
||||
databasesForQueueByEpoch,
|
||||
new MessageGuidCodec(aci.uuid(), deviceId, versionstampUUIDCipher),
|
||||
maxMessagesPerScan,
|
||||
maxUnacknowledgedMessages,
|
||||
doAfterCleanup,
|
||||
presenceRenewalExecutorService,
|
||||
clock);
|
||||
@@ -403,6 +425,15 @@ public class FoundationDbMessageStore {
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove any entries from each database's versionstamp-clock namespace that are strictly older than the given timestamp.
|
||||
///
|
||||
/// @param oldestRetainedEntryTimestamp the earliest time for which we still want to be able to obtain a versionstamp
|
||||
public void expireOldVersionstamps(final Instant oldestRetainedEntryTimestamp) {
|
||||
for (VersionstampClock versionstampClock : versionstampClocks.values()) {
|
||||
versionstampClock.clearExpiredEntries(oldestRetainedEntryTimestamp);
|
||||
}
|
||||
}
|
||||
|
||||
/// Delete messages for the given devices that were inserted before the given time.
|
||||
///
|
||||
/// This issues one range delete for every account/device pair in the map for each actual underlying FoundationDB
|
||||
@@ -420,7 +451,6 @@ public class FoundationDbMessageStore {
|
||||
/// @param cutoffTime the expiration threshold. Messages inserted before this time may be deleted; messages inserted
|
||||
/// after it will not be. Deletion depends on the underlying [versionstamp clocks][VersionstampClock] being kept up to
|
||||
/// date.
|
||||
@VisibleForTesting
|
||||
public void deleteMessagesBefore(final Map<AciServiceIdentifier, List<Byte>> accountDeviceIdentifiers, final Instant cutoffTime) {
|
||||
final Map<Database, List<Subspace>> queueSubspacesToTrimByDatabase = new IdentityHashMap<>();
|
||||
|
||||
|
||||
+69
-120
@@ -5,33 +5,23 @@ import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
import com.apple.foundationdb.Database;
|
||||
import com.apple.foundationdb.KeySelector;
|
||||
import com.apple.foundationdb.StreamingMode;
|
||||
import com.apple.foundationdb.Transaction;
|
||||
import com.apple.foundationdb.subspace.Subspace;
|
||||
import com.apple.foundationdb.tuple.ByteArrayUtil;
|
||||
import com.apple.foundationdb.tuple.Tuple;
|
||||
import com.apple.foundationdb.tuple.Versionstamp;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import java.time.Clock;
|
||||
import java.util.Arrays;
|
||||
import java.util.Comparator;
|
||||
import java.util.IdentityHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Flow;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.stream.Collectors;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.storage.MessageStream;
|
||||
import org.whispersystems.textsecuregcm.storage.MessageStreamEntry;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import reactor.adapter.JdkFlowAdapter;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
@@ -42,6 +32,10 @@ import reactor.util.function.Tuples;
|
||||
/// A [MessageStream] implementation that fetches messages from FoundationDB
|
||||
public class FoundationDbMessageStream implements MessageStream {
|
||||
|
||||
private final FoundationDbMessageStore foundationDbMessageStore;
|
||||
private final AciServiceIdentifier aciServiceIdentifier;
|
||||
private final byte deviceId;
|
||||
|
||||
private final Subspace deviceQueueSubspace;
|
||||
private final byte[] presenceKey;
|
||||
private final byte[] messagesAvailableWatchKey;
|
||||
@@ -54,8 +48,6 @@ public class FoundationDbMessageStream implements MessageStream {
|
||||
private final ScheduledExecutorService presenceRenewalExecutorService;
|
||||
private final Clock clock;
|
||||
|
||||
private final Map<Database, AcknowledgedMessageBuffer> acknowledgedMessageBuffersByDatabase;
|
||||
|
||||
private final Counter messageReadCounter =
|
||||
Metrics.counter(name(FoundationDbMessageStream.class, "messagesRead"));
|
||||
|
||||
@@ -66,27 +58,25 @@ public class FoundationDbMessageStream implements MessageStream {
|
||||
Metrics.counter(name(FoundationDbMessageStream.class, "staleEphemeralMessages"));
|
||||
|
||||
static final int DEFAULT_MAX_MESSAGES_PER_SCAN = 100;
|
||||
@VisibleForTesting
|
||||
static final int DEFAULT_MAX_UNACKNOWLEDGED_MESSAGES = 16_384;
|
||||
|
||||
private static final Comparator<FoundationDbMessageStreamEntry.Message> STREAM_ENTRY_TIMESTAMP_COMPARATOR =
|
||||
Comparator.comparingLong(streamEntry -> streamEntry.partialEnvelope().getServerTimestamp());
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(FoundationDbMessageStream.class);
|
||||
|
||||
FoundationDbMessageStream(final Subspace deviceQueueSubspace,
|
||||
final byte[] presenceKey,
|
||||
final byte[] messagesAvailableWatchKey,
|
||||
FoundationDbMessageStream(final FoundationDbMessageStore foundationDbMessageStore,
|
||||
final AciServiceIdentifier aciServiceIdentifier,
|
||||
final byte deviceId,
|
||||
final Database[] databasesByEpoch,
|
||||
final MessageGuidCodec messageGuidCodec,
|
||||
final int maxMessagesPerScan,
|
||||
final int maxUnacknowledgedMessages,
|
||||
final Runnable doAfterCleanup,
|
||||
final ScheduledExecutorService presenceRenewalExecutorService,
|
||||
final Clock clock) {
|
||||
this.deviceQueueSubspace = deviceQueueSubspace;
|
||||
this.presenceKey = presenceKey;
|
||||
this.messagesAvailableWatchKey = messagesAvailableWatchKey;
|
||||
this.foundationDbMessageStore = foundationDbMessageStore;
|
||||
this.aciServiceIdentifier = aciServiceIdentifier;
|
||||
this.deviceId = deviceId;
|
||||
this.deviceQueueSubspace = FoundationDbMessageStore.getDeviceQueueSubspace(aciServiceIdentifier, deviceId);
|
||||
this.presenceKey = FoundationDbMessageStore.getPresenceKey(aciServiceIdentifier, deviceId);
|
||||
this.messagesAvailableWatchKey = FoundationDbMessageStore.getMessagesAvailableWatchKey(aciServiceIdentifier);
|
||||
this.databasesByEpoch = databasesByEpoch;
|
||||
this.messageGuidCodec = messageGuidCodec;
|
||||
this.maxMessagesPerScan = maxMessagesPerScan;
|
||||
@@ -94,19 +84,6 @@ public class FoundationDbMessageStream implements MessageStream {
|
||||
this.doAfterCleanup = doAfterCleanup;
|
||||
this.presenceRenewalExecutorService = presenceRenewalExecutorService;
|
||||
this.clock = clock;
|
||||
|
||||
// Not all epochs may be in use (this is true most of the time) and if we DO have multiple epochs in play, it's
|
||||
// possible/likely that a given queue will be on the same shard in multiple epochs. We only want acknowledgement
|
||||
// buffer per distinct shard, so find the distinct shards for this queue and create a buffer for each.
|
||||
this.acknowledgedMessageBuffersByDatabase = Arrays.stream(databasesByEpoch)
|
||||
.filter(Objects::nonNull)
|
||||
.distinct()
|
||||
.collect(Collectors.toMap(database -> database,
|
||||
_ -> new AcknowledgedMessageBuffer(maxUnacknowledgedMessages),
|
||||
(_, _) -> {
|
||||
throw new AssertionError("Duplicate database in distinct stream");
|
||||
},
|
||||
IdentityHashMap::new));
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -114,6 +91,42 @@ public class FoundationDbMessageStream implements MessageStream {
|
||||
return this.messageStreamPublisher;
|
||||
}
|
||||
|
||||
public Flux<MessageStreamEntry> getFiniteMessageStream() {
|
||||
// This may seem like an odd construction since it looks like we could also just do `Flux#fromArray`, but
|
||||
// `Flux#fromArray` cannot handle `null` elements
|
||||
final List<Database> databases = Arrays.stream(databasesByEpoch).filter(Objects::nonNull).distinct().toList();
|
||||
|
||||
return Flux.fromIterable(databases)
|
||||
.flatMap(database -> Mono.fromFuture(getEndOfQueueKeyExclusive(database))
|
||||
.map(maybeEndOfQueueKeyExclusive -> Tuples.of(database, maybeEndOfQueueKeyExclusive)))
|
||||
.collectMap(Tuple2::getT1, Tuple2::getT2)
|
||||
.flatMapMany(endOfQueueKeysByDatabase -> {
|
||||
@SuppressWarnings("unchecked") final Flux<FoundationDbMessageStreamEntry.Message>[] finitePublishers =
|
||||
endOfQueueKeysByDatabase.entrySet().stream()
|
||||
.map(entry -> {
|
||||
final Database database = entry.getKey();
|
||||
final Optional<KeySelector> maybeEndOfQueueKeyExclusive = entry.getValue();
|
||||
|
||||
return maybeEndOfQueueKeyExclusive
|
||||
.map(endOfQueueKeyExclusive -> FoundationDbMessagePublisher.createFinitePublisher(
|
||||
database,
|
||||
clock,
|
||||
KeySelector.firstGreaterOrEqual(deviceQueueSubspace.range().begin),
|
||||
endOfQueueKeyExclusive,
|
||||
maxMessagesPerScan)
|
||||
.getMessages())
|
||||
.orElseGet(Flux::empty);
|
||||
})
|
||||
.toArray(Flux[]::new);
|
||||
|
||||
return Flux.concat(
|
||||
Flux.mergeComparing(maxMessagesPerScan, STREAM_ENTRY_TIMESTAMP_COMPARATOR, finitePublishers)
|
||||
.doOnNext(_ -> messageReadCounter.increment()),
|
||||
Mono.just(new FoundationDbMessageStreamEntry.QueueEmpty()))
|
||||
.map(fdbMessageStreamEntry -> fdbMessageStreamEntry.toMessageStreamEntry(messageGuidCodec));
|
||||
});
|
||||
}
|
||||
|
||||
/// Create a message publisher
|
||||
///
|
||||
/// @return a Flux of {@link MessageStreamEntry} fetched from FoundationDB
|
||||
@@ -121,25 +134,13 @@ public class FoundationDbMessageStream implements MessageStream {
|
||||
/// first to keep track of versionstamps sent to the client.
|
||||
private Flux<MessageStreamEntry> createMessagePublisher() {
|
||||
return createFoundationDbMessagePublisher()
|
||||
.<FoundationDbMessageStreamEntry>handle((messageStreamEntry, sink) -> {
|
||||
if (messageStreamEntry instanceof final FoundationDbMessageStreamEntry.Message message) {
|
||||
try {
|
||||
getAcknowledgedMessageBuffer(message.versionstamp()).addUnacknowledgedMessage(message.versionstamp());
|
||||
} catch (final TooManyUnacknowledgedMessagesException e) {
|
||||
sink.error(e);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
sink.next(messageStreamEntry);
|
||||
})
|
||||
.map(fdbMessageStreamEntry -> fdbMessageStreamEntry.toMessageStreamEntry(messageGuidCodec))
|
||||
.doOnNext(messageStreamEntry -> {
|
||||
if (messageStreamEntry instanceof MessageStreamEntry.Envelope) {
|
||||
messageReadCounter.increment();
|
||||
}
|
||||
})
|
||||
.doFinally(_ -> flushAllAcknowledgedMessages().thenRun(doAfterCleanup));
|
||||
.doFinally(_ -> doAfterCleanup.run());
|
||||
}
|
||||
|
||||
/// Create a message publisher that fetches messages from FoundationDB
|
||||
@@ -176,14 +177,16 @@ public class FoundationDbMessageStream implements MessageStream {
|
||||
clock,
|
||||
KeySelector.firstGreaterOrEqual(deviceQueueSubspace.range().begin),
|
||||
endOfQueueKeyExclusive,
|
||||
maxMessagesPerScan,
|
||||
() -> this.clearAcknowledgedMessages(database))
|
||||
maxMessagesPerScan)
|
||||
.getMessages())
|
||||
.orElseGet(Flux::empty)
|
||||
.handle((fdbMessageStreamEntry, sink) -> {
|
||||
final MessageProtos.Envelope partialEnvelope = fdbMessageStreamEntry.partialEnvelope();
|
||||
|
||||
// Ephemeral messages from the finite stream are considered stale and automatically discarded
|
||||
if (fdbMessageStreamEntry.partialEnvelope().getEphemeral()) {
|
||||
acknowledgedMessageBuffersByDatabase.get(database).acknowledgeStaleEphemeralMessage(fdbMessageStreamEntry.versionstamp());
|
||||
if (partialEnvelope.getEphemeral()) {
|
||||
foundationDbMessageStore.delete(aciServiceIdentifier, deviceId, fdbMessageStreamEntry.versionstamp());
|
||||
|
||||
staleEphemeralMessagesCounter.increment();
|
||||
return;
|
||||
}
|
||||
@@ -209,8 +212,7 @@ public class FoundationDbMessageStream implements MessageStream {
|
||||
maxMessagesPerScan,
|
||||
presenceKey,
|
||||
presenceRenewalExecutorService,
|
||||
messagesAvailableWatchKey,
|
||||
() -> clearAcknowledgedMessages(database)).getMessages();
|
||||
messagesAvailableWatchKey).getMessages();
|
||||
})
|
||||
.toArray(Flux[]::new);
|
||||
|
||||
@@ -236,74 +238,21 @@ public class FoundationDbMessageStream implements MessageStream {
|
||||
///
|
||||
/// @return a [KeySelector] for the first key greater than the current greatest key in the device queue.
|
||||
private CompletableFuture<Optional<KeySelector>> getEndOfQueueKeyExclusive(final Database database) {
|
||||
return database.runAsync(
|
||||
transaction -> transaction.getRange(deviceQueueSubspace.range(), 1, true, StreamingMode.EXACT).asList()
|
||||
.thenApply(items -> {
|
||||
if (items.isEmpty()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
assert items.size() == 1;
|
||||
return Optional.of(KeySelector.firstGreaterThan(items.getFirst().getKey()));
|
||||
}));
|
||||
return database.runAsync(transaction ->
|
||||
transaction.getRange(deviceQueueSubspace.range(), 1, true, StreamingMode.EXACT).asList())
|
||||
.thenApply(items -> {
|
||||
if (items.isEmpty()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
assert items.size() == 1;
|
||||
return Optional.of(KeySelector.firstGreaterThan(items.getFirst().getKey()));
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Void> acknowledgeMessage(final UUID messageGuid, final long serverTimestamp) {
|
||||
final Versionstamp versionstamp = messageGuidCodec.decodeMessageGuid(messageGuid);
|
||||
getAcknowledgedMessageBuffer(versionstamp).acknowledgeMessage(versionstamp);
|
||||
|
||||
messageAcknowledgedCounter.increment();
|
||||
|
||||
return CompletableFuture.completedFuture(null);
|
||||
}
|
||||
|
||||
/// Clear the versionstamp range (startInclusive, endInclusive) in a single FoundationDB operation.
|
||||
///
|
||||
/// @param transaction The FoundationDB transaction in which to perform the range clear
|
||||
/// @param startInclusive The starting versionstamp of the range to be cleared (inclusive)
|
||||
/// @param endInclusive The ending versionstamp of the range to be cleared (inclusive)
|
||||
private void clearRange(final Transaction transaction, final Versionstamp startInclusive, final Versionstamp endInclusive) {
|
||||
final byte[] startKeyInclusive = deviceQueueSubspace.pack(Tuple.from(startInclusive));
|
||||
final byte[] endKeyExclusive = ByteArrayUtil.keyAfter(deviceQueueSubspace.pack(Tuple.from(endInclusive)));
|
||||
transaction.clear(startKeyInclusive, endKeyExclusive);
|
||||
}
|
||||
|
||||
/// Clear all outstanding acknowledged messages. Called when the stream ends
|
||||
private CompletableFuture<Void> flushAllAcknowledgedMessages() {
|
||||
return CompletableFuture.allOf(Arrays.stream(databasesByEpoch)
|
||||
.filter(Objects::nonNull)
|
||||
.distinct()
|
||||
.map(database -> {
|
||||
final Consumer<Transaction> clearAllAcknowlegedMessagedConsumer = clearAcknowledgedMessages(database);
|
||||
|
||||
return database.runAsync(transaction -> {
|
||||
clearAllAcknowlegedMessagedConsumer.accept(transaction);
|
||||
return CompletableFuture.completedFuture((Void) null);
|
||||
})
|
||||
.whenComplete((_, throwable) -> {
|
||||
if (throwable != null) {
|
||||
LOGGER.warn("Failed to clear acknowledged messages", throwable);
|
||||
}
|
||||
});
|
||||
})
|
||||
.toArray(CompletableFuture[]::new));
|
||||
}
|
||||
|
||||
private AcknowledgedMessageBuffer getAcknowledgedMessageBuffer(final Versionstamp versionstamp) {
|
||||
final int epoch = FoundationDbMessageStore.getConfigurationEpoch(versionstamp);
|
||||
final Database database = databasesByEpoch[epoch];
|
||||
|
||||
if (database == null) {
|
||||
throw new IllegalStateException("Read message for unrecognized epoch");
|
||||
}
|
||||
|
||||
return acknowledgedMessageBuffersByDatabase.get(database);
|
||||
}
|
||||
|
||||
private synchronized Consumer<Transaction> clearAcknowledgedMessages(final Database database) {
|
||||
final List<Pair<Versionstamp, Versionstamp>> flushableRanges =
|
||||
acknowledgedMessageBuffersByDatabase.get(database).takeFlushableRanges();
|
||||
|
||||
return transaction -> flushableRanges.forEach(range -> clearRange(transaction, range.first(), range.second()));
|
||||
return foundationDbMessageStore.delete(aciServiceIdentifier, deviceId, messageGuid);
|
||||
}
|
||||
}
|
||||
+112
@@ -0,0 +1,112 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.workers;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.stream.Collectors;
|
||||
import net.sourceforge.argparse4j.inf.Subparser;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesManager;
|
||||
import reactor.core.publisher.Flux;
|
||||
|
||||
public class ClearExpiredFoundationDbMessagesCommand extends AbstractSinglePassCrawlAccountsCommand {
|
||||
|
||||
private final Clock clock;
|
||||
|
||||
@VisibleForTesting
|
||||
static final String DRY_RUN_ARGUMENT = "dry-run";
|
||||
|
||||
@VisibleForTesting
|
||||
static final String BATCH_SIZE_ARGUMENT = "batch-size";
|
||||
|
||||
@VisibleForTesting
|
||||
static final String MESSAGE_TTL_DAYS_ARGUMENT = "message-ttl-days";
|
||||
|
||||
@VisibleForTesting
|
||||
static final String VERSIONSTAMP_TTL_DAYS_ARGUMENT = "versionstamp-ttl-days";
|
||||
|
||||
@VisibleForTesting
|
||||
static final Duration TIMESTAMP_RETENTION_PERIOD = Duration.ofDays(60);
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(ClearExpiredFoundationDbMessagesCommand.class);
|
||||
|
||||
public ClearExpiredFoundationDbMessagesCommand(final Clock clock) {
|
||||
super("clear-expired-foundationdb-messages", "Removes expired messages from FoundationDB");
|
||||
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void configure(final Subparser subparser) {
|
||||
super.configure(subparser);
|
||||
|
||||
subparser.addArgument("--dry-run")
|
||||
.type(Boolean.class)
|
||||
.dest(DRY_RUN_ARGUMENT)
|
||||
.required(false)
|
||||
.setDefault(true)
|
||||
.help("If true, don't actually delete any messages (but do still make entries in the versionstamp clock)");
|
||||
|
||||
subparser.addArgument("--batch-size")
|
||||
.type(Integer.class)
|
||||
.dest(BATCH_SIZE_ARGUMENT)
|
||||
.required(false)
|
||||
.setDefault(10000)
|
||||
.help("Maximum number of queues to trim in a single transaction");
|
||||
|
||||
subparser.addArgument("--message-ttl-days")
|
||||
.type(Integer.class)
|
||||
.dest(MESSAGE_TTL_DAYS_ARGUMENT)
|
||||
.required(true)
|
||||
.help("Desired message TTL in days");
|
||||
|
||||
subparser.addArgument("--versionstamp-ttl-days")
|
||||
.type(Integer.class)
|
||||
.dest(VERSIONSTAMP_TTL_DAYS_ARGUMENT)
|
||||
.required(false)
|
||||
.setDefault(180)
|
||||
.help("Desired versionstamp-clock TTL in days");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void crawlAccounts(final Flux<Account> accounts) {
|
||||
final MessagesManager messagesManager = getCommandDependencies().messagesManager();
|
||||
|
||||
// Record the current versionstamp/time pair for the benefit of future runs. Because this job runs regularly, it has
|
||||
// the dual role of clearing messages and keeping the versionstamp/time mappings populated.
|
||||
messagesManager.recordFoundationDbVersionstamps();
|
||||
|
||||
final int batchSize = getNamespace().getInt(BATCH_SIZE_ARGUMENT);
|
||||
final boolean dryRun = getNamespace().getBoolean(DRY_RUN_ARGUMENT);
|
||||
final int messageTtlDays = getNamespace().getInt(MESSAGE_TTL_DAYS_ARGUMENT);
|
||||
final int versionstampTtlDays = getNamespace().getInt(VERSIONSTAMP_TTL_DAYS_ARGUMENT);
|
||||
|
||||
final Instant oldestMessageTime = clock.instant().minus(Duration.ofDays(messageTtlDays));
|
||||
final Instant oldestVersionstampTime = clock.instant().minus(Duration.ofDays(versionstampTtlDays));
|
||||
|
||||
accounts
|
||||
.buffer(batchSize)
|
||||
.map(batch -> batch.stream().collect(
|
||||
Collectors.toMap(
|
||||
account -> new AciServiceIdentifier(account.getIdentifier(IdentityType.ACI)),
|
||||
account -> account.getDevices().stream().map(Device::getId).toList())))
|
||||
.doOnNext(
|
||||
dryRun ? _ -> {}
|
||||
: deviceIdsByAccountIdentifier -> messagesManager.deleteFoundationDbMessagesBefore(deviceIdsByAccountIdentifier, oldestMessageTime))
|
||||
.then()
|
||||
.block();
|
||||
|
||||
messagesManager.expireOldFoundationDbVersionstamps(oldestVersionstampTime);
|
||||
}
|
||||
}
|
||||
@@ -6,14 +6,20 @@ package org.signal.chat.account;
|
||||
|
||||
import "org/signal/chat/common.proto";
|
||||
import "org/signal/chat/errors.proto";
|
||||
import "org/signal/chat/messages.proto";
|
||||
import "org/signal/chat/require.proto";
|
||||
import "org/signal/chat/tag.proto";
|
||||
|
||||
// Provides methods for working with Signal accounts.
|
||||
service Accounts {
|
||||
option (require.auth) = AUTH_ONLY_AUTHENTICATED;
|
||||
|
||||
// Returns basic identifiers for the authenticated account.
|
||||
rpc GetAccountIdentity(GetAccountIdentityRequest) returns (GetAccountIdentityResponse) {}
|
||||
|
||||
// Returns entitlements for the authenticated account.
|
||||
rpc GetEntitlements(GetEntitlementsRequest) returns (GetEntitlementsResponse) {}
|
||||
|
||||
// Deletes the authenticated account, purging all associated data in the
|
||||
// process.
|
||||
rpc DeleteAccount(DeleteAccountRequest) returns (DeleteAccountResponse) {}
|
||||
@@ -60,11 +66,19 @@ service Accounts {
|
||||
|
||||
// Store a public key used to issue and verify zero-knowledge (anonymous) credentials for the account.
|
||||
rpc SetZkCredentialKey(SetZkCredentialKeyRequest) returns (SetZkCredentialKeyResponse) {}
|
||||
|
||||
// Changes the phone number associated with the authenticated account.
|
||||
rpc ChangeNumber(ChangeNumberRequest) returns (ChangeNumberResponse) {}
|
||||
|
||||
// Produces a report of non-ephemeral account data stored by the service
|
||||
rpc GetAccountDataReport(GetAccountDataReportRequest) returns (GetAccountDataReportResponse) {}
|
||||
}
|
||||
|
||||
// Provides methods for looking up Signal accounts. Callers must not provide
|
||||
// identifying credentials when calling methods in this service.
|
||||
service AccountsAnonymous {
|
||||
option (require.auth) = AUTH_ONLY_ANONYMOUS;
|
||||
|
||||
// Checks whether an account with the given service identifier exists.
|
||||
rpc CheckAccountExistence(CheckAccountExistenceRequest) returns (CheckAccountExistenceResponse) {}
|
||||
|
||||
@@ -84,6 +98,35 @@ message GetAccountIdentityResponse {
|
||||
common.AccountIdentifiers account_identifiers = 1;
|
||||
}
|
||||
|
||||
message GetEntitlementsRequest {
|
||||
}
|
||||
|
||||
message GetEntitlementsResponse {
|
||||
message BadgeEntitlement {
|
||||
// The id of the badge the account is entitled. Metadata to display for
|
||||
// badges may be obtained by cross-referencing badge ids with
|
||||
// ProductConfiguration.GetConfiguration.
|
||||
string badge_id = 1;
|
||||
// When the badge expires, in number of seconds since epoch
|
||||
uint64 expiration_epoch_seconds = 2;
|
||||
// Whether the badge is currently configured to be visible
|
||||
bool visible = 3;
|
||||
}
|
||||
|
||||
message BackupEntitlement {
|
||||
// The backup level of the account
|
||||
uint64 level = 1;
|
||||
// When the backup entitlement expires, in number of seconds since epoch
|
||||
uint64 expiration_epoch_seconds = 2;
|
||||
}
|
||||
|
||||
// Active badges added via Donations.redeemReceipt
|
||||
repeated BadgeEntitlement badges = 1;
|
||||
|
||||
// If present, the backup level set via Backups.redeemReceipt
|
||||
BackupEntitlement backup = 2;
|
||||
}
|
||||
|
||||
message DeleteAccountRequest {
|
||||
}
|
||||
|
||||
@@ -280,3 +323,114 @@ message SetZkCredentialKeyResponse {
|
||||
// as reverting to the previous key will result in a new rotation ID.
|
||||
uint64 rotation_id = 1;
|
||||
}
|
||||
|
||||
message ChangeNumberRequest {
|
||||
// A means of authenticating the change-number request for the new phone
|
||||
// number. Exactly one must be provided.
|
||||
oneof verification {
|
||||
// A verified registration session ID (as returned by the registration
|
||||
// service) for the new phone number.
|
||||
bytes session_id = 1 [(require.nonEmpty) = true];
|
||||
|
||||
// A registration recovery password for the new phone number.
|
||||
bytes recovery_password = 2 [(require.exactlySize) = 32];
|
||||
}
|
||||
|
||||
// The new phone number for the authenticated account.
|
||||
string number = 3 [(require.e164) = true];
|
||||
|
||||
// The registration lock secret for the new phone number, if the account
|
||||
// associated with the new phone number has a registration lock configured.
|
||||
bytes registration_lock = 4 [(require.exactlySize) = 0, (require.exactlySize) = 32];
|
||||
|
||||
// The new public identity key to use for the phone-number identity (PNI)
|
||||
// associated with the new phone number.
|
||||
bytes pni_identity_key = 5 [(require.nonEmpty) = true];
|
||||
|
||||
// Synchronization messages to send to companion devices to supply the private
|
||||
// keys associated with the new identity key and their new pre-keys. Exactly
|
||||
// one message must be supplied for each device other than the sending
|
||||
// (primary) device. May be omitted if no companion devices are linked to the
|
||||
// account.
|
||||
messages.IndividualRecipientMessageBundle device_messages = 6;
|
||||
|
||||
// A new signed EC pre-key for each device on the account, including the
|
||||
// sending device, keyed by device ID. Each must be accompanied by a valid
|
||||
// signature from the identity key in this request.
|
||||
map<uint32, common.EcSignedPreKey> device_pni_signed_pre_keys = 7;
|
||||
|
||||
// A new signed post-quantum last-resort pre-key for each device on the
|
||||
// account, including the sending device, keyed by device ID. Each must be
|
||||
// accompanied by a valid signature from the identity key in this request.
|
||||
map<uint32, common.KemSignedPreKey> device_pni_pq_last_resort_pre_keys = 8;
|
||||
|
||||
// The new phone-number-identity registration ID for each device on the
|
||||
// account, including the sending device, keyed by device ID.
|
||||
map<uint32, uint32> pni_registration_ids = 9;
|
||||
}
|
||||
|
||||
message ChangeNumberResponse {
|
||||
oneof response {
|
||||
// The identifiers of the account after the successful
|
||||
// number change.
|
||||
common.AccountIdentifiers account_identifiers = 1;
|
||||
|
||||
// Mismatched number of devices or device ids in 'devices to notify' list
|
||||
messages.MismatchedDevices mismatched_devices = 2 [(tag.reason) = "mismatched_devices"];
|
||||
|
||||
// The account associated with the new phone number has a registration lock,
|
||||
// and the provided registration lock secret was missing or incorrect.
|
||||
RegistrationLockFailure registration_lock_failure = 3 [(tag.reason) = "registration_lock_failure"];
|
||||
|
||||
// Mismatched registration ids in 'devices to notify' list
|
||||
StaleDevices stale_devices = 4 [(tag.reason) = "stale_devices"];
|
||||
|
||||
// One or more device messages was too large
|
||||
errors.FailedPrecondition message_too_large = 5 [(tag.reason) = "message_too_large"];
|
||||
|
||||
// The registration session is unverified
|
||||
errors.FailedPrecondition unverified_registration_session = 6 [(tag.reason) = "unverified_registration_session"];
|
||||
|
||||
// The number does not match the registration session, or the registration session is invalid
|
||||
errors.FailedPrecondition invalid_registration_session = 7 [(tag.reason) = "invalid_registration_session"];
|
||||
|
||||
errors.FailedPrecondition recovery_password_verification_failed = 8 [(tag.reason) = "recovery_password_verification_failed"];
|
||||
}
|
||||
}
|
||||
|
||||
// Information about the current Registration lock and SVR credentials. With a correct PIN, the credentials can
|
||||
// be used to recover the secret used to derive the registration lock password.
|
||||
message RegistrationLockFailure {
|
||||
// Time remaining in milliseconds before the existing registration lock expires
|
||||
uint64 time_remaining_millis = 1;
|
||||
|
||||
// Credentials that can be used with SVR2
|
||||
ExternalServiceCredentials svr2_credentials = 2;
|
||||
}
|
||||
|
||||
// A username/password pair for authenticating with an external service.
|
||||
message ExternalServiceCredentials {
|
||||
// A username that can be presented to authenticate with the external service.
|
||||
string username = 1;
|
||||
|
||||
// A password that can be presented to authenticate with the external service.
|
||||
string password = 2;
|
||||
}
|
||||
|
||||
// A list of devices that are linked to the account but presented a stale
|
||||
// registration ID (indicating the device has likely been replaced by another
|
||||
// device).
|
||||
message StaleDevices {
|
||||
// The IDs of devices that are no longer active.
|
||||
repeated uint32 stale_devices = 1 [(require.each) = {range: {max: 0x7f}}];
|
||||
}
|
||||
|
||||
message GetAccountDataReportRequest {
|
||||
}
|
||||
|
||||
message GetAccountDataReportResponse {
|
||||
// The JSON representation of the data report
|
||||
string json = 3;
|
||||
// A plaintext representation of the data report
|
||||
string text = 4;
|
||||
}
|
||||
@@ -9,8 +9,11 @@ option java_multiple_files = true;
|
||||
|
||||
package org.signal.chat.calling.quality;
|
||||
|
||||
import "org/signal/chat/require.proto";
|
||||
|
||||
// Provides methods for submitting call quality surveys
|
||||
service CallQuality {
|
||||
option (require.auth) = AUTH_ONLY_ANONYMOUS;
|
||||
|
||||
// Submits a call quality survey response.
|
||||
rpc SubmitCallQualitySurvey(SubmitCallQualitySurveyRequest) returns (SubmitCallQualitySurveyResponse) {}
|
||||
|
||||
@@ -9,9 +9,12 @@ option java_multiple_files = true;
|
||||
|
||||
package org.signal.chat.calling;
|
||||
|
||||
import "org/signal/chat/require.proto";
|
||||
|
||||
// Provides methods for getting credentials and relay options for one-on-one
|
||||
// calls.
|
||||
service Calling {
|
||||
option (require.auth) = AUTH_ONLY_AUTHENTICATED;
|
||||
|
||||
// Retrieves TURN credentials and relay options for one-on-one calls.
|
||||
rpc GetCallingRelays(GetCallingRelaysRequest) returns (GetCallingRelaysResponse) {}
|
||||
|
||||
@@ -15,6 +15,7 @@ package org.signal.chat.credentials;
|
||||
// authenticated user to authenticate in another service or context without
|
||||
// revealing their identity.
|
||||
service Credentials {
|
||||
option (require.auth) = AUTH_ONLY_AUTHENTICATED;
|
||||
|
||||
// Generates and returns an external service credentials for the caller.
|
||||
rpc GetExternalServiceCredentials(GetExternalServiceCredentialsRequest)
|
||||
@@ -40,6 +41,7 @@ service Credentials {
|
||||
// revealing an association between the credentials and the caller's identity to
|
||||
// the server.
|
||||
service CredentialsAnonymous {
|
||||
option (require.auth) = AUTH_ONLY_ANONYMOUS;
|
||||
|
||||
// Given a list of secure value recovery (SVR) service credentials and a phone
|
||||
// number, checks and returns which of the provided credentials were generated
|
||||
|
||||
@@ -18,6 +18,8 @@ import "org/signal/chat/tag.proto";
|
||||
|
||||
// Provides methods for working with devices attached to a Signal account.
|
||||
service Devices {
|
||||
option (require.auth) = AUTH_ONLY_AUTHENTICATED;
|
||||
|
||||
// Returns a list of devices associated with the caller's account.
|
||||
rpc GetDevices(GetDevicesRequest) returns (GetDevicesResponse) {}
|
||||
|
||||
|
||||
@@ -18,6 +18,7 @@ import "org/signal/chat/tag.proto";
|
||||
|
||||
// Provides methods for working with pre-keys.
|
||||
service Keys {
|
||||
option (require.auth) = AUTH_ONLY_AUTHENTICATED;
|
||||
|
||||
// Retrieves an approximate count of the number of the various kinds of
|
||||
// pre-keys stored for the authenticated device.
|
||||
@@ -57,6 +58,7 @@ service Keys {
|
||||
// Provides methods for working with pre-keys using "unidentified access"
|
||||
// credentials.
|
||||
service KeysAnonymous {
|
||||
option (require.auth) = AUTH_ONLY_ANONYMOUS;
|
||||
|
||||
// Retrieves a set of pre-keys for establishing a session with the targeted
|
||||
// device or devices. Callers must not submit any self-identifying credentials
|
||||
|
||||
@@ -9,9 +9,13 @@ option java_multiple_files = true;
|
||||
|
||||
package org.signal.chat.payments;
|
||||
|
||||
import "org/signal/chat/require.proto";
|
||||
|
||||
// Provides methods for working with payments.
|
||||
service Payments {
|
||||
|
||||
option (require.auth) = AUTH_ONLY_AUTHENTICATED;
|
||||
|
||||
|
||||
rpc GetCurrencyConversions(GetCurrencyConversionsRequest) returns (GetCurrencyConversionsResponse) {}
|
||||
}
|
||||
|
||||
|
||||
@@ -18,6 +18,8 @@ import "org/signal/chat/tag.proto";
|
||||
|
||||
// Provides methods for working with profiles and profile-related data.
|
||||
service Profile {
|
||||
option (require.auth) = AUTH_ONLY_AUTHENTICATED;
|
||||
|
||||
// Sets profile data and, if needed, returns credentials used by clients to upload a v1 avatar.
|
||||
rpc SetProfile(SetProfileRequest) returns (SetProfileResponse) {}
|
||||
|
||||
@@ -42,6 +44,8 @@ service Profile {
|
||||
// without an unidentified access key should use the equivalent, authenticated
|
||||
// methods in `Profile` instead.
|
||||
service ProfileAnonymous {
|
||||
option (require.auth) = AUTH_ONLY_ANONYMOUS;
|
||||
|
||||
// Retrieves versioned profile data.
|
||||
rpc GetVersionedProfile(GetVersionedProfileAnonymousRequest) returns (GetVersionedProfileAnonymousResponse) {}
|
||||
// Retrieves unversioned profile data.
|
||||
@@ -193,8 +197,14 @@ message GetVersionedProfileRequest {
|
||||
message GetVersionedProfileAnonymousRequest {
|
||||
// Contains the data necessary to request a versioned profile.
|
||||
GetVersionedProfileRequest request = 1 [(require.present) = true];
|
||||
// The unidentified access key for the targeted account.
|
||||
bytes unidentified_access_key = 2 [(require.exactlySize) = 16];
|
||||
|
||||
oneof authentication {
|
||||
// The unidentified access key for the targeted account.
|
||||
bytes unidentified_access_key = 2 [(require.exactlySize) = 16];
|
||||
|
||||
// A group send endorsement token for the targeted account.
|
||||
bytes group_send_token = 3 [(require.nonEmpty) = true];
|
||||
}
|
||||
}
|
||||
|
||||
message DataEtag {
|
||||
@@ -286,13 +296,16 @@ message GetUnversionedProfileAnonymousRequest {
|
||||
message GetUnversionedProfileResult {
|
||||
// The identity key of the targeted account/identity type.
|
||||
bytes identity_key = 1;
|
||||
// A checksum of the unidentified access key for the targeted account.
|
||||
// A checksum of the unidentified access key for the targeted account. Absent
|
||||
// if the request was for a PNI.
|
||||
bytes unidentified_access = 2;
|
||||
// Whether the account has enabled sealed sender from anyone.
|
||||
// Whether the account has enabled sealed sender from anyone. Always false
|
||||
// if the request was for a PNI.
|
||||
bool unrestricted_unidentified_access = 3;
|
||||
// A list of capabilities enabled on the account.
|
||||
repeated common.DeviceCapability capabilities = 4;
|
||||
// A list of badges associated with the account.
|
||||
// A list of badges associated with the account. Absent if the request was for
|
||||
// a PNI.
|
||||
repeated common.Badge badges = 5;
|
||||
}
|
||||
|
||||
|
||||
+147
@@ -0,0 +1,147 @@
|
||||
package org.whispersystems.textsecuregcm;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.whispersystems.textsecuregcm.filters.RemoteAddressFilter.REMOTE_ADDRESS_ATTRIBUTE_NAME;
|
||||
|
||||
import io.dropwizard.core.Application;
|
||||
import io.dropwizard.core.Configuration;
|
||||
import io.dropwizard.core.server.DefaultServerFactory;
|
||||
import io.dropwizard.core.setup.Environment;
|
||||
import io.dropwizard.http2.Http2CConnectorFactory;
|
||||
import io.dropwizard.jetty.HttpConnectorFactory;
|
||||
import io.dropwizard.testing.DropwizardTestSupport;
|
||||
import java.net.URI;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import org.eclipse.jetty.client.HttpClient;
|
||||
import org.eclipse.jetty.ee10.websocket.server.config.JettyWebSocketServletContainerInitializer;
|
||||
import org.eclipse.jetty.http2.client.HTTP2Client;
|
||||
import org.eclipse.jetty.http2.client.transport.HttpClientTransportOverHTTP2;
|
||||
import org.eclipse.jetty.io.ClientConnector;
|
||||
import org.eclipse.jetty.server.Server;
|
||||
import org.eclipse.jetty.util.component.Graceful;
|
||||
import org.eclipse.jetty.websocket.api.Session;
|
||||
import org.eclipse.jetty.websocket.api.StatusCode;
|
||||
import org.eclipse.jetty.websocket.client.WebSocketClient;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Timeout;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.filters.PriorityFilter;
|
||||
import org.whispersystems.textsecuregcm.filters.RemoteAddressFilter;
|
||||
import org.whispersystems.textsecuregcm.tests.util.TestWebsocketListener;
|
||||
import org.whispersystems.websocket.WebSocketResourceProviderFactory;
|
||||
import org.whispersystems.websocket.configuration.WebSocketConfiguration;
|
||||
import org.whispersystems.websocket.setup.WebSocketEnvironment;
|
||||
|
||||
@Timeout(value = 10, threadMode = Timeout.ThreadMode.SEPARATE_THREAD)
|
||||
public class GracefulShutdownIntegrationTest {
|
||||
private WebSocketClient webSocketClient;
|
||||
private WebSocketClient h2WebSocketClient;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
webSocketClient = new WebSocketClient();
|
||||
webSocketClient.start();
|
||||
|
||||
final ClientConnector clientConnector = new ClientConnector();
|
||||
final HTTP2Client http2Client = new HTTP2Client(clientConnector);
|
||||
h2WebSocketClient = new WebSocketClient(new HttpClient(new HttpClientTransportOverHTTP2(http2Client)));
|
||||
h2WebSocketClient.start();
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() throws Exception {
|
||||
webSocketClient.stop();
|
||||
h2WebSocketClient.stop();
|
||||
}
|
||||
|
||||
private DropwizardTestSupport<Configuration> configureApplication() {
|
||||
final Http2CConnectorFactory applicationConnector = new Http2CConnectorFactory();
|
||||
applicationConnector.setPort(0);
|
||||
final HttpConnectorFactory adminConnector = new HttpConnectorFactory();
|
||||
adminConnector.setPort(0);
|
||||
|
||||
final DefaultServerFactory serverFactory = new DefaultServerFactory();
|
||||
serverFactory.setApplicationConnectors(List.of(applicationConnector));
|
||||
serverFactory.setAdminConnectors(List.of(adminConnector));
|
||||
|
||||
final Configuration configuration = new Configuration();
|
||||
configuration.setServerFactory(serverFactory);
|
||||
|
||||
return new DropwizardTestSupport<>(TestApplication.class, configuration);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {true, false})
|
||||
void jettyClosesOpenWebsocketSessions(final boolean useH2) throws Exception {
|
||||
final DropwizardTestSupport<Configuration> support = configureApplication();
|
||||
support.before();
|
||||
try {
|
||||
final Server server = support.getEnvironment().getApplicationContext().getServer();
|
||||
|
||||
final TestWebsocketListener listener = new TestWebsocketListener();
|
||||
final Session session = (useH2 ? h2WebSocketClient : webSocketClient)
|
||||
.connect(listener, URI.create("ws://localhost:%d/websocket".formatted(support.getLocalPort())))
|
||||
.join();
|
||||
assertTrue(session.isOpen(), "session should be open before shutdown");
|
||||
|
||||
// Open websockets should be closed by org.eclipse.jetty.websocket.common.SessionTracker
|
||||
// during the container Lifecycle stopping phase
|
||||
final CompletableFuture<Integer> closeObserved = listener.closeFuture();
|
||||
|
||||
// Keep the jetty graceful-shutdown window open until the client has observed the close
|
||||
server.addBean(new Graceful() {
|
||||
@Override
|
||||
public CompletableFuture<Void> shutdown() {
|
||||
return closeObserved.thenApply(_ -> null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isShutdown() {
|
||||
return closeObserved.isDone();
|
||||
}
|
||||
});
|
||||
server.setStopTimeout(TimeUnit.SECONDS.toMillis(10));
|
||||
server.stop();
|
||||
|
||||
final int shutdownCode = closeObserved.get(1, TimeUnit.SECONDS);
|
||||
|
||||
// In h2, when jetty shuts down a websocket with abnormal status code (e.g. 1001) it also cancels the underlying
|
||||
// H2 stream. It's possible that the stream cancellation makes it to the wire before the close frame which will
|
||||
// be parsed as a 1006, so we accept both . In practice, a 1001 vs an RST_STREAM shouldn't make a difference to a
|
||||
// client. We just care that jetty is attempting to shut down all websockets during graceful shutdowns.
|
||||
assertTrue(shutdownCode == StatusCode.SHUTDOWN || (shutdownCode == StatusCode.NO_CODE && useH2), "Shutdown code should be 1001 or 1006, was " + shutdownCode);
|
||||
} finally {
|
||||
support.after();
|
||||
}
|
||||
}
|
||||
|
||||
public static class TestApplication extends Application<Configuration> {
|
||||
|
||||
@Override
|
||||
public void run(final Configuration configuration, final Environment environment) throws Exception {
|
||||
final WebSocketEnvironment<AuthenticatedDevice> webSocketEnvironment =
|
||||
new WebSocketEnvironment<>(environment, new WebSocketConfiguration());
|
||||
webSocketEnvironment.jersey().register(new RemoteAddressFilter());
|
||||
webSocketEnvironment.setAuthenticator(upgradeRequest -> Optional.of(mock(AuthenticatedDevice.class)));
|
||||
webSocketEnvironment.setConnectListener(context -> {});
|
||||
|
||||
final WebSocketResourceProviderFactory<AuthenticatedDevice> webSocketServlet =
|
||||
new WebSocketResourceProviderFactory<>(webSocketEnvironment, AuthenticatedDevice.class,
|
||||
REMOTE_ADDRESS_ATTRIBUTE_NAME);
|
||||
|
||||
JettyWebSocketServletContainerInitializer.configure(environment.getApplicationContext(),
|
||||
(servletContext, container) -> {
|
||||
container.addMapping("/websocket", webSocketServlet);
|
||||
PriorityFilter.ensureFilter(servletContext, new RemoteAddressFilter());
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -132,15 +132,6 @@ class WhisperServerServiceTest {
|
||||
|
||||
final TestWebsocketListener testWebsocketListener = new TestWebsocketListener();
|
||||
|
||||
EXTENSION.getTestSupport().getEnvironment().getApplicationContext().getServer()
|
||||
.addEventListener(new LifeCycle.Listener() {
|
||||
@Override
|
||||
public void lifeCycleStopped(final LifeCycle event) {
|
||||
// closed by org.eclipse.jetty.websocket.common.SessionTracker during the container Lifecycle stopping phase
|
||||
assertEquals(StatusCode.SHUTDOWN, testWebsocketListener.closeFuture().getNow(-1));
|
||||
}
|
||||
});
|
||||
|
||||
// Session is Closeable, but we intentionally keep it open so that we can confirm the container Lifecycle behavior
|
||||
final Session session = (useH2 ? h2WebSocketClient : webSocketClient).connect(testWebsocketListener,
|
||||
URI.create(String.format("ws://localhost:%d/v1/websocket/", EXTENSION.getLocalPort())))
|
||||
|
||||
+44
-25
@@ -14,11 +14,7 @@ import static org.mockito.Mockito.when;
|
||||
|
||||
import com.google.i18n.phonenumbers.PhoneNumberUtil;
|
||||
import io.grpc.Status;
|
||||
import jakarta.ws.rs.BadRequestException;
|
||||
import jakarta.ws.rs.ForbiddenException;
|
||||
import jakarta.ws.rs.NotAuthorizedException;
|
||||
import jakarta.ws.rs.ServerErrorException;
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
@@ -79,8 +75,11 @@ class PhoneVerificationTokenManagerTest {
|
||||
.thenReturn(Optional.of(
|
||||
new RegistrationServiceSession(sessionId, PHONE_NUMBER, true, null, null, null, 0)));
|
||||
|
||||
assertDoesNotThrow(() -> phoneVerificationTokenManager.verify(mock(ContainerRequestContext.class),
|
||||
assertDoesNotThrow(() -> phoneVerificationTokenManager.verify(
|
||||
PHONE_NUMBER,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
sessionId,
|
||||
null));
|
||||
}
|
||||
@@ -92,8 +91,11 @@ class PhoneVerificationTokenManagerTest {
|
||||
when(registrationServiceClient.getSession(eq(sessionId), any()))
|
||||
.thenReturn(Optional.empty());
|
||||
|
||||
assertThrows(NotAuthorizedException.class, () -> phoneVerificationTokenManager.verify(mock(ContainerRequestContext.class),
|
||||
assertThrows(UnverifiedRegistrationSessionException.class, () -> phoneVerificationTokenManager.verify(
|
||||
PHONE_NUMBER,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
sessionId,
|
||||
null));
|
||||
}
|
||||
@@ -106,8 +108,11 @@ class PhoneVerificationTokenManagerTest {
|
||||
.thenReturn(Optional.of(
|
||||
new RegistrationServiceSession(sessionId, PHONE_NUMBER + "0", true, null, null, null, 0)));
|
||||
|
||||
assertThrows(BadRequestException.class, () -> phoneVerificationTokenManager.verify(mock(ContainerRequestContext.class),
|
||||
assertThrows(InvalidRegistrationSessionException.class, () -> phoneVerificationTokenManager.verify(
|
||||
PHONE_NUMBER,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
sessionId,
|
||||
null));
|
||||
}
|
||||
@@ -120,8 +125,11 @@ class PhoneVerificationTokenManagerTest {
|
||||
.thenReturn(Optional.of(
|
||||
new RegistrationServiceSession(sessionId, PHONE_NUMBER, false, null, null, null, 0)));
|
||||
|
||||
assertThrows(NotAuthorizedException.class, () -> phoneVerificationTokenManager.verify(mock(ContainerRequestContext.class),
|
||||
assertThrows(UnverifiedRegistrationSessionException.class, () -> phoneVerificationTokenManager.verify(
|
||||
PHONE_NUMBER,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
sessionId,
|
||||
null));
|
||||
}
|
||||
@@ -133,17 +141,20 @@ class PhoneVerificationTokenManagerTest {
|
||||
|
||||
when(registrationServiceClient.getSession(any(), any())).thenThrow(registrationServiceClientException);
|
||||
|
||||
assertThrows(expectedExceptionClass, () -> phoneVerificationTokenManager.verify(mock(ContainerRequestContext.class),
|
||||
assertThrows(expectedExceptionClass, () -> phoneVerificationTokenManager.verify(
|
||||
PHONE_NUMBER,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
TestRandomUtil.nextBytes(16),
|
||||
null));
|
||||
}
|
||||
|
||||
private static List<Arguments> verifyRegistrationServiceClientException() {
|
||||
return List.of(
|
||||
Arguments.arguments(Status.INVALID_ARGUMENT.asRuntimeException(), BadRequestException.class),
|
||||
Arguments.arguments(Status.RESOURCE_EXHAUSTED.asRuntimeException(), ServerErrorException.class),
|
||||
Arguments.arguments(Status.DEADLINE_EXCEEDED.asRuntimeException(), ServerErrorException.class)
|
||||
Arguments.arguments(Status.INVALID_ARGUMENT.asRuntimeException(), InvalidRegistrationSessionException.class),
|
||||
Arguments.arguments(Status.RESOURCE_EXHAUSTED.asRuntimeException(), IOException.class),
|
||||
Arguments.arguments(Status.DEADLINE_EXCEEDED.asRuntimeException(), IOException.class)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -153,52 +164,58 @@ class PhoneVerificationTokenManagerTest {
|
||||
|
||||
@Test
|
||||
void verify() {
|
||||
final ContainerRequestContext containerRequestContext = mock(ContainerRequestContext.class);
|
||||
final byte[] recoveryPassword = TestRandomUtil.nextBytes(16);
|
||||
|
||||
when(registrationRecoveryChecker.checkRegistrationRecoveryAttempt(containerRequestContext, PHONE_NUMBER))
|
||||
when(registrationRecoveryChecker.checkRegistrationRecoveryAttempt(PHONE_NUMBER, null, null, null))
|
||||
.thenReturn(true);
|
||||
|
||||
when(registrationRecoveryPasswordsManager.verify(PHONE_NUMBER_IDENTIFIER, recoveryPassword))
|
||||
.thenReturn(true);
|
||||
|
||||
assertDoesNotThrow(() -> phoneVerificationTokenManager.verify(containerRequestContext,
|
||||
assertDoesNotThrow(() -> phoneVerificationTokenManager.verify(
|
||||
PHONE_NUMBER,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
recoveryPassword));
|
||||
}
|
||||
|
||||
@Test
|
||||
void verifyRecoveryCheckerDeclined() {
|
||||
final ContainerRequestContext containerRequestContext = mock(ContainerRequestContext.class);
|
||||
final byte[] recoveryPassword = TestRandomUtil.nextBytes(16);
|
||||
|
||||
when(registrationRecoveryChecker.checkRegistrationRecoveryAttempt(containerRequestContext, PHONE_NUMBER))
|
||||
when(registrationRecoveryChecker.checkRegistrationRecoveryAttempt(PHONE_NUMBER, null, null, null))
|
||||
.thenReturn(false);
|
||||
|
||||
when(registrationRecoveryPasswordsManager.verify(PHONE_NUMBER_IDENTIFIER, recoveryPassword))
|
||||
.thenReturn(true);
|
||||
|
||||
assertThrows(ForbiddenException.class, () -> phoneVerificationTokenManager.verify(containerRequestContext,
|
||||
assertThrows(RecoveryPasswordVerificationFailedException.class, () -> phoneVerificationTokenManager.verify(
|
||||
PHONE_NUMBER,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
recoveryPassword));
|
||||
}
|
||||
|
||||
@Test
|
||||
void verifyRecoveryPasswordNotVerified() {
|
||||
final ContainerRequestContext containerRequestContext = mock(ContainerRequestContext.class);
|
||||
final byte[] recoveryPassword = TestRandomUtil.nextBytes(16);
|
||||
|
||||
when(registrationRecoveryChecker.checkRegistrationRecoveryAttempt(containerRequestContext, PHONE_NUMBER))
|
||||
when(registrationRecoveryChecker.checkRegistrationRecoveryAttempt(PHONE_NUMBER, null, null, null))
|
||||
.thenReturn(true);
|
||||
|
||||
when(registrationRecoveryPasswordsManager.verify(PHONE_NUMBER_IDENTIFIER, recoveryPassword))
|
||||
.thenReturn(false);
|
||||
|
||||
assertThrows(ForbiddenException.class, () -> phoneVerificationTokenManager.verify(containerRequestContext,
|
||||
assertThrows(RecoveryPasswordVerificationFailedException.class, () -> phoneVerificationTokenManager.verify(
|
||||
PHONE_NUMBER,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
recoveryPassword));
|
||||
}
|
||||
|
||||
@@ -206,18 +223,20 @@ class PhoneVerificationTokenManagerTest {
|
||||
@MethodSource
|
||||
void verifyPhoneNumberIdentifiersException(final Throwable phoneNumberIdentifiersException) {
|
||||
|
||||
final ContainerRequestContext containerRequestContext = mock(ContainerRequestContext.class);
|
||||
final byte[] recoveryPassword = TestRandomUtil.nextBytes(16);
|
||||
|
||||
when(registrationRecoveryChecker.checkRegistrationRecoveryAttempt(containerRequestContext, PHONE_NUMBER))
|
||||
when(registrationRecoveryChecker.checkRegistrationRecoveryAttempt(PHONE_NUMBER, null, null, null))
|
||||
.thenReturn(true);
|
||||
|
||||
when(phoneNumberIdentifiers.getPhoneNumberIdentifier(PHONE_NUMBER))
|
||||
.thenReturn(CompletableFuture.failedFuture(phoneNumberIdentifiersException));
|
||||
|
||||
assertThrows(ServerErrorException.class, () -> phoneVerificationTokenManager.verify(containerRequestContext,
|
||||
assertThrows(IOException.class, () -> phoneVerificationTokenManager.verify(
|
||||
PHONE_NUMBER,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
recoveryPassword));
|
||||
}
|
||||
|
||||
|
||||
+2
-5
@@ -6,7 +6,6 @@
|
||||
package org.whispersystems.textsecuregcm.auth;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.fail;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
@@ -19,7 +18,6 @@ import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import jakarta.ws.rs.WebApplicationException;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Consumer;
|
||||
@@ -101,9 +99,8 @@ class RegistrationLockVerificationManagerTest {
|
||||
final Pair<Class<? extends Exception>, Consumer<Exception>> exceptionType = switch (error) {
|
||||
case MISMATCH -> {
|
||||
when(existingRegistrationLock.verify(clientRegistrationLock)).thenReturn(false);
|
||||
yield new Pair<>(WebApplicationException.class, e -> {
|
||||
if (e instanceof WebApplicationException wae) {
|
||||
assertEquals(RegistrationLockVerificationManager.FAILURE_HTTP_STATUS, wae.getResponse().getStatus());
|
||||
yield new Pair<>(RegistrationLockFailureException.class, e -> {
|
||||
if (e instanceof RegistrationLockFailureException) {
|
||||
if (!verificationType.equals(PhoneVerificationRequest.VerificationType.RECOVERY_PASSWORD) || clientRegistrationLock != null) {
|
||||
verify(registrationRecoveryPasswordsManager).remove(account.getIdentifier(IdentityType.PNI));
|
||||
} else {
|
||||
|
||||
+1
-1
@@ -83,7 +83,7 @@ public class ConfiguredProfileBadgeConverterTest {
|
||||
return objects;
|
||||
}
|
||||
};
|
||||
return new BadgesConfiguration(badges, List.of(), Map.of());
|
||||
return new BadgesConfiguration(badges, Map.of());
|
||||
}
|
||||
|
||||
private BadgeConfiguration getBadge(BadgesConfiguration badgesConfiguration, int i) {
|
||||
|
||||
+19
-189
@@ -20,25 +20,16 @@ import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.google.i18n.phonenumbers.PhoneNumberUtil;
|
||||
import com.google.i18n.phonenumbers.Phonenumber;
|
||||
import io.dropwizard.auth.AuthValueFactoryProvider;
|
||||
import io.dropwizard.testing.junit5.DropwizardExtensionsSupport;
|
||||
import io.dropwizard.testing.junit5.ResourceExtension;
|
||||
import jakarta.ws.rs.BadRequestException;
|
||||
import jakarta.ws.rs.ForbiddenException;
|
||||
import jakarta.ws.rs.NotAuthorizedException;
|
||||
import jakarta.ws.rs.ServerErrorException;
|
||||
import jakarta.ws.rs.client.Entity;
|
||||
import jakarta.ws.rs.client.Invocation;
|
||||
import jakarta.ws.rs.core.HttpHeaders;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
@@ -58,6 +49,7 @@ import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.ArgumentsSource;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
@@ -65,7 +57,9 @@ import org.mockito.stubbing.Answer;
|
||||
import org.signal.libsignal.protocol.IdentityKey;
|
||||
import org.signal.libsignal.protocol.ecc.ECKeyPair;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
|
||||
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
|
||||
import org.whispersystems.textsecuregcm.auth.InvalidRegistrationSessionException;
|
||||
import org.whispersystems.textsecuregcm.auth.RecoveryPasswordVerificationFailedException;
|
||||
import org.whispersystems.textsecuregcm.auth.UnverifiedRegistrationSessionException;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountDataReportResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountIdentityResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.ChangeNumberRequest;
|
||||
@@ -78,15 +72,14 @@ import org.whispersystems.textsecuregcm.mappers.NonNormalizedPhoneNumberExceptio
|
||||
import org.whispersystems.textsecuregcm.mappers.RateLimitExceededExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.push.MessageTooLargeException;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountBadge;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ChangeNumberManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.tests.util.AccountsHelper;
|
||||
import org.whispersystems.textsecuregcm.tests.util.AccountsTestHelper;
|
||||
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
|
||||
import org.whispersystems.textsecuregcm.tests.util.KeysHelper;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
|
||||
@ExtendWith(DropwizardExtensionsSupport.class)
|
||||
class AccountControllerV2Test {
|
||||
@@ -122,7 +115,7 @@ class AccountControllerV2Test {
|
||||
|
||||
when(accountsManager.getByAccountIdentifier(AuthHelper.VALID_UUID)).thenReturn(Optional.of(AuthHelper.VALID_ACCOUNT));
|
||||
|
||||
when(changeNumberManager.changeNumber(any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any())).thenAnswer(
|
||||
when(changeNumberManager.changeNumber(any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any())).thenAnswer(
|
||||
(Answer<Account>) invocation -> {
|
||||
final UUID uuid = invocation.getArgument(0);
|
||||
final Account account = accountsManager.getByAccountIdentifier(uuid).orElseThrow();
|
||||
@@ -173,7 +166,7 @@ class AccountControllerV2Test {
|
||||
MediaType.APPLICATION_JSON_TYPE), AccountIdentityResponse.class);
|
||||
|
||||
verify(changeNumberManager).changeNumber(eq(AuthHelper.VALID_UUID), any(), any(), any(), eq(NEW_NUMBER), any(),
|
||||
any(), any(), any(), any(), any());
|
||||
any(), any(), any(), any(), any(), any(), any());
|
||||
|
||||
assertEquals(AuthHelper.VALID_UUID, accountIdentityResponse.uuid());
|
||||
assertEquals(NEW_NUMBER, accountIdentityResponse.number());
|
||||
@@ -276,7 +269,7 @@ class AccountControllerV2Test {
|
||||
@Test
|
||||
void rateLimitedNumber() throws Exception {
|
||||
doThrow(new RateLimitExceededException(null))
|
||||
.when(changeNumberManager).changeNumber(any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any());
|
||||
.when(changeNumberManager).changeNumber(any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any());
|
||||
|
||||
final Invocation.Builder request = resources.getJerseyTest()
|
||||
.target("/v2/accounts/number")
|
||||
@@ -292,9 +285,9 @@ class AccountControllerV2Test {
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void phoneVerificationException(final Exception exception, final int expectedStatus)
|
||||
throws InterruptedException, MessageTooLargeException, MismatchedDevicesException, RateLimitExceededException, MessageDeliveryNotAllowedException {
|
||||
throws Exception {
|
||||
doThrow(exception)
|
||||
.when(changeNumberManager).changeNumber(any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any());
|
||||
.when(changeNumberManager).changeNumber(any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any());
|
||||
|
||||
final Invocation.Builder request = resources.getJerseyTest()
|
||||
.target("/v2/accounts/number")
|
||||
@@ -309,17 +302,17 @@ class AccountControllerV2Test {
|
||||
|
||||
private static List<Arguments> phoneVerificationException() {
|
||||
return List.of(
|
||||
Arguments.argumentSet("Bad request", new BadRequestException(), HttpStatus.SC_BAD_REQUEST),
|
||||
Arguments.argumentSet("Not authorized", new NotAuthorizedException("test"), HttpStatus.SC_UNAUTHORIZED),
|
||||
Arguments.argumentSet("Forbidden", new ForbiddenException(), HttpStatus.SC_FORBIDDEN),
|
||||
Arguments.argumentSet("Unexpected exception", new ServerErrorException(Response.Status.SERVICE_UNAVAILABLE), HttpStatus.SC_SERVICE_UNAVAILABLE)
|
||||
Arguments.argumentSet("Bad request", new InvalidRegistrationSessionException("invalid registration session"), HttpStatus.SC_BAD_REQUEST),
|
||||
Arguments.argumentSet("Not authorized", new UnverifiedRegistrationSessionException(), HttpStatus.SC_UNAUTHORIZED),
|
||||
Arguments.argumentSet("Forbidden", new RecoveryPasswordVerificationFailedException(), HttpStatus.SC_FORBIDDEN),
|
||||
Arguments.argumentSet("Unexpected exception", new IOException("unavailable"), HttpStatus.SC_SERVICE_UNAVAILABLE)
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void deviceMessageTooLarge() throws Exception {
|
||||
doThrow(MessageTooLargeException.class)
|
||||
.when(changeNumberManager).changeNumber(any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any());
|
||||
.when(changeNumberManager).changeNumber(any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any());
|
||||
|
||||
try (final Response response = resources.getJerseyTest()
|
||||
.target("/v2/accounts/number")
|
||||
@@ -341,7 +334,7 @@ class AccountControllerV2Test {
|
||||
@Test
|
||||
void messageDeliveryNotAllowed() throws Exception {
|
||||
doThrow(MessageDeliveryNotAllowedException.class)
|
||||
.when(changeNumberManager).changeNumber(any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any());
|
||||
.when(changeNumberManager).changeNumber(any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any());
|
||||
|
||||
try (final Response response = resources.getJerseyTest()
|
||||
.target("/v2/accounts/number")
|
||||
@@ -360,13 +353,6 @@ class AccountControllerV2Test {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Valid request JSON with the given Recovery Password
|
||||
*/
|
||||
private static String requestJsonRecoveryPassword(final byte[] recoveryPassword, final String newNumber) {
|
||||
return requestJson("", recoveryPassword, newNumber, 123);
|
||||
}
|
||||
|
||||
/**
|
||||
* Valid request JSON with the give session ID and recovery password
|
||||
*/
|
||||
@@ -481,7 +467,7 @@ class AccountControllerV2Test {
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
@ArgumentsSource(AccountsTestHelper.AccountsDataReportArgumentProvider.class)
|
||||
void testGetAccountDataReport(final Account account, final String expectedTextAfterHeader) throws Exception {
|
||||
when(AuthHelper.ACCOUNTS_MANAGER.getByAccountIdentifier(account.getUuid())).thenReturn(Optional.of(account));
|
||||
when(accountsManager.getByAccountIdentifier(account.getUuid())).thenReturn(Optional.of(account));
|
||||
@@ -516,163 +502,7 @@ class AccountControllerV2Test {
|
||||
assertTrue(deviceIds.isEmpty());
|
||||
|
||||
final String actualText = (String) SystemMapper.jsonMapper().readValue(stringResponse, Map.class).get("text");
|
||||
final int headerEnd = actualText.indexOf("# Account");
|
||||
assertEquals(expectedTextAfterHeader, actualText.substring(headerEnd));
|
||||
|
||||
final String actualHeader = actualText.substring(0, headerEnd);
|
||||
assertTrue(actualHeader.matches(
|
||||
"Report ID: [a-z0-9]{8}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{12}\nReport timestamp: \\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z\n\n"));
|
||||
}
|
||||
|
||||
static Stream<Arguments> testGetAccountDataReport() {
|
||||
final String exampleNumber1 = toE164(PhoneNumberUtil.getInstance().getExampleNumber("ES"));
|
||||
final String account2PhoneNumber = toE164(PhoneNumberUtil.getInstance().getExampleNumber("AU"));
|
||||
final String account3PhoneNumber = toE164(PhoneNumberUtil.getInstance().getExampleNumber("IN"));
|
||||
|
||||
final Instant account1Device1Created = Instant.ofEpochSecond(1669323142); // 2022-11-24T20:52:22Z
|
||||
final Instant account1Device2Created = Instant.ofEpochSecond(1679155122); // 2023-03-18T15:58:42Z
|
||||
final Instant account1Device1LastSeen = Instant.ofEpochMilli(Util.todayInMillis());
|
||||
final Instant account1Device2LastSeen = Instant.ofEpochSecond(1678838400); // 2023-03-15T00:00:00Z
|
||||
|
||||
final Instant account2Device1Created = Instant.ofEpochSecond(1659123001); // 2022-07-29T19:30:01Z
|
||||
final Instant account2Device1LastSeen = Instant.ofEpochMilli(Util.todayInMillis());
|
||||
final Instant badgeAExpiration = Instant.now().plus(Duration.ofDays(21)).truncatedTo(ChronoUnit.SECONDS);
|
||||
|
||||
final Instant account3Device1Created = Instant.ofEpochSecond(1639923487); // 2021-12-19T14:18:07Z
|
||||
final Instant account3Device1LastSeen = Instant.ofEpochMilli(Util.todayInMillis());
|
||||
final Instant badgeBExpiration = Instant.now().plus(Duration.ofDays(21)).truncatedTo(ChronoUnit.SECONDS);
|
||||
final Instant badgeCExpiration = Instant.now().plus(Duration.ofDays(24)).truncatedTo(ChronoUnit.SECONDS);
|
||||
|
||||
return Stream.of(
|
||||
Arguments.of(
|
||||
buildTestAccountForDataReport(UUID.randomUUID(), exampleNumber1,
|
||||
true, true,
|
||||
Collections.emptyList(),
|
||||
List.of(new DeviceData(Device.PRIMARY_ID, account1Device1LastSeen, account1Device1Created, null),
|
||||
new DeviceData((byte) 2, account1Device2LastSeen, account1Device2Created, "OWP"))),
|
||||
String.format("""
|
||||
# Account
|
||||
Phone number: %s
|
||||
Allow sealed sender from anyone: true
|
||||
Find account by phone number: true
|
||||
Badges: None
|
||||
|
||||
# Devices
|
||||
- ID: 1
|
||||
Created: 2022-11-24T20:52:22Z
|
||||
Last seen: %s
|
||||
User-agent: null
|
||||
- ID: 2
|
||||
Created: 2023-03-18T15:58:42Z
|
||||
Last seen: 2023-03-15T00:00:00Z
|
||||
User-agent: OWP
|
||||
""",
|
||||
exampleNumber1,
|
||||
account1Device1LastSeen)
|
||||
),
|
||||
Arguments.of(
|
||||
buildTestAccountForDataReport(UUID.randomUUID(), account2PhoneNumber,
|
||||
false, true,
|
||||
List.of(new AccountBadge("badge_a", badgeAExpiration, true)),
|
||||
List.of(new DeviceData(Device.PRIMARY_ID, account2Device1LastSeen, account2Device1Created, "OWI"))),
|
||||
String.format("""
|
||||
# Account
|
||||
Phone number: %s
|
||||
Allow sealed sender from anyone: false
|
||||
Find account by phone number: true
|
||||
Badges:
|
||||
- ID: badge_a
|
||||
Expiration: %s
|
||||
Visible: true
|
||||
|
||||
# Devices
|
||||
- ID: 1
|
||||
Created: 2022-07-29T19:30:01Z
|
||||
Last seen: %s
|
||||
User-agent: OWI
|
||||
""", account2PhoneNumber,
|
||||
badgeAExpiration,
|
||||
account2Device1LastSeen)
|
||||
),
|
||||
Arguments.of(
|
||||
buildTestAccountForDataReport(UUID.randomUUID(), account3PhoneNumber,
|
||||
true, false,
|
||||
List.of(
|
||||
new AccountBadge("badge_b", badgeBExpiration, true),
|
||||
new AccountBadge("badge_c", badgeCExpiration, false)),
|
||||
List.of(new DeviceData(Device.PRIMARY_ID, account3Device1LastSeen, account3Device1Created, "OWA"))),
|
||||
String.format("""
|
||||
# Account
|
||||
Phone number: %s
|
||||
Allow sealed sender from anyone: true
|
||||
Find account by phone number: false
|
||||
Badges:
|
||||
- ID: badge_b
|
||||
Expiration: %s
|
||||
Visible: true
|
||||
- ID: badge_c
|
||||
Expiration: %s
|
||||
Visible: false
|
||||
|
||||
# Devices
|
||||
- ID: 1
|
||||
Created: 2021-12-19T14:18:07Z
|
||||
Last seen: %s
|
||||
User-agent: OWA
|
||||
""", account3PhoneNumber,
|
||||
badgeBExpiration,
|
||||
badgeCExpiration,
|
||||
account3Device1LastSeen)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an {@link Account} with data sufficient for
|
||||
* {@link AccountControllerV2#getAccountDataReport(AuthenticatedDevice)}.
|
||||
* <p>
|
||||
* Note: All devices will have a {@link SaltedTokenHash} for "password"
|
||||
*/
|
||||
static Account buildTestAccountForDataReport(final UUID aci, final String number,
|
||||
final boolean unrestrictedUnidentifiedAccess, final boolean discoverableByPhoneNumber,
|
||||
List<AccountBadge> badges, List<DeviceData> devices) {
|
||||
|
||||
final ECKeyPair aciIdentityKeyPair = ECKeyPair.generate();
|
||||
final ECKeyPair pniIdentityKeyPair = ECKeyPair.generate();
|
||||
|
||||
final Account account = new Account();
|
||||
account.setUuid(aci);
|
||||
account.setNumber(number, UUID.randomUUID());
|
||||
account.setUnrestrictedUnidentifiedAccess(unrestrictedUnidentifiedAccess);
|
||||
account.setDiscoverableByPhoneNumber(discoverableByPhoneNumber);
|
||||
account.setBadges(Clock.systemUTC(), new ArrayList<>(badges));
|
||||
account.setIdentityKey(new IdentityKey(aciIdentityKeyPair.getPublicKey()));
|
||||
account.setPhoneNumberIdentityKey(new IdentityKey(pniIdentityKeyPair.getPublicKey()));
|
||||
|
||||
assert !devices.isEmpty();
|
||||
|
||||
final SaltedTokenHash passwordTokenHash = SaltedTokenHash.generateFor("password");
|
||||
|
||||
devices.forEach(deviceData -> {
|
||||
final Device device = new Device();
|
||||
device.setId(deviceData.id);
|
||||
device.setAuthTokenHash(passwordTokenHash);
|
||||
device.setFetchesMessages(true);
|
||||
device.setLastSeen(deviceData.lastSeen().toEpochMilli());
|
||||
device.setCreated(deviceData.created().toEpochMilli());
|
||||
device.setUserAgent(deviceData.userAgent());
|
||||
account.addDevice(device);
|
||||
});
|
||||
|
||||
return account;
|
||||
}
|
||||
|
||||
private record DeviceData(byte id, Instant lastSeen, Instant created, @Nullable String userAgent) {
|
||||
|
||||
}
|
||||
|
||||
private static String toE164(Phonenumber.PhoneNumber phoneNumber) {
|
||||
return PhoneNumberUtil.getInstance().format(phoneNumber, PhoneNumberUtil.PhoneNumberFormat.E164);
|
||||
AccountsTestHelper.verifyAccountDataReportText(actualText, expectedTextAfterHeader);
|
||||
}
|
||||
}
|
||||
}
|
||||
-1
@@ -75,7 +75,6 @@ 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")))),
|
||||
List.of("TEST"),
|
||||
Map.of(1L, "TEST1", 2L, "TEST2", 3L, "TEST3"));
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -168,7 +168,7 @@ 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")))
|
||||
), List.of("TEST1"), Map.of(1L, "TEST1", 2L, "TEST2", 3L, "TEST3")),
|
||||
), Map.of(1L, "TEST1", 2L, "TEST2", 3L, "TEST3")),
|
||||
postPolicyGenerator,
|
||||
serverSecretParams,
|
||||
zkProfileOperations,
|
||||
|
||||
+13
-13
@@ -20,15 +20,12 @@ import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.google.i18n.phonenumbers.PhoneNumberUtil;
|
||||
import io.dropwizard.testing.junit5.DropwizardExtensionsSupport;
|
||||
import io.dropwizard.testing.junit5.ResourceExtension;
|
||||
import jakarta.ws.rs.BadRequestException;
|
||||
import jakarta.ws.rs.ForbiddenException;
|
||||
import jakarta.ws.rs.NotAuthorizedException;
|
||||
import jakarta.ws.rs.ServerErrorException;
|
||||
import jakarta.ws.rs.WebApplicationException;
|
||||
import jakarta.ws.rs.client.Entity;
|
||||
import jakarta.ws.rs.client.Invocation;
|
||||
import jakarta.ws.rs.core.HttpHeaders;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Arrays;
|
||||
@@ -60,9 +57,12 @@ import org.junitpioneer.jupiter.cartesian.ArgumentSets;
|
||||
import org.junitpioneer.jupiter.cartesian.CartesianTest;
|
||||
import org.signal.libsignal.protocol.IdentityKey;
|
||||
import org.signal.libsignal.protocol.ecc.ECKeyPair;
|
||||
import org.whispersystems.textsecuregcm.auth.InvalidRegistrationSessionException;
|
||||
import org.whispersystems.textsecuregcm.auth.PhoneVerificationTokenManager;
|
||||
import org.whispersystems.textsecuregcm.auth.RecoveryPasswordVerificationFailedException;
|
||||
import org.whispersystems.textsecuregcm.auth.RegistrationLockError;
|
||||
import org.whispersystems.textsecuregcm.auth.RegistrationLockVerificationManager;
|
||||
import org.whispersystems.textsecuregcm.auth.UnverifiedRegistrationSessionException;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountCreationResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountIdentityResponse;
|
||||
@@ -120,7 +120,7 @@ class RegistrationControllerTest {
|
||||
.build();
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws InterruptedException {
|
||||
void setUp() throws Exception {
|
||||
when(rateLimiters.getRegistrationLimiter()).thenReturn(registrationLimiter);
|
||||
|
||||
when(accountsManager.update(any(UUID.class), any())).thenAnswer(invocation -> {
|
||||
@@ -135,8 +135,8 @@ class RegistrationControllerTest {
|
||||
reset(registrationFraudChecker);
|
||||
reset(phoneVerificationTokenManager);
|
||||
|
||||
when(phoneVerificationTokenManager.verify(any(), any(), any(), any())).thenAnswer(invocation -> {
|
||||
final byte[] sessionId = invocation.getArgument(2);
|
||||
when(phoneVerificationTokenManager.verify(any(), any(), any(), any(), any(), any())).thenAnswer(invocation -> {
|
||||
final byte[] sessionId = invocation.getArgument(4);
|
||||
|
||||
return sessionId != null
|
||||
? PhoneVerificationRequest.VerificationType.SESSION
|
||||
@@ -235,9 +235,9 @@ class RegistrationControllerTest {
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void phoneVerificationException(final Exception exception, final int expectedStatus) throws InterruptedException {
|
||||
void phoneVerificationException(final Exception exception, final int expectedStatus) throws Exception {
|
||||
doThrow(exception)
|
||||
.when(phoneVerificationTokenManager).verify(any(), any(), any(), any());
|
||||
.when(phoneVerificationTokenManager).verify(any(), any(), any(), any(), any(), any());
|
||||
|
||||
final Invocation.Builder request = resources.getJerseyTest()
|
||||
.target("/v1/registration")
|
||||
@@ -251,10 +251,10 @@ class RegistrationControllerTest {
|
||||
|
||||
private static List<Arguments> phoneVerificationException() {
|
||||
return List.of(
|
||||
Arguments.argumentSet("Bad request", new BadRequestException(), HttpStatus.SC_BAD_REQUEST),
|
||||
Arguments.argumentSet("Not authorized", new NotAuthorizedException("test"), HttpStatus.SC_UNAUTHORIZED),
|
||||
Arguments.argumentSet("Forbidden", new ForbiddenException(), HttpStatus.SC_FORBIDDEN),
|
||||
Arguments.argumentSet("Unexpected exception", new ServerErrorException(Response.Status.SERVICE_UNAVAILABLE), HttpStatus.SC_SERVICE_UNAVAILABLE)
|
||||
Arguments.argumentSet("Bad request", new InvalidRegistrationSessionException("invalid registration session"), HttpStatus.SC_BAD_REQUEST),
|
||||
Arguments.argumentSet("Not authorized", new UnverifiedRegistrationSessionException(), HttpStatus.SC_UNAUTHORIZED),
|
||||
Arguments.argumentSet("Forbidden", new RecoveryPasswordVerificationFailedException(), HttpStatus.SC_FORBIDDEN),
|
||||
Arguments.argumentSet("Unexpected exception", new IOException("unavailable"), HttpStatus.SC_SERVICE_UNAVAILABLE)
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
+275
-1
@@ -5,6 +5,7 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.grpc;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
@@ -20,21 +21,27 @@ import static org.mockito.Mockito.when;
|
||||
import com.google.i18n.phonenumbers.PhoneNumberUtil;
|
||||
import com.google.protobuf.ByteString;
|
||||
import io.grpc.Status;
|
||||
import java.io.IOException;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
import java.util.stream.Stream;
|
||||
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.ArgumentsSource;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Mock;
|
||||
import org.signal.chat.account.AccountsGrpc;
|
||||
import org.signal.chat.account.ChangeNumberRequest;
|
||||
import org.signal.chat.account.ChangeNumberResponse;
|
||||
import org.signal.chat.account.ClearRegistrationLockRequest;
|
||||
import org.signal.chat.account.ClearRegistrationLockResponse;
|
||||
import org.signal.chat.account.ConfigureUnidentifiedAccessRequest;
|
||||
@@ -44,8 +51,14 @@ import org.signal.chat.account.DeleteAccountRequest;
|
||||
import org.signal.chat.account.DeleteAccountResponse;
|
||||
import org.signal.chat.account.DeleteUsernameHashRequest;
|
||||
import org.signal.chat.account.DeleteUsernameLinkRequest;
|
||||
import org.signal.chat.account.ExternalServiceCredentials;
|
||||
import org.signal.chat.account.GetAccountDataReportRequest;
|
||||
import org.signal.chat.account.GetAccountDataReportResponse;
|
||||
import org.signal.chat.account.GetAccountIdentityRequest;
|
||||
import org.signal.chat.account.GetAccountIdentityResponse;
|
||||
import org.signal.chat.account.GetEntitlementsRequest;
|
||||
import org.signal.chat.account.GetEntitlementsResponse;
|
||||
import org.signal.chat.account.RegistrationLockFailure;
|
||||
import org.signal.chat.account.ReserveUsernameHashRequest;
|
||||
import org.signal.chat.account.ReserveUsernameHashResponse;
|
||||
import org.signal.chat.account.SetDiscoverableByPhoneNumberRequest;
|
||||
@@ -56,29 +69,50 @@ import org.signal.chat.account.SetUsernameLinkRequest;
|
||||
import org.signal.chat.account.SetUsernameLinkResponse;
|
||||
import org.signal.chat.account.SetZkCredentialKeyRequest;
|
||||
import org.signal.chat.account.SetZkCredentialKeyResponse;
|
||||
import org.signal.chat.account.StaleDevices;
|
||||
import org.signal.chat.account.UsernameNotAvailable;
|
||||
import org.signal.chat.common.AccountIdentifiers;
|
||||
import org.signal.chat.common.EcSignedPreKey;
|
||||
import org.signal.chat.common.KemSignedPreKey;
|
||||
import org.signal.chat.errors.FailedPrecondition;
|
||||
import org.signal.libsignal.protocol.IdentityKey;
|
||||
import org.signal.libsignal.protocol.ecc.ECKeyPair;
|
||||
import org.signal.libsignal.usernames.BaseUsernameException;
|
||||
import org.signal.libsignal.zkgroup.ZkCredentialKeyPair;
|
||||
import org.signal.libsignal.zkgroup.ZkCredentialPublicKey;
|
||||
import org.whispersystems.textsecuregcm.auth.InvalidRegistrationSessionException;
|
||||
import org.whispersystems.textsecuregcm.auth.RecoveryPasswordVerificationFailedException;
|
||||
import org.whispersystems.textsecuregcm.auth.RegistrationLockFailureException;
|
||||
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
|
||||
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
|
||||
import org.whispersystems.textsecuregcm.auth.UnverifiedRegistrationSessionException;
|
||||
import org.whispersystems.textsecuregcm.controllers.AccountController;
|
||||
import org.whispersystems.textsecuregcm.controllers.MessageDeliveryNotAllowedException;
|
||||
import org.whispersystems.textsecuregcm.controllers.MismatchedDevices;
|
||||
import org.whispersystems.textsecuregcm.controllers.MismatchedDevicesException;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.EncryptedUsername;
|
||||
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiter;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.push.MessageTooLargeException;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountBadge;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.ChangeNumberManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.KeyIdUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.UsernameHashNotAvailableException;
|
||||
import org.whispersystems.textsecuregcm.storage.UsernameReservationNotFoundException;
|
||||
import org.whispersystems.textsecuregcm.tests.util.AccountsHelper;
|
||||
import org.whispersystems.textsecuregcm.util.TestClock;
|
||||
import org.whispersystems.textsecuregcm.tests.util.AccountsTestHelper;
|
||||
import org.whispersystems.textsecuregcm.tests.util.KeysHelper;
|
||||
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
import org.whispersystems.textsecuregcm.util.UsernameHashZkProofVerifier;
|
||||
@@ -97,6 +131,11 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
|
||||
@Mock
|
||||
private RegistrationRecoveryPasswordsManager registrationRecoveryPasswordsManager;
|
||||
|
||||
private final TestClock testClock = TestClock.pinned(Instant.now());
|
||||
|
||||
@Mock
|
||||
private ChangeNumberManager changeNumberManager;
|
||||
|
||||
@Override
|
||||
protected AccountsGrpcService createServiceBeforeEachTest() {
|
||||
AccountsHelper.setupMockUpdate(accountsManager);
|
||||
@@ -111,7 +150,9 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
|
||||
return new AccountsGrpcService(accountsManager,
|
||||
rateLimiters,
|
||||
usernameHashZkProofVerifier,
|
||||
registrationRecoveryPasswordsManager);
|
||||
registrationRecoveryPasswordsManager,
|
||||
testClock,
|
||||
changeNumberManager);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -146,6 +187,7 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
|
||||
assertEquals(expectedResponse, authenticatedServiceStub().getAccountIdentity(GetAccountIdentityRequest.newBuilder().build()));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
void deleteAccount() {
|
||||
final DeleteAccountResponse ignored =
|
||||
@@ -765,4 +807,236 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
|
||||
verify(accountsManager, never()).update(any(UUID.class), any());
|
||||
verify(account, never()).setZkCredentialKey(any());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {true, false})
|
||||
void getEntitlements(final boolean expired) {
|
||||
final Account account = mock(Account.class);
|
||||
final Instant expiration = expired
|
||||
? testClock.instant().minus(Duration.ofDays(1))
|
||||
: testClock.instant().plus(Duration.ofMillis(1));
|
||||
final AccountBadge badge1 = new AccountBadge("badge1", expiration, true);
|
||||
final AccountBadge badge2 = new AccountBadge("badge2", expiration, true);
|
||||
|
||||
when(account.getBackupVoucher()).thenReturn(new Account.BackupVoucher(100, expiration));
|
||||
when(account.getBadges()).thenReturn(List.of(badge1, badge2));
|
||||
when(account.getUuid()).thenReturn(AUTHENTICATED_ACI);
|
||||
when(accountsManager.getByAccountIdentifier(AUTHENTICATED_ACI)).thenReturn(Optional.of(account));
|
||||
|
||||
final GetEntitlementsResponse entitlements = authenticatedServiceStub()
|
||||
.getEntitlements(GetEntitlementsRequest.newBuilder().build());
|
||||
|
||||
if (expired) {
|
||||
assertThat(entitlements.getBadgesCount()).isEqualTo(0);
|
||||
assertThat(entitlements.hasBackup()).isFalse();
|
||||
} else {
|
||||
assertThat(entitlements.getBadges(0)).isEqualTo(toBadgeEntitlement(badge1));
|
||||
assertThat(entitlements.getBadges(1)).isEqualTo(toBadgeEntitlement(badge2));
|
||||
assertThat(entitlements.getBackup().getLevel()).isEqualTo(100);
|
||||
assertThat(entitlements.getBackup().getExpirationEpochSeconds()).isEqualTo(expiration.getEpochSecond());
|
||||
}
|
||||
}
|
||||
|
||||
private static GetEntitlementsResponse.BadgeEntitlement toBadgeEntitlement(AccountBadge badge) {
|
||||
return GetEntitlementsResponse.BadgeEntitlement.newBuilder()
|
||||
.setExpirationEpochSeconds(badge.expiration().getEpochSecond())
|
||||
.setBadgeId(badge.id())
|
||||
.setVisible(badge.visible())
|
||||
.build();
|
||||
}
|
||||
|
||||
@Test
|
||||
void changeNumber() throws Exception {
|
||||
final String newNumber = PhoneNumberUtil.getInstance().format(
|
||||
PhoneNumberUtil.getInstance().getExampleNumber("US"), PhoneNumberUtil.PhoneNumberFormat.E164);
|
||||
|
||||
final ECKeyPair pniIdentityKeyPair = ECKeyPair.generate();
|
||||
final IdentityKey pniIdentityKey = new IdentityKey(pniIdentityKeyPair.getPublicKey());
|
||||
|
||||
final ECSignedPreKey ecSignedPreKey = KeysHelper.signedECPreKey(1, pniIdentityKeyPair);
|
||||
final KEMSignedPreKey kemSignedPreKey = KeysHelper.signedKEMPreKey(2, pniIdentityKeyPair);
|
||||
|
||||
final byte[] sessionId = TestRandomUtil.nextBytes(16);
|
||||
final UUID updatedPni = UUID.randomUUID();
|
||||
|
||||
final Account updatedAccount = mock(Account.class);
|
||||
when(updatedAccount.getUuid()).thenReturn(AUTHENTICATED_ACI);
|
||||
when(updatedAccount.getNumber()).thenReturn(newNumber);
|
||||
when(updatedAccount.getPhoneNumberIdentifier()).thenReturn(updatedPni);
|
||||
when(updatedAccount.getUsernameHash()).thenReturn(Optional.empty());
|
||||
|
||||
when(changeNumberManager.changeNumber(eq(AUTHENTICATED_ACI), any(), any(), any(), eq(newNumber),
|
||||
any(), any(), any(), any(), any(), any(), any(), any()))
|
||||
.thenReturn(updatedAccount);
|
||||
|
||||
final ChangeNumberResponse response = authenticatedServiceStub().changeNumber(ChangeNumberRequest.newBuilder()
|
||||
.setSessionId(ByteString.copyFrom(sessionId))
|
||||
.setNumber(newNumber)
|
||||
.setRegistrationLock(ByteString.copyFrom(TestRandomUtil.nextBytes(32)))
|
||||
.setPniIdentityKey(ByteString.copyFrom(pniIdentityKey.serialize()))
|
||||
.putDevicePniSignedPreKeys(Device.PRIMARY_ID, EcSignedPreKey.newBuilder()
|
||||
.setKeyId(KeyIdUtil.toUnsignedInt(ecSignedPreKey.keyId()))
|
||||
.setPublicKey(ByteString.copyFrom(ecSignedPreKey.serializedPublicKey()))
|
||||
.setSignature(ByteString.copyFrom(ecSignedPreKey.signature()))
|
||||
.build())
|
||||
.putDevicePniPqLastResortPreKeys(Device.PRIMARY_ID, KemSignedPreKey.newBuilder()
|
||||
.setKeyId(KeyIdUtil.toUnsignedInt(kemSignedPreKey.keyId()))
|
||||
.setPublicKey(ByteString.copyFrom(kemSignedPreKey.serializedPublicKey()))
|
||||
.setSignature(ByteString.copyFrom(kemSignedPreKey.signature()))
|
||||
.build())
|
||||
.putPniRegistrationIds(Device.PRIMARY_ID, 17)
|
||||
.build());
|
||||
|
||||
final ChangeNumberResponse expectedResponse = ChangeNumberResponse.newBuilder()
|
||||
.setAccountIdentifiers(AccountIdentifiers.newBuilder()
|
||||
.addServiceIdentifiers(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(new AciServiceIdentifier(AUTHENTICATED_ACI)))
|
||||
.addServiceIdentifiers(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(new PniServiceIdentifier(updatedPni)))
|
||||
.setE164(newNumber))
|
||||
.build();
|
||||
|
||||
assertEquals(expectedResponse, response);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void changeNumberErrorResponse(final Exception exceptionToThrow, final ChangeNumberResponse expectedResponse)
|
||||
throws Exception {
|
||||
|
||||
when(changeNumberManager.changeNumber(any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any()))
|
||||
.thenThrow(exceptionToThrow);
|
||||
|
||||
assertEquals(expectedResponse, authenticatedServiceStub().changeNumber(createChangeNumberRequest()));
|
||||
}
|
||||
|
||||
private static List<Arguments> changeNumberErrorResponse() {
|
||||
return List.of(
|
||||
Arguments.argumentSet("Invalid registration session",
|
||||
new InvalidRegistrationSessionException("invalid registration session"),
|
||||
ChangeNumberResponse.newBuilder()
|
||||
.setInvalidRegistrationSession(FailedPrecondition.newBuilder().setDescription("invalid registration session"))
|
||||
.build()),
|
||||
Arguments.argumentSet("Unverified registration session",
|
||||
new UnverifiedRegistrationSessionException(),
|
||||
ChangeNumberResponse.newBuilder()
|
||||
.setUnverifiedRegistrationSession(FailedPrecondition.getDefaultInstance())
|
||||
.build()),
|
||||
Arguments.argumentSet("Recovery password verification failed",
|
||||
new RecoveryPasswordVerificationFailedException(),
|
||||
ChangeNumberResponse.newBuilder()
|
||||
.setRecoveryPasswordVerificationFailed(FailedPrecondition.getDefaultInstance())
|
||||
.build()),
|
||||
Arguments.argumentSet("Message too large",
|
||||
new MessageTooLargeException(),
|
||||
ChangeNumberResponse.newBuilder()
|
||||
.setMessageTooLarge(FailedPrecondition.newBuilder().setDescription("one or more device messages was too large"))
|
||||
.build()));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void changeNumberUnavailable(final Exception exceptionToThrow) throws Exception {
|
||||
when(changeNumberManager.changeNumber(any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any()))
|
||||
.thenThrow(exceptionToThrow);
|
||||
|
||||
//noinspection ResultOfMethodCallIgnored
|
||||
GrpcTestUtils.assertStatusException(Status.UNAVAILABLE,
|
||||
() -> authenticatedServiceStub().changeNumber(createChangeNumberRequest()));
|
||||
}
|
||||
|
||||
private static List<Arguments> changeNumberUnavailable() {
|
||||
return List.of(
|
||||
Arguments.argumentSet("Message delivery not allowed", new MessageDeliveryNotAllowedException()),
|
||||
Arguments.argumentSet("Registration service unavailable", new IOException("unavailable")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void changeNumberRegistrationLockFailure() throws Exception {
|
||||
final long timeRemaining = Duration.ofDays(7).toMillis();
|
||||
|
||||
when(changeNumberManager.changeNumber(any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any()))
|
||||
.thenThrow(new RegistrationLockFailureException(new org.whispersystems.textsecuregcm.entities.RegistrationLockFailure(
|
||||
timeRemaining,
|
||||
new org.whispersystems.textsecuregcm.auth.ExternalServiceCredentials("test-username", "test-password"))));
|
||||
|
||||
final ChangeNumberResponse expectedResponse = ChangeNumberResponse.newBuilder()
|
||||
.setRegistrationLockFailure(RegistrationLockFailure.newBuilder()
|
||||
.setTimeRemainingMillis(timeRemaining)
|
||||
.setSvr2Credentials(ExternalServiceCredentials.newBuilder()
|
||||
.setUsername("test-username")
|
||||
.setPassword("test-password")))
|
||||
.build();
|
||||
|
||||
assertEquals(expectedResponse, authenticatedServiceStub().changeNumber(createChangeNumberRequest()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void changeNumberStaleDevices() throws Exception {
|
||||
final byte staleDeviceId = (byte) (Device.PRIMARY_ID + 1);
|
||||
|
||||
when(changeNumberManager.changeNumber(any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any()))
|
||||
.thenThrow(new MismatchedDevicesException(new MismatchedDevices(Set.of(), Set.of(), Set.of(staleDeviceId))));
|
||||
|
||||
final ChangeNumberResponse expectedResponse = ChangeNumberResponse.newBuilder()
|
||||
.setStaleDevices(StaleDevices.newBuilder().addStaleDevices(staleDeviceId))
|
||||
.build();
|
||||
|
||||
assertEquals(expectedResponse, authenticatedServiceStub().changeNumber(createChangeNumberRequest()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void changeNumberMismatchedDevices() throws Exception {
|
||||
final byte missingDeviceId = (byte) (Device.PRIMARY_ID + 1);
|
||||
final byte extraDeviceId = (byte) (Device.PRIMARY_ID + 2);
|
||||
|
||||
when(changeNumberManager.changeNumber(any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any()))
|
||||
.thenThrow(new MismatchedDevicesException(new MismatchedDevices(Set.of(missingDeviceId), Set.of(extraDeviceId), Set.of())));
|
||||
|
||||
final ChangeNumberResponse expectedResponse = ChangeNumberResponse.newBuilder()
|
||||
.setMismatchedDevices(org.signal.chat.messages.MismatchedDevices.newBuilder()
|
||||
.setServiceIdentifier(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(new AciServiceIdentifier(AUTHENTICATED_ACI)))
|
||||
.addMissingDevices(missingDeviceId)
|
||||
.addExtraDevices(extraDeviceId))
|
||||
.build();
|
||||
|
||||
assertEquals(expectedResponse, authenticatedServiceStub().changeNumber(createChangeNumberRequest()));
|
||||
}
|
||||
|
||||
private static ChangeNumberRequest createChangeNumberRequest() {
|
||||
final ECKeyPair pniIdentityKeyPair = ECKeyPair.generate();
|
||||
final IdentityKey pniIdentityKey = new IdentityKey(pniIdentityKeyPair.getPublicKey());
|
||||
|
||||
final ECSignedPreKey ecSignedPreKey = KeysHelper.signedECPreKey(1, pniIdentityKeyPair);
|
||||
final KEMSignedPreKey kemSignedPreKey = KeysHelper.signedKEMPreKey(2, pniIdentityKeyPair);
|
||||
|
||||
return ChangeNumberRequest.newBuilder()
|
||||
.setSessionId(ByteString.copyFrom(TestRandomUtil.nextBytes(16)))
|
||||
.setNumber(PhoneNumberUtil.getInstance().format(
|
||||
PhoneNumberUtil.getInstance().getExampleNumber("US"), PhoneNumberUtil.PhoneNumberFormat.E164))
|
||||
.setPniIdentityKey(ByteString.copyFrom(pniIdentityKey.serialize()))
|
||||
.putDevicePniSignedPreKeys(Device.PRIMARY_ID, EcSignedPreKey.newBuilder()
|
||||
.setKeyId(KeyIdUtil.toUnsignedInt(ecSignedPreKey.keyId()))
|
||||
.setPublicKey(ByteString.copyFrom(ecSignedPreKey.serializedPublicKey()))
|
||||
.setSignature(ByteString.copyFrom(ecSignedPreKey.signature()))
|
||||
.build())
|
||||
.putDevicePniPqLastResortPreKeys(Device.PRIMARY_ID, KemSignedPreKey.newBuilder()
|
||||
.setKeyId(KeyIdUtil.toUnsignedInt(kemSignedPreKey.keyId()))
|
||||
.setPublicKey(ByteString.copyFrom(kemSignedPreKey.serializedPublicKey()))
|
||||
.setSignature(ByteString.copyFrom(kemSignedPreKey.signature()))
|
||||
.build())
|
||||
.putPniRegistrationIds(Device.PRIMARY_ID, 17)
|
||||
.build();
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ArgumentsSource(AccountsTestHelper.AccountsDataReportArgumentProvider.class)
|
||||
void getAccountDataReport(final Account account, final String expectedTextAfterHeader) {
|
||||
getMockAuthenticationInterceptor().setAuthenticatedDevice(account.getUuid(), Device.PRIMARY_ID);
|
||||
when(accountsManager.getByAccountIdentifier(account.getUuid())).thenReturn(Optional.of(account));
|
||||
|
||||
final GetAccountDataReportResponse response =
|
||||
authenticatedServiceStub().getAccountDataReport(GetAccountDataReportRequest.newBuilder().build());
|
||||
|
||||
final String actualText = response.getText();
|
||||
AccountsTestHelper.verifyAccountDataReportText(actualText, expectedTextAfterHeader);
|
||||
}
|
||||
}
|
||||
+4
-1
@@ -11,6 +11,7 @@ import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyByte;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.whispersystems.textsecuregcm.grpc.GrpcTestUtils.assertStatusException;
|
||||
@@ -334,7 +335,9 @@ class DevicesGrpcServiceTest extends SimpleBaseGrpcTest<DevicesGrpcService, Devi
|
||||
|
||||
final SetPushTokenResponse ignored = authenticatedServiceStub().setPushToken(request);
|
||||
|
||||
verify(accountsManager, never()).updateDevice(any(), anyByte(), any());
|
||||
// Update push token even if it matches the stored value for apns (to update the timestamp)
|
||||
verify(accountsManager, apnsToken == null ? never() : times(1))
|
||||
.updateDevice(any(), anyByte(), any());
|
||||
}
|
||||
|
||||
private static Stream<Arguments> setPushTokenUnchanged() {
|
||||
|
||||
+139
-51
@@ -10,6 +10,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.junit.jupiter.params.provider.EnumSource.Mode.EXCLUDE;
|
||||
import static org.mockito.AdditionalMatchers.aryEq;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyBoolean;
|
||||
@@ -49,8 +50,10 @@ import javax.annotation.Nullable;
|
||||
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.Mock;
|
||||
import org.signal.chat.common.IdentityType;
|
||||
import org.signal.chat.common.ServiceIdentifier;
|
||||
@@ -216,7 +219,7 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
|
||||
.setUnidentifiedAccess(ByteString.copyFrom(unidentifiedAccessChecksum))
|
||||
.setUnrestrictedUnidentifiedAccess(false)
|
||||
.addCapabilities(org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_SPARSE_POST_QUANTUM_RATCHET)
|
||||
.addAllBadges(ProfileGrpcHelper.buildBadges(badges))
|
||||
.addAllBadges(badges.stream().map(BadgeGrpcHelper::toGrpcBadge).toList())
|
||||
.build()
|
||||
)
|
||||
.build();
|
||||
@@ -270,7 +273,7 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
|
||||
.setIdentityKey(ByteString.copyFrom(identityKey.serialize()))
|
||||
.setUnrestrictedUnidentifiedAccess(false)
|
||||
.addAllCapabilities(ProfileGrpcHelper.buildAccountCapabilities(account))
|
||||
.addAllBadges(ProfileGrpcHelper.buildBadges(badges))
|
||||
.addAllBadges(badges.stream().map(BadgeGrpcHelper::toGrpcBadge).toList())
|
||||
.build();
|
||||
|
||||
verify(accountsManager).getByServiceIdentifier(serviceIdentifier);
|
||||
@@ -399,7 +402,9 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
|
||||
@MethodSource
|
||||
void getVersionedProfile(final byte[] requestVersion,
|
||||
@Nullable final byte[] accountVersion,
|
||||
final boolean expectResponseHasPaymentAddress) {
|
||||
final boolean expectResponseHasPaymentAddress,
|
||||
final GetVersionedProfileAnonymousRequest.AuthenticationCase authenticationCase) throws Exception {
|
||||
final AciServiceIdentifier serviceIdentifier = new AciServiceIdentifier(UUID.randomUUID());
|
||||
final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
|
||||
|
||||
final byte[] name = TestRandomUtil.nextBytes(81);
|
||||
@@ -418,18 +423,23 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
|
||||
when(accountsManager.getByServiceIdentifier(any())).thenReturn(Optional.of(account));
|
||||
when(profilesManager.getV1(any(), any())).thenReturn(profile);
|
||||
|
||||
final GetVersionedProfileAnonymousRequest request = GetVersionedProfileAnonymousRequest.newBuilder()
|
||||
.setUnidentifiedAccessKey(ByteString.copyFrom(unidentifiedAccessKey))
|
||||
final GetVersionedProfileAnonymousRequest.Builder requestBuilder = GetVersionedProfileAnonymousRequest.newBuilder()
|
||||
.setRequest(GetVersionedProfileRequest.newBuilder()
|
||||
.setAccountIdentifier(ServiceIdentifier.newBuilder()
|
||||
.setIdentityType(IdentityType.IDENTITY_TYPE_ACI)
|
||||
.setUuid(ByteString.copyFrom(UUIDUtil.toBytes(UUID.randomUUID())))
|
||||
.build())
|
||||
.setAccountIdentifier(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(serviceIdentifier))
|
||||
.setVersion(ByteString.copyFrom(requestVersion))
|
||||
.build())
|
||||
.build();
|
||||
.build());
|
||||
|
||||
final GetVersionedProfileAnonymousResponse response = unauthenticatedServiceStub().getVersionedProfile(request);
|
||||
switch (authenticationCase) {
|
||||
case GROUP_SEND_TOKEN -> {
|
||||
final Instant expiration = Instant.now().plus(Duration.ofDays(1)).truncatedTo(ChronoUnit.DAYS);
|
||||
final byte[] token = AuthHelper.validGroupSendToken(SERVER_SECRET_PARAMS, List.of(serviceIdentifier), expiration);
|
||||
requestBuilder.setGroupSendToken(ByteString.copyFrom(token));
|
||||
}
|
||||
case UNIDENTIFIED_ACCESS_KEY -> requestBuilder.setUnidentifiedAccessKey(ByteString.copyFrom(unidentifiedAccessKey));
|
||||
}
|
||||
|
||||
final GetVersionedProfileAnonymousResponse response = unauthenticatedServiceStub().getVersionedProfile(
|
||||
requestBuilder.build());
|
||||
|
||||
final GetVersionedProfileResult.Builder expectedResultBuilder = GetVersionedProfileResult.newBuilder()
|
||||
.setV1Response(GetVersionedProfileV1Response.newBuilder()
|
||||
@@ -454,14 +464,22 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
|
||||
final byte[] version1 = TestRandomUtil.nextBytes(32);
|
||||
final byte[] version2 = TestRandomUtil.nextBytes(32);
|
||||
return List.of(
|
||||
Arguments.argumentSet("current profile version matches", version1, version1, true),
|
||||
Arguments.argumentSet("current profile version absent",version1, null, true),
|
||||
Arguments.argumentSet("current profile version mismatch",version1, version2, false)
|
||||
Arguments.argumentSet("current profile version matches, unidentified access key auth", version1, version1, true,
|
||||
GetVersionedProfileAnonymousRequest.AuthenticationCase.UNIDENTIFIED_ACCESS_KEY),
|
||||
Arguments.argumentSet("current profile version absent, unidentified access key auth",version1, null, true,
|
||||
GetVersionedProfileAnonymousRequest.AuthenticationCase.UNIDENTIFIED_ACCESS_KEY),
|
||||
Arguments.argumentSet("current profile version mismatch, unidentified access key auth",version1, version2, false,
|
||||
GetVersionedProfileAnonymousRequest.AuthenticationCase.UNIDENTIFIED_ACCESS_KEY),
|
||||
Arguments.argumentSet("current profile version matches, group send endorsement auth", version1, version1, true,
|
||||
GetVersionedProfileAnonymousRequest.AuthenticationCase.GROUP_SEND_TOKEN)
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getVersionedProfileV2() {
|
||||
@ParameterizedTest
|
||||
@EnumSource(mode = EXCLUDE, names = "AUTHENTICATION_NOT_SET")
|
||||
void getVersionedProfileV2(
|
||||
final GetVersionedProfileAnonymousRequest.AuthenticationCase authenticationCase) throws Exception {
|
||||
final AciServiceIdentifier serviceIdentifier = new AciServiceIdentifier(UUID.randomUUID());
|
||||
final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
|
||||
final byte[] data = TestRandomUtil.nextBytes(128);
|
||||
final byte[] paymentAddress = TestRandomUtil.nextBytes(582);
|
||||
@@ -477,18 +495,22 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
|
||||
when(profilesManager.get(any(), any())).thenReturn(Optional.of(v2Profile));
|
||||
when(profilesManager.getV1(any(), any())).thenReturn(Optional.empty());
|
||||
|
||||
final GetVersionedProfileAnonymousRequest request = GetVersionedProfileAnonymousRequest.newBuilder()
|
||||
.setUnidentifiedAccessKey(ByteString.copyFrom(unidentifiedAccessKey))
|
||||
final GetVersionedProfileAnonymousRequest.Builder requestBuilder = GetVersionedProfileAnonymousRequest.newBuilder()
|
||||
.setRequest(GetVersionedProfileRequest.newBuilder()
|
||||
.setAccountIdentifier(ServiceIdentifier.newBuilder()
|
||||
.setIdentityType(IdentityType.IDENTITY_TYPE_ACI)
|
||||
.setUuid(ByteString.copyFrom(UUIDUtil.toBytes(UUID.randomUUID())))
|
||||
.build())
|
||||
.setAccountIdentifier(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(serviceIdentifier))
|
||||
.setVersion(ByteString.copyFrom(version))
|
||||
.build())
|
||||
.build();
|
||||
.build());
|
||||
|
||||
final GetVersionedProfileAnonymousResponse response = unauthenticatedServiceStub().getVersionedProfile(request);
|
||||
switch (authenticationCase) {
|
||||
case GROUP_SEND_TOKEN -> {
|
||||
final Instant expiration = Instant.now().plus(Duration.ofDays(1)).truncatedTo(ChronoUnit.DAYS);
|
||||
final byte[] token = AuthHelper.validGroupSendToken(SERVER_SECRET_PARAMS, List.of(serviceIdentifier), expiration);
|
||||
requestBuilder.setGroupSendToken(ByteString.copyFrom(token));
|
||||
}
|
||||
case UNIDENTIFIED_ACCESS_KEY -> requestBuilder.setUnidentifiedAccessKey(ByteString.copyFrom(unidentifiedAccessKey));
|
||||
}
|
||||
|
||||
final GetVersionedProfileAnonymousResponse response = unauthenticatedServiceStub().getVersionedProfile(requestBuilder.build());
|
||||
assertTrue(response.hasResult());
|
||||
|
||||
final GetVersionedProfileResult result = response.getResult();
|
||||
@@ -576,44 +598,38 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void getVersionedProfileUnauthenticated(final boolean missingUnidentifiedAccessKey, final boolean accountNotFound) {
|
||||
@EnumSource(mode = EXCLUDE, names = "AUTHENTICATION_NOT_SET")
|
||||
void getVersionedProfileAccountNotFound(
|
||||
final GetVersionedProfileAnonymousRequest.AuthenticationCase authenticationCase
|
||||
) throws Exception {
|
||||
final AciServiceIdentifier serviceIdentifier = new AciServiceIdentifier(UUID.randomUUID());
|
||||
final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
|
||||
|
||||
when(account.isUnrestrictedUnidentifiedAccess()).thenReturn(false);
|
||||
when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey));
|
||||
when(accountsManager.getByServiceIdentifier(any())).thenReturn(
|
||||
accountNotFound ? Optional.empty() : Optional.of(account));
|
||||
when(accountsManager.getByServiceIdentifier(any())).thenReturn(Optional.empty());
|
||||
|
||||
final GetVersionedProfileAnonymousRequest.Builder requestBuilder = GetVersionedProfileAnonymousRequest.newBuilder()
|
||||
.setRequest(GetVersionedProfileRequest.newBuilder()
|
||||
.setAccountIdentifier(ServiceIdentifier.newBuilder()
|
||||
.setIdentityType(IdentityType.IDENTITY_TYPE_ACI)
|
||||
.setUuid(ByteString.copyFrom(UUIDUtil.toBytes(UUID.randomUUID())))
|
||||
.build())
|
||||
.setAccountIdentifier(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(serviceIdentifier))
|
||||
.setVersion(ByteString.copyFrom(TestRandomUtil.nextBytes(32)))
|
||||
.build());
|
||||
|
||||
|
||||
if (missingUnidentifiedAccessKey) {
|
||||
assertStatusException(Status.INVALID_ARGUMENT,
|
||||
() -> unauthenticatedServiceStub().getVersionedProfile(requestBuilder.build()));
|
||||
} else {
|
||||
requestBuilder.setUnidentifiedAccessKey(ByteString.copyFrom(unidentifiedAccessKey));
|
||||
final GetVersionedProfileAnonymousResponse response = unauthenticatedServiceStub().getVersionedProfile(
|
||||
requestBuilder.build());
|
||||
|
||||
assertEquals(accountNotFound, response.hasNotFound());
|
||||
assertNotEquals(accountNotFound, response.hasFailedUnidentifiedAuthorization());
|
||||
switch (authenticationCase) {
|
||||
case GROUP_SEND_TOKEN -> {
|
||||
final Instant expiration = Instant.now().plus(Duration.ofDays(1)).truncatedTo(ChronoUnit.DAYS);
|
||||
final byte[] token = AuthHelper.validGroupSendToken(SERVER_SECRET_PARAMS, List.of(serviceIdentifier), expiration);
|
||||
requestBuilder.setGroupSendToken(ByteString.copyFrom(token));
|
||||
}
|
||||
case UNIDENTIFIED_ACCESS_KEY -> requestBuilder.setUnidentifiedAccessKey(ByteString.copyFrom(unidentifiedAccessKey));
|
||||
}
|
||||
|
||||
final GetVersionedProfileAnonymousResponse response = unauthenticatedServiceStub().getVersionedProfile(requestBuilder.build());
|
||||
|
||||
}
|
||||
private static Stream<Arguments> getVersionedProfileUnauthenticated() {
|
||||
return Stream.of(
|
||||
Arguments.of(true, false),
|
||||
Arguments.of(false, true)
|
||||
);
|
||||
switch (authenticationCase) {
|
||||
case GROUP_SEND_TOKEN -> assertTrue(response.hasNotFound());
|
||||
case UNIDENTIFIED_ACCESS_KEY, AUTHENTICATION_NOT_SET -> assertTrue(response.hasFailedUnidentifiedAuthorization());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -631,9 +647,81 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
|
||||
.build())
|
||||
.build();
|
||||
|
||||
//noinspection ThrowableNotThrown
|
||||
assertStatusException(Status.INVALID_ARGUMENT, () -> unauthenticatedServiceStub().getVersionedProfile(request));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getVersionedProfileNoAuth() {
|
||||
final GetVersionedProfileAnonymousRequest request = GetVersionedProfileAnonymousRequest.newBuilder()
|
||||
.setRequest(GetVersionedProfileRequest.newBuilder()
|
||||
.setAccountIdentifier(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(new AciServiceIdentifier(UUID.randomUUID()))))
|
||||
.build();
|
||||
|
||||
//noinspection ThrowableNotThrown
|
||||
assertStatusException(Status.INVALID_ARGUMENT, () -> unauthenticatedServiceStub().getVersionedProfile(request));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getVersionedProfileIncorrectUnidentifiedAccessKey() {
|
||||
final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
|
||||
|
||||
when(account.isUnrestrictedUnidentifiedAccess()).thenReturn(false);
|
||||
when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey));
|
||||
when(accountsManager.getByServiceIdentifier(any())).thenReturn(Optional.of(account));
|
||||
|
||||
final GetVersionedProfileAnonymousRequest request = GetVersionedProfileAnonymousRequest.newBuilder()
|
||||
.setUnidentifiedAccessKey(ByteString.copyFrom(new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH]))
|
||||
.setRequest(GetVersionedProfileRequest.newBuilder()
|
||||
.setAccountIdentifier(ServiceIdentifier.newBuilder()
|
||||
.setIdentityType(IdentityType.IDENTITY_TYPE_ACI)
|
||||
.setUuid(ByteString.copyFrom(UUIDUtil.toBytes(UUID.randomUUID())))
|
||||
.build())
|
||||
.setVersion(ByteString.copyFrom(TestRandomUtil.nextBytes(32)))
|
||||
.build())
|
||||
.build();
|
||||
|
||||
final GetVersionedProfileAnonymousResponse response = unauthenticatedServiceStub().getVersionedProfile(request);
|
||||
|
||||
assertTrue(response.hasFailedUnidentifiedAuthorization());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void getVersionedProfileFailingGroupSendEndorsement(final boolean expired, final boolean wrongIdentifier) throws Exception {
|
||||
final AciServiceIdentifier serviceIdentifier = new AciServiceIdentifier(UUID.randomUUID());
|
||||
final AciServiceIdentifier wrongServiceIdentifier = new AciServiceIdentifier(UUID.randomUUID());
|
||||
|
||||
when(accountsManager.getByServiceIdentifier(serviceIdentifier))
|
||||
.thenReturn(Optional.of(mock(Account.class)));
|
||||
|
||||
final Instant expiration = expired ? Instant.now().truncatedTo(ChronoUnit.DAYS) : Instant.now().plus(Duration.ofDays(1)).truncatedTo(ChronoUnit.DAYS);
|
||||
|
||||
final byte[] token = AuthHelper.validGroupSendToken(SERVER_SECRET_PARAMS,
|
||||
List.of(wrongIdentifier ? wrongServiceIdentifier : serviceIdentifier), expiration);
|
||||
|
||||
final GetVersionedProfileAnonymousRequest request = GetVersionedProfileAnonymousRequest.newBuilder()
|
||||
.setGroupSendToken(ByteString.copyFrom(token))
|
||||
.setRequest(GetVersionedProfileRequest.newBuilder()
|
||||
.setAccountIdentifier(
|
||||
GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(serviceIdentifier))
|
||||
.setVersion(ByteString.copyFrom(TestRandomUtil.nextBytes(32)))
|
||||
.build())
|
||||
.build();
|
||||
|
||||
final GetVersionedProfileAnonymousResponse response = unauthenticatedServiceStub().getVersionedProfile(request);
|
||||
|
||||
assertTrue(response.hasFailedUnidentifiedAuthorization());
|
||||
}
|
||||
|
||||
private static List<Arguments> getVersionedProfileFailingGroupSendEndorsement() {
|
||||
return List.of(
|
||||
Arguments.of(true, true),
|
||||
Arguments.of(true, false),
|
||||
Arguments.of(false, true)
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getExpiringProfileKeyCredential() throws Exception {
|
||||
final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
|
||||
|
||||
+1
-2
@@ -174,7 +174,6 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
|
||||
new BadgeSvg("ll", "ld")
|
||||
)
|
||||
)),
|
||||
List.of("TEST1"),
|
||||
Map.of(1L, "TEST1", 2L, "TEST2", 3L, "TEST3")
|
||||
);
|
||||
final RateLimiters rateLimiters = mock(RateLimiters.class);
|
||||
@@ -655,7 +654,7 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
|
||||
.setIdentityKey(ByteString.copyFrom(identityKey.serialize()))
|
||||
.setUnidentifiedAccess(ByteString.copyFrom(unidentifiedAccessChecksum))
|
||||
.setUnrestrictedUnidentifiedAccess(true)
|
||||
.addAllBadges(ProfileGrpcHelper.buildBadges(badges))
|
||||
.addAllBadges(badges.stream().map(BadgeGrpcHelper::toGrpcBadge).toList())
|
||||
.build();
|
||||
|
||||
final GetUnversionedProfileResult expectedResponse;
|
||||
|
||||
+3
@@ -8,6 +8,7 @@ package org.whispersystems.textsecuregcm.metrics;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
@@ -77,6 +78,8 @@ class MetricsRequestEventListenerTest {
|
||||
@BeforeEach
|
||||
void setup() {
|
||||
meterRegistry = mock(MeterRegistry.class);
|
||||
when(meterRegistry.gauge(anyString(), any(Number.class))).thenAnswer(invocation -> invocation.getArgument(1));
|
||||
|
||||
counter = mock(Counter.class);
|
||||
responseBytesCounter = mock(Counter.class);
|
||||
requestBytesCounter = mock(Counter.class);
|
||||
|
||||
+1
-1
@@ -64,7 +64,7 @@ class AcknowledgementMirroringMessageStreamTest {
|
||||
void acknowledgeMessages(final UUIDVersion uuidVersion) {
|
||||
final List<MessageStreamEntry> entries = new ArrayList<>();
|
||||
{
|
||||
for (int i = 0; i < 256; i++) {
|
||||
for (int i = 0; i < AcknowledgementMirroringMessageStream.FOUNDATIONDB_REQUEST_SIZE + 1; i++) {
|
||||
entries.add(generateEnvelopeEntry(uuidVersion));
|
||||
}
|
||||
|
||||
|
||||
+13
-13
@@ -20,8 +20,6 @@ import static org.mockito.Mockito.when;
|
||||
|
||||
import com.google.i18n.phonenumbers.PhoneNumberUtil;
|
||||
import com.google.protobuf.ByteString;
|
||||
import jakarta.ws.rs.WebApplicationException;
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Collection;
|
||||
@@ -41,6 +39,7 @@ import org.mockito.stubbing.Answer;
|
||||
import org.signal.libsignal.protocol.IdentityKey;
|
||||
import org.signal.libsignal.protocol.ecc.ECKeyPair;
|
||||
import org.whispersystems.textsecuregcm.auth.PhoneVerificationTokenManager;
|
||||
import org.whispersystems.textsecuregcm.auth.RegistrationLockFailureException;
|
||||
import org.whispersystems.textsecuregcm.auth.RegistrationLockVerificationManager;
|
||||
import org.whispersystems.textsecuregcm.controllers.MessageDeliveryNotAllowedException;
|
||||
import org.whispersystems.textsecuregcm.controllers.MismatchedDevicesException;
|
||||
@@ -50,6 +49,7 @@ import org.whispersystems.textsecuregcm.entities.IncomingMessage;
|
||||
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.entities.PhoneVerificationRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.RegistrationLockFailure;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier;
|
||||
@@ -85,8 +85,8 @@ public class ChangeNumberManagerTest {
|
||||
changeNumberWaitingPeriodManager = mock(ChangeNumberWaitingPeriodManager.class);
|
||||
rateLimiter = mock(RateLimiter.class);
|
||||
|
||||
when(phoneVerificationTokenManager.verify(any(), any(), any(), any())).thenAnswer(invocation -> {
|
||||
final byte[] sessionId = invocation.getArgument(2);
|
||||
when(phoneVerificationTokenManager.verify(any(), any(), any(), any(), any(), any())).thenAnswer(invocation -> {
|
||||
final byte[] sessionId = invocation.getArgument(4);
|
||||
|
||||
return sessionId != null
|
||||
? PhoneVerificationRequest.VerificationType.SESSION
|
||||
@@ -164,7 +164,7 @@ public class ChangeNumberManagerTest {
|
||||
when(accountsManager.getAccountsForChangeNumber(eq(accountIdentifier), any()))
|
||||
.thenReturn(new Pair<>(account, Optional.empty()));
|
||||
|
||||
changeNumberManager.changeNumber(accountIdentifier, null, null, null, targetNumber, pniIdentityKey, ecSignedPreKeys, kemLastResortPreKeys, Collections.emptyList(), Collections.emptyMap(), mock(ContainerRequestContext.class));
|
||||
changeNumberManager.changeNumber(accountIdentifier, null, null, null, targetNumber, pniIdentityKey, ecSignedPreKeys, kemLastResortPreKeys, Collections.emptyList(), Collections.emptyMap(), null, null, null);
|
||||
verify(accountsManager).changeNumber(accountIdentifier, targetNumber, pniIdentityKey, ecSignedPreKeys, kemLastResortPreKeys, Collections.emptyMap());
|
||||
verify(messageSender, never()).sendMessages(any(), any(), any(), any(), any(), any());
|
||||
}
|
||||
@@ -233,7 +233,7 @@ public class ChangeNumberManagerTest {
|
||||
kemLastResortPreKeys,
|
||||
List.of(incomingMessage),
|
||||
registrationIds,
|
||||
mock(ContainerRequestContext.class));
|
||||
null, null, null);
|
||||
|
||||
verify(accountsManager).changeNumber(aci,
|
||||
targetNumber,
|
||||
@@ -288,7 +288,7 @@ public class ChangeNumberManagerTest {
|
||||
when(accountsManager.getAccountsForChangeNumber(eq(accountIdentifier), any()))
|
||||
.thenReturn(new Pair<>(account, Optional.empty()));
|
||||
|
||||
changeNumberManager.changeNumber(accountIdentifier, null, null, null, targetNumber, pniIdentityKey, ecSignedPreKeys, kemLastResortPreKeys, Collections.emptyList(), Collections.emptyMap(), mock(ContainerRequestContext.class));
|
||||
changeNumberManager.changeNumber(accountIdentifier, null, null, null, targetNumber, pniIdentityKey, ecSignedPreKeys, kemLastResortPreKeys, Collections.emptyList(), Collections.emptyMap(), null, null, null);
|
||||
|
||||
verifyNoInteractions(rateLimiter);
|
||||
verifyNoInteractions(phoneVerificationTokenManager);
|
||||
@@ -340,7 +340,7 @@ public class ChangeNumberManagerTest {
|
||||
kemLastResortPreKeys,
|
||||
Collections.emptyList(),
|
||||
Collections.emptyMap(),
|
||||
mock(ContainerRequestContext.class)));
|
||||
null, null, null));
|
||||
|
||||
verify(accountsManager, never()).changeNumber(any(), any(), any(), any(), any(), any());
|
||||
verify(messageSender, never()).sendMessages(any(), any(), any(), any(), any(), any());
|
||||
@@ -348,7 +348,7 @@ public class ChangeNumberManagerTest {
|
||||
|
||||
@Test
|
||||
void changeNumberRegistrationLockFailed()
|
||||
throws MismatchedDevicesException, InterruptedException, MessageTooLargeException, RateLimitExceededException, MessageDeliveryNotAllowedException {
|
||||
throws Exception {
|
||||
final String originalNumber = PhoneNumberUtil.getInstance().format(
|
||||
PhoneNumberUtil.getInstance().getExampleNumber("DE"), PhoneNumberUtil.PhoneNumberFormat.E164);
|
||||
|
||||
@@ -378,10 +378,10 @@ public class ChangeNumberManagerTest {
|
||||
when(accountsManager.getAccountsForChangeNumber(eq(accountIdentifier), any()))
|
||||
.thenReturn(new Pair<>(account, Optional.of(existingAccount)));
|
||||
|
||||
doThrow(new WebApplicationException(423))
|
||||
doThrow(new RegistrationLockFailureException(new RegistrationLockFailure(0L, null)))
|
||||
.when(registrationLockVerificationManager).verifyRegistrationLock(eq(existingAccount), any(), any(), any(), any());
|
||||
|
||||
assertThrows(WebApplicationException.class, () -> changeNumberManager.changeNumber(accountIdentifier,
|
||||
assertThrows(RegistrationLockFailureException.class, () -> changeNumberManager.changeNumber(accountIdentifier,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
@@ -391,7 +391,7 @@ public class ChangeNumberManagerTest {
|
||||
kemLastResortPreKeys,
|
||||
Collections.emptyList(),
|
||||
Collections.emptyMap(),
|
||||
mock(ContainerRequestContext.class)));
|
||||
null, null, null));
|
||||
|
||||
verify(accountsManager, never()).changeNumber(any(), any(), any(), any(), any(), any());
|
||||
verify(messageSender, never()).sendMessages(any(), any(), any(), any(), any(), any());
|
||||
@@ -445,7 +445,7 @@ public class ChangeNumberManagerTest {
|
||||
kemLastResortPreKeys,
|
||||
Collections.emptyList(),
|
||||
Collections.emptyMap(),
|
||||
mock(ContainerRequestContext.class));
|
||||
null, null, null);
|
||||
if (expectRateLimited) {
|
||||
final RateLimitExceededException e = assertThrows(RateLimitExceededException.class, changeNumberOperation);
|
||||
assertEquals(waitingPeriod, e.getRetryDuration().orElseThrow());
|
||||
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStream;
|
||||
|
||||
class MirroringMessageStreamTest {
|
||||
|
||||
private FoundationDbMessageStream foundationDbMessageStream;
|
||||
private ExperimentEnrollmentManager experimentEnrollmentManager;
|
||||
|
||||
private MirroringMessageStream mirroringMessageStream;
|
||||
|
||||
private static final AciServiceIdentifier ACCOUNT_IDENTIFIER = new AciServiceIdentifier(UUID.randomUUID());
|
||||
private static final byte DEVICE_ID = Device.PRIMARY_ID;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
foundationDbMessageStream = mock(FoundationDbMessageStream.class);
|
||||
experimentEnrollmentManager = mock(ExperimentEnrollmentManager.class);
|
||||
|
||||
mirroringMessageStream = new MirroringMessageStream(
|
||||
mock(RedisDynamoDbMessageStream.class),
|
||||
foundationDbMessageStream,
|
||||
experimentEnrollmentManager,
|
||||
ACCOUNT_IDENTIFIER.uuid(),
|
||||
DEVICE_ID);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void acknowledgeMessage(final boolean enrolled, final UUID messageGuid, final boolean expectFoundationDbDeletion) {
|
||||
when(experimentEnrollmentManager.isEnrolled(any(UUID.class), eq(MessagesManager.MIRROR_DELETIONS_EXPERIMENT_NAME)))
|
||||
.thenReturn(enrolled);
|
||||
|
||||
final long serverTimestamp = System.currentTimeMillis();
|
||||
|
||||
mirroringMessageStream.acknowledgeMessage(messageGuid, serverTimestamp);
|
||||
|
||||
if (expectFoundationDbDeletion) {
|
||||
verify(foundationDbMessageStream).acknowledgeMessage(messageGuid, serverTimestamp);
|
||||
} else {
|
||||
verify(foundationDbMessageStream, never()).acknowledgeMessage(any(), anyLong());
|
||||
}
|
||||
}
|
||||
|
||||
private static List<Arguments> acknowledgeMessage() {
|
||||
return List.of(
|
||||
Arguments.argumentSet("Not enrolled, v4 UUID", false, UUID.randomUUID(), false),
|
||||
Arguments.argumentSet("Not enrolled, v8 UUID", false, MessageGuidUtil.generateRandomV8UUID(), false),
|
||||
Arguments.argumentSet("Enrolled, v4 UUID", true, UUID.randomUUID(), false),
|
||||
Arguments.argumentSet("Enrolled, v8 UUID", true, MessageGuidUtil.generateRandomV8UUID(), true)
|
||||
);
|
||||
}
|
||||
}
|
||||
-95
@@ -1,95 +0,0 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.storage.foundationdb;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import com.apple.foundationdb.tuple.Versionstamp;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.ByteOrder;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.stream.IntStream;
|
||||
import java.util.stream.Stream;
|
||||
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.Pair;
|
||||
|
||||
class AcknowledgedMessageBufferTest {
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void computeFlushableRanges(final List<Integer> versionstampsSent,
|
||||
final List<Integer> versionstampsAcknowledged,
|
||||
final List<Pair<Integer, Integer>> expectedRanges) {
|
||||
|
||||
final AcknowledgedMessageBuffer acknowledgedMessageBuffer =
|
||||
new AcknowledgedMessageBuffer(FoundationDbMessageStream.DEFAULT_MAX_UNACKNOWLEDGED_MESSAGES);
|
||||
|
||||
versionstampsSent.forEach(versionstamp -> assertDoesNotThrow(() ->
|
||||
acknowledgedMessageBuffer.addUnacknowledgedMessage(versionstampFromInt(versionstamp))));
|
||||
|
||||
versionstampsAcknowledged.forEach(versionstamp ->
|
||||
acknowledgedMessageBuffer.acknowledgeMessage(versionstampFromInt(versionstamp)));
|
||||
|
||||
final List<Pair<Versionstamp, Versionstamp>> flushableRanges = acknowledgedMessageBuffer.computeFlushableRanges();
|
||||
|
||||
assertEquals(expectedRanges
|
||||
.stream()
|
||||
.map(range -> new Pair<>(versionstampFromInt(range.first()), versionstampFromInt(range.second())))
|
||||
.toList(),
|
||||
flushableRanges);
|
||||
}
|
||||
|
||||
@Test
|
||||
void takeFlushableRanges() {
|
||||
final AcknowledgedMessageBuffer acknowledgedMessageBuffer =
|
||||
new AcknowledgedMessageBuffer(FoundationDbMessageStream.DEFAULT_MAX_UNACKNOWLEDGED_MESSAGES);
|
||||
|
||||
IntStream.range(0, 10)
|
||||
.mapToObj(AcknowledgedMessageBufferTest::versionstampFromInt)
|
||||
.forEach(versionstamp -> assertDoesNotThrow(
|
||||
() -> acknowledgedMessageBuffer.addUnacknowledgedMessage(versionstamp)));
|
||||
|
||||
assertEquals(10, acknowledgedMessageBuffer.getUnacknowledgedMessageCount());
|
||||
|
||||
IntStream.range(2, 8)
|
||||
.mapToObj(AcknowledgedMessageBufferTest::versionstampFromInt)
|
||||
.forEach(acknowledgedMessageBuffer::acknowledgeMessage);
|
||||
|
||||
assertEquals(List.of(new Pair<>(versionstampFromInt(2), versionstampFromInt(7))),
|
||||
acknowledgedMessageBuffer.takeFlushableRanges());
|
||||
|
||||
assertEquals(4, acknowledgedMessageBuffer.getUnacknowledgedMessageCount());
|
||||
}
|
||||
|
||||
static Stream<Arguments> computeFlushableRanges() {
|
||||
return Stream.of(
|
||||
Arguments.argumentSet("Single acknowledged message range", List.of(1, 2, 3), List.of(1),
|
||||
List.of(new Pair<>(1, 1))),
|
||||
Arguments.argumentSet("No acknowledged messages", List.of(1, 2, 3), Collections.emptyList(),
|
||||
Collections.emptyList()),
|
||||
Arguments.argumentSet("Fully acknowledged message range", List.of(1, 2, 3, 4),
|
||||
List.of(1, 2, 3, 4), List.of(new Pair<>(1, 4))),
|
||||
Arguments.argumentSet("Not all messages acknowledged", List.of(1, 2, 3, 4),
|
||||
List.of(1, 2, 3), List.of(new Pair<>(1, 3))),
|
||||
Arguments.argumentSet("Out-of-order acknowledged ranges", List.of(1, 2, 3, 4, 5, 6, 7, 8),
|
||||
List.of(1, 3, 4, 5, 7, 8), List.of(new Pair<>(1, 1), new Pair<>(3, 5), new Pair<>(7, 8))),
|
||||
Arguments.argumentSet("Out-of-order acknowledged single messages", List.of(1, 2, 3, 4, 5, 6, 7, 8),
|
||||
List.of(1, 3, 5), List.of(new Pair<>(1, 1), new Pair<>(3, 3), new Pair<>(5, 5)))
|
||||
);
|
||||
}
|
||||
|
||||
private static Versionstamp versionstampFromInt(final int version) {
|
||||
final ByteBuffer buf = ByteBuffer.allocate(10).order(ByteOrder.BIG_ENDIAN);
|
||||
buf.putLong(version); // 8 bytes: transaction version
|
||||
buf.putShort((short) 2); // 2 bytes: batch order within transaction
|
||||
return Versionstamp.complete(buf.array());
|
||||
}
|
||||
}
|
||||
+6
-16
@@ -35,9 +35,7 @@ import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Supplier;
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
@@ -66,8 +64,6 @@ class FoundationDbMessagePublisherTest {
|
||||
private static final byte[] MESSAGES_AVAILABLE_WATCH_KEY =
|
||||
FoundationDbMessageStore.getMessagesAvailableWatchKey(SERVICE_IDENTIFIER);
|
||||
|
||||
private static final Supplier<Consumer<Transaction>> NOOP_ON_PAGE_FETCH = () -> _ -> {};
|
||||
|
||||
private static final Clock CLOCK = Clock.systemUTC();
|
||||
|
||||
private static final int STREAM_ID = ThreadLocalRandom.current().nextInt();
|
||||
@@ -131,8 +127,7 @@ class FoundationDbMessagePublisherTest {
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
(_, newState) -> stateTransitions.add(newState),
|
||||
NOOP_ON_PAGE_FETCH
|
||||
(_, newState) -> stateTransitions.add(newState)
|
||||
);
|
||||
|
||||
StepVerifier.create(finitePublisher.getMessages())
|
||||
@@ -219,8 +214,7 @@ class FoundationDbMessagePublisherTest {
|
||||
watchFuture2.complete(null);
|
||||
}
|
||||
}
|
||||
},
|
||||
NOOP_ON_PAGE_FETCH
|
||||
}
|
||||
);
|
||||
|
||||
StepVerifier.create(infinitePublisher.getMessages())
|
||||
@@ -302,8 +296,7 @@ class FoundationDbMessagePublisherTest {
|
||||
.count() == 1) {
|
||||
watchFuture1.complete(null);
|
||||
}
|
||||
},
|
||||
NOOP_ON_PAGE_FETCH
|
||||
}
|
||||
);
|
||||
|
||||
StepVerifier.create(infinitePublisher.getMessages())
|
||||
@@ -338,8 +331,7 @@ class FoundationDbMessagePublisherTest {
|
||||
100,
|
||||
FoundationDbMessageStore.getPresenceKey(SERVICE_IDENTIFIER, Device.PRIMARY_ID),
|
||||
presenceRenewalExecutorService,
|
||||
MESSAGES_AVAILABLE_WATCH_KEY,
|
||||
() -> _ -> {});
|
||||
MESSAGES_AVAILABLE_WATCH_KEY);
|
||||
final MessageProtos.Envelope message = FoundationDbMessageStoreTest.generateRandomMessage(false);
|
||||
final Transaction transaction = mock(Transaction.class);
|
||||
final KeyValue keyValue = mockKeyValue((byte) 5, message);
|
||||
@@ -399,8 +391,7 @@ class FoundationDbMessagePublisherTest {
|
||||
FoundationDbMessageStore.getPresenceKey(SERVICE_IDENTIFIER, Device.PRIMARY_ID),
|
||||
presenceRenewalExecutorService,
|
||||
MESSAGES_AVAILABLE_WATCH_KEY,
|
||||
(_, newState) -> stateTransitions.add(newState),
|
||||
NOOP_ON_PAGE_FETCH
|
||||
(_, newState) -> stateTransitions.add(newState)
|
||||
);
|
||||
|
||||
final RuntimeException streamTerminationException = new RuntimeException("Stream terminated");
|
||||
@@ -464,8 +455,7 @@ class FoundationDbMessagePublisherTest {
|
||||
&& newState == FoundationDbMessagePublisher.State.MESSAGES_AVAILABLE) {
|
||||
latch.countDown();
|
||||
}
|
||||
},
|
||||
NOOP_ON_PAGE_FETCH
|
||||
}
|
||||
);
|
||||
|
||||
// Request two messages one at a time and verify that we only fetch a single batch (batch size = 2) and not two batches
|
||||
|
||||
+50
-44
@@ -74,6 +74,7 @@ import org.whispersystems.textsecuregcm.util.TestRandomUtil;
|
||||
import org.whispersystems.textsecuregcm.util.UUIDUtil;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
import reactor.adapter.JdkFlowAdapter;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.test.StepVerifier;
|
||||
|
||||
@Timeout(value = 5, threadMode = Timeout.ThreadMode.SEPARATE_THREAD)
|
||||
@@ -493,6 +494,36 @@ class FoundationDbMessageStoreTest {
|
||||
Map.of(generateRandomAciForShard(0), Collections.emptyMap())));
|
||||
}
|
||||
|
||||
@Test
|
||||
void delete() {
|
||||
final AciServiceIdentifier deletedMessageAci = new AciServiceIdentifier(UUID.randomUUID());
|
||||
final byte deletedMessageDeviceId = Device.PRIMARY_ID;
|
||||
final MessageProtos.Envelope deletedMessage = generateRandomMessage(false);
|
||||
|
||||
final AciServiceIdentifier retainedMessageAci = new AciServiceIdentifier(UUID.randomUUID());
|
||||
final byte retainedMessageDeviceId = Device.PRIMARY_ID;
|
||||
final MessageProtos.Envelope retainedMessage = generateRandomMessage(false);
|
||||
|
||||
final UUID deletedMessageGuid =
|
||||
foundationDbMessageStore.insert(deletedMessageAci, Map.of(deletedMessageDeviceId, deletedMessage)).join()
|
||||
.get(deletedMessageDeviceId).messageGuid().orElseThrow();
|
||||
|
||||
foundationDbMessageStore.insert(retainedMessageAci, Map.of(retainedMessageDeviceId, retainedMessage)).join();
|
||||
|
||||
assertArrayEquals(deletedMessage.toByteArray(),
|
||||
getItemsInDeviceQueue(deletedMessageAci, deletedMessageDeviceId).getFirst().getValue());
|
||||
|
||||
assertArrayEquals(retainedMessage.toByteArray(),
|
||||
getItemsInDeviceQueue(retainedMessageAci, retainedMessageDeviceId).getFirst().getValue());
|
||||
|
||||
foundationDbMessageStore.delete(deletedMessageAci, deletedMessageDeviceId, deletedMessageGuid).join();
|
||||
|
||||
assertTrue(getItemsInDeviceQueue(deletedMessageAci, deletedMessageDeviceId).isEmpty());
|
||||
|
||||
assertArrayEquals(retainedMessage.toByteArray(),
|
||||
getItemsInDeviceQueue(retainedMessageAci, retainedMessageDeviceId).getFirst().getValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void clearAllForAccount() {
|
||||
final AciServiceIdentifier deletedAccountIdentifier = new AciServiceIdentifier(UUID.randomUUID());
|
||||
@@ -564,7 +595,7 @@ class FoundationDbMessageStoreTest {
|
||||
.toList();
|
||||
|
||||
final MessageStream messageStream =
|
||||
foundationDbMessageStore.getMessages(aci, Device.PRIMARY_ID, batchSize, numMessages, Util.NOOP);
|
||||
foundationDbMessageStore.getMessages(aci, Device.PRIMARY_ID, batchSize, Util.NOOP);
|
||||
|
||||
final List<MessageStreamEntry> retrievedEntries = new ArrayList<>();
|
||||
StepVerifier.create(JdkFlowAdapter.flowPublisherToFlux(messageStream.getMessages()))
|
||||
@@ -878,7 +909,6 @@ class FoundationDbMessageStoreTest {
|
||||
final CountDownLatch latch = new CountDownLatch(1);
|
||||
final MessageStream messageStream = foundationDbMessageStore.getMessages(aci, Device.PRIMARY_ID,
|
||||
FoundationDbMessageStream.DEFAULT_MAX_MESSAGES_PER_SCAN,
|
||||
FoundationDbMessageStream.DEFAULT_MAX_UNACKNOWLEDGED_MESSAGES,
|
||||
latch::countDown);
|
||||
final List<CompletableFuture<Void>> acknowledgeFutures = new ArrayList<>();
|
||||
final AtomicInteger messageCounter = new AtomicInteger(0);
|
||||
@@ -949,7 +979,6 @@ class FoundationDbMessageStoreTest {
|
||||
final MessageStream messageStream = foundationDbMessageStore.getMessages(aci,
|
||||
deviceId,
|
||||
FoundationDbMessageStream.DEFAULT_MAX_MESSAGES_PER_SCAN,
|
||||
FoundationDbMessageStream.DEFAULT_MAX_UNACKNOWLEDGED_MESSAGES,
|
||||
cleanupLatch::countDown);
|
||||
|
||||
final List<MessageStreamEntry> retrievedEntries = new ArrayList<>();
|
||||
@@ -990,28 +1019,6 @@ class FoundationDbMessageStoreTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void outstandingUnacknowledgedMessages() {
|
||||
final int numMessages = 5;
|
||||
final int maxUnacknowledgedMessages = 3;
|
||||
|
||||
final AciServiceIdentifier aci = new AciServiceIdentifier(UUID.randomUUID());
|
||||
|
||||
for (int i = 0; i < numMessages; i++) {
|
||||
foundationDbMessageStore.insert(aci, Map.of(Device.PRIMARY_ID, generateRandomMessage(false))).join();
|
||||
}
|
||||
|
||||
final MessageStream messageStream = foundationDbMessageStore.getMessages(aci, Device.PRIMARY_ID,
|
||||
FoundationDbMessageStream.DEFAULT_MAX_MESSAGES_PER_SCAN,
|
||||
maxUnacknowledgedMessages,
|
||||
Util.NOOP);
|
||||
|
||||
StepVerifier.create(JdkFlowAdapter.flowPublisherToFlux(messageStream.getMessages()), numMessages)
|
||||
.expectNextCount(maxUnacknowledgedMessages)
|
||||
.expectError(TooManyUnacknowledgedMessagesException.class)
|
||||
.verify();
|
||||
}
|
||||
|
||||
@Test
|
||||
void discardStaleEphemeralMessages() throws InterruptedException {
|
||||
final AciServiceIdentifier aci = new AciServiceIdentifier(UUID.randomUUID());
|
||||
@@ -1048,7 +1055,6 @@ class FoundationDbMessageStoreTest {
|
||||
|
||||
final MessageStream messageStream = foundationDbMessageStore.getMessages(aci, Device.PRIMARY_ID,
|
||||
FoundationDbMessageStream.DEFAULT_MAX_MESSAGES_PER_SCAN,
|
||||
FoundationDbMessageStream.DEFAULT_MAX_UNACKNOWLEDGED_MESSAGES,
|
||||
cleanUpLatch::countDown);
|
||||
StepVerifier.create(JdkFlowAdapter.flowPublisherToFlux(messageStream.getMessages()))
|
||||
// We should have discarded the already-inserted ephemeral message
|
||||
@@ -1077,14 +1083,13 @@ class FoundationDbMessageStoreTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
@Disabled("flaky test")
|
||||
void deleteExpiredMessages() {
|
||||
final Instant oldTime = CLOCK.instant();
|
||||
final Instant threshold = oldTime.plus(Duration.ofDays(1));
|
||||
final Instant newTime = oldTime.plus(Duration.ofDays(2));
|
||||
final Instant testTime = oldTime.plus(Duration.ofDays(3));
|
||||
|
||||
final List<AciServiceIdentifier> acis = IntStream.range(0, 1024).mapToObj(_ -> new AciServiceIdentifier(UUID.randomUUID())).toList();
|
||||
final List<AciServiceIdentifier> acis = IntStream.range(0, 10).mapToObj(_ -> new AciServiceIdentifier(UUID.randomUUID())).toList();
|
||||
final byte deviceId = Device.PRIMARY_ID;
|
||||
|
||||
// insert some old messages
|
||||
@@ -1117,22 +1122,23 @@ class FoundationDbMessageStoreTest {
|
||||
threshold);
|
||||
|
||||
// make sure we have new but not old messages
|
||||
for (AciServiceIdentifier aci : acis) {
|
||||
final MessageStream messageStream = foundationDbMessageStore.getMessages(aci, deviceId);
|
||||
final List<MessageProtos.Envelope> messages =
|
||||
JdkFlowAdapter.flowPublisherToFlux(messageStream.getMessages())
|
||||
.takeUntil(entry -> entry instanceof MessageStreamEntry.QueueEmpty)
|
||||
.filter(entry -> entry instanceof MessageStreamEntry.Envelope)
|
||||
.cast(MessageStreamEntry.Envelope.class)
|
||||
.map(MessageStreamEntry.Envelope::message)
|
||||
.collectList()
|
||||
.blockOptional()
|
||||
.orElseGet(Collections::emptyList);
|
||||
assertEquals(10, messages.size());
|
||||
for (MessageProtos.Envelope m : messages) {
|
||||
assertEquals(newTime.toEpochMilli(), m.getServerTimestamp());
|
||||
}
|
||||
}
|
||||
Flux.fromIterable(acis)
|
||||
.flatMap(aci ->
|
||||
JdkFlowAdapter.flowPublisherToFlux(foundationDbMessageStore.getMessages(aci, deviceId).getMessages())
|
||||
.takeUntil(entry -> entry instanceof MessageStreamEntry.QueueEmpty)
|
||||
.filter(entry -> entry instanceof MessageStreamEntry.Envelope)
|
||||
.cast(MessageStreamEntry.Envelope.class)
|
||||
.map(MessageStreamEntry.Envelope::message)
|
||||
.collectList())
|
||||
.doOnNext(
|
||||
messages -> {
|
||||
assertEquals(10, messages.size());
|
||||
for (MessageProtos.Envelope m : messages) {
|
||||
assertEquals(newTime.toEpochMilli(), m.getServerTimestamp());
|
||||
}
|
||||
})
|
||||
.then()
|
||||
.block();
|
||||
}
|
||||
|
||||
static MessageProtos.Envelope generateRandomMessage(final boolean ephemeral, final int contentSize) {
|
||||
|
||||
+196
@@ -0,0 +1,196 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.tests.util;
|
||||
|
||||
import com.google.i18n.phonenumbers.PhoneNumberUtil;
|
||||
import com.google.i18n.phonenumbers.Phonenumber;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Stream;
|
||||
import javax.annotation.Nullable;
|
||||
import org.junit.jupiter.api.extension.ExtensionContext;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.ArgumentsProvider;
|
||||
import org.junit.jupiter.params.support.ParameterDeclarations;
|
||||
import org.signal.libsignal.protocol.IdentityKey;
|
||||
import org.signal.libsignal.protocol.ecc.ECKeyPair;
|
||||
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountBadge;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
public class AccountsTestHelper {
|
||||
|
||||
public static class AccountsDataReportArgumentProvider implements ArgumentsProvider {
|
||||
|
||||
@Override
|
||||
public Stream<? extends Arguments> provideArguments(final ParameterDeclarations parameters,
|
||||
final ExtensionContext context) {
|
||||
|
||||
final String exampleNumber1 = toE164(PhoneNumberUtil.getInstance().getExampleNumber("ES"));
|
||||
final String account2PhoneNumber = toE164(PhoneNumberUtil.getInstance().getExampleNumber("AU"));
|
||||
final String account3PhoneNumber = toE164(PhoneNumberUtil.getInstance().getExampleNumber("IN"));
|
||||
|
||||
final Instant account1Device1Created = Instant.ofEpochSecond(1669323142); // 2022-11-24T20:52:22Z
|
||||
final Instant account1Device2Created = Instant.ofEpochSecond(1679155122); // 2023-03-18T15:58:42Z
|
||||
final Instant account1Device1LastSeen = Instant.ofEpochMilli(Util.todayInMillis());
|
||||
final Instant account1Device2LastSeen = Instant.ofEpochSecond(1678838400); // 2023-03-15T00:00:00Z
|
||||
|
||||
final Instant account2Device1Created = Instant.ofEpochSecond(1659123001); // 2022-07-29T19:30:01Z
|
||||
final Instant account2Device1LastSeen = Instant.ofEpochMilli(Util.todayInMillis());
|
||||
final Instant badgeAExpiration = Instant.now().plus(Duration.ofDays(21)).truncatedTo(ChronoUnit.SECONDS);
|
||||
|
||||
final Instant account3Device1Created = Instant.ofEpochSecond(1639923487); // 2021-12-19T14:18:07Z
|
||||
final Instant account3Device1LastSeen = Instant.ofEpochMilli(Util.todayInMillis());
|
||||
final Instant badgeBExpiration = Instant.now().plus(Duration.ofDays(21)).truncatedTo(ChronoUnit.SECONDS);
|
||||
final Instant badgeCExpiration = Instant.now().plus(Duration.ofDays(24)).truncatedTo(ChronoUnit.SECONDS);
|
||||
|
||||
return Stream.of(
|
||||
Arguments.of(
|
||||
buildTestAccountForDataReport(UUID.randomUUID(), exampleNumber1,
|
||||
true, true,
|
||||
Collections.emptyList(),
|
||||
List.of(new DeviceData(Device.PRIMARY_ID, account1Device1LastSeen, account1Device1Created, null),
|
||||
new DeviceData((byte) 2, account1Device2LastSeen, account1Device2Created, "OWP"))),
|
||||
String.format("""
|
||||
# Account
|
||||
Phone number: %s
|
||||
Allow sealed sender from anyone: true
|
||||
Find account by phone number: true
|
||||
Badges: None
|
||||
|
||||
# Devices
|
||||
- ID: 1
|
||||
Created: 2022-11-24T20:52:22Z
|
||||
Last seen: %s
|
||||
User-agent: null
|
||||
- ID: 2
|
||||
Created: 2023-03-18T15:58:42Z
|
||||
Last seen: 2023-03-15T00:00:00Z
|
||||
User-agent: OWP
|
||||
""",
|
||||
exampleNumber1,
|
||||
account1Device1LastSeen)
|
||||
),
|
||||
Arguments.of(
|
||||
buildTestAccountForDataReport(UUID.randomUUID(), account2PhoneNumber,
|
||||
false, true,
|
||||
List.of(new AccountBadge("badge_a", badgeAExpiration, true)),
|
||||
List.of(new DeviceData(Device.PRIMARY_ID, account2Device1LastSeen, account2Device1Created, "OWI"))),
|
||||
String.format("""
|
||||
# Account
|
||||
Phone number: %s
|
||||
Allow sealed sender from anyone: false
|
||||
Find account by phone number: true
|
||||
Badges:
|
||||
- ID: badge_a
|
||||
Expiration: %s
|
||||
Visible: true
|
||||
|
||||
# Devices
|
||||
- ID: 1
|
||||
Created: 2022-07-29T19:30:01Z
|
||||
Last seen: %s
|
||||
User-agent: OWI
|
||||
""", account2PhoneNumber,
|
||||
badgeAExpiration,
|
||||
account2Device1LastSeen)
|
||||
),
|
||||
Arguments.of(
|
||||
buildTestAccountForDataReport(UUID.randomUUID(), account3PhoneNumber,
|
||||
true, false,
|
||||
List.of(
|
||||
new AccountBadge("badge_b", badgeBExpiration, true),
|
||||
new AccountBadge("badge_c", badgeCExpiration, false)),
|
||||
List.of(new DeviceData(Device.PRIMARY_ID, account3Device1LastSeen, account3Device1Created, "OWA"))),
|
||||
String.format("""
|
||||
# Account
|
||||
Phone number: %s
|
||||
Allow sealed sender from anyone: true
|
||||
Find account by phone number: false
|
||||
Badges:
|
||||
- ID: badge_b
|
||||
Expiration: %s
|
||||
Visible: true
|
||||
- ID: badge_c
|
||||
Expiration: %s
|
||||
Visible: false
|
||||
|
||||
# Devices
|
||||
- ID: 1
|
||||
Created: 2021-12-19T14:18:07Z
|
||||
Last seen: %s
|
||||
User-agent: OWA
|
||||
""", account3PhoneNumber,
|
||||
badgeBExpiration,
|
||||
badgeCExpiration,
|
||||
account3Device1LastSeen)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
public static Account buildTestAccountForDataReport(final UUID aci, final String number,
|
||||
final boolean unrestrictedUnidentifiedAccess, final boolean discoverableByPhoneNumber,
|
||||
final List<AccountBadge> badges, final List<DeviceData> devices) {
|
||||
|
||||
final ECKeyPair aciIdentityKeyPair = ECKeyPair.generate();
|
||||
final ECKeyPair pniIdentityKeyPair = ECKeyPair.generate();
|
||||
|
||||
final Account account = new Account();
|
||||
account.setUuid(aci);
|
||||
account.setNumber(number, UUID.randomUUID());
|
||||
account.setUnrestrictedUnidentifiedAccess(unrestrictedUnidentifiedAccess);
|
||||
account.setDiscoverableByPhoneNumber(discoverableByPhoneNumber);
|
||||
account.setBadges(Clock.systemUTC(), new ArrayList<>(badges));
|
||||
account.setIdentityKey(new IdentityKey(aciIdentityKeyPair.getPublicKey()));
|
||||
account.setPhoneNumberIdentityKey(new IdentityKey(pniIdentityKeyPair.getPublicKey()));
|
||||
|
||||
assert !devices.isEmpty();
|
||||
|
||||
final SaltedTokenHash passwordTokenHash = SaltedTokenHash.generateFor("password");
|
||||
|
||||
devices.forEach(deviceData -> {
|
||||
final Device device = new Device();
|
||||
device.setId(deviceData.id());
|
||||
device.setAuthTokenHash(passwordTokenHash);
|
||||
device.setFetchesMessages(true);
|
||||
device.setLastSeen(deviceData.lastSeen().toEpochMilli());
|
||||
device.setCreated(deviceData.created().toEpochMilli());
|
||||
device.setUserAgent(deviceData.userAgent());
|
||||
account.addDevice(device);
|
||||
});
|
||||
|
||||
return account;
|
||||
}
|
||||
|
||||
private static String toE164(final Phonenumber.PhoneNumber phoneNumber) {
|
||||
return PhoneNumberUtil.getInstance().format(phoneNumber, PhoneNumberUtil.PhoneNumberFormat.E164);
|
||||
}
|
||||
|
||||
public record DeviceData(byte id, Instant lastSeen, Instant created, @Nullable String userAgent) {
|
||||
}
|
||||
}
|
||||
|
||||
public static void verifyAccountDataReportText(final String actualText, final String expectedTextAfterHeader) {
|
||||
final int headerEnd = actualText.indexOf("# Account");
|
||||
assertEquals(expectedTextAfterHeader, actualText.substring(headerEnd));
|
||||
|
||||
final String actualHeader = actualText.substring(0, headerEnd);
|
||||
assertTrue(actualHeader.matches(
|
||||
"Report ID: [a-z0-9]{8}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{12}\nReport timestamp: \\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z\n\n"));
|
||||
|
||||
}
|
||||
}
|
||||
+124
@@ -0,0 +1,124 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.workers;
|
||||
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import net.sourceforge.argparse4j.inf.Namespace;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagesManager;
|
||||
import org.whispersystems.textsecuregcm.util.TestClock;
|
||||
import reactor.core.publisher.Flux;
|
||||
|
||||
class ClearExpiredFoundationDbMessagesCommandTest {
|
||||
|
||||
private MessagesManager messagesManager = mock(MessagesManager.class);
|
||||
|
||||
private static class TestClearExpiredFoundationDbMessagesCommand extends ClearExpiredFoundationDbMessagesCommand {
|
||||
|
||||
private final CommandDependencies commandDependencies;
|
||||
|
||||
private final boolean dryRun;
|
||||
|
||||
public TestClearExpiredFoundationDbMessagesCommand(final MessagesManager messagesManager,
|
||||
final boolean dryRun,
|
||||
final Clock clock) {
|
||||
|
||||
super(clock);
|
||||
|
||||
this.commandDependencies = new CommandDependencies(null, null, null, null, messagesManager, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null);
|
||||
this.dryRun = dryRun;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected CommandDependencies getCommandDependencies() {
|
||||
return commandDependencies;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Namespace getNamespace() {
|
||||
return new Namespace(Map.of(
|
||||
ClearExpiredFoundationDbMessagesCommand.BATCH_SIZE_ARGUMENT, 4,
|
||||
ClearExpiredFoundationDbMessagesCommand.DRY_RUN_ARGUMENT, dryRun,
|
||||
ClearExpiredFoundationDbMessagesCommand.MESSAGE_TTL_DAYS_ARGUMENT, 1,
|
||||
ClearExpiredFoundationDbMessagesCommand.VERSIONSTAMP_TTL_DAYS_ARGUMENT, 10
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans={true, false})
|
||||
void crawlAccounts(final boolean dryRun) {
|
||||
|
||||
final Clock clock = TestClock.pinned(Instant.now());
|
||||
final Instant messageCutoffTime = clock.instant().minus(Duration.ofDays(1));
|
||||
final Instant versionstampCutoffTime = clock.instant().minus(Duration.ofDays(10));
|
||||
|
||||
final TestClearExpiredFoundationDbMessagesCommand clearExpiredFoundationDbMessagesCommand =
|
||||
new TestClearExpiredFoundationDbMessagesCommand(messagesManager,
|
||||
dryRun,
|
||||
clock);
|
||||
|
||||
final List<Account> accounts = new ArrayList<>();
|
||||
final AciServiceIdentifier[] acis = new AciServiceIdentifier[10];
|
||||
for (int i = 0; i < 10; i++) {
|
||||
final UUID accountIdentifier = UUID.randomUUID();
|
||||
final byte primaryDeviceId = Device.PRIMARY_ID;
|
||||
final byte linkedDeviceId = 2;
|
||||
|
||||
final Device primaryDevice = mock(Device.class);
|
||||
when(primaryDevice.getId()).thenReturn(primaryDeviceId);
|
||||
|
||||
final Device linkedDevice = mock(Device.class);
|
||||
when(linkedDevice.getId()).thenReturn(linkedDeviceId);
|
||||
|
||||
final Account account = mock(Account.class);
|
||||
when(account.getIdentifier(IdentityType.ACI)).thenReturn(accountIdentifier);
|
||||
when(account.getDevices()).thenReturn(i % 2 == 0 ? List.of(primaryDevice) : List.of(primaryDevice, linkedDevice));
|
||||
|
||||
accounts.add(account);
|
||||
acis[i] = new AciServiceIdentifier(accountIdentifier);
|
||||
}
|
||||
|
||||
clearExpiredFoundationDbMessagesCommand.crawlAccounts(Flux.fromIterable(accounts));
|
||||
|
||||
final List<Byte> oneDeviceId = List.of(Device.PRIMARY_ID);
|
||||
final List<Byte> twoDeviceIds = List.of(Device.PRIMARY_ID, (byte) 2);
|
||||
if (!dryRun) {
|
||||
verify(messagesManager).deleteFoundationDbMessagesBefore(
|
||||
Map.of(acis[0], oneDeviceId, acis[1], twoDeviceIds, acis[2], oneDeviceId, acis[3], twoDeviceIds),
|
||||
messageCutoffTime);
|
||||
verify(messagesManager).deleteFoundationDbMessagesBefore(
|
||||
Map.of(acis[4], oneDeviceId, acis[5], twoDeviceIds, acis[6], oneDeviceId, acis[7], twoDeviceIds),
|
||||
messageCutoffTime);
|
||||
verify(messagesManager).deleteFoundationDbMessagesBefore(
|
||||
Map.of(acis[8], oneDeviceId, acis[9], twoDeviceIds),
|
||||
messageCutoffTime);
|
||||
} else {
|
||||
verify(messagesManager, never()).deleteFoundationDbMessagesBefore(any(), any());
|
||||
}
|
||||
|
||||
verify(messagesManager).recordFoundationDbVersionstamps();
|
||||
verify(messagesManager)
|
||||
.expireOldFoundationDbVersionstamps(versionstampCutoffTime);
|
||||
}
|
||||
}
|
||||
@@ -372,8 +372,6 @@ badges:
|
||||
svgs:
|
||||
- light: example-light.svg
|
||||
dark: example-dark.svg
|
||||
badgeIdsEnabledForAll:
|
||||
- TEST
|
||||
receiptLevels:
|
||||
'1': TEST
|
||||
|
||||
|
||||
+1
-1
Submodule spam-filter updated: 9aa14d4596...466e4cf117.
Reference in new issue
Block a user