Compare commits

..
Author SHA1 Message Date
Ravi Khadiwala 90a5ad589b Fix close code check in test 2026-07-15 11:35:57 -05:00
Ravi Khadiwala 749d9c4f92 Require donation permit headers 2026-07-15 11:35:46 -05:00
ravi-signal 3d45706a35 Add GetCapabilities rpcs 2026-07-15 11:35:20 -05:00
Ravi Khadiwala ed90c1c15c Drop unversioned profiles from grpc service 2026-07-14 16:06:31 -05:00
Ravi Khadiwala 5147fe57f2 Update stripe SDK to 33.1.0 2026-07-14 16:05:51 -05:00
Jon Chambers 1d366c98a9 Mirror demand signals and establish presence when mirroring reads to FoundationDB 2026-07-14 08:56:57 -07:00
Jon Chambers 8c19171284 Retire AcknowledgementMirroringMessageStream 2026-07-14 08:56:57 -07:00
Katherine 47a461ef1f Update description for status code 400 on KT endpoints 2026-07-14 11:55:43 -04:00
Jon Chambers a959656c96 Terminate the publisher if presence renewal fails 2026-07-14 11:10:51 -04:00
Jon Chambers ab08a3a0e4 Address some synchronization holes with presence renewal 2026-07-11 10:16:31 -04:00
Jon Chambers 688d3a2212 Log exceptions when fetching end-of-queue keys 2026-07-10 14:29:44 -07:00
Jon Chambers 25fdc95843 Update to the latest version of the spam filter 2026-07-10 14:13:30 -04:00
Ameya Lokare d3c93dd1a2 Port AccountControllerV2 to gRPC 2026-07-10 13:56:49 -04:00
Jonathan Klabunde Tomer 54ea7a288c test with smaller number of accounts 2026-07-10 13:56:18 -04:00
Jonathan Klabunde Tomer e2cb484743 async fetch messages in test 2026-07-10 13:56:18 -04:00
Jonathan Klabunde Tomer 45f176d5a8 re-enable FoundationDbMessageStoreTest#deleteExpiredMessages 2026-07-10 13:56:18 -04:00
Jon Chambers 450945a9cc Perform end-of-queue-key processing outside of a transaction retry loop 2026-07-10 13:55:37 -04:00
Ravi Khadiwala 253671c206 Improve assertion failure message in GracefulShutdownIntegrationTest 2026-07-10 13:54:33 -04:00
Jon Chambers cdd461b8f4 Simplify FoundationDbMessageStream construction 2026-07-10 10:47:03 -04:00
Jon Chambers d9a54a0d42 Don't parse messages inside of a retryable transaction block 2026-07-10 10:47:03 -04:00
Jon Chambers 3f3aa89b0f Retire batched acknowledgement system in favor of point deletions 2026-07-10 10:47:03 -04:00
Ravi Khadiwala 55fa60dd4e Setting apns push tokens should always update the timestamp 2026-07-10 10:46:41 -04:00
Ravi Khadiwala b539df8e48 Add some missing authentication specifiers 2026-07-10 10:46:28 -04:00
Ravi Khadiwala 0cd0716eb5 Register ProductConfigurationGrpcService in WhisperServerService 2026-07-10 10:46:28 -04:00
Jon Chambers 6386aada73 Add an "active requests" gauge for WebSocket requests 2026-07-10 10:46:16 -04:00
Jon Chambers 5c44398bb5 Add an "active requests" counter to the gRPC metrics interceptor 2026-07-10 10:46:16 -04:00
Jon Chambers 54736bb117 Update logback to 1.5.38 2026-07-10 10:46:07 -04:00
ravi-signal aed8e60789 Create a dedicated graceful shutdown test 2026-07-09 13:52:21 -05:00
Jon Chambers 5fa50e8ad7 Increment a counter for timeouts rather than logging the full exception 2026-07-09 09:49:32 -04:00
Jon Chambers fdaba751bd Update logback to 1.5.33 2026-07-09 09:48:48 -04:00
Ravi Khadiwala 0eebb58956 Remove unused badgeIdsEnabledForAll configuration 2026-07-09 09:48:18 -04:00
Ravi Khadiwala 6bb85d77a7 Add badge/backup entitlement RPC 2026-07-09 09:48:18 -04:00
Ravi Khadiwala 9e3844ee5a Add issue hook to integration test workflow 2026-07-07 12:30:08 -05:00
Jonathan Klabunde Tomer 7ee8e349e2 add command to periodically clear expired messages from foundationdb 2026-07-06 14:17:12 -04:00
Katherine 4d9e252697 Support group send endorsement authentication for versioned profile fetches on ProfileAnonymous gRPC service 2026-07-06 14:10:07 -04:00
Jon Chambers 222e5a033b Add an experiment to partially mirror reads from FoundationDB 2026-07-06 14:01:24 -04:00
Jon Chambers 8c6fbbfa65 Revert "Switch back to AcknowledgementMirroringMessageStream"
This reverts commit 5174550ef3.
2026-07-02 15:52:45 -04:00
85 changed files with 3393 additions and 2241 deletions

No files matched your search

+9
View File
@@ -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 }}"
+2 -2
View File
@@ -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>
@@ -85,7 +85,7 @@
<semver4j.version>3.1.0</semver4j.version>
<simple-grpc.version>0.2.0</simple-grpc.version>
<slf4j.version>2.0.17</slf4j.version>
<stripe.version>31.2.0</stripe.version>
<stripe.version>33.1.0</stripe.version>
<swagger.version>2.2.46</swagger.version>
<testcontainers.version>2.0.4</testcontainers.version>
-2
View File
@@ -365,8 +365,6 @@ badges:
svgs:
- light: example-light.svg
dark: example-dark.svg
badgeIdsEnabledForAll:
- TEST
receiptLevels:
'1': TEST
+6
View File
@@ -572,6 +572,12 @@
<artifactId>google-auth-library-oauth2-http</artifactId>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk18on</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.stripe</groupId>
<artifactId>stripe-java</artifactId>
@@ -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!
@@ -1094,7 +1108,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
requireAuthenticationInterceptor))
.toList();
final List<ServerServiceDefinition> unauthenticatedServices = Stream.of(
new AccountsAnonymousGrpcService(accountsManager, rateLimiters),
new AccountsAnonymousGrpcService(accountsManager, rateLimiters, groupSendTokenUtil),
new CallQualitySurveyGrpcService(callQualitySurveyManager, rateLimiters),
new KeysAnonymousGrpcService(accountsManager, keysManager, groupZkSecretParams, Clock.systemUTC()),
new ProfileAnonymousGrpcService(accountsManager, profilesManager, profileBadgeConverter, profileCdnPolicyGenerator, chatGenericZkSecretParams, groupZkSecretParams, rateLimiters, clock),
@@ -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);
@@ -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);
}
}
@@ -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);
}
}
}
@@ -0,0 +1,6 @@
package org.whispersystems.textsecuregcm.auth;
import org.whispersystems.textsecuregcm.util.NoStackTraceException;
public class RecoveryPasswordVerificationFailedException extends NoStackTraceException {
}
@@ -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;
}
}
@@ -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);
@@ -0,0 +1,6 @@
package org.whispersystems.textsecuregcm.auth;
import org.whispersystems.textsecuregcm.util.NoStackTraceException;
public class UnverifiedRegistrationSessionException extends NoStackTraceException {
}
@@ -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;
}
@@ -68,12 +65,27 @@ public class ConfiguredProfileBadgeConverter implements ProfileBadgeConverter, B
false);
}
@Override
public List<String> visibleBadgeIds(final List<AccountBadge> accountBadges) {
if (accountBadges.isEmpty()) {
return List.of();
}
final Instant now = clock.instant();
return accountBadges.stream()
.filter(accountBadge -> accountBadge.visible()
&& now.isBefore(accountBadge.expiration())
&& knownBadges.containsKey(accountBadge.id()))
.map(AccountBadge::id)
.toList();
}
@Override
public List<Badge> convert(
final List<Locale> acceptableLanguages,
final List<AccountBadge> accountBadges,
final boolean isSelf) {
if (accountBadges.isEmpty() && badgeIdsEnabledForAll.isEmpty()) {
if (accountBadges.isEmpty()) {
return List.of();
}
@@ -99,20 +111,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;
}
@@ -12,6 +12,12 @@ import org.whispersystems.textsecuregcm.storage.AccountBadge;
public interface ProfileBadgeConverter {
/// Determine displayable badge ids for an account's badges
///
/// @param badges The full list of badges on an account
/// @return The list of badge-ids that should appear on this account's profile to other users
List<String> visibleBadgeIds(final List<AccountBadge> badges);
/**
* Converts the {@link AccountBadge}s for an account into the objects
* that can be returned on a profile fetch.
@@ -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() {
@@ -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");
}
}
@@ -75,7 +75,7 @@ public class KeyTransparencyController {
"""
)
@ApiResponse(responseCode = "200", description = "The ACI was found and its mapped value matched the provided ACI identity key", useReturnTypeSchema = true)
@ApiResponse(responseCode = "400", description = "Invalid request. See response for any available details.")
@ApiResponse(responseCode = "400", description = "Request was authenticated but endpoint requires unauthenticated access.")
@ApiResponse(responseCode = "403", description = """
The ACI was found but its mapped value did not match the provided ACI identity key
or the ACI was not found in the log.
@@ -135,7 +135,7 @@ public class KeyTransparencyController {
"""
)
@ApiResponse(responseCode = "200", description = "All identifiers exist in the log", useReturnTypeSchema = true)
@ApiResponse(responseCode = "400", description = "Invalid request. See response for any available details.")
@ApiResponse(responseCode = "400", description = "Request was authenticated but endpoint requires unauthenticated access.")
@ApiResponse(responseCode = "403", description = "One or more of the provided commitment indexes did not match")
@ApiResponse(responseCode = "404", description = "At least one identifier was not found")
@ApiResponse(responseCode = "429", description = "Rate-limited")
@@ -205,7 +205,7 @@ public class KeyTransparencyController {
"""
)
@ApiResponse(responseCode = "200", description = "The `distinguished` search key exists in the log", useReturnTypeSchema = true)
@ApiResponse(responseCode = "400", description = "Invalid request. See response for any available details.")
@ApiResponse(responseCode = "400", description = "Request was authenticated but endpoint requires unauthenticated access.")
@ApiResponse(responseCode = "422", description = "Invalid request format")
@ApiResponse(responseCode = "429", description = "Rate-limited")
@GET
@@ -194,7 +194,7 @@ public class OneTimeDonationController {
return false;
}
})
.orElse(true);
.orElse(false);
if (!spendSuccessful) {
throw new WebApplicationException(Response.Status.UNAUTHORIZED);
}
@@ -559,7 +559,7 @@ public class ProfileController {
private static Map<String, Boolean> getAccountCapabilities(final Account account) {
return Arrays.stream(DeviceCapability.values())
.filter(DeviceCapability::includeInProfile)
.filter(DeviceCapability::includeInLegacyProfile)
.collect(Collectors.toMap(DeviceCapability::getName, account::hasCapability));
}
}
@@ -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.
@@ -234,7 +234,7 @@ public class SubscriptionController {
return false;
}
})
.orElse(true);
.orElse(false);
subscriptionManager.updateSubscriber(subscriberCredentials, creationPermitted);
return Response.ok().build();
@@ -248,6 +248,16 @@ public class SubscriptionController {
@Path("/{subscriberId}/create_payment_method")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Operation(summary = "Create a payment method", description = """
Creates a payment method setup token with the payment processor and returns a client secret that can be used to
complete the payment method setup.
""")
@ApiResponse(responseCode = "200", description = "The payment method was created", content = @Content(schema = @Schema(implementation = CreatePaymentMethodResponse.class)))
@ApiResponse(responseCode = "400", description = "The requested payment method type is not supported by this endpoint")
@ApiResponse(responseCode = "401", description = "Donation permit was invalid or already spent")
@ApiResponse(responseCode = "403", description = "subscriberId authentication failure OR account authentication is present")
@ApiResponse(responseCode = "404", description = "subscriberId is malformed OR the subscriber does not exist")
@ApiResponse(responseCode = "409", description = "The subscriber is already associated with a different payment processor")
@ManagedAsync
@RateLimitedByIp(RateLimiters.For.ADD_SUBSCRIPTION_PAYMENT_METHOD)
public CreatePaymentMethodResponse createPaymentMethod(
@@ -283,7 +293,7 @@ public class SubscriptionController {
return false;
}
})
.orElse(true);
.orElse(false);
if (!spendSuccessful) {
throw new WebApplicationException(Response.Status.UNAUTHORIZED);
@@ -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();
@@ -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")
@@ -6,31 +6,43 @@
package org.whispersystems.textsecuregcm.grpc;
import com.google.protobuf.ByteString;
import java.util.Optional;
import java.util.UUID;
import org.signal.chat.account.Capabilities;
import org.signal.chat.account.CheckAccountExistenceRequest;
import org.signal.chat.account.CheckAccountExistenceResponse;
import org.signal.chat.account.GetCapabilitiesAnonymousRequest;
import org.signal.chat.account.GetCapabilitiesAnonymousResponse;
import org.signal.chat.account.LookupUsernameHashRequest;
import org.signal.chat.account.LookupUsernameHashResponse;
import org.signal.chat.account.LookupUsernameLinkRequest;
import org.signal.chat.account.LookupUsernameLinkResponse;
import org.signal.chat.account.SimpleAccountsAnonymousGrpc;
import org.signal.chat.errors.FailedUnidentifiedAuthorization;
import org.signal.chat.errors.NotFound;
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
public class AccountsAnonymousGrpcService extends SimpleAccountsAnonymousGrpc.AccountsAnonymousImplBase {
private final AccountsManager accountsManager;
private final RateLimiters rateLimiters;
private final GroupSendTokenUtil groupSendTokenUtil;
public AccountsAnonymousGrpcService(final AccountsManager accountsManager, final RateLimiters rateLimiters) {
public AccountsAnonymousGrpcService(
final AccountsManager accountsManager,
final RateLimiters rateLimiters,
final GroupSendTokenUtil groupSendTokenUtil) {
this.accountsManager = accountsManager;
this.rateLimiters = rateLimiters;
this.groupSendTokenUtil = groupSendTokenUtil;
}
@Override
@@ -80,4 +92,40 @@ public class AccountsAnonymousGrpcService extends SimpleAccountsAnonymousGrpc.Ac
.build())
.orElseGet(() -> LookupUsernameLinkResponse.newBuilder().setNotFound(NotFound.getDefaultInstance()).build());
}
@Override
public GetCapabilitiesAnonymousResponse getCapabilities(GetCapabilitiesAnonymousRequest request) {
final ServiceIdentifier targetIdentifier =
GrpcServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getAccountIdentifier());
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 GetCapabilitiesAnonymousResponse.newBuilder()
.setFailedUnidentifiedAuthorization(FailedUnidentifiedAuthorization.getDefaultInstance())
.build();
}
return targetAccount.map(target -> {
final Capabilities.Builder builder = Capabilities.newBuilder();
for (DeviceCapability capability : DeviceCapability.PUBLIC_VISIBLE_CAPABILITIES) {
if (target.hasCapability(capability)) {
builder.addCapabilities(DeviceCapabilityUtil.toGrpcDeviceCapability(capability));
}
}
return GetCapabilitiesAnonymousResponse.newBuilder().setCapabilities(builder.build()).build();
})
.orElseGet(() -> GetCapabilitiesAnonymousResponse.newBuilder()
.setNotFound(NotFound.getDefaultInstance())
.build());
}
}
@@ -6,12 +6,23 @@
package org.whispersystems.textsecuregcm.grpc;
import com.google.protobuf.ByteString;
import io.grpc.StatusRuntimeException;
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.Optional;
import java.util.UUID;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.signal.chat.account.Capabilities;
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 +35,16 @@ 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.GetCapabilitiesRequest;
import org.signal.chat.account.GetCapabilitiesResponse;
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 +58,47 @@ 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.errors.NotFound;
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.DeviceCapability;
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 +110,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 +171,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 +360,190 @@ 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();
}
@Override
public GetCapabilitiesResponse getCapabilities(GetCapabilitiesRequest request) {
final Account account = getAuthenticatedAccount();
final Capabilities.Builder builder = Capabilities.newBuilder();
for (DeviceCapability capability : DeviceCapability.SELF_VISIBLE_CAPABILITIES) {
if (account.hasCapability(capability)) {
builder.addCapabilities(DeviceCapabilityUtil.toGrpcDeviceCapability(capability));
}
}
return GetCapabilitiesResponse.newBuilder().setCapabilities(builder.build()).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 +552,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);
@@ -6,19 +6,31 @@
package org.whispersystems.textsecuregcm.grpc;
import com.google.protobuf.ByteString;
import java.util.Arrays;
import java.util.Map;
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.auth.UnidentifiedAccessChecksum;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
import org.whispersystems.textsecuregcm.storage.KeyIdUtil;
import org.whispersystems.textsecuregcm.storage.KeysManager;
@@ -63,7 +75,16 @@ class KeysGrpcHelper {
}
final AccountPreKeyBundles.Builder preKeyBundlesBuilder = AccountPreKeyBundles.newBuilder()
.setIdentityKey(ByteString.copyFrom(targetAccount.getIdentityKey(targetServiceIdentifier.identityType()).serialize()));
.setIdentityKey(ByteString.copyFrom(targetAccount.getIdentityKey(targetServiceIdentifier.identityType()).serialize()))
.setUnrestrictedUnidentifiedAccess(targetServiceIdentifier.identityType() == IdentityType.ACI && targetAccount.isUnrestrictedUnidentifiedAccess());
// Set the UAK hash if the account has a UAK and we're targeting an ACI. PNIs don't allow unidentified access.
targetAccount
.getUnidentifiedAccessKey()
.filter(_ -> targetServiceIdentifier.identityType() == IdentityType.ACI)
.map(UnidentifiedAccessChecksum::generateFor)
.map(ByteString::copyFrom)
.ifPresent(preKeyBundlesBuilder::setUnidentifiedAccessKeyFingerprint);
preKeysByDeviceId.forEach((deviceId, devicePreKeys) -> {
final Device device = targetAccount.getDevice(deviceId).orElseThrow();
@@ -89,4 +110,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)
@@ -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();
}
}
@@ -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();
}
}
@@ -22,10 +22,8 @@ import org.signal.chat.profile.GetAvatarUploadFormRequest;
import org.signal.chat.profile.GetAvatarUploadFormResponse;
import org.signal.chat.profile.GetExpiringProfileKeyCredentialAnonymousRequest;
import org.signal.chat.profile.GetExpiringProfileKeyCredentialAnonymousResponse;
import org.signal.chat.profile.GetUnversionedProfileAnonymousRequest;
import org.signal.chat.profile.GetUnversionedProfileAnonymousResponse;
import org.signal.chat.profile.GetVersionedProfileAnonymousRequest;
import org.signal.chat.profile.GetVersionedProfileAnonymousResponse;
import org.signal.chat.profile.GetProfileAnonymousRequest;
import org.signal.chat.profile.GetProfileAnonymousResponse;
import org.signal.chat.profile.SimpleProfileAnonymousGrpc;
import org.signal.libsignal.zkgroup.GenericServerSecretParams;
import org.signal.libsignal.zkgroup.InvalidInputException;
@@ -36,7 +34,6 @@ import org.signal.libsignal.zkgroup.profiles.ServerZkProfileOperations;
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
import org.whispersystems.textsecuregcm.badges.ProfileBadgeConverter;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
@@ -101,14 +98,8 @@ public class ProfileAnonymousGrpcService extends SimpleProfileAnonymousGrpc.Prof
}
@Override
public GetUnversionedProfileAnonymousResponse getUnversionedProfile(final GetUnversionedProfileAnonymousRequest request) {
final ServiceIdentifier targetIdentifier =
GrpcServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getRequest().getServiceIdentifier());
// Callers must be authenticated to request unversioned profiles by PNI
if (targetIdentifier.identityType() == IdentityType.PNI) {
throw GrpcExceptions.invalidArguments("aci service identifier type required");
}
public GetProfileAnonymousResponse getProfile(final GetProfileAnonymousRequest request) {
final ServiceIdentifier targetIdentifier = GrpcServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getRequest().getAccountIdentifier());
final Optional<Account> targetAccount = accountsManager.getByServiceIdentifier(targetIdentifier);
@@ -121,43 +112,25 @@ public class ProfileAnonymousGrpcService extends SimpleProfileAnonymousGrpc.Prof
};
if (!authorized) {
return GetUnversionedProfileAnonymousResponse.newBuilder()
return GetProfileAnonymousResponse.newBuilder()
.setFailedUnidentifiedAuthorization(FailedUnidentifiedAuthorization.getDefaultInstance())
.build();
}
final byte[] version = request.getRequest().getVersion().toByteArray();
return targetAccount.map(account ->
GetUnversionedProfileAnonymousResponse.newBuilder()
.setResult(ProfileGrpcHelper.buildUnversionedProfileResult(targetIdentifier,
null,
account,
profileBadgeConverter))
.build())
.orElseGet(() -> GetUnversionedProfileAnonymousResponse.newBuilder()
.setNotFound(NotFound.getDefaultInstance())
.build());
}
return targetAccount.flatMap(account -> ProfileGrpcHelper
.getProfile(account, profilesManager, profileBadgeConverter, version)
@Override
public GetVersionedProfileAnonymousResponse getVersionedProfile(final GetVersionedProfileAnonymousRequest request) {
final ServiceIdentifier targetIdentifier = GrpcServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getRequest().getAccountIdentifier());
// If the etag matches, drop the result
.map(profileResult -> request.getRequest().getEtag().equals(profileResult.getEtag())
? GetProfileAnonymousResponse.newBuilder().setEtagMatched(true).build()
: GetProfileAnonymousResponse.newBuilder().setProfile(profileResult).build())
final Optional<Account> targetAccount = getTargetAccountAndValidateUnidentifiedAccess(targetIdentifier, request.getUnidentifiedAccessKey().toByteArray());
return targetAccount.flatMap(account ->
ProfileGrpcHelper.getVersionedProfile(account,
profilesManager,
request.getRequest().getVersion().toByteArray(),
request.getRequest().getDataEtag().toByteArray(),
request.getRequest().getPaymentAddressEtag().toByteArray()))
.map(result ->
GetVersionedProfileAnonymousResponse.newBuilder()
.setResult(result)
.build())
.orElseGet(() ->
GetVersionedProfileAnonymousResponse.newBuilder()
.setNotFound(NotFound.getDefaultInstance())
.build());
// If we didn't find a v2 profile, try a v1 profile
.or(() -> ProfileGrpcHelper
.getProfileV1(account, profilesManager, profileBadgeConverter, version)
.map(v1Result -> GetProfileAnonymousResponse.newBuilder().setProfileV1(v1Result).build())))
.orElseGet(() -> GetProfileAnonymousResponse.newBuilder().setNotFound(NotFound.getDefaultInstance()).build());
}
@Override
@@ -7,23 +7,21 @@ package org.whispersystems.textsecuregcm.grpc;
import com.google.common.annotations.VisibleForTesting;
import com.google.protobuf.ByteString;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;
import java.time.Clock;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HexFormat;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import org.signal.chat.common.Badge;
import org.signal.chat.common.BadgeSvg;
import org.bouncycastle.crypto.digests.TupleHash;
import org.signal.chat.common.S3UploadForm;
import org.signal.chat.profile.DataEtag;
import org.signal.chat.profile.GetExpiringProfileKeyCredentialResult;
import org.signal.chat.profile.GetUnversionedProfileResult;
import org.signal.chat.profile.GetVersionedProfileResult;
import org.signal.chat.profile.GetVersionedProfileV1Response;
import org.signal.chat.profile.ProfileResult;
import org.signal.chat.profile.ProfileResultOrBuilder;
import org.signal.chat.profile.LegacyProfileResult;
import org.signal.chat.profile.AccountInfo;
import org.signal.libsignal.protocol.ServiceId;
import org.signal.libsignal.zkgroup.InvalidInputException;
import org.signal.libsignal.zkgroup.VerificationFailedException;
@@ -33,7 +31,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.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
@@ -44,154 +42,84 @@ import org.whispersystems.textsecuregcm.util.ProfileHelper;
public class ProfileGrpcHelper {
private static final byte[] ETAG_DOMAIN = "ProfileETag/v1".getBytes(StandardCharsets.UTF_8);
private static final int ETAG_LENGTH = 10;
private static final S3UploadForm PROTOTYPE_AVATAR_UPLOAD_FORM = S3UploadForm.newBuilder()
.setAcl(PostPolicyGenerator.ACL)
.setAlgorithm(PostPolicyGenerator.ALGORITHM)
.build();
static Optional<GetVersionedProfileResult> getVersionedProfile(final Account account,
static Optional<LegacyProfileResult> getProfileV1(final Account account,
final ProfilesManager profilesManager,
final byte[] requestVersion,
final byte[] requestDataEtag,
final byte[] requestPaymentAddressEtag) {
final Optional<VersionedProfile> profile;
if (account.hasCapability(DeviceCapability.PROFILES_V2)) {
profile = profilesManager.get(account.getUuid(), requestVersion);
} else {
profile = Optional.empty();
}
final Optional<VersionedProfileV1> v1Profile;
if (profile.isEmpty()) {
v1Profile = profilesManager.getV1(account.getUuid(), HexFormat.of().formatHex(requestVersion));
} else {
v1Profile = Optional.empty();
}
if (profile.isEmpty() && v1Profile.isEmpty()) {
final ProfileBadgeConverter profileBadgeConverter,
final byte[] requestVersion) {
final Optional<VersionedProfileV1> maybeV1Profile =
profilesManager.getV1(account.getUuid(), HexFormat.of().formatHex(requestVersion));
if (maybeV1Profile.isEmpty()) {
return Optional.empty();
}
final VersionedProfileV1 v1Profile = maybeV1Profile.get();
final GetVersionedProfileResult.Builder responseBuilder = GetVersionedProfileResult.newBuilder();
final LegacyProfileResult.Builder builder = LegacyProfileResult.newBuilder()
.setAccountInfo(buildAccountInfo(profileBadgeConverter, account))
.setName(ByteString.copyFrom(v1Profile.name()))
.setAbout(ByteString.copyFrom(v1Profile.about()))
.setAboutEmoji(ByteString.copyFrom(v1Profile.aboutEmoji()))
.setPhoneNumberSharing(ByteString.copyFrom(v1Profile.phoneNumberSharing()));
profile.ifPresent(p -> {
if (requestDataEtag.length > 0 && Arrays.equals(requestDataEtag, p.dataHash())) {
responseBuilder.setDataEtagMatched(true);
} else {
responseBuilder.setDataEtag(DataEtag.newBuilder()
.setData(ByteString.copyFrom(p.data()))
.setEtagSha256(ByteString.copyFrom(p.dataHash()))
.build());
}
});
v1Profile.ifPresent(p -> {
final GetVersionedProfileV1Response.Builder v1ResponseBuilder = GetVersionedProfileV1Response.newBuilder();
v1ResponseBuilder
.setName(ByteString.copyFrom(p.name()))
.setAbout(ByteString.copyFrom(p.about()))
.setAboutEmoji(ByteString.copyFrom(p.aboutEmoji()))
.setPhoneNumberSharing(ByteString.copyFrom(p.phoneNumberSharing()));
if (p.avatar() != null) {
v1ResponseBuilder.setAvatar(p.avatar());
}
responseBuilder.setV1Response(v1ResponseBuilder);
});
// Include payment address if the version matches the latest version on Account or the latest version on Account
// is empty
if (account.getCurrentProfileVersion().map(v -> Arrays.equals(v, requestVersion)).orElse(true)) {
final Optional<byte []> paymentAddress = profile.map(VersionedProfile::paymentAddress).or(() -> v1Profile.map(VersionedProfileV1::paymentAddress));
if (paymentAddress.isPresent()) {
final boolean paymentAddressETagMatches = requestPaymentAddressEtag.length > 0 &&
profile.map(VersionedProfile::paymentAddressHash)
.map(h -> Arrays.equals(requestPaymentAddressEtag, h))
.orElse(false);
if (paymentAddressETagMatches) {
responseBuilder.setPaymentAddressEtagMatched(true);
} else {
responseBuilder.setPaymentAddressDataEtag(DataEtag.newBuilder()
.setData(ByteString.copyFrom(paymentAddress.get()))
.setEtagSha256(ByteString.copyFrom(
profile.map(VersionedProfile::paymentAddressHash).orElseGet(() -> hash(paymentAddress.get()))))
.build());
}
}
if (v1Profile.avatar() != null) {
builder.setAvatar(v1Profile.avatar());
}
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())
.filter(DeviceCapability::includeInProfile)
.filter(account::hasCapability)
.map(DeviceCapabilityUtil::toGrpcDeviceCapability)
.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()
.setIdentityKey(ByteString.copyFrom(targetAccount.getIdentityKey(targetIdentifier.identityType()).serialize()))
.addAllCapabilities(buildAccountCapabilities(targetAccount));
switch (targetIdentifier.identityType()) {
case ACI -> {
resultBuilder.setUnrestrictedUnidentifiedAccess(targetAccount.isUnrestrictedUnidentifiedAccess())
.addAllBadges(
buildBadges(profileBadgeConverter.convert(RequestAttributesUtil.getAvailableAcceptedLocales(),
targetAccount.getBadges(),
ProfileHelper.isSelfProfileRequest(requesterUuid, targetIdentifier))));
targetAccount.getUnidentifiedAccessKey()
.map(UnidentifiedAccessChecksum::generateFor)
.map(ByteString::copyFrom)
.ifPresent(resultBuilder::setUnidentifiedAccess);
}
case PNI -> resultBuilder.setUnrestrictedUnidentifiedAccess(false);
// If present, include the payment address if the version matches the latest version on Account or the latest
// version on Account is empty
if (v1Profile.paymentAddress() != null && account.getCurrentProfileVersion().map(v -> Arrays.equals(v, requestVersion)).orElse(true)) {
builder.setPaymentAddress(ByteString.copyFrom(v1Profile.paymentAddress()));
}
return resultBuilder.build();
return Optional.of(builder.build());
}
static Optional<ProfileResult> getProfile(final Account account,
final ProfilesManager profilesManager,
final ProfileBadgeConverter profileBadgeConverter,
final byte[] requestVersion) {
final Optional<VersionedProfile> maybeProfile = account.hasCapability(DeviceCapability.PROFILES_V2)
? profilesManager.get(account.getUuid(), requestVersion)
: Optional.empty();
if (maybeProfile.isEmpty()) {
return Optional.empty();
}
final VersionedProfile profile = maybeProfile.get();
final ProfileResult.Builder builder = ProfileResult.newBuilder()
.setData(ByteString.copyFrom(profile.data()))
.setAccountInfo(buildAccountInfo(profileBadgeConverter, account));
// If present, include the payment address if the version matches the latest version on Account or the latest
// version on Account is empty
if (profile.paymentAddress() != null && account.getCurrentProfileVersion().map(v -> Arrays.equals(v, requestVersion)).orElse(true)) {
builder.setPaymentAddress(ByteString.copyFrom(profile.paymentAddress()));
}
builder.setEtag(ByteString.copyFrom(etag(builder)));
return Optional.of(builder.build());
}
private static AccountInfo buildAccountInfo(final ProfileBadgeConverter profileBadgeConverter,
final Account account) {
final AccountInfo.Builder accountInfoBuilder = AccountInfo.newBuilder()
.addAllBadgeIds(profileBadgeConverter.visibleBadgeIds(account.getBadges()))
.setIdentityKey(ByteString.copyFrom(account.getIdentityKey(IdentityType.ACI).serialize()))
.setUnrestrictedUnidentifiedAccess(account.isUnrestrictedUnidentifiedAccess());
account.getUnidentifiedAccessKey()
.map(UnidentifiedAccessChecksum::generateFor)
.map(ByteString::copyFrom)
.ifPresent(accountInfoBuilder::setUnidentifiedAccessKeyFingerprint);
return accountInfoBuilder.build();
}
static Optional<GetExpiringProfileKeyCredentialResult> getExpiringProfileKeyCredentialResult(
@@ -209,12 +137,14 @@ public class ProfileGrpcHelper {
}
return versionedProfile.map(VersionedProfile::commitment)
.or(() -> profilesManager.getV1(account.getUuid(), HexFormat.of().formatHex(version)).map(VersionedProfileV1::commitment))
.or(() -> profilesManager.getV1(account.getUuid(), HexFormat.of().formatHex(version))
.map(VersionedProfileV1::commitment))
.map(commitment -> {
final ExpiringProfileKeyCredentialResponse profileKeyCredentialResponse;
try {
profileKeyCredentialResponse = ProfileHelper.getExpiringProfileKeyCredential(new ProfileKeyCredentialRequest(encodedCredentialRequest),
profileKeyCredentialResponse = ProfileHelper.getExpiringProfileKeyCredential(
new ProfileKeyCredentialRequest(encodedCredentialRequest),
new ProfileKeyCommitment(commitment), new ServiceId.Aci(account.getUuid()), zkProfileOperations);
} catch (VerificationFailedException | InvalidInputException e) {
throw GrpcExceptions.invalidArguments("invalid credential request");
@@ -240,19 +170,37 @@ public class ProfileGrpcHelper {
.build();
}
/**
* Computes the SHA-256 hash of the given data.
* <p>
* Only needed during the v1 -> v2 migration. See also: VersionedProfile#hash(byte[])
*/
/// Compute the etag of a [ProfileResult]
///
/// @implNote This uses the NIST-SP 800-185 TupleHash to provide a cryptographic hash over variable length fields.
/// Clients must be able to reproduce the same etag from the data, so hash must be stable.
@VisibleForTesting
public static byte[] hash(final byte[] data) {
final MessageDigest sha256;
try {
sha256 = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
throw new AssertionError(e);
}
return sha256.digest(data);
static byte[] etag(final ProfileResultOrBuilder profile) {
final TupleHash h = new TupleHash(256, ETAG_DOMAIN, ETAG_LENGTH * Byte.SIZE);
final AccountInfo accountInfo = profile.getAccountInfo();
addByteArray(h, profile.getData().toByteArray());
addByteArray(h, profile.getPaymentAddress().toByteArray());
addByteArray(h, accountInfo.getIdentityKey().toByteArray());
addByteArray(h, accountInfo.getUnidentifiedAccessKeyFingerprint().toByteArray());
h.update(accountInfo.getUnrestrictedUnidentifiedAccess() ? (byte) 1 : (byte) 0);
addInt(h, accountInfo.getBadgeIdsCount());
accountInfo.getBadgeIdsList().asByteStringList().stream()
.map(ByteString::toByteArray)
.sorted(Arrays::compareUnsigned)
.forEach(badgeId -> addByteArray(h, badgeId));
final byte[] out = new byte[ETAG_LENGTH];
h.doFinal(out, 0);
return out;
}
private static void addByteArray(final TupleHash hash, final byte[] bytes) {
hash.update(bytes, 0, bytes.length);
}
private static void addInt(final TupleHash hash, final int v) {
addByteArray(hash, ByteBuffer.allocate(Integer.BYTES).order(ByteOrder.BIG_ENDIAN).putInt(v).array());
}
}
@@ -22,10 +22,8 @@ import org.signal.chat.errors.FailedPrecondition;
import org.signal.chat.errors.NotFound;
import org.signal.chat.profile.GetAvatarCredentialsRequest;
import org.signal.chat.profile.GetAvatarCredentialsResponse;
import org.signal.chat.profile.GetUnversionedProfileRequest;
import org.signal.chat.profile.GetUnversionedProfileResponse;
import org.signal.chat.profile.GetVersionedProfileRequest;
import org.signal.chat.profile.GetVersionedProfileResponse;
import org.signal.chat.profile.GetProfileRequest;
import org.signal.chat.profile.GetProfileResponse;
import org.signal.chat.profile.PaymentsForbiddenInRegion;
import org.signal.chat.profile.ProfilesV2CapabilityRequired;
import org.signal.chat.profile.SetProfileRequest;
@@ -252,44 +250,27 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
}
@Override
public GetUnversionedProfileResponse getUnversionedProfile(final GetUnversionedProfileRequest request) throws RateLimitExceededException {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
final ServiceIdentifier targetIdentifier =
GrpcServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getServiceIdentifier());
final Optional<Account> maybeAccount = validateRateLimitAndGetAccount(authenticatedDevice.accountIdentifier(), targetIdentifier);
return maybeAccount.map(account -> GetUnversionedProfileResponse.newBuilder()
.setResult(ProfileGrpcHelper.buildUnversionedProfileResult(targetIdentifier,
authenticatedDevice.accountIdentifier(),
account,
profileBadgeConverter))
.build()).orElseGet(() -> GetUnversionedProfileResponse.newBuilder()
.setNotFound(NotFound.getDefaultInstance())
.build());
}
@Override
public GetVersionedProfileResponse getVersionedProfile(final GetVersionedProfileRequest request) throws RateLimitExceededException {
public GetProfileResponse getProfile(final GetProfileRequest request) throws RateLimitExceededException {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
final ServiceIdentifier targetIdentifier =
GrpcServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getAccountIdentifier());
final byte[] version = request.getVersion().toByteArray();
final Optional<Account> maybeAccount =
validateRateLimitAndGetAccount(authenticatedDevice.accountIdentifier(), targetIdentifier);
final Optional<Account> maybeAccount = validateRateLimitAndGetAccount(authenticatedDevice.accountIdentifier(), targetIdentifier);
return maybeAccount.flatMap(account -> ProfileGrpcHelper
.getProfile(account, profilesManager, profileBadgeConverter, version)
return maybeAccount.map(account ->
ProfileGrpcHelper.getVersionedProfile(account, profilesManager,
request.getVersion().toByteArray(),
request.getDataEtag().toByteArray(),
request.getPaymentAddressEtag().toByteArray())
.map(result ->
GetVersionedProfileResponse.newBuilder()
.setResult(result)
.build())
.orElseGet(() -> GetVersionedProfileResponse.newBuilder()
.setNotFound(NotFound.getDefaultInstance())
.build())).orElseGet(() -> GetVersionedProfileResponse.newBuilder()
.setNotFound(NotFound.getDefaultInstance())
.build());
// If the etag matches, drop the result
.map(profileResult -> request.getEtag().equals(profileResult.getEtag())
? GetProfileResponse.newBuilder().setEtagMatched(true).build()
: GetProfileResponse.newBuilder().setProfile(profileResult).build())
// If we didn't find a v2 profile, try a v1 profile
.or(() -> ProfileGrpcHelper
.getProfileV1(account, profilesManager, profileBadgeConverter, version)
.map(v1Result -> GetProfileResponse.newBuilder().setLegacyProfile(v1Result).build())))
.orElseGet(() -> GetProfileResponse.newBuilder().setNotFound(NotFound.getDefaultInstance()).build());
}
private Optional<Account> validateRateLimitAndGetAccount(final UUID requesterUuid,
@@ -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();
}
}
@@ -12,6 +12,7 @@ import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.ext.ExceptionMapper;
import java.util.Map;
import org.whispersystems.textsecuregcm.subscriptions.SubscriberIdCreationNotPermittedException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionChargeFailurePaymentRequiredException;
import org.whispersystems.textsecuregcm.subscriptions.SubscriptionException;
import org.whispersystems.textsecuregcm.subscriptions.ChargeFailure;
@@ -63,6 +64,7 @@ public class SubscriptionExceptionMapper implements ExceptionMapper<Subscription
case SubscriptionProcessorConflictException _ -> Response.Status.CONFLICT;
case SubscriptionPaymentRequiredException _ -> Response.Status.PAYMENT_REQUIRED;
case SubscriptionReceiptAlreadyRedeemedException _ -> Response.Status.CONFLICT;
case SubscriberIdCreationNotPermittedException _ -> Response.Status.UNAUTHORIZED;
default -> Response.Status.INTERNAL_SERVER_ERROR;
});
@@ -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;
@@ -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;
}
}
@@ -1,162 +0,0 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.storage;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Flow;
import java.util.function.BiConsumer;
import com.google.common.annotations.VisibleForTesting;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Metrics;
import org.reactivestreams.Subscription;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStream;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
import reactor.adapter.JdkFlowAdapter;
import reactor.core.publisher.BaseSubscriber;
/// A temporary message stream that can mirror message acknowledgements (deletion requests) to FoundationDB
public class AcknowledgementMirroringMessageStream implements MessageStream {
private final RedisDynamoDbMessageStream redisDynamoDbMessageStream;
private final FoundationDbMessageStream foundationDbMessageStream;
private final Set<UUID> messagesPendingAcknowledgement = new HashSet<>();
private static final int HIGH_PENDING_ACKNOWLEDGEMENT_COUNT_WARNING_THRESHOLD = 1024;
@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"));
private static final Counter MAX_PENDING_ACKNOWLEDGEMENT_LIMIT_BREACHED_COUNTER =
Metrics.counter(MetricsUtil.name(AcknowledgementMirroringMessageStream.class, "maxPendingAcknowledgementLimitBreached"));
private static class FoundationDbSubscriber extends BaseSubscriber<MessageStreamEntry.Envelope> {
private final BiConsumer<UUID, Long> mirroredMessageHandler;
private long mirroredEntriesDelivered = 0;
private long requested = 0;
private FoundationDbSubscriber(final BiConsumer<UUID, Long> mirroredMessageHandler) {
this.mirroredMessageHandler = mirroredMessageHandler;
}
public void handleRedisDynamoDbMessageStreamEntry(final MessageStreamEntry messageStreamEntry) {
final boolean isMirroredMessage = switch (messageStreamEntry) {
case MessageStreamEntry.Envelope envelopeEntry ->
UUIDUtil.fromByteString(envelopeEntry.message().getServerGuid()).version() == 8;
case MessageStreamEntry.QueueEmpty _ -> false;
};
if (!isMirroredMessage) {
return;
}
final boolean requestMore;
synchronized (this) {
requestMore = ++mirroredEntriesDelivered > requested;
if (requestMore) {
requested += FOUNDATIONDB_REQUEST_SIZE;
}
}
if (requestMore) {
request(FOUNDATIONDB_REQUEST_SIZE);
}
}
@Override
protected void hookOnSubscribe(final Subscription subscription) {
// The base `hookOnSubscribe` requests `Long.MAX_VALUE` elements, and that is something we're explicitly trying
// to avoid with this subscriber
}
@Override
protected void hookOnNext(final MessageStreamEntry.Envelope envelope) {
mirroredMessageHandler.accept(
UUIDUtil.fromByteString(envelope.message().getServerGuid()), envelope.message().getServerTimestamp());
}
}
public AcknowledgementMirroringMessageStream(final RedisDynamoDbMessageStream redisDynamoDbMessageStream,
final FoundationDbMessageStream foundationDbMessageStream) {
this.redisDynamoDbMessageStream = redisDynamoDbMessageStream;
this.foundationDbMessageStream = foundationDbMessageStream;
}
@Override
public Flow.Publisher<MessageStreamEntry> getMessages() {
final FoundationDbSubscriber subscriber = new FoundationDbSubscriber(this::handleMirroredMessageAcknowledged);
JdkFlowAdapter.flowPublisherToFlux(foundationDbMessageStream.getMessages())
.filter(messageStreamEntry -> messageStreamEntry instanceof MessageStreamEntry.Envelope)
.cast(MessageStreamEntry.Envelope.class)
.subscribe(subscriber);
return JdkFlowAdapter.publisherToFlowPublisher(
JdkFlowAdapter.flowPublisherToFlux(redisDynamoDbMessageStream.getMessages())
// Mirror demand and termination signals to the FoundationDB message stream
.doOnNext(subscriber::handleRedisDynamoDbMessageStreamEntry)
.doFinally(_ -> subscriber.dispose()));
}
@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) {
handleMirroredMessageAcknowledged(messageGuid, serverTimestamp);
}
return redisDynamoDbMessageStream.acknowledgeMessage(messageGuid, serverTimestamp);
}
private void handleMirroredMessageAcknowledged(final UUID messageGuid, final long serverTimestamp) {
// Before we can acknowledge and delete the message in FoundationDB, two things need to happen:
//
// 1. The client needs to acknowledge the message on the Redis/DDB stream.
// 2. The message needs to pass through the FoundationDB message stream pipeline because it needs to be registered
// in the acknowledged message buffer machinery before it can be deleted.
//
// We can't guarantee the order in which these two things happen, so we use a synchronized set to coordinate and
// determine when both have happened.
synchronized (messagesPendingAcknowledgement) {
if (messagesPendingAcknowledgement.remove(messageGuid)) {
// One of the two streams had already acknowledged this message, and this is the second acknowledgement. Now we
// can pass the acknowledgement along to FoundationDB.
foundationDbMessageStream.acknowledgeMessage(messageGuid, serverTimestamp);
} else {
// Either this message came from FoundationDB and got auto-acknowledged before getting explicitly acknowledged
// on the Redis/DynamoDB stream or the message got explicitly acknowledged on the Redis/DynamoDB stream before
// passing through the FoundationDB stream. Either way, wait for both streams to have done their part.
if (messagesPendingAcknowledgement.add(messageGuid)) {
if (messagesPendingAcknowledgement.size() == HIGH_PENDING_ACKNOWLEDGEMENT_COUNT_WARNING_THRESHOLD) {
HIGH_PENDING_ACKNOWLEDGEMENT_COUNT_WARNING_COUNTER.increment();
}
if (messagesPendingAcknowledgement.size() > MAX_PENDING_ACKNOWLEDGEMENTS) {
MAX_PENDING_ACKNOWLEDGEMENT_LIMIT_BREACHED_COUNTER.increment();
throw new IllegalStateException("Too many pending acknowledgements");
}
}
}
}
}
}
@@ -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);
@@ -7,38 +7,54 @@ package org.whispersystems.textsecuregcm.storage;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
public enum DeviceCapability {
STORAGE("storage", AccountCapabilityMode.ANY_DEVICE, false, false, false),
TRANSFER("transfer", AccountCapabilityMode.PRIMARY_DEVICE, false, false, false),
ATTACHMENT_BACKFILL("attachmentBackfill", AccountCapabilityMode.PRIMARY_DEVICE, false, true, false),
SPARSE_POST_QUANTUM_RATCHET("spqr", AccountCapabilityMode.ALL_DEVICES, true, true, true),
PROFILES_V2("profiles_v2", AccountCapabilityMode.ALL_DEVICES, false, true, false),
USERNAME_CHANGE_SYNC_MESSAGE("usernameChangeSyncMessage", AccountCapabilityMode.ALL_DEVICES, true, true, false);
STORAGE("storage", AccountCapabilityMode.ANY_DEVICE, AccountCapabilityVisibility.SERVER, false, false),
TRANSFER("transfer", AccountCapabilityMode.PRIMARY_DEVICE, AccountCapabilityVisibility.SERVER, false, false),
ATTACHMENT_BACKFILL("attachmentBackfill", AccountCapabilityMode.PRIMARY_DEVICE, AccountCapabilityVisibility.SELF, false, false),
SPARSE_POST_QUANTUM_RATCHET("spqr", AccountCapabilityMode.ALL_DEVICES, AccountCapabilityVisibility.PUBLIC, true, true),
PROFILES_V2("profiles_v2", AccountCapabilityMode.ALL_DEVICES, AccountCapabilityVisibility.SELF, false, false),
USERNAME_CHANGE_SYNC_MESSAGE("usernameChangeSyncMessage", AccountCapabilityMode.ALL_DEVICES, AccountCapabilityVisibility.SELF, true, false);
public static final List<DeviceCapability> PUBLIC_VISIBLE_CAPABILITIES = Arrays.stream(DeviceCapability.values())
.filter(c -> c.accountCapabilityVisibility == AccountCapabilityVisibility.PUBLIC)
.toList();
public static final List<DeviceCapability> SELF_VISIBLE_CAPABILITIES = Arrays.stream(DeviceCapability.values())
.filter(c -> c.accountCapabilityVisibility == AccountCapabilityVisibility.PUBLIC
|| c.accountCapabilityVisibility == AccountCapabilityVisibility.SELF)
.toList();
public enum AccountCapabilityMode {
/**
* The account will have the capability iff the primary device has the capability
*/
/// The account will have the capability iff the primary device has the capability
PRIMARY_DEVICE,
/**
* The account will have the capability iff any device on the account has the capability
*/
/// The account will have the capability iff any device on the account has the capability
ANY_DEVICE,
/**
* The account will have the capability iff all devices on the account have the capability
*/
/// The account will have the capability iff all devices on the account have the capability
ALL_DEVICES,
/**
* The account always has this capability, regardless of the constituent devices' capabilities.
* This supports retiring capabilities where older clients still need the field provided.
*/
/// The account always has this capability, regardless of the constituent devices' capabilities.
/// This supports retiring capabilities where older clients still need the field provided.
ALWAYS_CAPABLE,
}
public enum AccountCapabilityVisibility {
/// The capability is only visible to the server.
SERVER,
/// The capability is visible to all devices on the account.
SELF,
/// The capability is publicly visible.
PUBLIC
}
public static final Set<DeviceCapability> CAPABILITIES_REQUIRED_FOR_NEW_DEVICES =
EnumSet.copyOf(Arrays.stream(DeviceCapability.values())
.filter(DeviceCapability::requireForNewDevices)
@@ -46,34 +62,32 @@ public enum DeviceCapability {
private final String name;
private final AccountCapabilityMode accountCapabilityMode;
private final AccountCapabilityVisibility accountCapabilityVisibility;
private final boolean preventDowngrade;
private final boolean includeInProfile;
private final boolean requireForNewDevices;
/**
* Create a DeviceCapability
*
* @param name The name of the device capability that clients will see
* @param accountCapabilityMode How to combine the constituent device's capabilities in the account to an overall
* account capability
* @param preventDowngrade If true, don't let linked devices join that don't have a device capability if the
* overall account has the capability. Most of the time this should only be used in
* conjunction with AccountCapabilityMode.ALL_DEVICES.
* @param includeInProfile Whether to return this capability on the account's profile. If false, the capability
* is only visible to the server.
* @param requireForNewDevices If true, prevent device creation if the new device does not have this capability
*/
/// Create a DeviceCapability
///
/// @param name The name of the device capability that clients will see
/// @param accountCapabilityMode How to combine the constituent device's capabilities in the account to an
/// overall account capability
/// @param accountCapabilityVisibility Who should be able to view this capability
/// @param preventDowngrade If true, don't let linked devices join that don't have a device capability if
/// the overall account has the capability. Most of the time this should only be
/// used in conjunction with AccountCapabilityMode.ALL_DEVICES.
/// @param requireForNewDevices If true, prevent device creation if the new device does not have this
/// capability
DeviceCapability(final String name,
final AccountCapabilityMode accountCapabilityMode,
final AccountCapabilityVisibility accountCapabilityVisibility,
final boolean preventDowngrade,
final boolean includeInProfile,
final boolean requireForNewDevices) {
this.name = name;
this.accountCapabilityMode = accountCapabilityMode;
this.preventDowngrade = preventDowngrade;
this.includeInProfile = includeInProfile;
this.requireForNewDevices = requireForNewDevices;
this.accountCapabilityVisibility = accountCapabilityVisibility;
}
public String getName() {
@@ -84,12 +98,17 @@ public enum DeviceCapability {
return accountCapabilityMode;
}
public AccountCapabilityVisibility getAccountCapabilityVisibility() {
return accountCapabilityVisibility;
}
public boolean preventDowngrade() {
return preventDowngrade;
}
public boolean includeInProfile() {
return includeInProfile;
public boolean includeInLegacyProfile() {
// Profiles v1 does not distinguish between self/public capabilities
return accountCapabilityVisibility != AccountCapabilityVisibility.SERVER;
}
public boolean requireForNewDevices() {
@@ -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);
}
}
@@ -0,0 +1,109 @@
/*
* 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.reactivestreams.Subscription;
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 org.whispersystems.textsecuregcm.util.UUIDUtil;
import reactor.adapter.JdkFlowAdapter;
import reactor.core.publisher.BaseSubscriber;
/// 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);
private static class FoundationDbSubscriber extends BaseSubscriber<MessageStreamEntry> {
public void handleRedisDynamoDbMessageStreamEntry(final MessageStreamEntry messageStreamEntry) {
final boolean isMirroredMessage = switch (messageStreamEntry) {
case MessageStreamEntry.Envelope envelopeEntry ->
UUIDUtil.fromByteString(envelopeEntry.message().getServerGuid()).version() == 8;
case MessageStreamEntry.QueueEmpty _ -> true;
};
if (isMirroredMessage) {
request(1);
}
}
@Override
protected void hookOnSubscribe(final Subscription subscription) {
// The base `hookOnSubscribe` requests `Long.MAX_VALUE` elements, and that is something we're explicitly trying
// to avoid with this subscriber
}
}
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() {
final FoundationDbSubscriber subscriber = new FoundationDbSubscriber();
if (experimentEnrollmentManager.isEnrolled(accountIdentifier.uuid(), MessagesManager.MIRROR_READS_EXPERIMENT_NAME)) {
JdkFlowAdapter.flowPublisherToFlux(foundationDbMessageStream.getMessages())
.subscribe(subscriber);
return JdkFlowAdapter.publisherToFlowPublisher(
JdkFlowAdapter.flowPublisherToFlux(redisDynamoDbMessageStream.getMessages())
.doOnNext(subscriber::handleRedisDynamoDbMessageStreamEntry)
.doFinally(_ -> {
try {
subscriber.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);
}
}
@@ -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);
}
}
@@ -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,13 +20,10 @@ 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;
@@ -61,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;
@@ -79,14 +72,20 @@ class FoundationDbMessagePublisher {
/// Future that completes when the watch for {@link #messagesAvailableWatchKey} triggers.
private CompletableFuture<Void> watchFuture;
/// A future for refreshing the connected client's presence value at regular intervals.
@Nullable private ScheduledFuture<?> renewPresenceFuture;
/// An executor service for refreshing the connected client's presence value at regular intervals.
@Nullable final ScheduledExecutorService presenceRenewalExecutorService;
/// A future that represents the next pending presence renewal.
@Nullable private CompletableFuture<?> renewPresenceFuture;
private final AtomicLong totalRequested = new AtomicLong(0);
private final AtomicLong totalEmitted = new AtomicLong(0);
private static final AtomicInteger NEXT_STREAM_ID = new AtomicInteger();
private static final long RENEWAL_INTERVAL_MILLIS =
FoundationDbMessageStore.PRESENCE_STALE_THRESHOLD.multipliedBy(4).dividedBy(5).toMillis();
private static final Logger LOGGER = LoggerFactory.getLogger(FoundationDbMessagePublisher.class);
enum State {
@@ -132,8 +131,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;
@@ -141,31 +139,25 @@ class FoundationDbMessagePublisher {
this.endKeyExclusive = endKeyExclusive;
this.maxMessagesPerScan = maxMessagesPerScan;
this.presenceKey = presenceKey;
this.presenceRenewalExecutorService = presenceRenewalExecutorService;
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 = 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);
}
})
final Mono<Void> establishPresence = terminateOnQueueEmpty
? Mono.empty()
// 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.
: Mono.fromFuture(this::renewPresence).then(Mono.fromRunnable(this::schedulePresenceRenewal));
this.messagePublisher = establishPresence
.thenMany(Flux.create(emitter -> {
this.emitter = emitter;
emitter.onRequest(n -> {
@@ -187,8 +179,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,
@@ -198,8 +189,7 @@ class FoundationDbMessagePublisher {
null,
null,
null,
null,
beforePageFetch);
null);
}
/// Creates a [FoundationDbMessagePublisher] that publishes a non-terminating stream of messages from a device queue.
@@ -213,8 +203,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,
@@ -224,8 +213,7 @@ class FoundationDbMessagePublisher {
presenceKey,
presenceRenewalExecutorService,
messagesAvailableWatchKey,
null,
beforePageFetch);
null);
}
private synchronized void setState(final State newState, final Event event) {
@@ -314,70 +302,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);
});
}
@@ -426,61 +387,81 @@ class FoundationDbMessagePublisher {
}
}
private synchronized void startPresenceRenewal(final ScheduledExecutorService presenceRenewalExecutorService) {
final long renewalIntervalMillis =
FoundationDbMessageStore.PRESENCE_STALE_THRESHOLD.multipliedBy(4).dividedBy(5).toMillis();
renewPresenceFuture = presenceRenewalExecutorService.scheduleWithFixedDelay(this::renewPresence,
renewalIntervalMillis,
renewalIntervalMillis,
TimeUnit.MILLISECONDS);
}
private synchronized void renewPresence() {
private synchronized void schedulePresenceRenewal() {
if (state == State.TERMINATED || state == State.ERROR) {
return;
}
database.runAsync(transaction -> {
setPresence(transaction);
return CompletableFuture.completedFuture(null);
})
.whenComplete((_, throwable) -> {
assert presenceRenewalExecutorService != null;
renewPresenceFuture = new CompletableFuture<>();
final ScheduledFuture<?> scheduledFuture = presenceRenewalExecutorService.schedule(() -> {
renewPresence().whenComplete((_, throwable) -> {
if (throwable != null) {
LOGGER.warn("Failed to renew presence", throwable);
renewPresenceFuture.completeExceptionally(throwable);
} else {
renewPresenceFuture.complete(null);
}
});
}, RENEWAL_INTERVAL_MILLIS, TimeUnit.MILLISECONDS);
renewPresenceFuture.whenComplete((_, throwable) -> {
if (throwable != null) {
LOGGER.warn("Failed to renew presence; will terminate publisher", throwable);
// We can wind up here in one of two ways:
//
// 1. We're shutting down the publisher, in which case `throwable` is a `CancellationException`. We don't NEED
// to terminate the publisher in this case (since it's already terminated), but it's harmless to issue a
// second termination request, which will just be a no-op.
// 2. Something unexpected has gone wrong. We DO need to terminate the publisher in this case, because a failure
// to renew presence means that we won't get notified of new messages and so the publisher is in a bad state.
//
// In both cases, we should stop trying to schedule presence renewal.
scheduledFuture.cancel(false);
terminateWithError(throwable);
} else {
// We renewed presence successfully and the publisher is still active; renew presence again at some point in the
// future.
schedulePresenceRenewal();
}
});
}
private void setPresence(final Transaction transaction) {
transaction.set(presenceKey, FoundationDbMessageStore.getPresenceValue(clock.instant(), streamId));
private synchronized CompletableFuture<Void> renewPresence() {
if (state == State.TERMINATED || state == State.ERROR) {
return CompletableFuture.failedFuture(new IllegalStateException("Publisher already terminated"));
}
return database.runAsync(transaction -> {
transaction.set(presenceKey, FoundationDbMessageStore.getPresenceValue(clock.instant(), streamId));
return CompletableFuture.completedFuture(null);
});
}
@VisibleForTesting
synchronized void clearPresence() {
if (renewPresenceFuture != null) {
renewPresenceFuture.cancel(true);
}
if (!terminateOnQueueEmpty) {
database.runAsync(transaction -> transaction.get(presenceKey).thenAccept(presenceValue -> {
if (presenceValue == null) {
return;
}
renewPresenceFuture.whenComplete((_, _) ->
database.runAsync(transaction -> transaction.get(presenceKey).thenAccept(presenceValue -> {
if (presenceValue == null) {
return;
}
final byte[] presenceServerId = FoundationDbMessageStore.getPresenceServerId(presenceValue);
final int presenceStreamId = FoundationDbMessageStore.getPresenceStreamId(presenceValue);
final byte[] presenceServerId = FoundationDbMessageStore.getPresenceServerId(presenceValue);
final int presenceStreamId = FoundationDbMessageStore.getPresenceStreamId(presenceValue);
if (Arrays.equals(presenceServerId, FoundationDbMessageStore.getServerId()) && streamId == presenceStreamId) {
transaction.clear(presenceKey);
}
}))
.whenComplete((_, throwable) -> {
if (throwable != null) {
LOGGER.warn("Failed to clear presence on disposal", throwable);
}
});
if (Arrays.equals(presenceServerId, FoundationDbMessageStore.getServerId()) && streamId == presenceStreamId) {
transaction.clear(presenceKey);
}
}))
.whenComplete((_, throwable) -> {
if (throwable != null) {
LOGGER.warn("Failed to clear presence on disposal", throwable);
}
}));
}
}
@@ -488,9 +469,8 @@ class FoundationDbMessagePublisher {
synchronized void terminateWithError(final Throwable throwable) {
if (state != State.TERMINATED && state != State.ERROR) {
setState(State.ERROR, Event.INTERNAL_TRIGGER);
emitter.error(throwable);
}
emitter.error(throwable);
}
private synchronized void onDispose() {
@@ -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<>();
@@ -5,33 +5,25 @@ 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 +34,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 +50,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 +60,27 @@ 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);
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 +88,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
@@ -121,25 +102,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 +145,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 +180,7 @@ public class FoundationDbMessageStream implements MessageStream {
maxMessagesPerScan,
presenceKey,
presenceRenewalExecutorService,
messagesAvailableWatchKey,
() -> clearAcknowledgedMessages(database)).getMessages();
messagesAvailableWatchKey).getMessages();
})
.toArray(Flux[]::new);
@@ -236,74 +206,26 @@ 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())
.<Optional<KeySelector>>thenApply(items -> {
if (items.isEmpty()) {
return Optional.empty();
}
assert items.size() == 1;
return Optional.of(KeySelector.firstGreaterThan(items.getFirst().getKey()));
})
.whenComplete((_, throwable) -> {
if (throwable != null) {
logger.warn("Failed to fetch end-of-queue key", throwable);
}
});
}
@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);
}
}
@@ -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,22 @@ 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) {}
// Gets the capabilities for the authenticated account.
rpc GetCapabilities(GetCapabilitiesRequest) returns (GetCapabilitiesResponse) {}
}
// 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) {}
@@ -74,6 +91,10 @@ service AccountsAnonymous {
// Finds the encrypted username identified by a given username link handle.
rpc LookupUsernameLink(LookupUsernameLinkRequest) returns (LookupUsernameLinkResponse) {}
// Gets the publicly-visible capabilities enabled on the account identified by
// the provided ACI.
rpc GetCapabilities(GetCapabilitiesAnonymousRequest) returns (GetCapabilitiesAnonymousResponse) {}
}
message GetAccountIdentityRequest {
@@ -84,6 +105,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 +330,149 @@ 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;
}
message GetCapabilitiesRequest {
}
message Capabilities {
// A list of capabilities enabled on the account.
repeated common.DeviceCapability capabilities = 1;
}
message GetCapabilitiesResponse {
// A list of capabilities enabled on the account.
Capabilities capabilities = 1;
}
message GetCapabilitiesAnonymousRequest {
// The ACI of the account for which to get capabilities.
common.ServiceIdentifier account_identifier = 1 [(require.present) = true, (require.identityType) = IDENTITY_TYPE_ACI];
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 GetCapabilitiesAnonymousResponse {
oneof response {
// A list of capabilities enabled on the account.
Capabilities capabilities = 1;
errors.NotFound not_found = 2 [(tag.reason) = "not_found"];
errors.FailedUnidentifiedAuthorization failed_unidentified_authorization = 3 [(tag.reason) = "failed_unidentified_authorization"];
}
}
@@ -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
@@ -144,6 +146,15 @@ message AccountPreKeyBundles {
// A map of device IDs to pre-key "bundles" for the targeted account.
map<uint32, DevicePreKeyBundle> device_pre_keys = 2;
// Whether the account has enabled sealed sender from anyone. Always false
// if the request was for a PNI, which does not allow any unidentified access.
bool unrestricted_unidentified_access = 3;
// If the target supports unidentified access and has an unidentified access
// key, a fingerprint of the target's UAK. This may be used to detect a change
// in the UAK that the sender has for the target before actually sending a message. Otherwise, empty.
bytes unidentified_access_key_fingerprint = 4;
}
message GetPreKeysResponse {
@@ -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,16 +18,14 @@ 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) {}
// Retrieves versioned profile data. Callers with an unidentified access key for the account
// Retrieves profile data. Callers with an unidentified access key for the account
// should use the version of this method in `ProfileAnonymous` instead.
rpc GetVersionedProfile(GetVersionedProfileRequest) returns (GetVersionedProfileResponse) {}
// Retrieves unversioned profile data. Callers with an unidentified access key for the account
// should use the version of this method in `ProfileAnonymous` instead.
rpc GetUnversionedProfile(GetUnversionedProfileRequest) returns (GetUnversionedProfileResponse) {}
rpc GetProfile(GetProfileRequest) returns (GetProfileResponse) {}
// Returns anonymous credentials that may be presented with avatar operations in ProfilesAnonymous
//
@@ -42,10 +40,11 @@ service Profile {
// without an unidentified access key should use the equivalent, authenticated
// methods in `Profile` instead.
service ProfileAnonymous {
// Retrieves versioned profile data.
rpc GetVersionedProfile(GetVersionedProfileAnonymousRequest) returns (GetVersionedProfileAnonymousResponse) {}
// Retrieves unversioned profile data.
rpc GetUnversionedProfile(GetUnversionedProfileAnonymousRequest) returns (GetUnversionedProfileAnonymousResponse) {}
option (require.auth) = AUTH_ONLY_ANONYMOUS;
// Retrieves profile data.
rpc GetProfile(GetProfileAnonymousRequest) returns (GetProfileAnonymousResponse) {}
// Retrieves a profile key credential.
rpc GetExpiringProfileKeyCredential(GetExpiringProfileKeyCredentialAnonymousRequest) returns (GetExpiringProfileKeyCredentialAnonymousResponse) {}
@@ -173,84 +172,86 @@ message SetProfileResponse {
}
}
message GetVersionedProfileRequest {
message GetProfileRequest {
// The ACI of the account for which to get profile data.
common.ServiceIdentifier accountIdentifier = 1 [(require.present) = true, (require.identityType) = IDENTITY_TYPE_ACI];
common.ServiceIdentifier account_identifier = 1 [(require.present) = true, (require.identityType) = IDENTITY_TYPE_ACI];
// The profile version to retrieve.
bytes version = 2 [(require.exactlySize) = 32];
// The `data_etag` from the previous request for this Profile version. If
// unchanged, the response will omit `data` and `data_etag_matched` will be
// The `etag` from the previous request for this Profile version. If
// unchanged, the response will omit `profile` and `etag_matched` will be
// `true`.
bytes data_etag = 3 [(require.exactlySize) = 0, (require.exactlySize) = 32];
// The `payment_address_etag` from the previous request for this account’s
// profile. If unchanged, the response will omit `payment_address` and
// `payment_address_etag_matched` will be `true`.
bytes payment_address_etag = 4 [(require.exactlySize) = 0, (require.exactlySize) = 32];
bytes etag = 3 [(require.exactlySize) = 0, (require.exactlySize) = 10];
}
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];
message GetProfileAnonymousRequest {
// Contains the data necessary to request a profile.
GetProfileRequest request = 1 [(require.present) = true];
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 {
message AccountInfo {
// The account identity key of the targeted account.
bytes identity_key = 1;
// A checksum of the unidentified access key for the targeted account.
bytes unidentified_access_key_fingerprint = 2;
// Whether the account has enabled sealed sender from anyone.
bool unrestricted_unidentified_access = 3;
// A list of the badges ids associated with the account. Metadata to display
// badges may be obtained by cross-referencing badge ids with
// ProductConfiguration.GetConfiguration.
repeated string badge_ids = 4;
}
message ProfileResult {
// The ciphertext of the requested version of the profile
bytes data = 1;
// An entity tag for `data`. This may be used in subsequent requests for
// this profile version to optimize bandwidth.
// The ciphertext of the MobileCoin wallet ID on the profile.
bytes payment_address = 2;
// Information about the targeted account
AccountInfo account_info = 3;
// An entity tag for the profile. This may be used in subsequent requests
// for this profile version to optimize bandwidth.
//
// Clients may validate that the value has been correctly calculated by deriving
// the SHA-256 digest of `data`.
bytes etag_sha256 = 2;
// Note that this hash will not match the expected_data_hash used on
// SetProfile for concurrency control.
//
// Clients may validate that the value has been correctly calculated by
// calculating a 10-byte truncated TupleHash256 as follows:
//
// ```
// TupleHash256(S = "ProfileETag/v1", L = 80 bits, tuple = [
// data,
// payment_address,
// account_info.identity_key,
// account_info.unidentified_access_key_fingerprint,
// account_info.unrestricted_unidentified_access ? 0x01 : 0x00,
// uint32BE(count(account_info.badge_ids)),
// utf8(id) for each id in sortLexAscendingByUtf8Bytes(account_info.badge_ids),
// ])
//```
//
// Absent/empty fields contribute an empty element (not zero bytes omitted):
// a missing payment_address is still a present, zero-length tuple element.
//
// This etag will always exclusively cover the documented fields. If fields
// are added in the future, a new etag field must be introduced.
bytes etag = 4;
}
message GetVersionedProfileResult {
oneof data_result {
// The ciphertext of a serialized Profile.
// Absent if a v2 Profile is not available
// for this version, in which the client should use `v1_response`.
DataEtag data_etag = 1;
// Indicates that the request’s ETag matched the stored `data`
bool data_etag_matched = 2;
// Will be present if there is no v2 Profile data for this version.
//
// Because this is a temporary field during the migration, it has the highest
// field number without serialization overhead. This is purely aesthetic.
GetVersionedProfileV1Response v1_response = 15;
}
oneof payment_address_result {
// The ciphertext of the MobileCoin wallet ID on the profile.
DataEtag payment_address_data_etag = 3;
// Indicates that the request’s ETag matched the stored `payment_address`
bool payment_address_etag_matched = 4;
}
// next: 5
}
message GetVersionedProfileResponse {
oneof response {
GetVersionedProfileResult result = 1;
errors.NotFound not_found = 2 [(tag.reason) = "not_found"];
}
}
message GetVersionedProfileAnonymousResponse {
oneof response {
GetVersionedProfileResult result = 1;
errors.NotFound not_found = 2 [(tag.reason) = "not_found"];
errors.FailedUnidentifiedAuthorization failed_unidentified_authorization = 3 [(tag.reason) = "failed_unidentified_authorization"];
}
}
message GetVersionedProfileV1Response {
message LegacyProfileResult {
// The ciphertext of the name on the profile.
bytes name = 1;
@@ -260,58 +261,54 @@ message GetVersionedProfileV1Response {
bytes about_emoji = 3;
// The cdn0 path of the avatar on the profile.
string avatar = 4;
// The ciphertext of the phone-number sharing setting on the profile.
bytes phone_number_sharing = 5;
// The ciphertext of the MobileCoin wallet ID on the profile.
bytes payment_address = 6;
// Information about the targeted account
AccountInfo account_info = 7;
}
message GetUnversionedProfileRequest {
// The service identifier of the account for which to get profile data.
common.ServiceIdentifier service_identifier = 1 [(require.present) = true];
}
message GetUnversionedProfileAnonymousRequest {
// Note: Only ACI service identifiers are permitted for anonymous requests.
GetUnversionedProfileRequest request = 1 [(require.present) = true];
oneof authentication {
// The unidentified access key for the targeted account.
bytes unidentified_access_key = 2;
// A group send endorsement token for the targeted account.
bytes group_send_token = 3;
}
}
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.
bytes unidentified_access = 2;
// Whether the account has enabled sealed sender from anyone.
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.
repeated common.Badge badges = 5;
}
message GetUnversionedProfileResponse {
message GetProfileResponse {
oneof response {
GetUnversionedProfileResult result = 1;
errors.NotFound not_found = 2 [(tag.reason) = "not_found"];
// The full profile data. The current profile did not match the provided
// etag (or no etag was provided).
ProfileResult profile = 1;
// The current profile matched the provided etag. If present, this will always be true.
bool etag_matched = 2 [(tag.reason) = "etag_match"];
errors.NotFound not_found = 3 [(tag.reason) = "not_found"];
// Will be present if there is no v2 Profile data for this version.
//
// Because this is a temporary field during the migration, it has the highest
// field number without serialization overhead. This is purely aesthetic.
LegacyProfileResult legacy_profile = 15 [(tag.reason) = "legacy_profile"];
}
// next: 4
}
message GetUnversionedProfileAnonymousResponse {
message GetProfileAnonymousResponse {
oneof response {
GetUnversionedProfileResult result = 1;
// The target profile was not found
errors.NotFound not_found = 2 [(tag.reason) = "not_found"];
// The unidentified access key or group send endorsement were not valid for
// the request.
errors.FailedUnidentifiedAuthorization failed_unidentified_authorization = 3 [(tag.reason) = "failed_unidentified_authorization"];
// The full profile data. The current profile did not match the provided
// etag (or no etag was provided).
ProfileResult profile = 1;
// The current profile matched the provided etag. If present, this will always be true.
bool etag_matched = 2 [(tag.reason) = "etag_match"];
errors.NotFound not_found = 3 [(tag.reason) = "not_found"];
errors.FailedUnidentifiedAuthorization failed_unidentified_authorization = 4 [(tag.reason) = "failed_unidentified_authorization"];
// Will be present if there is no v2 Profile data for this version.
//
// Because this is a temporary field during the migration, it has the highest
// field number without serialization overhead. This is purely aesthetic.
LegacyProfileResult profile_v1 = 15 [(tag.reason) = "profile_v1"];
}
// next: 5
}
message GetExpiringProfileKeyCredentialRequest {
@@ -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_CLOSE && 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())))
@@ -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));
}
@@ -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 {
@@ -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) {
@@ -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);
}
}
}
@@ -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"));
}
@@ -203,6 +203,21 @@ class OneTimeDonationControllerTest extends AbstractV1SubscriptionControllerTest
}
}
@Test
void createBoostPaymentIntentMissingDonationPermit() {
when(STRIPE_MANAGER.getSupportedCurrenciesForPaymentMethod(PaymentMethod.CARD))
.thenReturn(Set.of("usd", "jpy", "bif", "eur"));
try (Response response = RESOURCE_EXTENSION.target("/v1/subscription/boost/create")
.request()
.post(Entity.json("""
{"currency": "USD", "amount": 300}
"""
))) {
assertThat(response.getStatus()).isEqualTo(401);
}
}
@Test
void testCreateBoostPayPal() throws IOException {
final BraintreeManager.PayPalOneTimePaymentApprovalDetails payPalOneTimePaymentApprovalDetails = mock(
@@ -45,6 +45,7 @@ import java.util.Collection;
import java.util.Collections;
import java.util.HexFormat;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
@@ -80,6 +81,7 @@ import org.signal.libsignal.zkgroup.profiles.ProfileKeyCredentialRequestContext;
import org.signal.libsignal.zkgroup.profiles.ServerZkProfileOperations;
import org.whispersystems.textsecuregcm.auth.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
import org.whispersystems.textsecuregcm.badges.ProfileBadgeConverter;
import org.whispersystems.textsecuregcm.configuration.BadgeConfiguration;
import org.whispersystems.textsecuregcm.configuration.BadgesConfiguration;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
@@ -160,15 +162,29 @@ class ProfileControllerTest {
accountsManager,
profilesManager,
dynamicConfigurationManager,
(acceptableLanguages, accountBadges, isSelf) -> List.of(new Badge("TEST", "other", "Test Badge",
"This badge is in unit tests.", List.of("l", "m", "h", "x", "xx", "xxx"), "SVG", List.of(new BadgeSvg("sl", "sd"), new BadgeSvg("ml", "md"), new BadgeSvg("ll", "ld")))
),
new ProfileBadgeConverter() {
@Override
public List<String> visibleBadgeIds(final List<AccountBadge> badges) {
return List.of("TEST");
}
@Override
public List<Badge> convert(final List<Locale> acceptableLanguages, final List<AccountBadge> accountBadges,
final boolean isSelf) {
return List.of(new Badge("TEST", "other", "Test Badge",
"This badge is in unit tests.",
List.of("l", "m", "h", "x", "xx", "xxx"),
"SVG", List.of(new BadgeSvg("sl", "sd"),
new BadgeSvg("ml", "md"),
new BadgeSvg("ll", "ld"))));
}
},
new BadgesConfiguration(List.of(
new BadgeConfiguration("TEST", "other", 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("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,
@@ -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)
);
}
@@ -340,6 +340,7 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest {
try (Response managerCreateNullResponse = RESOURCE_EXTENSION.target(
String.format("/v1/subscription/%s", subscriberId))
.request()
.header(HeaderUtils.DONATION_PERMIT, getDonationPermitHeader())
.put(Entity.json(""))) {
assertThat(managerCreateNullResponse.getStatus()).isEqualTo(403);
}
@@ -434,6 +435,49 @@ class SubscriptionControllerTest extends AbstractV1SubscriptionControllerTest {
}
}
@Test
void updateSubscriberMissingDonationPermit() {
final byte[] subscriberUserAndKey = new byte[32];
Arrays.fill(subscriberUserAndKey, (byte) 1);
final String subscriberId = Base64.getEncoder().encodeToString(subscriberUserAndKey);
// Creating a subscriber requires a permit
when(SUBSCRIPTIONS.get(any(), any())).thenReturn(Subscriptions.GetResult.NOT_STORED);
try (Response response = RESOURCE_EXTENSION.target(String.format("/v1/subscription/%s", subscriberId))
.request()
.put(Entity.json(""))) {
assertThat(response.getStatus()).isEqualTo(401);
}
// Updating a subscriber does not require a permit
when(SUBSCRIPTIONS.get(any(), any())).thenReturn(Subscriptions.GetResult.found(
Subscriptions.Record.from(Arrays.copyOfRange(subscriberUserAndKey, 0, 16), Map.of(
Subscriptions.KEY_PASSWORD, b(new byte[16]),
Subscriptions.KEY_CREATED_AT, n(Instant.now().getEpochSecond()),
Subscriptions.KEY_ACCESSED_AT, n(Instant.now().getEpochSecond())
))));
try (Response response = RESOURCE_EXTENSION.target(String.format("/v1/subscription/%s", subscriberId))
.request()
.put(Entity.json(""))) {
assertThat(response.getStatus()).isEqualTo(200);
}
}
@Test
void createPaymentMethodMissingDonationPermit() {
final byte[] subscriberUserAndKey = new byte[32];
Arrays.fill(subscriberUserAndKey, (byte) 1);
final String subscriberId = Base64.getEncoder().encodeToString(subscriberUserAndKey);
try (Response response = RESOURCE_EXTENSION
.target(String.format("/v1/subscription/%s/create_payment_method", subscriberId))
.request()
.post(Entity.json(""))) {
assertThat(response.getStatus()).isEqualTo(401);
}
}
@Test
void setSubscriptionLevelMissingProcessorCustomer() {
// set up record
@@ -10,6 +10,7 @@ import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -26,16 +27,22 @@ 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.junit.jupiter.params.provider.ValueSource;
import org.mockito.Mock;
import org.signal.chat.account.AccountsAnonymousGrpc;
import org.signal.chat.account.Capabilities;
import org.signal.chat.account.CheckAccountExistenceRequest;
import org.signal.chat.account.GetCapabilitiesAnonymousRequest;
import org.signal.chat.account.GetCapabilitiesAnonymousResponse;
import org.signal.chat.account.LookupUsernameHashRequest;
import org.signal.chat.account.LookupUsernameHashResponse;
import org.signal.chat.account.LookupUsernameLinkRequest;
import org.signal.chat.account.LookupUsernameLinkResponse;
import org.signal.chat.common.IdentityType;
import org.signal.chat.errors.NotFound;
import org.signal.chat.common.ServiceIdentifier;
import org.signal.chat.errors.FailedUnidentifiedAuthorization;
import org.signal.chat.errors.NotFound;
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
import org.whispersystems.textsecuregcm.controllers.AccountController;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
@@ -43,6 +50,7 @@ import org.whispersystems.textsecuregcm.limits.RateLimiter;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
import reactor.core.publisher.Mono;
@@ -59,6 +67,9 @@ class AccountsAnonymousGrpcServiceTest extends
@Mock
private RateLimiter rateLimiter;
@Mock
private GroupSendTokenUtil groupSendTokenUtil;
@Override
protected AccountsAnonymousGrpcService createServiceBeforeEachTest() {
when(accountsManager.getByServiceIdentifier(any()))
@@ -79,7 +90,7 @@ class AccountsAnonymousGrpcServiceTest extends
getMockRequestAttributesInterceptor().setRequestAttributes(
new RequestAttributes(InetAddresses.forString("127.0.0.1"), null, null));
return new AccountsAnonymousGrpcService(accountsManager, rateLimiters);
return new AccountsAnonymousGrpcService(accountsManager, rateLimiters, groupSendTokenUtil);
}
@Test
@@ -268,4 +279,111 @@ class AccountsAnonymousGrpcServiceTest extends
.build()),
accountsManager);
}
@ParameterizedTest
@ValueSource(booleans = {true, false})
void getCapabilities(final boolean useGroupSendToken) {
final AciServiceIdentifier serviceIdentifier = new AciServiceIdentifier(UUID.randomUUID());
final Account account = mock(Account.class);
when(accountsManager.getByServiceIdentifier(serviceIdentifier)).thenReturn(Optional.of(account));
// should be returned since it's public
when(account.hasCapability(DeviceCapability.SPARSE_POST_QUANTUM_RATCHET)).thenReturn(true);
// should not be returned since it's self-only
when(account.hasCapability(DeviceCapability.USERNAME_CHANGE_SYNC_MESSAGE)).thenReturn(true);
final GetCapabilitiesAnonymousRequest.Builder builder = GetCapabilitiesAnonymousRequest.newBuilder()
.setAccountIdentifier(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(serviceIdentifier));
if (useGroupSendToken) {
when(groupSendTokenUtil.checkGroupSendToken(any(), eq(serviceIdentifier))).thenReturn(true);
builder.setGroupSendToken(ByteString.copyFrom(TestRandomUtil.nextBytes(32)));
} else {
final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey));
builder.setUnidentifiedAccessKey(ByteString.copyFrom(unidentifiedAccessKey));
}
final GetCapabilitiesAnonymousResponse response = unauthenticatedServiceStub().getCapabilities(builder.build());
assertEquals(Capabilities.newBuilder()
.addCapabilities(org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_SPARSE_POST_QUANTUM_RATCHET)
.build(),
response.getCapabilities());
}
@ParameterizedTest
@ValueSource(booleans = {true, false})
void getCapabilitiesUnauthorized(final boolean useGroupSendToken) {
final AciServiceIdentifier serviceIdentifier = new AciServiceIdentifier(UUID.randomUUID());
final Account account = mock(Account.class);
when(accountsManager.getByServiceIdentifier(serviceIdentifier)).thenReturn(Optional.of(account));
final GetCapabilitiesAnonymousRequest.Builder builder = GetCapabilitiesAnonymousRequest.newBuilder()
.setAccountIdentifier(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(serviceIdentifier));
if (useGroupSendToken) {
when(groupSendTokenUtil.checkGroupSendToken(any(), eq(serviceIdentifier))).thenReturn(false);
builder.setGroupSendToken(ByteString.copyFrom(TestRandomUtil.nextBytes(32)));
} else {
when(account.getUnidentifiedAccessKey())
.thenReturn(Optional.of(TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH)));
builder.setUnidentifiedAccessKey(ByteString.copyFrom(TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH)));
}
final GetCapabilitiesAnonymousResponse response = unauthenticatedServiceStub().getCapabilities(builder.build());
assertEquals(FailedUnidentifiedAuthorization.getDefaultInstance(), response.getFailedUnidentifiedAuthorization());
}
@Test
void getCapabilitiesNotFound() {
final AciServiceIdentifier serviceIdentifier = new AciServiceIdentifier(UUID.randomUUID());
final byte[] groupSendToken = TestRandomUtil.nextBytes(32);
when(accountsManager.getByServiceIdentifier(serviceIdentifier))
.thenReturn(Optional.empty());
when(groupSendTokenUtil.checkGroupSendToken(ByteString.copyFrom(groupSendToken), serviceIdentifier))
.thenReturn(true);
final GetCapabilitiesAnonymousResponse response =
unauthenticatedServiceStub().getCapabilities(GetCapabilitiesAnonymousRequest.newBuilder()
.setAccountIdentifier(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(serviceIdentifier))
.setGroupSendToken(ByteString.copyFrom(groupSendToken))
.build());
assertEquals(NotFound.getDefaultInstance(), response.getNotFound());
}
private static Stream<Arguments> getCapabilitiesIllegalRequest() {
final ServiceIdentifier aci =
GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(new AciServiceIdentifier(UUID.randomUUID()));
return Stream.of(
Arguments.argumentSet("no aci", GetCapabilitiesAnonymousRequest.newBuilder()
.setUnidentifiedAccessKey(
ByteString.copyFrom(new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH]))
.build()),
Arguments.argumentSet("wrong uak length", GetCapabilitiesAnonymousRequest.newBuilder()
.setAccountIdentifier(aci)
.setUnidentifiedAccessKey(ByteString.copyFrom(new byte[15]))
.build()),
Arguments.argumentSet("invalid gse", GetCapabilitiesAnonymousRequest.newBuilder()
.setAccountIdentifier(aci)
.setGroupSendToken(ByteString.EMPTY)
.build()),
Arguments.argumentSet("no auth", GetCapabilitiesAnonymousRequest.newBuilder()
.setAccountIdentifier(
GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(new AciServiceIdentifier(UUID.randomUUID())))
.build())
);
}
@ParameterizedTest
@MethodSource
void getCapabilitiesIllegalRequest(final GetCapabilitiesAnonymousRequest request) {
GrpcTestUtils.assertStatusException(Status.INVALID_ARGUMENT,
() -> unauthenticatedServiceStub().getCapabilities(request));
}
}
@@ -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,28 @@ 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.Capabilities;
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 +52,16 @@ 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.GetCapabilitiesRequest;
import org.signal.chat.account.GetCapabilitiesResponse;
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 +72,51 @@ 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.DeviceCapability;
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.tests.util.AccountsTestHelper;
import org.whispersystems.textsecuregcm.tests.util.KeysHelper;
import org.whispersystems.textsecuregcm.util.TestClock;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
import org.whispersystems.textsecuregcm.util.UsernameHashZkProofVerifier;
@@ -97,6 +135,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 +154,9 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
return new AccountsGrpcService(accountsManager,
rateLimiters,
usernameHashZkProofVerifier,
registrationRecoveryPasswordsManager);
registrationRecoveryPasswordsManager,
testClock,
changeNumberManager);
}
@Test
@@ -146,6 +191,7 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
assertEquals(expectedResponse, authenticatedServiceStub().getAccountIdentity(GetAccountIdentityRequest.newBuilder().build()));
}
@Test
void deleteAccount() {
final DeleteAccountResponse ignored =
@@ -765,4 +811,257 @@ 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);
}
@Test
void getCapabilities() {
final Account account = mock(Account.class);
when(account.getUuid()).thenReturn(AUTHENTICATED_ACI);
// public-visible and self-visible capabilities should be returned on the authenticated RPC
when(account.hasCapability(DeviceCapability.SPARSE_POST_QUANTUM_RATCHET)).thenReturn(true);
when(account.hasCapability(DeviceCapability.USERNAME_CHANGE_SYNC_MESSAGE)).thenReturn(true);
when(account.getUuid()).thenReturn(AUTHENTICATED_ACI);
when(accountsManager.getByAccountIdentifier(AUTHENTICATED_ACI)).thenReturn(Optional.of(account));
final GetCapabilitiesResponse response = authenticatedServiceStub()
.getCapabilities(GetCapabilitiesRequest.getDefaultInstance());
assertEquals(Capabilities.newBuilder()
.addCapabilities(org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_SPARSE_POST_QUANTUM_RATCHET)
.addCapabilities(org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_USERNAME_CHANGE_SYNC_MESSAGE)
.build(), response.getCapabilities());
}
}
@@ -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() {
@@ -55,6 +55,7 @@ import org.signal.libsignal.protocol.IdentityKey;
import org.signal.libsignal.protocol.InvalidKeyException;
import org.signal.libsignal.protocol.ecc.ECKeyPair;
import org.signal.libsignal.zkgroup.ServerSecretParams;
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessChecksum;
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
import org.whispersystems.textsecuregcm.entities.ECPreKey;
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
@@ -129,6 +130,7 @@ class KeysAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<KeysAnonymousGrpcS
final GetPreKeysAnonymousResponse expectedResponse = GetPreKeysAnonymousResponse.newBuilder()
.setPreKeys(AccountPreKeyBundles.newBuilder()
.setIdentityKey(ByteString.copyFrom(identityKey.serialize()))
.setUnidentifiedAccessKeyFingerprint(ByteString.copyFrom(UnidentifiedAccessChecksum.generateFor(unidentifiedAccessKey)))
.putDevicePreKeys(Device.PRIMARY_ID, DevicePreKeyBundle.newBuilder()
.setEcOneTimePreKey(toGrpcEcPreKey(ecPreKey))
.setEcSignedPreKey(toGrpcEcSignedPreKey(ecSignedPreKey))
@@ -182,6 +184,7 @@ class KeysAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<KeysAnonymousGrpcS
final GetPreKeysAnonymousResponse expectedResponse = GetPreKeysAnonymousResponse.newBuilder()
.setPreKeys(AccountPreKeyBundles.newBuilder()
.setIdentityKey(ByteString.copyFrom(identityKey.serialize()))
.setUnidentifiedAccessKeyFingerprint(ByteString.copyFrom(UnidentifiedAccessChecksum.generateFor(unidentifiedAccessKey)))
.putDevicePreKeys(Device.PRIMARY_ID, DevicePreKeyBundle.newBuilder()
.setEcOneTimePreKey(toGrpcEcPreKey(ecPreKey))
.setEcSignedPreKey(toGrpcEcSignedPreKey(ecSignedPreKey))
@@ -235,6 +238,8 @@ class KeysAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<KeysAnonymousGrpcS
final GetPreKeysAnonymousResponse expectedResponse = GetPreKeysAnonymousResponse.newBuilder()
.setPreKeys(AccountPreKeyBundles.newBuilder()
.setIdentityKey(ByteString.copyFrom(identityKey.serialize()))
.setUnidentifiedAccessKeyFingerprint(ByteString.copyFrom(UnidentifiedAccessChecksum.generateFor(unidentifiedAccessKey)))
.setUnrestrictedUnidentifiedAccess(true)
.putDevicePreKeys(Device.PRIMARY_ID, DevicePreKeyBundle.newBuilder()
.setEcOneTimePreKey(toGrpcEcPreKey(ecPreKey))
.setEcSignedPreKey(toGrpcEcSignedPreKey(ecSignedPreKey))
@@ -5,7 +5,9 @@
package org.whispersystems.textsecuregcm.grpc;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
@@ -56,6 +58,8 @@ import org.signal.chat.keys.SetOneTimeEcPreKeysRequest;
import org.signal.chat.keys.SetOneTimeKemSignedPreKeysRequest;
import org.signal.libsignal.protocol.IdentityKey;
import org.signal.libsignal.protocol.ecc.ECKeyPair;
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessChecksum;
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.entities.ECPreKey;
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
@@ -68,9 +72,11 @@ import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
import org.whispersystems.textsecuregcm.storage.KeyIdUtil;
import org.whispersystems.textsecuregcm.storage.KeysManager;
import org.whispersystems.textsecuregcm.tests.util.KeysHelper;
import org.whispersystems.textsecuregcm.util.TestRandomUtil;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
import reactor.core.publisher.Mono;
@@ -643,4 +649,68 @@ class KeysGrpcServiceTest extends SimpleBaseGrpcTest<KeysGrpcService, KeysGrpc.K
assertRateLimitExceeded(retryAfterDuration, () -> authenticatedServiceStub().getPreKeys(builder.build()));
verify(preKeysRateLimiter).validate(expectedRateLimitKey);
}
@CartesianTest
void getPreKeysUnidentifiedInfo(
@CartesianTest.Enum(names = {"IDENTITY_TYPE_ACI", "IDENTITY_TYPE_PNI"}) final org.signal.chat.common.IdentityType grpcIdentityType,
@CartesianTest.Values(booleans = {false , true}) final boolean hasUak,
@CartesianTest.Values(booleans = {false , true}) final boolean hasUua) {
final Account targetAccount = mock(Account.class);
final ECKeyPair identityKeyPair = ECKeyPair.generate();
final IdentityKey identityKey = new IdentityKey(identityKeyPair.getPublicKey());
final UUID identifier = UUID.randomUUID();
final IdentityType identityType = IdentityTypeUtil.fromGrpcIdentityType(grpcIdentityType);
final org.whispersystems.textsecuregcm.identity.ServiceIdentifier serviceIdentifier = switch (identityType) {
case PNI -> new PniServiceIdentifier(identifier);
case ACI -> new AciServiceIdentifier(identifier);
};
when(targetAccount.getUuid()).thenReturn(UUID.randomUUID());
when(targetAccount.getIdentifier(identityType)).thenReturn(identifier);
when(targetAccount.getIdentityKey(identityType)).thenReturn(identityKey);
when(accountsManager.getByServiceIdentifier(serviceIdentifier))
.thenReturn(Optional.of(targetAccount));
final byte deviceId1 = 1;
final int registrationId = 123;
final ECSignedPreKey ecSignedPreKey = KeysHelper.signedECPreKey(3, identityKeyPair);
final Optional<ECPreKey> maybeEcPreKey = Optional.of(new ECPreKey(1, ECKeyPair.generate().getPublicKey()));
final KEMSignedPreKey kemSignedPreKey = KeysHelper.signedKEMPreKey(2, identityKeyPair);
when(keysManager.takeDevicePreKeys(eq(deviceId1), eq(serviceIdentifier), any()))
.thenReturn(CompletableFuture.completedFuture(Optional.of(new KeysManager.DevicePreKeys(ecSignedPreKey, maybeEcPreKey, kemSignedPreKey))));
final Device device = mock(Device.class);
when(device.getId()).thenReturn(deviceId1);
when(device.getRegistrationId(any())).thenReturn(registrationId);
final Map<Byte, Device> devices = Map.of(deviceId1, device);
when(targetAccount.getDevice(deviceId1)).thenReturn(Optional.of(device));
when(targetAccount.getDevices()).thenReturn(new ArrayList<>(devices.values()));
final byte[] uak = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
when(targetAccount.getUnidentifiedAccessKey()).thenReturn(hasUak ? Optional.of(uak) : Optional.empty());
when(targetAccount.isUnrestrictedUnidentifiedAccess()).thenReturn(hasUua);
final GetPreKeysResponse response = authenticatedServiceStub().getPreKeys(GetPreKeysRequest.newBuilder()
.setTargetIdentifier(ServiceIdentifier.newBuilder()
.setIdentityType(grpcIdentityType)
.setUuid(UUIDUtil.toByteString(identifier))
.build())
.setDeviceId(1)
.build());
assertTrue(response.hasPreKeys());
assertEquals(identityType == IdentityType.ACI && hasUua,
response.getPreKeys().getUnrestrictedUnidentifiedAccess());
if (identityType == IdentityType.ACI && hasUak) {
assertArrayEquals(UnidentifiedAccessChecksum.generateFor(uak),
response.getPreKeys().getUnidentifiedAccessKeyFingerprint().toByteArray());
} else {
assertTrue(response.getPreKeys().getUnidentifiedAccessKeyFingerprint().isEmpty());
}
}
}
@@ -10,9 +10,10 @@ 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;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
@@ -40,7 +41,6 @@ import java.util.Collection;
import java.util.Collections;
import java.util.HexFormat;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;
@@ -49,13 +49,12 @@ 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.mockito.Mock;
import org.signal.chat.common.IdentityType;
import org.signal.chat.common.ServiceIdentifier;
import org.signal.chat.profile.CredentialType;
import org.signal.chat.profile.DataEtag;
import org.signal.chat.profile.DeleteAvatarRequest;
import org.signal.chat.profile.DeleteAvatarResponse;
import org.signal.chat.profile.ExtendAvatarTTLRequest;
@@ -65,16 +64,13 @@ import org.signal.chat.profile.GetAvatarUploadFormResponse;
import org.signal.chat.profile.GetExpiringProfileKeyCredentialAnonymousRequest;
import org.signal.chat.profile.GetExpiringProfileKeyCredentialAnonymousResponse;
import org.signal.chat.profile.GetExpiringProfileKeyCredentialRequest;
import org.signal.chat.profile.GetUnversionedProfileAnonymousRequest;
import org.signal.chat.profile.GetUnversionedProfileAnonymousResponse;
import org.signal.chat.profile.GetUnversionedProfileRequest;
import org.signal.chat.profile.GetUnversionedProfileResult;
import org.signal.chat.profile.GetVersionedProfileAnonymousRequest;
import org.signal.chat.profile.GetVersionedProfileAnonymousResponse;
import org.signal.chat.profile.GetVersionedProfileRequest;
import org.signal.chat.profile.GetVersionedProfileResult;
import org.signal.chat.profile.GetVersionedProfileV1Response;
import org.signal.chat.profile.GetProfileAnonymousRequest;
import org.signal.chat.profile.GetProfileAnonymousResponse;
import org.signal.chat.profile.GetProfileRequest;
import org.signal.chat.profile.ProfileAnonymousGrpc;
import org.signal.chat.profile.ProfileResult;
import org.signal.chat.profile.LegacyProfileResult;
import org.signal.chat.profile.AccountInfo;
import org.signal.libsignal.protocol.IdentityKey;
import org.signal.libsignal.protocol.ServiceId;
import org.signal.libsignal.protocol.ecc.ECKeyPair;
@@ -96,8 +92,6 @@ import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessChecksum;
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
import org.whispersystems.textsecuregcm.badges.ProfileBadgeConverter;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.entities.Badge;
import org.whispersystems.textsecuregcm.entities.BadgeSvg;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.limits.RateLimiter;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
@@ -166,241 +160,18 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
);
}
@Test
void getUnversionedProfileUnidentifiedAccessKey() {
final UUID targetUuid = UUID.randomUUID();
final org.whispersystems.textsecuregcm.identity.ServiceIdentifier serviceIdentifier = new AciServiceIdentifier(targetUuid);
final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
final ECKeyPair identityKeyPair = ECKeyPair.generate();
final IdentityKey identityKey = new IdentityKey(identityKeyPair.getPublicKey());
final List<Badge> badges = List.of(new Badge(
"TEST",
"other",
"Test Badge",
"This badge is in unit tests.",
List.of("l", "m", "h", "x", "xx", "xxx"),
"SVG",
List.of(
new BadgeSvg("sl", "sd"),
new BadgeSvg("ml", "md"),
new BadgeSvg("ll", "ld")))
);
when(account.getBadges()).thenReturn(Collections.emptyList());
when(profileBadgeConverter.convert(any(), any(), anyBoolean())).thenReturn(badges);
when(account.isUnrestrictedUnidentifiedAccess()).thenReturn(false);
when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey));
when(account.getIdentityKey(org.whispersystems.textsecuregcm.identity.IdentityType.ACI)).thenReturn(identityKey);
when(account.hasCapability(any())).thenReturn(false);
when(account.hasCapability(DeviceCapability.SPARSE_POST_QUANTUM_RATCHET)).thenReturn(true);
when(accountsManager.getByServiceIdentifier(serviceIdentifier)).thenReturn(Optional.of(account));
final GetUnversionedProfileAnonymousRequest request = GetUnversionedProfileAnonymousRequest.newBuilder()
.setUnidentifiedAccessKey(ByteString.copyFrom(unidentifiedAccessKey))
.setRequest(GetUnversionedProfileRequest.newBuilder()
.setServiceIdentifier(ServiceIdentifier.newBuilder()
.setIdentityType(IdentityType.IDENTITY_TYPE_ACI)
.setUuid(ByteString.copyFrom(UUIDUtil.toBytes(targetUuid)))
.build())
.build())
.build();
final GetUnversionedProfileAnonymousResponse response = unauthenticatedServiceStub().getUnversionedProfile(request);
final byte[] unidentifiedAccessChecksum = UnidentifiedAccessChecksum.generateFor(unidentifiedAccessKey);
final GetUnversionedProfileAnonymousResponse expectedResponse = GetUnversionedProfileAnonymousResponse.newBuilder()
.setResult(GetUnversionedProfileResult.newBuilder()
.setIdentityKey(ByteString.copyFrom(identityKey.serialize()))
.setUnidentifiedAccess(ByteString.copyFrom(unidentifiedAccessChecksum))
.setUnrestrictedUnidentifiedAccess(false)
.addCapabilities(org.signal.chat.common.DeviceCapability.DEVICE_CAPABILITY_SPARSE_POST_QUANTUM_RATCHET)
.addAllBadges(ProfileGrpcHelper.buildBadges(badges))
.build()
)
.build();
verify(accountsManager).getByServiceIdentifier(serviceIdentifier);
assertEquals(expectedResponse, response);
}
@Test
void getUnversionedProfileGroupSendEndorsement() throws Exception {
final UUID targetUuid = UUID.randomUUID();
final org.whispersystems.textsecuregcm.identity.ServiceIdentifier serviceIdentifier = new AciServiceIdentifier(targetUuid);
// Expiration must be on a day boundary; we want one in the future
final Instant expiration = Instant.now().plus(Duration.ofDays(1)).truncatedTo(ChronoUnit.DAYS);
final byte[] token = AuthHelper.validGroupSendToken(SERVER_SECRET_PARAMS, List.of(serviceIdentifier), expiration);
final ECKeyPair identityKeyPair = ECKeyPair.generate();
final IdentityKey identityKey = new IdentityKey(identityKeyPair.getPublicKey());
final List<Badge> badges = List.of(new Badge(
"TEST",
"other",
"Test Badge",
"This badge is in unit tests.",
List.of("l", "m", "h", "x", "xx", "xxx"),
"SVG",
List.of(
new BadgeSvg("sl", "sd"),
new BadgeSvg("ml", "md"),
new BadgeSvg("ll", "ld")))
);
when(account.getBadges()).thenReturn(Collections.emptyList());
when(profileBadgeConverter.convert(any(), any(), anyBoolean())).thenReturn(badges);
when(account.isUnrestrictedUnidentifiedAccess()).thenReturn(false);
when(account.getIdentityKey(org.whispersystems.textsecuregcm.identity.IdentityType.ACI)).thenReturn(identityKey);
when(accountsManager.getByServiceIdentifier(serviceIdentifier)).thenReturn(Optional.of(account));
final GetUnversionedProfileAnonymousRequest request = GetUnversionedProfileAnonymousRequest.newBuilder()
.setGroupSendToken(ByteString.copyFrom(token))
.setRequest(GetUnversionedProfileRequest.newBuilder()
.setServiceIdentifier(
GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(serviceIdentifier))
.build())
.build();
final GetUnversionedProfileAnonymousResponse response = unauthenticatedServiceStub().getUnversionedProfile(request);
final GetUnversionedProfileResult expectedResult = GetUnversionedProfileResult.newBuilder()
.setIdentityKey(ByteString.copyFrom(identityKey.serialize()))
.setUnrestrictedUnidentifiedAccess(false)
.addAllCapabilities(ProfileGrpcHelper.buildAccountCapabilities(account))
.addAllBadges(ProfileGrpcHelper.buildBadges(badges))
.build();
verify(accountsManager).getByServiceIdentifier(serviceIdentifier);
assertTrue(response.hasResult());
assertEquals(expectedResult, response.getResult());
}
@Test
void getUnversionedProfileNoAuth() {
final GetUnversionedProfileAnonymousRequest request = GetUnversionedProfileAnonymousRequest.newBuilder()
.setRequest(GetUnversionedProfileRequest.newBuilder()
.setServiceIdentifier(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(new AciServiceIdentifier(UUID.randomUUID()))))
.build();
assertStatusException(Status.INVALID_ARGUMENT, () -> unauthenticatedServiceStub().getUnversionedProfile(request));
}
@ParameterizedTest
@MethodSource
void getUnversionedProfileIncorrectUnidentifiedAccessKey(final IdentityType identityType, final boolean wrongUnidentifiedAccessKey, final boolean accountNotFound) {
final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey));
when(account.isUnrestrictedUnidentifiedAccess()).thenReturn(false);
when(accountsManager.getByServiceIdentifier(any())).thenReturn(
accountNotFound ? Optional.empty() : Optional.of(account));
final GetUnversionedProfileAnonymousRequest request = GetUnversionedProfileAnonymousRequest.newBuilder()
.setUnidentifiedAccessKey(
ByteString.copyFrom(wrongUnidentifiedAccessKey
? new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH]
: unidentifiedAccessKey))
.setRequest(GetUnversionedProfileRequest.newBuilder()
.setServiceIdentifier(ServiceIdentifier.newBuilder()
.setIdentityType(identityType)
.setUuid(ByteString.copyFrom(UUIDUtil.toBytes(UUID.randomUUID())))))
.build();
if (IdentityType.IDENTITY_TYPE_PNI.equals(identityType)) {
assertStatusException(Status.INVALID_ARGUMENT, () -> unauthenticatedServiceStub().getUnversionedProfile(request));
} else {
final GetUnversionedProfileAnonymousResponse response = unauthenticatedServiceStub().getUnversionedProfile(request);
assertTrue(response.hasFailedUnidentifiedAuthorization());
}
}
private static Stream<Arguments> getUnversionedProfileIncorrectUnidentifiedAccessKey() {
return Stream.of(
Arguments.of(IdentityType.IDENTITY_TYPE_PNI, false, false),
Arguments.of(IdentityType.IDENTITY_TYPE_ACI, true, false),
Arguments.of(IdentityType.IDENTITY_TYPE_ACI, false, true)
);
}
@ParameterizedTest
@ValueSource(booleans = {true, false})
void getUnversionedProfileExpiredGroupSendEndorsement(final boolean accountNotFound) throws Exception {
final AciServiceIdentifier serviceIdentifier = new AciServiceIdentifier(UUID.randomUUID());
when(accountsManager.getByServiceIdentifier(serviceIdentifier))
.thenReturn(accountNotFound ? Optional.empty() : Optional.of(mock(Account.class)));
// Expirations must be on a day boundary; pick one in the recent past
final Instant expiration = Instant.now().truncatedTo(ChronoUnit.DAYS);
final byte[] token = AuthHelper.validGroupSendToken(SERVER_SECRET_PARAMS, List.of(serviceIdentifier), expiration);
final GetUnversionedProfileAnonymousRequest request = GetUnversionedProfileAnonymousRequest.newBuilder()
.setGroupSendToken(ByteString.copyFrom(token))
.setRequest(GetUnversionedProfileRequest.newBuilder()
.setServiceIdentifier(
GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(serviceIdentifier)))
.build();
final GetUnversionedProfileAnonymousResponse response = unauthenticatedServiceStub().getUnversionedProfile(
request);
assertTrue(response.hasFailedUnidentifiedAuthorization());
}
@Test
void getUnversionedProfileIncorrectGroupSendEndorsement() throws Exception {
final AciServiceIdentifier targetServiceIdentifier = new AciServiceIdentifier(UUID.randomUUID());
final AciServiceIdentifier authorizedServiceIdentifier = new AciServiceIdentifier(UUID.randomUUID());
// Expiration must be on a day boundary; we want one in the future
final Instant expiration = Instant.now().plus(Duration.ofDays(1)).truncatedTo(ChronoUnit.DAYS);
final byte[] token = AuthHelper.validGroupSendToken(SERVER_SECRET_PARAMS, List.of(authorizedServiceIdentifier), expiration);
when(accountsManager.getByServiceIdentifier(any())).thenReturn(
Optional.of(mock(Account.class)));
final GetUnversionedProfileAnonymousRequest request = GetUnversionedProfileAnonymousRequest.newBuilder()
.setGroupSendToken(ByteString.copyFrom(token))
.setRequest(GetUnversionedProfileRequest.newBuilder()
.setServiceIdentifier(
GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(targetServiceIdentifier)))
.build();
final GetUnversionedProfileAnonymousResponse response = unauthenticatedServiceStub().getUnversionedProfile(request);
assertTrue(response.hasFailedUnidentifiedAuthorization());
}
@Test
void getUnversionedProfileGroupSendEndorsementAccountNotFound() throws Exception {
final AciServiceIdentifier serviceIdentifier = new AciServiceIdentifier(UUID.randomUUID());
// Expiration must be on a day boundary; we want one in the future
final Instant expiration = Instant.now().plus(Duration.ofDays(1)).truncatedTo(ChronoUnit.DAYS);
final byte[] token = AuthHelper.validGroupSendToken(SERVER_SECRET_PARAMS, List.of(serviceIdentifier), expiration);
when(accountsManager.getByServiceIdentifier(any())).thenReturn(Optional.empty());
final GetUnversionedProfileAnonymousRequest request = GetUnversionedProfileAnonymousRequest.newBuilder()
.setGroupSendToken(ByteString.copyFrom(token))
.setRequest(GetUnversionedProfileRequest.newBuilder()
.setServiceIdentifier(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(serviceIdentifier)))
.build();
final GetUnversionedProfileAnonymousResponse response = unauthenticatedServiceStub().getUnversionedProfile(
request);
assertTrue(response.hasNotFound());
}
@ParameterizedTest
@MethodSource
void getVersionedProfile(final byte[] requestVersion,
@Nullable final byte[] accountVersion,
final boolean expectResponseHasPaymentAddress) {
final boolean expectResponseHasPaymentAddress,
final GetProfileAnonymousRequest.AuthenticationCase authenticationCase) throws Exception {
final AciServiceIdentifier serviceIdentifier = new AciServiceIdentifier(UUID.randomUUID());
final ECKeyPair identityKeyPair = ECKeyPair.generate();
final IdentityKey identityKey = new IdentityKey(identityKeyPair.getPublicKey());
final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
final List<String> badgeIds = List.of("TEST-BADGE");
final byte[] name = TestRandomUtil.nextBytes(81);
final byte[] emoji = TestRandomUtil.nextBytes(60);
@@ -413,56 +184,74 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
when(account.getCurrentProfileVersion()).thenReturn(Optional.ofNullable(accountVersion));
when(account.isUnrestrictedUnidentifiedAccess()).thenReturn(false);
when(account.getIdentityKey(org.whispersystems.textsecuregcm.identity.IdentityType.ACI)).thenReturn(identityKey);
when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey));
when(account.getBadges()).thenReturn(Collections.emptyList());
when(profileBadgeConverter.visibleBadgeIds(anyList())).thenReturn(badgeIds);
when(accountsManager.getByServiceIdentifier(any())).thenReturn(Optional.of(account));
when(profilesManager.getV1(any(), any())).thenReturn(profile);
final GetVersionedProfileAnonymousRequest request = GetVersionedProfileAnonymousRequest.newBuilder()
.setUnidentifiedAccessKey(ByteString.copyFrom(unidentifiedAccessKey))
.setRequest(GetVersionedProfileRequest.newBuilder()
.setAccountIdentifier(ServiceIdentifier.newBuilder()
.setIdentityType(IdentityType.IDENTITY_TYPE_ACI)
.setUuid(ByteString.copyFrom(UUIDUtil.toBytes(UUID.randomUUID())))
.build())
.setVersion(ByteString.copyFrom(requestVersion))
.build())
.build();
final GetVersionedProfileAnonymousResponse response = unauthenticatedServiceStub().getVersionedProfile(request);
final GetVersionedProfileResult.Builder expectedResultBuilder = GetVersionedProfileResult.newBuilder()
.setV1Response(GetVersionedProfileV1Response.newBuilder()
.setName(ByteString.copyFrom(name))
.setAbout(ByteString.copyFrom(about))
.setAboutEmoji(ByteString.copyFrom(emoji))
.setAvatar(avatar)
.setPhoneNumberSharing(ByteString.copyFrom(phoneNumberSharing))
);
if (expectResponseHasPaymentAddress) {
expectedResultBuilder.setPaymentAddressDataEtag(DataEtag.newBuilder()
.setData(ByteString.copyFrom(paymentAddress))
.setEtagSha256(ByteString.copyFrom(ProfileGrpcHelper.hash(paymentAddress)))
.build());
final GetProfileAnonymousRequest.Builder requestBuilder = GetProfileAnonymousRequest.newBuilder()
.setRequest(GetProfileRequest.newBuilder()
.setAccountIdentifier(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(serviceIdentifier))
.setVersion(ByteString.copyFrom(requestVersion)));
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));
}
assertEquals(expectedResultBuilder.build(), response.getResult());
final GetProfileAnonymousResponse response = unauthenticatedServiceStub().getProfile(requestBuilder.build());
final LegacyProfileResult.Builder expectedResultBuilder = LegacyProfileResult.newBuilder()
.setName(ByteString.copyFrom(name))
.setAbout(ByteString.copyFrom(about))
.setAboutEmoji(ByteString.copyFrom(emoji))
.setAvatar(avatar)
.setPhoneNumberSharing(ByteString.copyFrom(phoneNumberSharing))
.setAccountInfo(AccountInfo.newBuilder()
.addAllBadgeIds(badgeIds)
.setIdentityKey(ByteString.copyFrom(identityKey.serialize()))
.setUnrestrictedUnidentifiedAccess(false)
.setUnidentifiedAccessKeyFingerprint(ByteString.copyFrom(UnidentifiedAccessChecksum.generateFor(unidentifiedAccessKey))));
if (expectResponseHasPaymentAddress) {
expectedResultBuilder.setPaymentAddress(ByteString.copyFrom(paymentAddress));
}
assertTrue(response.hasProfileV1());
assertEquals(expectedResultBuilder.build(), response.getProfileV1());
}
private static Collection<Arguments> getVersionedProfile() {
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,
GetProfileAnonymousRequest.AuthenticationCase.UNIDENTIFIED_ACCESS_KEY),
Arguments.argumentSet("current profile version absent, unidentified access key auth",version1, null, true,
GetProfileAnonymousRequest.AuthenticationCase.UNIDENTIFIED_ACCESS_KEY),
Arguments.argumentSet("current profile version mismatch, unidentified access key auth",version1, version2, false,
GetProfileAnonymousRequest.AuthenticationCase.UNIDENTIFIED_ACCESS_KEY),
Arguments.argumentSet("current profile version matches, group send endorsement auth", version1, version1, true,
GetProfileAnonymousRequest.AuthenticationCase.GROUP_SEND_TOKEN)
);
}
@Test
void getVersionedProfileV2() {
@ParameterizedTest
@EnumSource(mode = EXCLUDE, names = "AUTHENTICATION_NOT_SET")
void getVersionedProfileV2(
final GetProfileAnonymousRequest.AuthenticationCase authenticationCase) throws Exception {
final AciServiceIdentifier serviceIdentifier = new AciServiceIdentifier(UUID.randomUUID());
final ECKeyPair identityKeyPair = ECKeyPair.generate();
final IdentityKey identityKey = new IdentityKey(identityKeyPair.getPublicKey());
final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
final List<String> badgeIds = List.of("TEST-BADGE");
final byte[] data = TestRandomUtil.nextBytes(128);
final byte[] paymentAddress = TestRandomUtil.nextBytes(582);
final byte[] commitment = TestRandomUtil.nextBytes(97);
@@ -470,82 +259,96 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
final VersionedProfile v2Profile = new VersionedProfile(version, data, paymentAddress, commitment);
when(account.getCurrentProfileVersion()).thenReturn(Optional.of(version));
when(account.isUnrestrictedUnidentifiedAccess()).thenReturn(false);
when(account.isUnrestrictedUnidentifiedAccess()).thenReturn(true);
when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey));
when(account.hasCapability(DeviceCapability.PROFILES_V2)).thenReturn(true);
when(account.getIdentityKey(org.whispersystems.textsecuregcm.identity.IdentityType.ACI)).thenReturn(identityKey);
when(account.getBadges()).thenReturn(Collections.emptyList());
when(profileBadgeConverter.visibleBadgeIds(anyList())).thenReturn(badgeIds);
when(accountsManager.getByServiceIdentifier(any())).thenReturn(Optional.of(account));
when(profilesManager.get(any(), any())).thenReturn(Optional.of(v2Profile));
when(profilesManager.getV1(any(), any())).thenReturn(Optional.empty());
final GetVersionedProfileAnonymousRequest request = GetVersionedProfileAnonymousRequest.newBuilder()
final GetProfileAnonymousRequest.Builder requestBuilder = GetProfileAnonymousRequest.newBuilder()
.setRequest(GetProfileRequest.newBuilder()
.setAccountIdentifier(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(serviceIdentifier))
.setVersion(ByteString.copyFrom(version)));
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 GetProfileAnonymousResponse response = unauthenticatedServiceStub().getProfile(requestBuilder.build());
assertTrue(response.hasProfile());
final ProfileResult.Builder expectedBuilder = ProfileResult.newBuilder()
.setData(ByteString.copyFrom(data))
.setPaymentAddress(ByteString.copyFrom(paymentAddress))
.setAccountInfo(AccountInfo.newBuilder()
.addAllBadgeIds(badgeIds)
.setIdentityKey(ByteString.copyFrom(identityKey.serialize()))
.setUnrestrictedUnidentifiedAccess(true)
.setUnidentifiedAccessKeyFingerprint(ByteString.copyFrom(UnidentifiedAccessChecksum.generateFor(unidentifiedAccessKey))));
expectedBuilder.setEtag(ByteString.copyFrom(ProfileGrpcHelper.etag(expectedBuilder)));
final ProfileResult result = response.getProfile();
assertEquals(expectedBuilder.build(), result);
}
@Test
void getVersionedProfileV2EtagMatched() {
final ECKeyPair identityKeyPair = ECKeyPair.generate();
final IdentityKey identityKey = new IdentityKey(identityKeyPair.getPublicKey());
final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(
UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
final List<String> badgeIds = List.of("TEST-BADGE");
final byte[] data = TestRandomUtil.nextBytes(128);
final byte[] paymentAddress = TestRandomUtil.nextBytes(582);
final byte[] commitment = TestRandomUtil.nextBytes(97);
final byte[] version = TestRandomUtil.nextBytes(32);
final VersionedProfile v2Profile = new VersionedProfile(version, data, paymentAddress, commitment);
when(account.getCurrentProfileVersion()).thenReturn(Optional.of(version));
when(account.isUnrestrictedUnidentifiedAccess()).thenReturn(true);
when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey));
when(account.hasCapability(DeviceCapability.PROFILES_V2)).thenReturn(true);
when(account.getIdentityKey(org.whispersystems.textsecuregcm.identity.IdentityType.ACI)).thenReturn(identityKey);
when(account.getBadges()).thenReturn(Collections.emptyList());
when(profileBadgeConverter.visibleBadgeIds(anyList())).thenReturn(badgeIds);
when(accountsManager.getByServiceIdentifier(any())).thenReturn(Optional.of(account));
when(profilesManager.get(any(), any())).thenReturn(Optional.of(v2Profile));
when(profilesManager.getV1(any(), any())).thenReturn(Optional.empty());
final byte[] expectedEtag = ProfileGrpcHelper.etag(ProfileResult.newBuilder()
.setData(ByteString.copyFrom(data))
.setPaymentAddress(ByteString.copyFrom(paymentAddress))
.setAccountInfo(AccountInfo.newBuilder()
.addAllBadgeIds(badgeIds)
.setIdentityKey(ByteString.copyFrom(identityKey.serialize()))
.setUnrestrictedUnidentifiedAccess(true)
.setUnidentifiedAccessKeyFingerprint(ByteString.copyFrom(UnidentifiedAccessChecksum.generateFor(unidentifiedAccessKey)))));
final GetProfileAnonymousRequest request = GetProfileAnonymousRequest.newBuilder()
.setUnidentifiedAccessKey(ByteString.copyFrom(unidentifiedAccessKey))
.setRequest(GetVersionedProfileRequest.newBuilder()
.setRequest(GetProfileRequest.newBuilder()
.setAccountIdentifier(ServiceIdentifier.newBuilder()
.setIdentityType(IdentityType.IDENTITY_TYPE_ACI)
.setUuid(ByteString.copyFrom(UUIDUtil.toBytes(UUID.randomUUID())))
.build())
.setVersion(ByteString.copyFrom(version))
.build())
.setEtag(ByteString.copyFrom(expectedEtag)))
.build();
final GetVersionedProfileAnonymousResponse response = unauthenticatedServiceStub().getVersionedProfile(request);
assertTrue(response.hasResult());
final GetVersionedProfileResult result = response.getResult();
assertTrue(result.hasDataEtag());
assertEquals(ByteString.copyFrom(data), result.getDataEtag().getData());
assertEquals(ByteString.copyFrom(v2Profile.dataHash()), result.getDataEtag().getEtagSha256());
assertTrue(result.hasPaymentAddressDataEtag());
assertEquals(ByteString.copyFrom(paymentAddress), result.getPaymentAddressDataEtag().getData());
assertEquals(ByteString.copyFrom(Objects.requireNonNull(v2Profile.paymentAddressHash())), result.getPaymentAddressDataEtag().getEtagSha256());
assertFalse(result.getDataEtagMatched());
assertFalse(result.getPaymentAddressEtagMatched());
assertFalse(result.hasV1Response());
}
@Test
void getVersionedProfileV2EtagMatched() {
final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
final byte[] data = TestRandomUtil.nextBytes(128);
final byte[] paymentAddress = TestRandomUtil.nextBytes(582);
final byte[] commitment = TestRandomUtil.nextBytes(97);
final byte[] version = TestRandomUtil.nextBytes(32);
final VersionedProfile v2Profile = new VersionedProfile(version, data, paymentAddress, commitment);
when(account.getCurrentProfileVersion()).thenReturn(Optional.of(version));
when(account.isUnrestrictedUnidentifiedAccess()).thenReturn(false);
when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey));
when(account.hasCapability(DeviceCapability.PROFILES_V2)).thenReturn(true);
when(accountsManager.getByServiceIdentifier(any())).thenReturn(Optional.of(account));
when(profilesManager.get(any(), any())).thenReturn(Optional.of(v2Profile));
when(profilesManager.getV1(any(), any())).thenReturn(Optional.empty());
final GetVersionedProfileRequest.Builder builder = GetVersionedProfileRequest.newBuilder()
.setAccountIdentifier(ServiceIdentifier.newBuilder()
.setIdentityType(IdentityType.IDENTITY_TYPE_ACI)
.setUuid(ByteString.copyFrom(UUIDUtil.toBytes(UUID.randomUUID())))
.build())
.setVersion(ByteString.copyFrom(version))
.setDataEtag(ByteString.copyFrom(v2Profile.dataHash()));
if (v2Profile.paymentAddressHash() != null) {
builder.setPaymentAddressEtag(ByteString.copyFrom(v2Profile.paymentAddressHash()));
}
final GetVersionedProfileAnonymousRequest request = GetVersionedProfileAnonymousRequest.newBuilder()
.setUnidentifiedAccessKey(ByteString.copyFrom(unidentifiedAccessKey))
.setRequest(builder.build())
.build();
final GetVersionedProfileAnonymousResponse response = unauthenticatedServiceStub().getVersionedProfile(request);
assertTrue(response.hasResult());
final GetVersionedProfileResult result = response.getResult();
assertTrue(result.getDataEtagMatched());
assertTrue(result.getPaymentAddressEtagMatched());
assertFalse(result.hasDataEtag());
assertFalse(result.hasPaymentAddressDataEtag());
assertFalse(result.hasV1Response());
final GetProfileAnonymousResponse response = unauthenticatedServiceStub().getProfile(request);
assertTrue(response.hasEtagMatched());
assertTrue(response.getEtagMatched());
}
@Test
@@ -558,9 +361,9 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
when(accountsManager.getByServiceIdentifier(any())).thenReturn(Optional.of(account));
when(profilesManager.getV1(any(), any())).thenReturn(Optional.empty());
final GetVersionedProfileAnonymousRequest request = GetVersionedProfileAnonymousRequest.newBuilder()
final GetProfileAnonymousRequest request = GetProfileAnonymousRequest.newBuilder()
.setUnidentifiedAccessKey(ByteString.copyFrom(unidentifiedAccessKey))
.setRequest(GetVersionedProfileRequest.newBuilder()
.setRequest(GetProfileRequest.newBuilder()
.setAccountIdentifier(ServiceIdentifier.newBuilder()
.setIdentityType(IdentityType.IDENTITY_TYPE_ACI)
.setUuid(ByteString.copyFrom(UUIDUtil.toBytes(UUID.randomUUID())))
@@ -569,60 +372,54 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
.build())
.build();
final GetVersionedProfileAnonymousResponse response = unauthenticatedServiceStub().getVersionedProfile(
final GetProfileAnonymousResponse response = unauthenticatedServiceStub().getProfile(
request);
assertTrue(response.hasNotFound());
}
@ParameterizedTest
@MethodSource
void getVersionedProfileUnauthenticated(final boolean missingUnidentifiedAccessKey, final boolean accountNotFound) {
@EnumSource(mode = EXCLUDE, names = "AUTHENTICATION_NOT_SET")
void getVersionedProfileAccountNotFound(
final GetProfileAnonymousRequest.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())
final GetProfileAnonymousRequest.Builder requestBuilder = GetProfileAnonymousRequest.newBuilder()
.setRequest(GetProfileRequest.newBuilder()
.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 GetProfileAnonymousResponse response = unauthenticatedServiceStub().getProfile(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
void getVersionedProfilePniInvalidArgument() {
final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
final GetVersionedProfileAnonymousRequest request = GetVersionedProfileAnonymousRequest.newBuilder()
final GetProfileAnonymousRequest request = GetProfileAnonymousRequest.newBuilder()
.setUnidentifiedAccessKey(ByteString.copyFrom(unidentifiedAccessKey))
.setRequest(GetVersionedProfileRequest.newBuilder()
.setRequest(GetProfileRequest.newBuilder()
.setAccountIdentifier(ServiceIdentifier.newBuilder()
.setIdentityType(IdentityType.IDENTITY_TYPE_PNI)
.setUuid(ByteString.copyFrom(UUIDUtil.toBytes(UUID.randomUUID())))
@@ -631,7 +428,79 @@ public class ProfileAnonymousGrpcServiceTest extends SimpleBaseGrpcTest<ProfileA
.build())
.build();
assertStatusException(Status.INVALID_ARGUMENT, () -> unauthenticatedServiceStub().getVersionedProfile(request));
//noinspection ThrowableNotThrown
assertStatusException(Status.INVALID_ARGUMENT, () -> unauthenticatedServiceStub().getProfile(request));
}
@Test
void getVersionedProfileNoAuth() {
final GetProfileAnonymousRequest request = GetProfileAnonymousRequest.newBuilder()
.setRequest(GetProfileRequest.newBuilder()
.setAccountIdentifier(GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(new AciServiceIdentifier(UUID.randomUUID()))))
.build();
//noinspection ThrowableNotThrown
assertStatusException(Status.INVALID_ARGUMENT, () -> unauthenticatedServiceStub().getProfile(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 GetProfileAnonymousRequest request = GetProfileAnonymousRequest.newBuilder()
.setUnidentifiedAccessKey(ByteString.copyFrom(new byte[UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH]))
.setRequest(GetProfileRequest.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 GetProfileAnonymousResponse response = unauthenticatedServiceStub().getProfile(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 GetProfileAnonymousRequest request = GetProfileAnonymousRequest.newBuilder()
.setGroupSendToken(ByteString.copyFrom(token))
.setRequest(GetProfileRequest.newBuilder()
.setAccountIdentifier(
GrpcServiceIdentifierUtil.toGrpcServiceIdentifier(serviceIdentifier))
.setVersion(ByteString.copyFrom(TestRandomUtil.nextBytes(32)))
.build())
.build();
final GetProfileAnonymousResponse response = unauthenticatedServiceStub().getProfile(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
@@ -0,0 +1,101 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.grpc;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import com.google.protobuf.ByteString;
import java.util.Base64;
import java.util.Collections;
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.signal.chat.common.DeviceCapability;
import org.signal.chat.profile.ProfileResult;
import org.signal.chat.profile.AccountInfo;
class ProfileGrpcHelperTest {
public static Stream<Arguments> etagTestVectors() {
// Expected values of the etag calculation for example profile data sets. A failure here indicates a potential
// backwards compatability issue.
return Stream.of(
Arguments.argumentSet("empty", ProfileResult.newBuilder().setAccountInfo(AccountInfo.getDefaultInstance()).build(), "6NXrB3FC907RoA=="),
Arguments.argumentSet("all fields set", profile().build(), "zrvx5cC+UDrLzQ=="),
Arguments.argumentSet("collection ordering", ProfileResult.newBuilder().setAccountInfo(AccountInfo.newBuilder()
.addBadgeIds("badgeZ").addBadgeIds("badgeQ").addBadgeIds("badgeQQ"))
.build() , "AS2DN9M/IapIgA=="),
Arguments.argumentSet("data only", ProfileResult.newBuilder().setData(ByteString.fromHex("abcde123")).build(), "ZKDfIrGEKT1+Sw=="),
Arguments.argumentSet("payment address only", ProfileResult.newBuilder().setPaymentAddress(ByteString.fromHex("abcde123")).build(), "5CWKoXAq1/cuAg==")
);
}
@ParameterizedTest
@MethodSource
void etagTestVectors(final ProfileResult profile, final String expectedEtagB64) {
final byte[] etag = ProfileGrpcHelper.etag(profile);
final byte[] expectedEtag = Base64.getDecoder().decode(expectedEtagB64);
assertEquals(10, etag.length);
assertArrayEquals(expectedEtag, etag);
}
@Test
void etagIgnoresBadgeOrdering() {
final byte[] ascending = ProfileGrpcHelper.etag(ProfileResult.newBuilder()
.setAccountInfo(AccountInfo.newBuilder()
.addBadgeIds("badge-a")
.addBadgeIds("badge-b"))
.build());
final byte[] descending = ProfileGrpcHelper.etag(ProfileResult.newBuilder()
.setAccountInfo(AccountInfo.newBuilder()
.addBadgeIds("badge-b")
.addBadgeIds("badge-a"))
.build());
assertArrayEquals(ascending, descending);
}
@Test
void etagIgnoresEtag() {
final ProfileResult profile = profile().build();
final byte[] etag = ProfileGrpcHelper.etag(profile);
final ProfileResult withEtagSet = profile.toBuilder().setEtag(ByteString.copyFrom(etag)).build();
assertArrayEquals(etag, ProfileGrpcHelper.etag(withEtagSet));
}
@Test
void absentAndEmptyHaveSameEtag() {
final byte[] unset = ProfileGrpcHelper.etag(ProfileResult.newBuilder().build());
final byte[] explicitlyEmpty = ProfileGrpcHelper.etag(ProfileResult.newBuilder()
.setData(ByteString.EMPTY)
.setPaymentAddress(ByteString.EMPTY)
.setAccountInfo(AccountInfo.newBuilder()
.setIdentityKey(ByteString.EMPTY)
.setUnidentifiedAccessKeyFingerprint(ByteString.EMPTY)
.addAllBadgeIds(Collections.emptyList()))
.build());
assertArrayEquals(unset, explicitlyEmpty);
}
private static ProfileResult.Builder profile() {
return ProfileResult.newBuilder()
.setData(ByteString.copyFromUtf8("profile-data"))
.setPaymentAddress(ByteString.copyFromUtf8("payment-address"))
.setAccountInfo(AccountInfo.newBuilder()
.setIdentityKey(ByteString.copyFromUtf8("identity-key"))
.setUnidentifiedAccessKeyFingerprint(ByteString.copyFromUtf8("uak-checksum"))
.setUnrestrictedUnidentifiedAccess(true)
.addBadgeIds("badge-a")
.addBadgeIds("badge-b"));
}
}
@@ -8,11 +8,10 @@ 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.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.AdditionalMatchers.aryEq;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
@@ -52,24 +51,20 @@ 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.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.signal.chat.common.IdentityType;
import org.signal.chat.common.ServiceIdentifier;
import org.signal.chat.profile.DataEtag;
import org.signal.chat.profile.GetAvatarCredentialsRequest;
import org.signal.chat.profile.GetAvatarCredentialsResponse;
import org.signal.chat.profile.GetUnversionedProfileRequest;
import org.signal.chat.profile.GetUnversionedProfileResponse;
import org.signal.chat.profile.GetUnversionedProfileResult;
import org.signal.chat.profile.GetVersionedProfileRequest;
import org.signal.chat.profile.GetVersionedProfileResponse;
import org.signal.chat.profile.GetVersionedProfileResult;
import org.signal.chat.profile.GetVersionedProfileV1Response;
import org.signal.chat.profile.GetProfileRequest;
import org.signal.chat.profile.GetProfileResponse;
import org.signal.chat.profile.LegacyProfileResult;
import org.signal.chat.profile.ProfileGrpc;
import org.signal.chat.profile.ProfileResult;
import org.signal.chat.profile.AccountInfo;
import org.signal.chat.profile.SetProfileRequest;
import org.signal.chat.profile.SetProfileResponse;
import org.signal.chat.profile.SetProfileResult;
@@ -93,11 +88,8 @@ import org.whispersystems.textsecuregcm.configuration.BadgeConfiguration;
import org.whispersystems.textsecuregcm.configuration.BadgesConfiguration;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicPaymentsConfiguration;
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
import org.whispersystems.textsecuregcm.entities.Badge;
import org.whispersystems.textsecuregcm.entities.BadgeSvg;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier;
import org.whispersystems.textsecuregcm.limits.RateLimiter;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
@@ -174,7 +166,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);
@@ -611,107 +602,13 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
}
@ParameterizedTest
@EnumSource(value = org.signal.chat.common.IdentityType.class, names = {"IDENTITY_TYPE_ACI", "IDENTITY_TYPE_PNI"})
void getUnversionedProfile(final IdentityType identityType) throws Exception {
final UUID targetUuid = UUID.randomUUID();
final org.whispersystems.textsecuregcm.identity.ServiceIdentifier targetIdentifier =
identityType == IdentityType.IDENTITY_TYPE_ACI ? new AciServiceIdentifier(targetUuid) : new PniServiceIdentifier(targetUuid);
final GetUnversionedProfileRequest request = GetUnversionedProfileRequest.newBuilder()
.setServiceIdentifier(ServiceIdentifier.newBuilder()
.setIdentityType(identityType)
.setUuid(ByteString.copyFrom(UUIDUtil.toBytes(targetUuid)))
.build())
.build();
final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
@MethodSource
void getProfile(final byte[] requestVersion, @Nullable final byte[] accountVersion, final boolean expectResponseHasPaymentAddress) {
final ECKeyPair identityKeyPair = ECKeyPair.generate();
final IdentityKey identityKey = new IdentityKey(identityKeyPair.getPublicKey());
final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
final List<String> badgeIds = List.of("TEST-BADGE");
final List<Badge> badges = List.of(new Badge(
"TEST",
"other",
"Test Badge",
"This badge is in unit tests.",
List.of("l", "m", "h", "x", "xx", "xxx"),
"SVG",
List.of(
new BadgeSvg("sl", "sd"),
new BadgeSvg("ml", "md"),
new BadgeSvg("ll", "ld")))
);
when(account.getIdentityKey(IdentityTypeUtil.fromGrpcIdentityType(identityType))).thenReturn(identityKey);
when(account.isUnrestrictedUnidentifiedAccess()).thenReturn(true);
when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey));
when(account.getBadges()).thenReturn(Collections.emptyList());
when(account.hasCapability(any())).thenReturn(false);
when(profileBadgeConverter.convert(any(), any(), anyBoolean())).thenReturn(badges);
when(accountsManager.getByServiceIdentifier(any())).thenReturn(Optional.of(account));
final GetUnversionedProfileResponse response = authenticatedServiceStub().getUnversionedProfile(request);
final byte[] unidentifiedAccessChecksum = UnidentifiedAccessChecksum.generateFor(unidentifiedAccessKey);
final GetUnversionedProfileResult prototypeExpectedResult = GetUnversionedProfileResult.newBuilder()
.setIdentityKey(ByteString.copyFrom(identityKey.serialize()))
.setUnidentifiedAccess(ByteString.copyFrom(unidentifiedAccessChecksum))
.setUnrestrictedUnidentifiedAccess(true)
.addAllBadges(ProfileGrpcHelper.buildBadges(badges))
.build();
final GetUnversionedProfileResult expectedResponse;
if (identityType == IdentityType.IDENTITY_TYPE_PNI) {
expectedResponse = GetUnversionedProfileResult.newBuilder(prototypeExpectedResult)
.clearUnidentifiedAccess()
.clearBadges()
.setUnrestrictedUnidentifiedAccess(false)
.build();
} else {
expectedResponse = prototypeExpectedResult;
}
verify(rateLimiter).validate(AUTHENTICATED_ACI);
verify(accountsManager).getByServiceIdentifier(targetIdentifier);
assertTrue(response.hasResult());
assertEquals(expectedResponse, response.getResult());
}
@Test
void getUnversionedProfileTargetAccountNotFound() {
when(accountsManager.getByServiceIdentifier(any())).thenReturn(Optional.empty());
final GetUnversionedProfileRequest request = GetUnversionedProfileRequest.newBuilder()
.setServiceIdentifier(ServiceIdentifier.newBuilder()
.setIdentityType(IdentityType.IDENTITY_TYPE_ACI)
.setUuid(ByteString.copyFrom(UUIDUtil.toBytes(UUID.randomUUID())))
.build())
.build();
final GetUnversionedProfileResponse response = authenticatedServiceStub().getUnversionedProfile(request);
assertTrue(response.hasNotFound());
}
@ParameterizedTest
@EnumSource(value = org.signal.chat.common.IdentityType.class, names = {"IDENTITY_TYPE_ACI", "IDENTITY_TYPE_PNI"})
void getUnversionedProfileRatelimited(final IdentityType identityType) throws Exception {
final Duration retryAfterDuration = Duration.ofMinutes(7);
when(accountsManager.getByServiceIdentifier(any())).thenReturn(Optional.of(account));
doThrow(new RateLimitExceededException(retryAfterDuration))
.when(rateLimiter).validate(any(UUID.class));
final GetUnversionedProfileRequest request = GetUnversionedProfileRequest.newBuilder()
.setServiceIdentifier(ServiceIdentifier.newBuilder()
.setIdentityType(identityType)
.setUuid(ByteString.copyFrom(UUIDUtil.toBytes(UUID.randomUUID())))
.build())
.build();
assertRateLimitExceeded(retryAfterDuration, () -> authenticatedServiceStub().getUnversionedProfile(request), accountsManager);
}
@ParameterizedTest
@MethodSource
void getVersionedProfile(final byte[] requestVersion, @Nullable final byte[] accountVersion, final boolean expectResponseHasPaymentAddress) {
final byte[] name = TestRandomUtil.nextBytes(81);
final byte[] emoji = TestRandomUtil.nextBytes(60);
final byte[] about = TestRandomUtil.nextBytes(156);
@@ -722,7 +619,7 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
final Optional<VersionedProfileV1> profile = Optional.of(new VersionedProfileV1(HexFormat.of().formatHex(requestVersion), name, avatar, emoji, about, paymentAddress,
phoneNumberSharing, new byte[0]));
final GetVersionedProfileRequest request = GetVersionedProfileRequest.newBuilder()
final GetProfileRequest request = GetProfileRequest.newBuilder()
.setAccountIdentifier(ServiceIdentifier.newBuilder()
.setIdentityType(IdentityType.IDENTITY_TYPE_ACI)
.setUuid(ByteString.copyFrom(UUIDUtil.toBytes(UUID.randomUUID())))
@@ -734,29 +631,35 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
when(accountsManager.getByServiceIdentifier(any())).thenReturn(Optional.of(account));
when(profilesManager.getV1(any(), any())).thenReturn(profile);
final GetVersionedProfileResponse response = authenticatedServiceStub().getVersionedProfile(request);
when(account.getIdentityKey(org.whispersystems.textsecuregcm.identity.IdentityType.ACI)).thenReturn(identityKey);
when(account.isUnrestrictedUnidentifiedAccess()).thenReturn(true);
when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey));
when(account.getBadges()).thenReturn(Collections.emptyList());
when(account.hasCapability(any())).thenReturn(false);
when(profileBadgeConverter.visibleBadgeIds(anyList())).thenReturn(badgeIds);
final GetVersionedProfileResult.Builder expectedResultBuilder = GetVersionedProfileResult.newBuilder()
.setV1Response(GetVersionedProfileV1Response.newBuilder()
.setName(ByteString.copyFrom(name))
.setAbout(ByteString.copyFrom(about))
.setAboutEmoji(ByteString.copyFrom(emoji))
.setAvatar(avatar)
.setPhoneNumberSharing(ByteString.copyFrom(phoneNumberSharing))
.build());
final GetProfileResponse response = authenticatedServiceStub().getProfile(request);
final LegacyProfileResult.Builder expectedV1ResponseBuilder = LegacyProfileResult.newBuilder()
.setName(ByteString.copyFrom(name))
.setAbout(ByteString.copyFrom(about))
.setAboutEmoji(ByteString.copyFrom(emoji))
.setAvatar(avatar)
.setPhoneNumberSharing(ByteString.copyFrom(phoneNumberSharing))
.setAccountInfo(AccountInfo.newBuilder()
.addAllBadgeIds(badgeIds)
.setIdentityKey(ByteString.copyFrom(identityKey.serialize()))
.setUnrestrictedUnidentifiedAccess(true)
.setUnidentifiedAccessKeyFingerprint(ByteString.copyFrom(UnidentifiedAccessChecksum.generateFor(unidentifiedAccessKey))));
if (expectResponseHasPaymentAddress) {
expectedResultBuilder.setPaymentAddressDataEtag(
DataEtag.newBuilder().setData(ByteString.copyFrom(paymentAddress))
.setEtagSha256(ByteString.copyFrom(ProfileGrpcHelper.hash(paymentAddress)))
.build());
expectedV1ResponseBuilder.setPaymentAddress(ByteString.copyFrom(paymentAddress));
}
assertTrue(response.hasResult());
assertEquals(expectedResultBuilder.build(), response.getResult());
assertTrue(response.hasLegacyProfile());
assertEquals(expectedV1ResponseBuilder.build(), response.getLegacyProfile());
}
private static Collection<Arguments> getVersionedProfile() {
private static Collection<Arguments> getProfile() {
final byte[] version1 = TestRandomUtil.nextBytes(32);
final byte[] version2 = TestRandomUtil.nextBytes(32);
return List.of(
@@ -767,7 +670,12 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
}
@Test
void getVersionedProfileV2() {
void getProfileV2() {
final ECKeyPair identityKeyPair = ECKeyPair.generate();
final IdentityKey identityKey = new IdentityKey(identityKeyPair.getPublicKey());
final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
final List<String> badgeIds = List.of("TEST-BADGE");
final byte[] data = TestRandomUtil.nextBytes(128);
final byte[] paymentAddress = TestRandomUtil.nextBytes(582);
final byte[] commitment = TestRandomUtil.nextBytes(97);
@@ -776,17 +684,21 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
final UUID targetAci = UUID.randomUUID();
final VersionedProfile v2Profile = new VersionedProfile(version, data, paymentAddress, commitment);
final Account targetAccount = mock(Account.class);
when(account.getUuid()).thenReturn(targetAci);
when(account.getCurrentProfileVersion()).thenReturn(Optional.of(version));
when(account.hasCapability(DeviceCapability.PROFILES_V2)).thenReturn(true);
when(account.getIdentityKey(org.whispersystems.textsecuregcm.identity.IdentityType.ACI)).thenReturn(identityKey);
when(account.isUnrestrictedUnidentifiedAccess()).thenReturn(true);
when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey));
when(account.getBadges()).thenReturn(Collections.emptyList());
when(accountsManager.getByServiceIdentifier(new AciServiceIdentifier(targetAci)))
.thenReturn(Optional.of(targetAccount));
when(targetAccount.getUuid()).thenReturn(targetAci);
when(targetAccount.getCurrentProfileVersion()).thenReturn(Optional.of(version));
when(targetAccount.hasCapability(DeviceCapability.PROFILES_V2)).thenReturn(true);
.thenReturn(Optional.of(account));
when(profileBadgeConverter.visibleBadgeIds(anyList())).thenReturn(badgeIds);
when(profilesManager.get(eq(targetAci), aryEq(version))).thenReturn(Optional.of(v2Profile));
when(profilesManager.getV1(any(), any())).thenReturn(Optional.empty());
final GetVersionedProfileRequest request = GetVersionedProfileRequest.newBuilder()
final GetProfileRequest request = GetProfileRequest.newBuilder()
.setAccountIdentifier(ServiceIdentifier.newBuilder()
.setIdentityType(IdentityType.IDENTITY_TYPE_ACI)
.setUuid(ByteString.copyFrom(UUIDUtil.toBytes(targetAci)))
@@ -794,23 +706,30 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
.setVersion(ByteString.copyFrom(version))
.build();
final GetVersionedProfileResponse response = authenticatedServiceStub().getVersionedProfile(request);
assertTrue(response.hasResult());
final GetVersionedProfileResult result = response.getResult();
final GetProfileResponse response = authenticatedServiceStub().getProfile(request);
assertTrue(result.hasDataEtag());
assertEquals(ByteString.copyFrom(data), result.getDataEtag().getData());
assertEquals(ByteString.copyFrom(v2Profile.dataHash()), result.getDataEtag().getEtagSha256());
assertTrue(result.hasPaymentAddressDataEtag());
assertEquals(ByteString.copyFrom(paymentAddress), result.getPaymentAddressDataEtag().getData());
assertEquals(ByteString.copyFrom(v2Profile.paymentAddressHash()), result.getPaymentAddressDataEtag().getEtagSha256());
assertFalse(result.getDataEtagMatched());
assertFalse(result.getPaymentAddressEtagMatched());
assertFalse(result.hasV1Response());
final ProfileResult.Builder expectedBuilder = ProfileResult.newBuilder()
.setData(ByteString.copyFrom(data))
.setPaymentAddress(ByteString.copyFrom(paymentAddress))
.setAccountInfo(AccountInfo.newBuilder()
.addAllBadgeIds(badgeIds)
.setIdentityKey(ByteString.copyFrom(identityKey.serialize()))
.setUnrestrictedUnidentifiedAccess(true)
.setUnidentifiedAccessKeyFingerprint(ByteString.copyFrom(UnidentifiedAccessChecksum.generateFor(unidentifiedAccessKey))));
expectedBuilder.setEtag(ByteString.copyFrom(ProfileGrpcHelper.etag(expectedBuilder)));
assertTrue(response.hasProfile());
final ProfileResult result = response.getProfile();
assertEquals(expectedBuilder.build(), result);
}
@Test
void getVersionedProfileV2EtagMatched() {
void getProfileV2EtagMatched() {
final ECKeyPair identityKeyPair = ECKeyPair.generate();
final IdentityKey identityKey = new IdentityKey(identityKeyPair.getPublicKey());
final byte[] unidentifiedAccessKey = TestRandomUtil.nextBytes(UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH);
final List<String> badgeIds = List.of("TEST-BADGE");
final byte[] data = TestRandomUtil.nextBytes(128);
final byte[] paymentAddress = TestRandomUtil.nextBytes(582);
final byte[] commitment = TestRandomUtil.nextBytes(97);
@@ -818,44 +737,48 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
final VersionedProfile v2Profile = new VersionedProfile(version, data, paymentAddress, commitment);
final UUID targetAci = UUID.randomUUID();
final Account targetAccount = mock(Account.class);
when(targetAccount.getUuid()).thenReturn(targetAci);
when(targetAccount.hasCapability(DeviceCapability.PROFILES_V2)).thenReturn(true);
when(accountsManager.getByServiceIdentifier(new AciServiceIdentifier(targetAci))).thenReturn(Optional.of(targetAccount));
when(account.getUuid()).thenReturn(targetAci);
when(account.hasCapability(DeviceCapability.PROFILES_V2)).thenReturn(true);
when(accountsManager.getByServiceIdentifier(new AciServiceIdentifier(targetAci))).thenReturn(Optional.of(account));
when(targetAccount.getCurrentProfileVersion()).thenReturn(Optional.of(version));
when(account.getIdentityKey(org.whispersystems.textsecuregcm.identity.IdentityType.ACI)).thenReturn(identityKey);
when(account.isUnrestrictedUnidentifiedAccess()).thenReturn(true);
when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey));
when(account.getBadges()).thenReturn(Collections.emptyList());
when(profileBadgeConverter.visibleBadgeIds(anyList())).thenReturn(badgeIds);
when(account.getCurrentProfileVersion()).thenReturn(Optional.of(version));
when(profilesManager.get(targetAci, version)).thenReturn(Optional.of(v2Profile));
when(profilesManager.getV1(any(), any())).thenReturn(Optional.empty());
final GetVersionedProfileRequest.Builder builder = GetVersionedProfileRequest.newBuilder()
final byte[] expectedEtag = ProfileGrpcHelper.etag(ProfileResult.newBuilder()
.setData(ByteString.copyFrom(data))
.setPaymentAddress(ByteString.copyFrom(paymentAddress))
.setAccountInfo(AccountInfo.newBuilder()
.addAllBadgeIds(badgeIds)
.setIdentityKey(ByteString.copyFrom(identityKey.serialize()))
.setUnrestrictedUnidentifiedAccess(true)
.setUnidentifiedAccessKeyFingerprint(ByteString.copyFrom(UnidentifiedAccessChecksum.generateFor(unidentifiedAccessKey)))));
final GetProfileRequest.Builder builder = GetProfileRequest.newBuilder()
.setAccountIdentifier(ServiceIdentifier.newBuilder()
.setIdentityType(IdentityType.IDENTITY_TYPE_ACI)
.setUuid(ByteString.copyFrom(UUIDUtil.toBytes(targetAci)))
.build())
.setVersion(ByteString.copyFrom(version))
.setDataEtag(ByteString.copyFrom(v2Profile.dataHash()));
.setEtag(ByteString.copyFrom(expectedEtag));
if (v2Profile.paymentAddressHash() != null) {
builder.setPaymentAddressEtag(ByteString.copyFrom(v2Profile.paymentAddressHash()));
}
final GetProfileRequest request = builder.build();
final GetVersionedProfileRequest request = builder.build();
final GetVersionedProfileResponse response = authenticatedServiceStub().getVersionedProfile(request);
assertTrue(response.hasResult());
final GetVersionedProfileResult result = response.getResult();
assertTrue(result.getDataEtagMatched());
assertTrue(result.getPaymentAddressEtagMatched());
assertFalse(result.hasDataEtag());
assertFalse(result.hasPaymentAddressDataEtag());
assertFalse(result.hasV1Response());
final GetProfileResponse response = authenticatedServiceStub().getProfile(request);
assertTrue(response.hasEtagMatched());
assertTrue(response.getEtagMatched());
}
@ParameterizedTest
@MethodSource
void getVersionedProfileAccountOrProfileNotFound(final boolean missingAccount, final boolean missingProfile) {
final GetVersionedProfileRequest request = GetVersionedProfileRequest.newBuilder()
void getProfileAccountOrProfileNotFound(final boolean missingAccount, final boolean missingProfile) {
final GetProfileRequest request = GetProfileRequest.newBuilder()
.setAccountIdentifier(ServiceIdentifier.newBuilder()
.setIdentityType(IdentityType.IDENTITY_TYPE_ACI)
.setUuid(ByteString.copyFrom(UUIDUtil.toBytes(UUID.randomUUID())))
@@ -865,11 +788,11 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
when(accountsManager.getByServiceIdentifier(any())).thenReturn(missingAccount ? Optional.empty() : Optional.of(account));
when(profilesManager.getV1(any(), any())).thenReturn(missingProfile ? Optional.empty() : Optional.of(profile));
final GetVersionedProfileResponse response = authenticatedServiceStub().getVersionedProfile(request);
final GetProfileResponse response = authenticatedServiceStub().getProfile(request);
assertTrue(response.hasNotFound());
}
private static Stream<Arguments> getVersionedProfileAccountOrProfileNotFound() {
private static Stream<Arguments> getProfileAccountOrProfileNotFound() {
return Stream.of(
Arguments.of(true, false),
Arguments.of(false, true)
@@ -877,10 +800,10 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
}
@Test
void getVersionedProfileRatelimited() {
void getProfileRatelimited() {
final Duration retryAfterDuration = MockUtils.updateRateLimiterResponseToFail(rateLimiter, AUTHENTICATED_ACI, Duration.ofMinutes(7));
final GetVersionedProfileRequest request = GetVersionedProfileRequest.newBuilder()
final GetProfileRequest request = GetProfileRequest.newBuilder()
.setAccountIdentifier(ServiceIdentifier.newBuilder()
.setIdentityType(IdentityType.IDENTITY_TYPE_ACI)
.setUuid(ByteString.copyFrom(UUIDUtil.toBytes(UUID.randomUUID())))
@@ -888,12 +811,12 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
.setVersion(ByteString.copyFrom(TestRandomUtil.nextBytes(32)))
.build();
assertRateLimitExceeded(retryAfterDuration, () -> authenticatedServiceStub().getVersionedProfile(request), accountsManager, profilesManager);
assertRateLimitExceeded(retryAfterDuration, () -> authenticatedServiceStub().getProfile(request), accountsManager, profilesManager);
}
@Test
void getVersionedProfilePniInvalidArgument() {
final GetVersionedProfileRequest request = GetVersionedProfileRequest.newBuilder()
void getProfilePniInvalidArgument() {
final GetProfileRequest request = GetProfileRequest.newBuilder()
.setAccountIdentifier(ServiceIdentifier.newBuilder()
.setIdentityType(IdentityType.IDENTITY_TYPE_PNI)
.setUuid(ByteString.copyFrom(UUIDUtil.toBytes(UUID.randomUUID())))
@@ -901,7 +824,7 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
.setVersion(ByteString.copyFrom(TestRandomUtil.nextBytes(32)))
.build();
assertStatusException(Status.INVALID_ARGUMENT, () -> authenticatedServiceStub().getVersionedProfile(request));
assertStatusException(Status.INVALID_ARGUMENT, () -> authenticatedServiceStub().getProfile(request));
}
@Test
@@ -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,146 +0,0 @@
/*
* Copyright 2026 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.storage;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
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.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStream;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
import reactor.adapter.JdkFlowAdapter;
import reactor.core.publisher.Flux;
class AcknowledgementMirroringMessageStreamTest {
private RedisDynamoDbMessageStream redisDynamoDbMessageStream;
private FoundationDbMessageStream foundationDbMessageStream;
private AcknowledgementMirroringMessageStream mirroringMessageStream;
private static long serialMessageTimestamp = 0;
private enum UUIDVersion {
V4,
V8
}
@BeforeEach
void setUp() {
redisDynamoDbMessageStream = mock(RedisDynamoDbMessageStream.class);
when(redisDynamoDbMessageStream.acknowledgeMessage(any(), anyLong()))
.thenReturn(CompletableFuture.completedFuture(null));
foundationDbMessageStream = mock(FoundationDbMessageStream.class);
when(foundationDbMessageStream.acknowledgeMessage(any(), anyLong()))
.thenReturn(CompletableFuture.completedFuture(null));
mirroringMessageStream = new AcknowledgementMirroringMessageStream(
redisDynamoDbMessageStream,
foundationDbMessageStream);
}
@ParameterizedTest
@EnumSource(UUIDVersion.class)
void acknowledgeMessages(final UUIDVersion uuidVersion) {
final List<MessageStreamEntry> entries = new ArrayList<>();
{
for (int i = 0; i < AcknowledgementMirroringMessageStream.FOUNDATIONDB_REQUEST_SIZE + 1; i++) {
entries.add(generateEnvelopeEntry(uuidVersion));
}
entries.add(new MessageStreamEntry.QueueEmpty());
}
when(redisDynamoDbMessageStream.getMessages())
.thenReturn(JdkFlowAdapter.publisherToFlowPublisher(Flux.fromIterable(entries)));
when(foundationDbMessageStream.getMessages())
.thenReturn(JdkFlowAdapter.publisherToFlowPublisher(Flux.fromIterable(
uuidVersion == UUIDVersion.V8 ? entries : Collections.emptyList())));
JdkFlowAdapter.flowPublisherToFlux(mirroringMessageStream.getMessages())
.doOnNext(entry -> {
if (entry instanceof MessageStreamEntry.Envelope(MessageProtos.Envelope message)) {
mirroringMessageStream.acknowledgeMessage(UUIDUtil.fromByteString(message.getServerGuid()),
message.getServerTimestamp());
}
})
.takeUntil(entry -> entry instanceof MessageStreamEntry.QueueEmpty)
.then()
.block();
if (uuidVersion == UUIDVersion.V8) {
entries.stream()
.filter(streamEntry -> streamEntry instanceof MessageStreamEntry.Envelope)
.map(streamEntry -> ((MessageStreamEntry.Envelope) streamEntry).message())
.forEach(envelope -> verify(foundationDbMessageStream).acknowledgeMessage(
UUIDUtil.fromByteString(envelope.getServerGuid()), envelope.getServerTimestamp()));
} else {
verify(foundationDbMessageStream, never()).acknowledgeMessage(any(), anyLong());
}
}
@Test
void acknowledgeMessagesOverflow() {
final List<MessageStreamEntry> entries = new ArrayList<>();
{
for (int i = 0; i < AcknowledgementMirroringMessageStream.MAX_PENDING_ACKNOWLEDGEMENTS + 1; i++) {
entries.add(generateEnvelopeEntry(UUIDVersion.V8));
}
entries.add(new MessageStreamEntry.QueueEmpty());
}
when(redisDynamoDbMessageStream.getMessages())
.thenReturn(JdkFlowAdapter.publisherToFlowPublisher(Flux.fromIterable(entries)));
when(foundationDbMessageStream.getMessages())
.thenReturn(JdkFlowAdapter.publisherToFlowPublisher(Flux.empty()));
assertThrows(IllegalStateException.class,
() -> JdkFlowAdapter.flowPublisherToFlux(mirroringMessageStream.getMessages())
.doOnNext(entry -> {
if (entry instanceof MessageStreamEntry.Envelope(MessageProtos.Envelope message)) {
mirroringMessageStream.acknowledgeMessage(UUIDUtil.fromByteString(message.getServerGuid()),
message.getServerTimestamp());
}
})
.takeUntil(entry -> entry instanceof MessageStreamEntry.QueueEmpty)
.then()
.block());
verify(foundationDbMessageStream, never()).acknowledgeMessage(any(), anyLong());
}
private static MessageStreamEntry.Envelope generateEnvelopeEntry(final UUIDVersion uuidVersion) {
final UUID messageGuid = switch (uuidVersion) {
case V4 -> UUID.randomUUID();
case V8 -> MessageGuidUtil.generateRandomV8UUID();
};
return new MessageStreamEntry.Envelope(MessageProtos.Envelope.newBuilder()
.setServerGuid(UUIDUtil.toByteString(messageGuid))
.setServerTimestamp(serialMessageTimestamp++)
.build());
}
}
@@ -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());
@@ -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)
);
}
}
@@ -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());
}
}
@@ -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
@@ -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) {
@@ -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"));
}
}
@@ -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