mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-12-01 05:56:47 +00:00
Compare commits
17
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
aa60fae3b1 | ||
|
|
8cb9c60a3c | ||
|
|
dd7a20a774 | ||
|
|
374fe087bc | ||
|
|
11691c3122 | ||
|
|
8d129b10ca | ||
|
|
d6e03f50b9 | ||
|
|
f60c9f2a15 | ||
|
|
1c617284f3 | ||
|
|
5bc6ff0e77 | ||
|
|
020c21f4ef | ||
|
|
bd57c1c7e7 | ||
|
|
f4b94a7a89 | ||
|
|
b666b66160 | ||
|
|
8bafb1a641 | ||
|
|
42d4574213 | ||
|
|
9ef6f8aec9 |
No files matched your search
@@ -167,6 +167,7 @@ import org.whispersystems.textsecuregcm.keytransparency.KeyTransparencyServiceCl
|
||||
import org.whispersystems.textsecuregcm.limits.CardinalityEstimator;
|
||||
import org.whispersystems.textsecuregcm.limits.MessageDeliveryLoopMonitor;
|
||||
import org.whispersystems.textsecuregcm.limits.PushChallengeManager;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimitByIpFilter;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimitChallengeManager;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.mappers.CompletionExceptionMapper;
|
||||
@@ -650,7 +651,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
secureStorageClient, secureValueRecovery2Client,
|
||||
clientPresenceManager,
|
||||
registrationRecoveryPasswordsManager, clientPublicKeysManager, accountLockExecutor, clientPresenceExecutor,
|
||||
clock);
|
||||
clock, dynamicConfigurationManager);
|
||||
RemoteConfigsManager remoteConfigsManager = new RemoteConfigsManager(remoteConfigs);
|
||||
APNSender apnSender = new APNSender(apnSenderExecutor, config.getApnConfiguration());
|
||||
FcmSender fcmSender = new FcmSender(fcmSenderExecutor, config.getFcmConfiguration().credentials().value());
|
||||
@@ -1003,6 +1004,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
|
||||
environment.jersey().register(new BufferingInterceptor());
|
||||
environment.jersey().register(new VirtualExecutorServiceProvider("managed-async-virtual-thread-"));
|
||||
environment.jersey().register(new RateLimitByIpFilter(rateLimiters, true));
|
||||
environment.jersey().register(new RequestStatisticsFilter(TrafficSource.HTTP));
|
||||
environment.jersey().register(MultiRecipientMessageProvider.class);
|
||||
environment.jersey().register(new AuthDynamicFeature(accountAuthFilter));
|
||||
@@ -1021,11 +1023,13 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
clientReleaseManager, messageDeliveryLoopMonitor));
|
||||
webSocketEnvironment.jersey()
|
||||
.register(new WebsocketRefreshApplicationEventListener(accountsManager, clientPresenceManager));
|
||||
webSocketEnvironment.jersey().register(new RateLimitByIpFilter(rateLimiters, true));
|
||||
webSocketEnvironment.jersey().register(new RequestStatisticsFilter(TrafficSource.WEBSOCKET));
|
||||
webSocketEnvironment.jersey().register(MultiRecipientMessageProvider.class);
|
||||
webSocketEnvironment.jersey().register(new MetricsApplicationEventListener(TrafficSource.WEBSOCKET, clientReleaseManager));
|
||||
webSocketEnvironment.jersey().register(new KeepAliveController(clientPresenceManager));
|
||||
|
||||
|
||||
final List<SpamFilter> spamFilters = ServiceLoader.load(SpamFilter.class)
|
||||
.stream()
|
||||
.map(ServiceLoader.Provider::get)
|
||||
|
||||
+4
-9
@@ -6,8 +6,7 @@
|
||||
package org.whispersystems.textsecuregcm.captcha;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
@@ -21,22 +20,19 @@ public class HCaptchaResponse {
|
||||
@JsonProperty
|
||||
boolean success;
|
||||
|
||||
@JsonProperty(value = "challenge-ts")
|
||||
Duration challengeTs;
|
||||
@JsonProperty(value = "challenge_ts")
|
||||
Instant challengeTs;
|
||||
|
||||
@JsonProperty
|
||||
String hostname;
|
||||
|
||||
@JsonProperty
|
||||
boolean credit;
|
||||
|
||||
@JsonProperty(value = "error-codes")
|
||||
List<String> errorCodes = Collections.emptyList();
|
||||
|
||||
@JsonProperty
|
||||
float score;
|
||||
|
||||
@JsonProperty(value = "score-reasons")
|
||||
@JsonProperty(value = "score_reason")
|
||||
List<String> scoreReasons = Collections.emptyList();
|
||||
|
||||
public HCaptchaResponse() {
|
||||
@@ -48,7 +44,6 @@ public class HCaptchaResponse {
|
||||
"success=" + success +
|
||||
", challengeTs=" + challengeTs +
|
||||
", hostname='" + hostname + '\'' +
|
||||
", credit=" + credit +
|
||||
", errorCodes=" + errorCodes +
|
||||
", score=" + score +
|
||||
", scoreReasons=" + scoreReasons +
|
||||
|
||||
+3
-2
@@ -2,6 +2,7 @@ package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.Map;
|
||||
import javax.validation.Valid;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import org.whispersystems.textsecuregcm.configuration.secrets.SecretString;
|
||||
|
||||
@@ -24,8 +25,8 @@ public record Cdn3StorageManagerConfiguration(
|
||||
@NotNull SecretString clientSecret,
|
||||
@NotNull Map<Integer, String> sourceSchemes,
|
||||
@NotNull Integer numHttpClients,
|
||||
@NotNull CircuitBreakerConfiguration circuitBreaker,
|
||||
@NotNull RetryConfiguration retry) {
|
||||
@NotNull @Valid CircuitBreakerConfiguration circuitBreaker,
|
||||
@NotNull @Valid RetryConfiguration retry) {
|
||||
|
||||
public Cdn3StorageManagerConfiguration {
|
||||
if (numHttpClients == null) {
|
||||
|
||||
+3
@@ -1,6 +1,7 @@
|
||||
package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import javax.validation.Valid;
|
||||
import javax.validation.constraints.NotBlank;
|
||||
import javax.validation.constraints.NotEmpty;
|
||||
import javax.validation.constraints.NotNull;
|
||||
@@ -15,10 +16,12 @@ public class ClientCdnConfiguration {
|
||||
|
||||
@JsonProperty
|
||||
@NotNull
|
||||
@Valid
|
||||
CircuitBreakerConfiguration circuitBreaker = new CircuitBreakerConfiguration();
|
||||
|
||||
@JsonProperty
|
||||
@NotNull
|
||||
@Valid
|
||||
RetryConfiguration retry = new RetryConfiguration();
|
||||
|
||||
public CircuitBreakerConfiguration getCircuitBreaker() {
|
||||
|
||||
+3
@@ -6,6 +6,7 @@
|
||||
package org.whispersystems.textsecuregcm.configuration;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import javax.validation.Valid;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import com.fasterxml.jackson.annotation.JsonTypeName;
|
||||
import org.whispersystems.textsecuregcm.captcha.HCaptchaClient;
|
||||
@@ -24,10 +25,12 @@ public class HCaptchaConfiguration implements HCaptchaClientFactory {
|
||||
|
||||
@JsonProperty
|
||||
@NotNull
|
||||
@Valid
|
||||
CircuitBreakerConfiguration circuitBreaker = new CircuitBreakerConfiguration();
|
||||
|
||||
@JsonProperty
|
||||
@NotNull
|
||||
@Valid
|
||||
RetryConfiguration retry = new RetryConfiguration();
|
||||
|
||||
|
||||
|
||||
+6
-4
@@ -104,11 +104,13 @@ public class SubscriptionConfiguration {
|
||||
@JsonIgnore
|
||||
@ValidationMethod(message = "has a mismatch between the levels supported currencies")
|
||||
public boolean isCurrencyListSameAcrossAllLevels() {
|
||||
final Map<Long, SubscriptionLevelConfiguration> subscriptionLevels = Stream
|
||||
.concat(donationLevels.entrySet().stream(), backupLevels.entrySet().stream())
|
||||
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
|
||||
return isCurrencyListSameAccrossLevelConfigurations(donationLevels)
|
||||
&& isCurrencyListSameAccrossLevelConfigurations(backupLevels);
|
||||
}
|
||||
|
||||
Optional<SubscriptionLevelConfiguration> any = subscriptionLevels.values().stream().findAny();
|
||||
private static boolean isCurrencyListSameAccrossLevelConfigurations(
|
||||
Map<Long, ? extends SubscriptionLevelConfiguration> subscriptionLevels) {
|
||||
Optional<? extends SubscriptionLevelConfiguration> any = subscriptionLevels.values().stream().findAny();
|
||||
if (any.isEmpty()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
+9
@@ -8,6 +8,7 @@ package org.whispersystems.textsecuregcm.configuration.dynamic;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import javax.validation.Valid;
|
||||
@@ -71,6 +72,10 @@ public class DynamicConfiguration {
|
||||
@Valid
|
||||
DynamicMessagesConfiguration messagesConfiguration = new DynamicMessagesConfiguration();
|
||||
|
||||
@JsonProperty
|
||||
@Valid
|
||||
List<String> svrStatusCodesToIgnoreForAccountDeletion = Collections.emptyList();
|
||||
|
||||
public Optional<DynamicExperimentEnrollmentConfiguration> getExperimentEnrollmentConfiguration(
|
||||
final String experimentName) {
|
||||
return Optional.ofNullable(experiments.get(experimentName));
|
||||
@@ -129,4 +134,8 @@ public class DynamicConfiguration {
|
||||
return messagesConfiguration;
|
||||
}
|
||||
|
||||
public List<String> getSvrStatusCodesToIgnoreForAccountDeletion() {
|
||||
return svrStatusCodesToIgnoreForAccountDeletion;
|
||||
}
|
||||
|
||||
}
|
||||
+12
@@ -8,8 +8,10 @@ package org.whispersystems.textsecuregcm.controllers;
|
||||
import static com.codahale.metrics.MetricRegistry.name;
|
||||
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.common.net.HttpHeaders;
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import java.security.InvalidKeyException;
|
||||
import java.time.Clock;
|
||||
@@ -23,6 +25,7 @@ import javax.annotation.Nonnull;
|
||||
import javax.ws.rs.BadRequestException;
|
||||
import javax.ws.rs.DefaultValue;
|
||||
import javax.ws.rs.GET;
|
||||
import javax.ws.rs.HeaderParam;
|
||||
import javax.ws.rs.Path;
|
||||
import javax.ws.rs.Produces;
|
||||
import javax.ws.rs.QueryParam;
|
||||
@@ -39,6 +42,7 @@ import org.whispersystems.textsecuregcm.auth.CertificateGenerator;
|
||||
import org.whispersystems.textsecuregcm.entities.DeliveryCertificate;
|
||||
import org.whispersystems.textsecuregcm.entities.GroupCredentials;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.websocket.auth.ReadOnly;
|
||||
|
||||
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
|
||||
@@ -55,6 +59,8 @@ public class CertificateController {
|
||||
public static final Duration MAX_REDEMPTION_DURATION = Duration.ofDays(7);
|
||||
private static final String GENERATE_DELIVERY_CERTIFICATE_COUNTER_NAME = name(CertificateGenerator.class, "generateCertificate");
|
||||
private static final String INCLUDE_E164_TAG_NAME = "includeE164";
|
||||
private static final String GET_GROUP_AUTHENTICATION_CREDENTIALS_COUNTER_NAME = name(CertificateController.class,
|
||||
"getGroupAuthenticationCredentials");
|
||||
|
||||
public CertificateController(
|
||||
@Nonnull CertificateGenerator certificateGenerator,
|
||||
@@ -90,6 +96,7 @@ public class CertificateController {
|
||||
@Path("/auth/group")
|
||||
public GroupCredentials getGroupAuthenticationCredentials(
|
||||
@ReadOnly @Auth AuthenticatedDevice auth,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) String userAgent,
|
||||
@QueryParam("redemptionStartSeconds") long startSeconds,
|
||||
@QueryParam("redemptionEndSeconds") long endSeconds,
|
||||
@QueryParam("zkcCredential") boolean zkcCredential) {
|
||||
@@ -107,6 +114,11 @@ public class CertificateController {
|
||||
throw new BadRequestException();
|
||||
}
|
||||
|
||||
Metrics
|
||||
.counter(GET_GROUP_AUTHENTICATION_CREDENTIALS_COUNTER_NAME,
|
||||
Tags.of(UserAgentTagUtil.getPlatformTag(userAgent)).and("zkcCredential", String.valueOf(zkcCredential)))
|
||||
.increment();
|
||||
|
||||
final List<GroupCredentials.GroupCredential> credentials = new ArrayList<>();
|
||||
final List<GroupCredentials.CallLinkAuthCredential> callLinkAuthCredentials = new ArrayList<>();
|
||||
|
||||
|
||||
+34
-42
@@ -279,26 +279,26 @@ public class MessageController {
|
||||
@ApiResponse(
|
||||
responseCode = "410", description = "Mismatched registration ids supplied for some recipient devices",
|
||||
content = @Content(schema = @Schema(implementation = AccountStaleDevices[].class)))
|
||||
public Response sendMessage(@ReadOnly @Auth Optional<AuthenticatedDevice> source,
|
||||
public Response sendMessage(@ReadOnly @Auth final Optional<AuthenticatedDevice> source,
|
||||
@Parameter(description="The recipient's unidentified access key")
|
||||
@HeaderParam(HeaderUtils.UNIDENTIFIED_ACCESS_KEY) Optional<Anonymous> accessKey,
|
||||
@HeaderParam(HeaderUtils.UNIDENTIFIED_ACCESS_KEY) final Optional<Anonymous> accessKey,
|
||||
|
||||
@Parameter(description="A group send endorsement token covering the recipient. Must not be combined with `Unidentified-Access-Key` or set on a story message.")
|
||||
@HeaderParam(HeaderUtils.GROUP_SEND_TOKEN)
|
||||
@Nullable GroupSendTokenHeader groupSendToken,
|
||||
@Nullable final GroupSendTokenHeader groupSendToken,
|
||||
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) String userAgent,
|
||||
@HeaderParam(HttpHeaders.USER_AGENT) final String userAgent,
|
||||
|
||||
@Parameter(description="If true, deliver the message only to recipients that are online when it is sent")
|
||||
@PathParam("destination") ServiceIdentifier destinationIdentifier,
|
||||
@PathParam("destination") final ServiceIdentifier destinationIdentifier,
|
||||
|
||||
@Parameter(description="If true, the message is a story; access tokens are not checked and sending to nonexistent recipients is permitted")
|
||||
@QueryParam("story") boolean isStory,
|
||||
@QueryParam("story") final boolean isStory,
|
||||
|
||||
@Parameter(description="The encrypted message payloads for each recipient device")
|
||||
@NotNull @Valid IncomingMessageList messages,
|
||||
@NotNull @Valid final IncomingMessageList messages,
|
||||
|
||||
@Context ContainerRequestContext context) throws RateLimitExceededException {
|
||||
@Context final ContainerRequestContext context) throws RateLimitExceededException {
|
||||
|
||||
final Sample sample = Timer.start();
|
||||
try {
|
||||
@@ -307,7 +307,7 @@ public class MessageController {
|
||||
}
|
||||
|
||||
if (groupSendToken != null) {
|
||||
if (!source.isEmpty() || !accessKey.isEmpty()) {
|
||||
if (source.isPresent() || accessKey.isPresent()) {
|
||||
throw new BadRequestException(
|
||||
"Group send endorsement tokens should not be combined with other authentication");
|
||||
} else if (isStory) {
|
||||
@@ -315,24 +315,17 @@ public class MessageController {
|
||||
}
|
||||
}
|
||||
|
||||
final String senderType;
|
||||
if (source.isPresent()) {
|
||||
if (source.get().getAccount().isIdentifiedBy(destinationIdentifier)) {
|
||||
senderType = SENDER_TYPE_SELF;
|
||||
} else {
|
||||
senderType = SENDER_TYPE_IDENTIFIED;
|
||||
}
|
||||
} else {
|
||||
senderType = SENDER_TYPE_UNIDENTIFIED;
|
||||
}
|
||||
final String senderType = source.map(
|
||||
s -> s.getAccount().isIdentifiedBy(destinationIdentifier) ? SENDER_TYPE_SELF : SENDER_TYPE_IDENTIFIED)
|
||||
.orElse(SENDER_TYPE_UNIDENTIFIED);
|
||||
|
||||
boolean isSyncMessage = source.isPresent() && source.get().getAccount().isIdentifiedBy(destinationIdentifier);
|
||||
final boolean isSyncMessage = senderType.equals(SENDER_TYPE_SELF);
|
||||
|
||||
if (isSyncMessage && destinationIdentifier.identityType() == IdentityType.PNI) {
|
||||
throw new WebApplicationException(Status.FORBIDDEN);
|
||||
}
|
||||
|
||||
Optional<Account> destination;
|
||||
final Optional<Account> destination;
|
||||
if (!isSyncMessage) {
|
||||
destination = accountsManager.getByServiceIdentifier(destinationIdentifier);
|
||||
} else {
|
||||
@@ -387,7 +380,7 @@ public class MessageController {
|
||||
destinationIdentifier);
|
||||
}
|
||||
|
||||
boolean needsSync = !isSyncMessage && source.isPresent() && source.get().getAccount().getDevices().size() > 1;
|
||||
final boolean needsSync = !isSyncMessage && source.isPresent() && source.get().getAccount().getDevices().size() > 1;
|
||||
|
||||
// We return 200 when stories are sent to a non-existent account. Since story sends bypass OptionalAccess.verify
|
||||
// we leak information about whether a destination UUID exists if we return any other code (e.g. 404) from
|
||||
@@ -444,34 +437,33 @@ public class MessageController {
|
||||
Tag.of(AUTH_TYPE_TAG_NAME, authType),
|
||||
Tag.of(IDENTITY_TYPE_TAG_NAME, destinationIdentifier.identityType().name()));
|
||||
|
||||
for (IncomingMessage incomingMessage : messages.messages()) {
|
||||
Optional<Device> destinationDevice = destination.get().getDevice(incomingMessage.destinationDeviceId());
|
||||
|
||||
if (destinationDevice.isPresent()) {
|
||||
Metrics.counter(SENT_MESSAGE_COUNTER_NAME, tags).increment();
|
||||
sendIndividualMessage(
|
||||
source,
|
||||
destination.get(),
|
||||
destinationDevice.get(),
|
||||
destinationIdentifier,
|
||||
messages.timestamp(),
|
||||
messages.online(),
|
||||
isStory,
|
||||
messages.urgent(),
|
||||
incomingMessage,
|
||||
userAgent,
|
||||
spamReportToken);
|
||||
}
|
||||
for (final IncomingMessage incomingMessage : messages.messages()) {
|
||||
destination.get().getDevice(incomingMessage.destinationDeviceId())
|
||||
.ifPresent(destinationDevice -> {
|
||||
Metrics.counter(SENT_MESSAGE_COUNTER_NAME, tags).increment();
|
||||
sendIndividualMessage(
|
||||
source,
|
||||
destination.get(),
|
||||
destinationDevice,
|
||||
destinationIdentifier,
|
||||
messages.timestamp(),
|
||||
messages.online(),
|
||||
isStory,
|
||||
messages.urgent(),
|
||||
incomingMessage,
|
||||
userAgent,
|
||||
spamReportToken);
|
||||
});
|
||||
}
|
||||
|
||||
return Response.ok(new SendMessageResponse(needsSync)).build();
|
||||
} catch (MismatchedDevicesException e) {
|
||||
} catch (final MismatchedDevicesException e) {
|
||||
throw new WebApplicationException(Response.status(409)
|
||||
.type(MediaType.APPLICATION_JSON_TYPE)
|
||||
.entity(new MismatchedDevices(e.getMissingDevices(),
|
||||
e.getExtraDevices()))
|
||||
.build());
|
||||
} catch (StaleDevicesException e) {
|
||||
} catch (final StaleDevicesException e) {
|
||||
throw new WebApplicationException(Response.status(410)
|
||||
.type(MediaType.APPLICATION_JSON)
|
||||
.entity(new StaleDevices(e.getStaleDevices()))
|
||||
|
||||
+3
-2
@@ -397,8 +397,9 @@ public class VerificationController {
|
||||
Tag.of(SCORE_TAG_NAME, assessmentResult.getScoreString())))
|
||||
.increment();
|
||||
|
||||
} catch (IOException e) {
|
||||
throw new ServerErrorException(Response.Status.SERVICE_UNAVAILABLE);
|
||||
} catch (final IOException e) {
|
||||
logger.error("error assessing captcha", e);
|
||||
throw new ServerErrorException(Response.Status.SERVICE_UNAVAILABLE, e);
|
||||
}
|
||||
|
||||
if (assessmentResult.isValid(captchaScoreThreshold)) {
|
||||
|
||||
+27
-4
@@ -22,6 +22,11 @@ import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.filters.RemoteAddressFilter;
|
||||
import org.whispersystems.textsecuregcm.mappers.RateLimitExceededExceptionMapper;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tag;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
|
||||
public class RateLimitByIpFilter implements ContainerRequestFilter {
|
||||
|
||||
@@ -33,11 +38,18 @@ public class RateLimitByIpFilter implements ContainerRequestFilter {
|
||||
|
||||
private static final ExceptionMapper<RateLimitExceededException> EXCEPTION_MAPPER = new RateLimitExceededExceptionMapper();
|
||||
|
||||
private final RateLimiters rateLimiters;
|
||||
private static final String NO_IP_COUNTER_NAME = MetricsUtil.name(RateLimitByIpFilter.class, "noIpAddress");
|
||||
|
||||
private final RateLimiters rateLimiters;
|
||||
private final boolean softEnforcement;
|
||||
|
||||
public RateLimitByIpFilter(final RateLimiters rateLimiters, final boolean softEnforcement) {
|
||||
this.rateLimiters = requireNonNull(rateLimiters);
|
||||
this.softEnforcement = softEnforcement;
|
||||
}
|
||||
|
||||
public RateLimitByIpFilter(final RateLimiters rateLimiters) {
|
||||
this.rateLimiters = requireNonNull(rateLimiters);
|
||||
this(rateLimiters, false);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -65,10 +77,19 @@ public class RateLimitByIpFilter implements ContainerRequestFilter {
|
||||
|
||||
// checking if we failed to extract the most recent IP for any reason
|
||||
if (remoteAddress.isEmpty()) {
|
||||
Metrics.counter(
|
||||
NO_IP_COUNTER_NAME,
|
||||
Tags.of(
|
||||
Tag.of("limiter", handle.id()),
|
||||
Tag.of("fail", String.valueOf(annotation.failOnUnresolvedIp()))))
|
||||
.increment();
|
||||
|
||||
// checking if annotation is configured to fail when the most recent IP is not resolved
|
||||
if (annotation.failOnUnresolvedIp()) {
|
||||
logger.error("Remote address was null");
|
||||
throw INVALID_HEADER_EXCEPTION;
|
||||
if (!softEnforcement) {
|
||||
throw INVALID_HEADER_EXCEPTION;
|
||||
}
|
||||
}
|
||||
// otherwise, allow request
|
||||
return;
|
||||
@@ -78,7 +99,9 @@ public class RateLimitByIpFilter implements ContainerRequestFilter {
|
||||
rateLimiter.validate(remoteAddress.get());
|
||||
} catch (RateLimitExceededException e) {
|
||||
final Response response = EXCEPTION_MAPPER.toResponse(e);
|
||||
throw new ClientErrorException(response);
|
||||
if (!softEnforcement) {
|
||||
throw new ClientErrorException(response);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -70,7 +70,7 @@ public class MessageSender {
|
||||
if (clientPresent) {
|
||||
messagesManager.insert(account.getUuid(), device.getId(), message.toBuilder().setEphemeral(true).build());
|
||||
} else {
|
||||
messagesManager.removeRecipientViewFromMrmData(account.getUuid(), device.getId(), message);
|
||||
messagesManager.removeRecipientViewFromMrmData(device.getId(), message);
|
||||
}
|
||||
} else {
|
||||
messagesManager.insert(account.getUuid(), device.getId(), message);
|
||||
|
||||
+1
-1
@@ -72,7 +72,7 @@ public class SecureValueRecovery2Client {
|
||||
return null;
|
||||
}
|
||||
|
||||
throw new SecureValueRecoveryException("Failed to delete backup: " + response.statusCode());
|
||||
throw new SecureValueRecoveryException("Failed to delete backup", String.valueOf(response.statusCode()));
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
+7
-1
@@ -6,8 +6,14 @@
|
||||
package org.whispersystems.textsecuregcm.securevaluerecovery;
|
||||
|
||||
public class SecureValueRecoveryException extends RuntimeException {
|
||||
private final String statusCode;
|
||||
|
||||
public SecureValueRecoveryException(final String message) {
|
||||
public SecureValueRecoveryException(final String message, final String statusCode) {
|
||||
super(message);
|
||||
this.statusCode = statusCode;
|
||||
}
|
||||
|
||||
public String getStatusCode() {
|
||||
return statusCode;
|
||||
}
|
||||
}
|
||||
+17
-2
@@ -33,6 +33,7 @@ import java.util.Optional;
|
||||
import java.util.Queue;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionException;
|
||||
import java.util.concurrent.CompletionStage;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
@@ -48,6 +49,7 @@ import org.signal.libsignal.protocol.IdentityKey;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.controllers.MismatchedDevicesException;
|
||||
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
|
||||
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
|
||||
@@ -60,6 +62,7 @@ import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
|
||||
import org.whispersystems.textsecuregcm.redis.RedisOperation;
|
||||
import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
|
||||
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecovery2Client;
|
||||
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecoveryException;
|
||||
import org.whispersystems.textsecuregcm.util.DestinationDeviceValidator;
|
||||
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
@@ -107,6 +110,7 @@ public class AccountsManager {
|
||||
private final Executor accountLockExecutor;
|
||||
private final Executor clientPresenceExecutor;
|
||||
private final Clock clock;
|
||||
private final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager;
|
||||
|
||||
private static final ObjectWriter ACCOUNT_REDIS_JSON_WRITER = SystemMapper.jsonMapper()
|
||||
.writer(SystemMapper.excludingField(Account.class, List.of("uuid")));
|
||||
@@ -147,7 +151,8 @@ public class AccountsManager {
|
||||
final ClientPublicKeysManager clientPublicKeysManager,
|
||||
final Executor accountLockExecutor,
|
||||
final Executor clientPresenceExecutor,
|
||||
final Clock clock) {
|
||||
final Clock clock,
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager) {
|
||||
this.accounts = accounts;
|
||||
this.phoneNumberIdentifiers = phoneNumberIdentifiers;
|
||||
this.cacheCluster = cacheCluster;
|
||||
@@ -163,6 +168,7 @@ public class AccountsManager {
|
||||
this.accountLockExecutor = accountLockExecutor;
|
||||
this.clientPresenceExecutor = clientPresenceExecutor;
|
||||
this.clock = requireNonNull(clock);
|
||||
this.dynamicConfigurationManager = dynamicConfigurationManager;
|
||||
}
|
||||
|
||||
public Account create(final String number,
|
||||
@@ -982,10 +988,19 @@ public class AccountsManager {
|
||||
account.getIdentifier(IdentityType.ACI),
|
||||
device.getId())))
|
||||
.toList();
|
||||
CompletableFuture<Void> deleteBackupFuture = secureValueRecovery2Client.deleteBackups(account.getUuid())
|
||||
.exceptionally(ExceptionUtils.exceptionallyHandler(SecureValueRecoveryException.class, exception -> {
|
||||
final List<String> svrStatusCodesToIgnore = dynamicConfigurationManager.getConfiguration().getSvrStatusCodesToIgnoreForAccountDeletion();
|
||||
if (svrStatusCodesToIgnore.contains(exception.getStatusCode())) {
|
||||
logger.warn("Failed to delete backup for account: " + account.getUuid(), exception);
|
||||
return null;
|
||||
}
|
||||
throw new CompletionException(exception);
|
||||
}));
|
||||
|
||||
return CompletableFuture.allOf(
|
||||
secureStorageClient.deleteStoredData(account.getUuid()),
|
||||
secureValueRecovery2Client.deleteBackups(account.getUuid()),
|
||||
deleteBackupFuture,
|
||||
keysManager.deleteSingleUsePreKeys(account.getUuid()),
|
||||
keysManager.deleteSingleUsePreKeys(account.getPhoneNumberIdentifier()),
|
||||
messagesManager.clear(account.getUuid()),
|
||||
|
||||
+3
-16
@@ -15,22 +15,14 @@ import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Timer;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.util.function.Tuple2;
|
||||
import reactor.util.function.Tuples;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ItemCollectionSizeLimitExceededException;
|
||||
|
||||
public class MessagePersister implements Managed {
|
||||
@@ -38,8 +30,6 @@ public class MessagePersister implements Managed {
|
||||
private final MessagesCache messagesCache;
|
||||
private final MessagesManager messagesManager;
|
||||
private final AccountsManager accountsManager;
|
||||
private final ClientPresenceManager clientPresenceManager;
|
||||
private final KeysManager keysManager;
|
||||
|
||||
private final Duration persistDelay;
|
||||
|
||||
@@ -72,17 +62,14 @@ public class MessagePersister implements Managed {
|
||||
private static final Logger logger = LoggerFactory.getLogger(MessagePersister.class);
|
||||
|
||||
public MessagePersister(final MessagesCache messagesCache, final MessagesManager messagesManager,
|
||||
final AccountsManager accountsManager, final ClientPresenceManager clientPresenceManager,
|
||||
final KeysManager keysManager,
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager,
|
||||
final Duration persistDelay,
|
||||
final AccountsManager accountsManager,
|
||||
final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager, final Duration persistDelay,
|
||||
final int dedicatedProcessWorkerThreadCount
|
||||
) {
|
||||
|
||||
this.messagesCache = messagesCache;
|
||||
this.messagesManager = messagesManager;
|
||||
this.accountsManager = accountsManager;
|
||||
this.clientPresenceManager = clientPresenceManager;
|
||||
this.keysManager = keysManager;
|
||||
this.persistDelay = persistDelay;
|
||||
this.workerThreads = new Thread[dedicatedProcessWorkerThreadCount];
|
||||
|
||||
|
||||
@@ -11,7 +11,6 @@ import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.protobuf.ByteString;
|
||||
import com.google.protobuf.InvalidProtocolBufferException;
|
||||
import io.dropwizard.lifecycle.Managed;
|
||||
import io.lettuce.core.ScoredValue;
|
||||
import io.lettuce.core.ZAddArgs;
|
||||
import io.lettuce.core.cluster.SlotHash;
|
||||
import io.lettuce.core.cluster.models.partitions.RedisClusterNode;
|
||||
@@ -42,13 +41,14 @@ import java.util.function.Predicate;
|
||||
import javax.annotation.Nullable;
|
||||
import org.reactivestreams.Publisher;
|
||||
import org.signal.libsignal.protocol.SealedSenderMultiRecipientMessage;
|
||||
import org.signal.libsignal.protocol.ServiceId;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicMessagesConfiguration;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.experiment.Experiment;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantPubSubConnection;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
|
||||
@@ -270,23 +270,24 @@ public class MessagesCache extends RedisClusterPubSubAdapter<String, String> imp
|
||||
return insertTimer.record(() -> insertScript.execute(destinationUuid, destinationDevice, messageWithGuid));
|
||||
}
|
||||
|
||||
public byte[] insertSharedMultiRecipientMessagePayload(UUID mrmGuid,
|
||||
SealedSenderMultiRecipientMessage sealedSenderMultiRecipientMessage) {
|
||||
final byte[] sharedMrmKey = getSharedMrmKey(mrmGuid);
|
||||
insertSharedMrmPayloadTimer.record(() -> insertMrmScript.execute(sharedMrmKey, sealedSenderMultiRecipientMessage));
|
||||
return sharedMrmKey;
|
||||
public byte[] insertSharedMultiRecipientMessagePayload(
|
||||
final SealedSenderMultiRecipientMessage sealedSenderMultiRecipientMessage) {
|
||||
return insertSharedMrmPayloadTimer.record(() -> {
|
||||
final byte[] sharedMrmKey = getSharedMrmKey(UUID.randomUUID());
|
||||
insertMrmScript.execute(sharedMrmKey, sealedSenderMultiRecipientMessage);
|
||||
return sharedMrmKey;
|
||||
});
|
||||
}
|
||||
|
||||
public CompletableFuture<Optional<RemovedMessage>> remove(final UUID destinationUuid,
|
||||
final byte destinationDevice,
|
||||
public CompletableFuture<Optional<RemovedMessage>> remove(final UUID destinationUuid, final byte destinationDevice,
|
||||
final UUID messageGuid) {
|
||||
|
||||
return remove(destinationUuid, destinationDevice, List.of(messageGuid))
|
||||
.thenApply(removed -> removed.isEmpty() ? Optional.empty() : Optional.of(removed.getFirst()));
|
||||
}
|
||||
|
||||
public CompletableFuture<List<RemovedMessage>> remove(final UUID destinationUuid,
|
||||
final byte destinationDevice, final List<UUID> messageGuids) {
|
||||
public CompletableFuture<List<RemovedMessage>> remove(final UUID destinationUuid, final byte destinationDevice,
|
||||
final List<UUID> messageGuids) {
|
||||
|
||||
final Timer.Sample sample = Timer.start();
|
||||
|
||||
@@ -294,21 +295,25 @@ public class MessagesCache extends RedisClusterPubSubAdapter<String, String> imp
|
||||
.thenApplyAsync(serialized -> {
|
||||
|
||||
final List<RemovedMessage> removedMessages = new ArrayList<>(serialized.size());
|
||||
final List<byte[]> sharedMrmKeysToUpdate = new ArrayList<>();
|
||||
final Map<ServiceIdentifier, List<byte[]>> serviceIdentifierToMrmKeys = new HashMap<>();
|
||||
|
||||
for (final byte[] bytes : serialized) {
|
||||
try {
|
||||
final MessageProtos.Envelope envelope = MessageProtos.Envelope.parseFrom(bytes);
|
||||
removedMessages.add(RemovedMessage.fromEnvelope(envelope));
|
||||
if (envelope.hasSharedMrmKey()) {
|
||||
sharedMrmKeysToUpdate.add(envelope.getSharedMrmKey().toByteArray());
|
||||
serviceIdentifierToMrmKeys.computeIfAbsent(
|
||||
ServiceIdentifier.valueOf(envelope.getDestinationServiceId()), ignored -> new ArrayList<>())
|
||||
.add(envelope.getSharedMrmKey().toByteArray());
|
||||
}
|
||||
} catch (final InvalidProtocolBufferException e) {
|
||||
logger.warn("Failed to parse envelope", e);
|
||||
}
|
||||
}
|
||||
|
||||
removeRecipientViewFromMrmData(sharedMrmKeysToUpdate, destinationUuid, destinationDevice);
|
||||
serviceIdentifierToMrmKeys.forEach(
|
||||
(serviceId, keysToUpdate) -> removeRecipientViewFromMrmData(keysToUpdate, serviceId, destinationDevice));
|
||||
|
||||
return removedMessages;
|
||||
}, messageDeletionExecutorService).whenComplete((ignored, throwable) -> sample.stop(removeByGuidTimer));
|
||||
|
||||
@@ -431,8 +436,9 @@ public class MessagesCache extends RedisClusterPubSubAdapter<String, String> imp
|
||||
final Experiment experiment = new Experiment(MRM_VIEWS_EXPERIMENT_NAME);
|
||||
|
||||
final byte[] key = mrmMessage.getSharedMrmKey().toByteArray();
|
||||
final byte[] sharedMrmViewKey = MessagesCache.getSharedMrmViewKey(new AciServiceIdentifier(destinationUuid),
|
||||
destinationDevice);
|
||||
final byte[] sharedMrmViewKey = MessagesCache.getSharedMrmViewKey(
|
||||
// the message might be addressed to the account's PNI, so use the service ID from the envelope
|
||||
ServiceIdentifier.valueOf(mrmMessage.getDestinationServiceId()), destinationDevice);
|
||||
|
||||
final Mono<MessageProtos.Envelope> mrmMessageMono = Mono.from(redisCluster.withBinaryClusterReactive(
|
||||
conn -> conn.reactive().hmget(key, "data".getBytes(StandardCharsets.UTF_8), sharedMrmViewKey)
|
||||
@@ -469,7 +475,7 @@ public class MessagesCache extends RedisClusterPubSubAdapter<String, String> imp
|
||||
/**
|
||||
* Makes a best-effort attempt at asynchronously updating (and removing when empty) the MRM data structure
|
||||
*/
|
||||
void removeRecipientViewFromMrmData(final List<byte[]> sharedMrmKeys, final UUID accountUuid,
|
||||
void removeRecipientViewFromMrmData(final List<byte[]> sharedMrmKeys, final ServiceIdentifier serviceIdentifier,
|
||||
final byte deviceId) {
|
||||
|
||||
if (sharedMrmKeys.isEmpty()) {
|
||||
@@ -481,7 +487,7 @@ public class MessagesCache extends RedisClusterPubSubAdapter<String, String> imp
|
||||
.collectMultimap(SlotHash::getSlot)
|
||||
.flatMapMany(slotsAndKeys -> Flux.fromIterable(slotsAndKeys.values()))
|
||||
.flatMap(
|
||||
keys -> removeRecipientViewFromMrmDataScript.execute(keys, new AciServiceIdentifier(accountUuid), deviceId),
|
||||
keys -> removeRecipientViewFromMrmDataScript.execute(keys, serviceIdentifier, deviceId),
|
||||
REMOVE_MRM_RECIPIENT_VIEW_CONCURRENCY)
|
||||
.doOnNext(sharedMrmDataKeyRemovedCounter::increment)
|
||||
.onErrorResume(e -> {
|
||||
@@ -493,8 +499,7 @@ public class MessagesCache extends RedisClusterPubSubAdapter<String, String> imp
|
||||
.subscribe();
|
||||
}
|
||||
|
||||
private Mono<Pair<List<byte[]>, Long>> getNextMessagePage(final UUID destinationUuid,
|
||||
final byte destinationDevice,
|
||||
private Mono<Pair<List<byte[]>, Long>> getNextMessagePage(final UUID destinationUuid, final byte destinationDevice,
|
||||
long messageId) {
|
||||
|
||||
return getItemsScript.execute(destinationUuid, destinationDevice, PAGE_SIZE, messageId)
|
||||
@@ -520,22 +525,40 @@ public class MessagesCache extends RedisClusterPubSubAdapter<String, String> imp
|
||||
@VisibleForTesting
|
||||
List<MessageProtos.Envelope> getMessagesToPersist(final UUID accountUuid, final byte destinationDevice,
|
||||
final int limit) {
|
||||
return getMessagesTimer.record(() -> {
|
||||
final List<ScoredValue<byte[]>> scoredMessages = redisCluster.withBinaryCluster(
|
||||
connection -> connection.sync()
|
||||
.zrangeWithScores(getMessageQueueKey(accountUuid, destinationDevice), 0, limit));
|
||||
final List<MessageProtos.Envelope> envelopes = new ArrayList<>(scoredMessages.size());
|
||||
|
||||
for (final ScoredValue<byte[]> scoredMessage : scoredMessages) {
|
||||
try {
|
||||
envelopes.add(MessageProtos.Envelope.parseFrom(scoredMessage.getValue()));
|
||||
} catch (InvalidProtocolBufferException e) {
|
||||
logger.warn("Failed to parse envelope", e);
|
||||
}
|
||||
}
|
||||
final Timer.Sample sample = Timer.start();
|
||||
|
||||
return envelopes;
|
||||
});
|
||||
final List<byte[]> messages = redisCluster.withBinaryCluster(connection ->
|
||||
connection.sync().zrange(getMessageQueueKey(accountUuid, destinationDevice), 0, limit));
|
||||
|
||||
return Flux.fromIterable(messages)
|
||||
.mapNotNull(message -> {
|
||||
try {
|
||||
return MessageProtos.Envelope.parseFrom(message);
|
||||
} catch (InvalidProtocolBufferException e) {
|
||||
logger.warn("Failed to parse envelope", e);
|
||||
return null;
|
||||
}
|
||||
})
|
||||
.concatMap(message -> {
|
||||
final Mono<MessageProtos.Envelope> messageMono;
|
||||
if (message.hasSharedMrmKey()) {
|
||||
final Mono<?> experimentMono = maybeRunMrmViewExperiment(message, accountUuid, destinationDevice);
|
||||
|
||||
// mrm views phase 1: messageMono for sharedMrmKey is always Mono.just(), because messages always have content
|
||||
// To avoid races, wait for the experiment to run, but ignore any errors
|
||||
messageMono = experimentMono
|
||||
.onErrorComplete()
|
||||
.then(Mono.just(message.toBuilder().clearSharedMrmKey().build()));
|
||||
} else {
|
||||
messageMono = Mono.just(message);
|
||||
}
|
||||
|
||||
return messageMono;
|
||||
})
|
||||
.collectList()
|
||||
.doOnTerminate(() -> sample.stop(getMessagesTimer))
|
||||
.block(Duration.ofSeconds(5));
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> clear(final UUID destinationUuid) {
|
||||
@@ -556,7 +579,7 @@ public class MessagesCache extends RedisClusterPubSubAdapter<String, String> imp
|
||||
return Mono.empty();
|
||||
}
|
||||
|
||||
final List<byte[]> mrmKeys = new ArrayList<>(messagesToProcess.size());
|
||||
final Map<ServiceIdentifier, List<byte[]>> serviceIdentifierToMrmKeys = new HashMap<>();
|
||||
final List<String> processedMessages = new ArrayList<>(messagesToProcess.size());
|
||||
for (byte[] serialized : messagesToProcess) {
|
||||
try {
|
||||
@@ -565,14 +588,17 @@ public class MessagesCache extends RedisClusterPubSubAdapter<String, String> imp
|
||||
processedMessages.add(message.getServerGuid());
|
||||
|
||||
if (message.hasSharedMrmKey()) {
|
||||
mrmKeys.add(message.getSharedMrmKey().toByteArray());
|
||||
serviceIdentifierToMrmKeys.computeIfAbsent(ServiceIdentifier.valueOf(message.getDestinationServiceId()),
|
||||
ignored -> new ArrayList<>())
|
||||
.add(message.getSharedMrmKey().toByteArray());
|
||||
}
|
||||
} catch (final InvalidProtocolBufferException e) {
|
||||
logger.warn("Failed to parse envelope", e);
|
||||
}
|
||||
}
|
||||
|
||||
removeRecipientViewFromMrmData(mrmKeys, destinationUuid, deviceId);
|
||||
serviceIdentifierToMrmKeys.forEach((serviceId, keysToUpdate) ->
|
||||
removeRecipientViewFromMrmData(keysToUpdate, serviceId, deviceId));
|
||||
|
||||
return removeQueueScript.execute(destinationUuid, deviceId, processedMessages);
|
||||
})
|
||||
@@ -770,9 +796,19 @@ public class MessagesCache extends RedisClusterPubSubAdapter<String, String> imp
|
||||
return ("user_queue_persisting::{" + accountUuid + "::" + deviceId + "}").getBytes(StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
static byte[] getSharedMrmViewKey(final AciServiceIdentifier serviceIdentifier, final byte deviceId) {
|
||||
static byte[] getSharedMrmViewKey(final ServiceId serviceId, final byte deviceId) {
|
||||
return getSharedMrmViewKey(serviceId.toServiceIdFixedWidthBinary(), deviceId);
|
||||
}
|
||||
|
||||
static byte[] getSharedMrmViewKey(final ServiceIdentifier serviceIdentifier, final byte deviceId) {
|
||||
return getSharedMrmViewKey(serviceIdentifier.toFixedWidthByteArray(), deviceId);
|
||||
}
|
||||
|
||||
private static byte[] getSharedMrmViewKey(final byte[] fixedWithServiceId, final byte deviceId) {
|
||||
assert fixedWithServiceId.length == 17;
|
||||
|
||||
final ByteBuffer keyBb = ByteBuffer.allocate(18);
|
||||
keyBb.put(serviceIdentifier.toFixedWidthByteArray());
|
||||
keyBb.put(fixedWithServiceId);
|
||||
keyBb.put(deviceId);
|
||||
assert !keyBb.hasRemaining();
|
||||
return keyBb.array();
|
||||
|
||||
+3
-4
@@ -23,6 +23,8 @@ class MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript {
|
||||
|
||||
private final ClusterLuaScript script;
|
||||
|
||||
static final String ERROR_KEY_EXISTS = "ERR key exists";
|
||||
|
||||
MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript(FaultTolerantRedisCluster redisCluster)
|
||||
throws IOException {
|
||||
this.script = ClusterLuaScript.fromResource(redisCluster, "lua/insert_shared_multirecipient_message_data.lua",
|
||||
@@ -40,10 +42,7 @@ class MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript {
|
||||
|
||||
message.getRecipients().forEach((serviceId, recipient) -> {
|
||||
for (byte device : recipient.getDevices()) {
|
||||
final byte[] key = new byte[18];
|
||||
System.arraycopy(serviceId.toServiceIdFixedWidthBinary(), 0, key, 0, 17);
|
||||
key[17] = device;
|
||||
args.add(key);
|
||||
args.add(MessagesCache.getSharedMrmViewKey(serviceId, device));
|
||||
args.add(message.serializedRecipientView(recipient));
|
||||
}
|
||||
});
|
||||
|
||||
+3
-2
@@ -10,7 +10,7 @@ import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.redis.ClusterLuaScript;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
|
||||
import reactor.core.publisher.Mono;
|
||||
@@ -30,8 +30,9 @@ class MessagesCacheRemoveRecipientViewFromMrmDataScript {
|
||||
"lua/remove_recipient_view_from_mrm_data.lua", ScriptOutputType.INTEGER);
|
||||
}
|
||||
|
||||
Mono<Long> execute(final Collection<byte[]> keysCollection, final AciServiceIdentifier serviceIdentifier,
|
||||
Mono<Long> execute(final Collection<byte[]> keysCollection, final ServiceIdentifier serviceIdentifier,
|
||||
final byte deviceId) {
|
||||
|
||||
final List<byte[]> keys = keysCollection instanceof List<byte[]>
|
||||
? (List<byte[]>) keysCollection
|
||||
: new ArrayList<>(keysCollection);
|
||||
|
||||
+12
-59
@@ -118,38 +118,24 @@ public class MessagesDynamoDb extends AbstractDynamoDbStore {
|
||||
}
|
||||
|
||||
public CompletableFuture<Boolean> mayHaveMessages(final UUID accountIdentifier, final Device device) {
|
||||
final List<CompletableFuture<Boolean>> mayHaveMessagesFutures =
|
||||
Stream.of(convertPartitionKeyDeprecated(accountIdentifier, device), convertPartitionKey(accountIdentifier, device))
|
||||
.distinct()
|
||||
.map(partitionKey -> dbAsyncClient.query(QueryRequest.builder()
|
||||
.tableName(tableName)
|
||||
.consistentRead(false)
|
||||
.limit(1)
|
||||
.keyConditionExpression("#part = :part")
|
||||
.expressionAttributeNames(Map.of("#part", KEY_PARTITION))
|
||||
.expressionAttributeValues(Map.of(":part", partitionKey)).build())
|
||||
.thenApply(queryResponse -> queryResponse.count() > 0))
|
||||
.toList();
|
||||
|
||||
return CompletableFuture.allOf(mayHaveMessagesFutures.toArray(EMPTY_FUTURE_ARRAY))
|
||||
.thenApply(ignored -> mayHaveMessagesFutures.stream().anyMatch(CompletableFuture::join));
|
||||
return
|
||||
dbAsyncClient.query(QueryRequest.builder()
|
||||
.tableName(tableName)
|
||||
.consistentRead(false)
|
||||
.limit(1)
|
||||
.keyConditionExpression("#part = :part")
|
||||
.expressionAttributeNames(Map.of("#part", KEY_PARTITION))
|
||||
.expressionAttributeValues(Map.of(":part", convertPartitionKey(accountIdentifier, device))).build())
|
||||
.thenApply(queryResponse -> queryResponse.count() > 0);
|
||||
}
|
||||
|
||||
public Publisher<MessageProtos.Envelope> load(final UUID destinationAccountUuid, final Device device, final Integer limit) {
|
||||
return Flux.concat(
|
||||
Stream.of(convertPartitionKeyDeprecated(destinationAccountUuid, device), convertPartitionKey(destinationAccountUuid, device))
|
||||
.distinct()
|
||||
.map(pk -> load(limit, pk))
|
||||
.toList());
|
||||
}
|
||||
|
||||
public Publisher<MessageProtos.Envelope> load(final Integer limit, final AttributeValue partitionKey) {
|
||||
QueryRequest.Builder queryRequestBuilder = QueryRequest.builder()
|
||||
.tableName(tableName)
|
||||
.consistentRead(true)
|
||||
.keyConditionExpression("#part = :part")
|
||||
.expressionAttributeNames(Map.of("#part", KEY_PARTITION))
|
||||
.expressionAttributeValues(Map.of(":part", partitionKey));
|
||||
.expressionAttributeValues(Map.of(":part", convertPartitionKey(destinationAccountUuid, device)));
|
||||
|
||||
if (limit != null) {
|
||||
// some callers don’t take advantage of reactive streams, so we want to support limiting the fetch size. Otherwise,
|
||||
@@ -173,19 +159,7 @@ public class MessagesDynamoDb extends AbstractDynamoDbStore {
|
||||
|
||||
public CompletableFuture<Optional<MessageProtos.Envelope>> deleteMessageByDestinationAndGuid(
|
||||
final UUID destinationAccountUuid, final Device destinationDevice, final UUID messageUuid) {
|
||||
return Stream.of(convertPartitionKey(destinationAccountUuid, destinationDevice),
|
||||
convertPartitionKeyDeprecated(destinationAccountUuid, destinationDevice))
|
||||
.distinct()
|
||||
.map(pk -> deleteMessageByDestinationAndGuid(pk, messageUuid))
|
||||
// this combines the futures by producing a future that returns an arbitrary nonempty
|
||||
// result if there is one, which should be OK because only one of the keys
|
||||
// should produce a nonempty result for any given message uuid
|
||||
.reduce((f, g) -> f.thenCombine(g, (a, b) -> a.or(() -> b)))
|
||||
.get();
|
||||
}
|
||||
|
||||
public CompletableFuture<Optional<MessageProtos.Envelope>> deleteMessageByDestinationAndGuid(
|
||||
final AttributeValue partitionKey, final UUID messageUuid) {
|
||||
final AttributeValue partitionKey = convertPartitionKey(destinationAccountUuid, destinationDevice);
|
||||
final QueryRequest queryRequest = QueryRequest.builder()
|
||||
.tableName(tableName)
|
||||
.indexName(LOCAL_INDEX_MESSAGE_UUID_NAME)
|
||||
@@ -227,22 +201,9 @@ public class MessagesDynamoDb extends AbstractDynamoDbStore {
|
||||
|
||||
public CompletableFuture<Optional<MessageProtos.Envelope>> deleteMessage(final UUID destinationAccountUuid,
|
||||
final Device destinationDevice, final UUID messageUuid, final long serverTimestamp) {
|
||||
return Stream.of(convertPartitionKey(destinationAccountUuid, destinationDevice),
|
||||
convertPartitionKeyDeprecated(destinationAccountUuid, destinationDevice))
|
||||
.distinct()
|
||||
.map(pk -> deleteMessage(pk, destinationDevice, messageUuid, serverTimestamp))
|
||||
// this combines the futures by producing a future that returns an arbitrary nonempty
|
||||
// result if there is one, which should be OK because only one of the keys
|
||||
// should produce a nonempty result for any given message uuid
|
||||
.reduce((f, g) -> f.thenCombine(g, (a, b) -> a.or(() -> b)))
|
||||
.get();
|
||||
}
|
||||
|
||||
public CompletableFuture<Optional<MessageProtos.Envelope>> deleteMessage(final AttributeValue partitionKey, final Device destinationDevice, final UUID messageUuid, final long serverTimestamp) {
|
||||
final AttributeValue sortKey = convertSortKey(serverTimestamp, messageUuid);
|
||||
DeleteItemRequest.Builder deleteItemRequest = DeleteItemRequest.builder()
|
||||
.tableName(tableName)
|
||||
.key(Map.of(KEY_PARTITION, partitionKey, KEY_SORT, sortKey))
|
||||
.key(Map.of(KEY_PARTITION, convertPartitionKey(destinationAccountUuid, destinationDevice), KEY_SORT, convertSortKey(serverTimestamp, messageUuid)))
|
||||
.returnValues(ReturnValue.ALL_OLD);
|
||||
|
||||
return dbAsyncClient.deleteItem(deleteItemRequest.build())
|
||||
@@ -278,14 +239,6 @@ public class MessagesDynamoDb extends AbstractDynamoDbStore {
|
||||
return AttributeValues.fromByteBuffer(byteBuffer.flip());
|
||||
}
|
||||
|
||||
private static AttributeValue convertPartitionKeyDeprecated(final UUID destinationAccountUuid, final Device destinationDevice) {
|
||||
final ByteBuffer byteBuffer = ByteBuffer.allocate(24);
|
||||
byteBuffer.putLong(destinationAccountUuid.getMostSignificantBits());
|
||||
byteBuffer.putLong(destinationAccountUuid.getLeastSignificantBits());
|
||||
byteBuffer.putLong(destinationDevice.getCreated() & ~0x7f + destinationDevice.getId());
|
||||
return AttributeValues.fromByteBuffer(byteBuffer.flip());
|
||||
}
|
||||
|
||||
private static AttributeValue convertSortKey(final long serverTimestamp, final UUID messageUuid) {
|
||||
final ByteBuffer byteBuffer = ByteBuffer.allocate(24);
|
||||
byteBuffer.putLong(serverTimestamp);
|
||||
|
||||
@@ -24,6 +24,7 @@ import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos.Envelope;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import reactor.core.observability.micrometer.Micrometer;
|
||||
@@ -207,17 +208,17 @@ public class MessagesManager {
|
||||
* @see MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript
|
||||
*/
|
||||
public byte[] insertSharedMultiRecipientMessagePayload(
|
||||
SealedSenderMultiRecipientMessage sealedSenderMultiRecipientMessage) {
|
||||
return messagesCache.insertSharedMultiRecipientMessagePayload(UUID.randomUUID(), sealedSenderMultiRecipientMessage);
|
||||
final SealedSenderMultiRecipientMessage sealedSenderMultiRecipientMessage) {
|
||||
return messagesCache.insertSharedMultiRecipientMessagePayload(sealedSenderMultiRecipientMessage);
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes the recipient's view from shared MRM data if necessary
|
||||
*/
|
||||
public void removeRecipientViewFromMrmData(final UUID destinationUuid, final byte destinationDeviceId,
|
||||
final Envelope message) {
|
||||
public void removeRecipientViewFromMrmData(final byte destinationDeviceId, final Envelope message) {
|
||||
if (message.hasSharedMrmKey()) {
|
||||
messagesCache.removeRecipientViewFromMrmData(List.of(message.getSharedMrmKey().toByteArray()), destinationUuid,
|
||||
messagesCache.removeRecipientViewFromMrmData(List.of(message.getSharedMrmKey().toByteArray()),
|
||||
ServiceIdentifier.valueOf(message.getDestinationServiceId()),
|
||||
destinationDeviceId);
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -222,7 +222,7 @@ record CommandDependencies(
|
||||
accountLockManager, keys, messagesManager, profilesManager,
|
||||
secureStorageClient, secureValueRecovery2Client, clientPresenceManager,
|
||||
registrationRecoveryPasswordsManager, clientPublicKeysManager, accountLockExecutor, clientPresenceExecutor,
|
||||
clock);
|
||||
clock, dynamicConfigurationManager);
|
||||
RateLimiters rateLimiters = RateLimiters.createAndValidate(configuration.getLimitsConfiguration(),
|
||||
dynamicConfigurationManager, rateLimitersCluster);
|
||||
final BackupsDb backupsDb =
|
||||
|
||||
+1
-4
@@ -61,10 +61,7 @@ public class MessagePersisterServiceCommand extends ServerCommand<WhisperServerC
|
||||
}
|
||||
|
||||
final MessagePersister messagePersister = new MessagePersister(deps.messagesCache(), deps.messagesManager(),
|
||||
deps.accountsManager(),
|
||||
deps.clientPresenceManager(),
|
||||
deps.keysManager(),
|
||||
deps.dynamicConfigurationManager(),
|
||||
deps.accountsManager(), deps.dynamicConfigurationManager(),
|
||||
Duration.ofMinutes(configuration.getMessageCacheConfiguration().getPersistDelayMinutes()),
|
||||
namespace.getInt(WORKER_COUNT));
|
||||
|
||||
|
||||
@@ -4,6 +4,10 @@ local sharedMrmKey = KEYS[1] -- [string] the key containing the shared MRM data
|
||||
local mrmData = ARGV[1] -- [bytes] the serialized multi-recipient message data
|
||||
-- the remainder of ARGV is list of recipient keys and view data
|
||||
|
||||
if 1 == redis.call("EXISTS", sharedMrmKey) then
|
||||
return redis.error_reply("ERR key exists")
|
||||
end
|
||||
|
||||
redis.call("HSET", sharedMrmKey, "data", mrmData);
|
||||
redis.call("EXPIRE", sharedMrmKey, 604800) -- 7 days
|
||||
|
||||
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
/*
|
||||
* Copyright 2024 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.captcha;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
|
||||
class HCaptchaResponseTest {
|
||||
|
||||
@Test
|
||||
void testParse() throws Exception {
|
||||
|
||||
final Instant challengeTs = Instant.parse("2024-09-13T21:36:15Z");
|
||||
|
||||
final HCaptchaResponse response =
|
||||
SystemMapper.jsonMapper().readValue("""
|
||||
{
|
||||
"success": "true",
|
||||
"challenge_ts": "2024-09-13T21:36:15.000000Z",
|
||||
"hostname": "example.com",
|
||||
"error-codes": ["one", "two"],
|
||||
"score": 0.5,
|
||||
"score_reason": ["three", "four"]
|
||||
}
|
||||
""", HCaptchaResponse.class);
|
||||
|
||||
assertEquals(challengeTs, response.challengeTs);
|
||||
assertEquals(List.of("one", "two"), response.errorCodes);
|
||||
assertEquals(List.of("three", "four"), response.scoreReasons);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -73,8 +73,7 @@ class MessageSenderTest {
|
||||
MessageProtos.Envelope.class);
|
||||
|
||||
verify(messagesManager).insert(any(), anyByte(), envelopeArgumentCaptor.capture());
|
||||
verify(messagesManager, never()).removeRecipientViewFromMrmData(any(), anyByte(),
|
||||
any(MessageProtos.Envelope.class));
|
||||
verify(messagesManager, never()).removeRecipientViewFromMrmData(anyByte(), any(MessageProtos.Envelope.class));
|
||||
|
||||
assertTrue(envelopeArgumentCaptor.getValue().getEphemeral());
|
||||
|
||||
@@ -96,7 +95,7 @@ class MessageSenderTest {
|
||||
}
|
||||
|
||||
verify(messagesManager, never()).insert(any(), anyByte(), any());
|
||||
verify(messagesManager).removeRecipientViewFromMrmData(any(), anyByte(), any(MessageProtos.Envelope.class));
|
||||
verify(messagesManager).removeRecipientViewFromMrmData(anyByte(), any(MessageProtos.Envelope.class));
|
||||
|
||||
verifyNoInteractions(pushNotificationManager);
|
||||
}
|
||||
|
||||
+2
-1
@@ -152,7 +152,8 @@ public class AccountCreationDeletionIntegrationTest {
|
||||
clientPublicKeysManager,
|
||||
accountLockExecutor,
|
||||
clientPresenceExecutor,
|
||||
CLOCK);
|
||||
CLOCK,
|
||||
dynamicConfigurationManager);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
|
||||
+2
-1
@@ -147,7 +147,8 @@ class AccountsManagerChangeNumberIntegrationTest {
|
||||
clientPublicKeysManager,
|
||||
accountLockExecutor,
|
||||
clientPresenceExecutor,
|
||||
mock(Clock.class));
|
||||
mock(Clock.class),
|
||||
dynamicConfigurationManager);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+2
-1
@@ -134,7 +134,8 @@ class AccountsManagerConcurrentModificationIntegrationTest {
|
||||
mock(ClientPublicKeysManager.class),
|
||||
mock(Executor.class),
|
||||
mock(Executor.class),
|
||||
mock(Clock.class)
|
||||
mock(Clock.class),
|
||||
dynamicConfigurationManager
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
+35
-4
@@ -48,6 +48,7 @@ import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionException;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Supplier;
|
||||
@@ -76,6 +77,7 @@ import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
|
||||
import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
|
||||
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecovery2Client;
|
||||
import org.whispersystems.textsecuregcm.securevaluerecovery.SecureValueRecoveryException;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager.UsernameReservation;
|
||||
import org.whispersystems.textsecuregcm.storage.Device.DeviceCapabilities;
|
||||
import org.whispersystems.textsecuregcm.tests.util.AccountsHelper;
|
||||
@@ -113,6 +115,8 @@ class AccountsManagerTest {
|
||||
private RedisAdvancedClusterAsyncCommands<String, String> asyncCommands;
|
||||
private TestClock clock;
|
||||
private AccountsManager accountsManager;
|
||||
private SecureValueRecovery2Client svr2Client;
|
||||
private DynamicConfiguration dynamicConfiguration;
|
||||
|
||||
private static final Answer<?> ACCOUNT_UPDATE_ANSWER = (answer) -> {
|
||||
// it is implicit in the update() contract is that a successful call will
|
||||
@@ -139,6 +143,7 @@ class AccountsManagerTest {
|
||||
profilesManager = mock(ProfilesManager.class);
|
||||
clientPresenceManager = mock(ClientPresenceManager.class);
|
||||
clientPublicKeysManager = mock(ClientPublicKeysManager.class);
|
||||
dynamicConfiguration = mock(DynamicConfiguration.class);
|
||||
|
||||
final Executor clientPresenceExecutor = mock(Executor.class);
|
||||
|
||||
@@ -175,7 +180,7 @@ class AccountsManagerTest {
|
||||
final SecureStorageClient storageClient = mock(SecureStorageClient.class);
|
||||
when(storageClient.deleteStoredData(any())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
final SecureValueRecovery2Client svr2Client = mock(SecureValueRecovery2Client.class);
|
||||
svr2Client = mock(SecureValueRecovery2Client.class);
|
||||
when(svr2Client.deleteBackups(any())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
final PhoneNumberIdentifiers phoneNumberIdentifiers = mock(PhoneNumberIdentifiers.class);
|
||||
@@ -189,9 +194,8 @@ class AccountsManagerTest {
|
||||
@SuppressWarnings("unchecked") final DynamicConfigurationManager<DynamicConfiguration> dynamicConfigurationManager =
|
||||
mock(DynamicConfigurationManager.class);
|
||||
|
||||
final DynamicConfiguration dynamicConfiguration = mock(DynamicConfiguration.class);
|
||||
|
||||
when(dynamicConfigurationManager.getConfiguration()).thenReturn(dynamicConfiguration);
|
||||
when(dynamicConfiguration.getSvrStatusCodesToIgnoreForAccountDeletion()).thenReturn(Collections.emptyList());
|
||||
|
||||
final AccountLockManager accountLockManager = mock(AccountLockManager.class);
|
||||
|
||||
@@ -218,6 +222,7 @@ class AccountsManagerTest {
|
||||
|
||||
clock = TestClock.now();
|
||||
|
||||
|
||||
accountsManager = new AccountsManager(
|
||||
accounts,
|
||||
phoneNumberIdentifiers,
|
||||
@@ -236,7 +241,33 @@ class AccountsManagerTest {
|
||||
clientPublicKeysManager,
|
||||
mock(Executor.class),
|
||||
clientPresenceExecutor,
|
||||
clock);
|
||||
clock,
|
||||
dynamicConfigurationManager);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void testDeleteWithSvrErrorStatusCodes(final String statusCode, final boolean expectError) throws InterruptedException {
|
||||
when(svr2Client.deleteBackups(any())).thenReturn(
|
||||
CompletableFuture.failedFuture(new SecureValueRecoveryException("Failed to delete backup", statusCode)));
|
||||
when(dynamicConfiguration.getSvrStatusCodesToIgnoreForAccountDeletion()).thenReturn(List.of("500"));
|
||||
|
||||
final AccountAttributes attributes = new AccountAttributes(false, 1, 2, null, null, true, null);
|
||||
|
||||
final Account createdAccount = createAccount("+18005550123", attributes);
|
||||
|
||||
if (expectError) {
|
||||
assertThrows(CompletionException.class, () -> accountsManager.delete(createdAccount, AccountsManager.DeletionReason.USER_REQUEST).toCompletableFuture().join());
|
||||
} else {
|
||||
assertDoesNotThrow(() -> accountsManager.delete(createdAccount, AccountsManager.DeletionReason.USER_REQUEST).toCompletableFuture().join());
|
||||
}
|
||||
}
|
||||
|
||||
private static Stream<Arguments> testDeleteWithSvrErrorStatusCodes() {
|
||||
return Stream.of(
|
||||
Arguments.of("500", false),
|
||||
Arguments.of("429", true)
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+2
-1
@@ -146,7 +146,8 @@ class AccountsManagerUsernameIntegrationTest {
|
||||
mock(ClientPublicKeysManager.class),
|
||||
Executors.newSingleThreadExecutor(),
|
||||
Executors.newSingleThreadExecutor(),
|
||||
mock(Clock.class));
|
||||
mock(Clock.class),
|
||||
dynamicConfigurationManager);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+2
-1
@@ -140,7 +140,8 @@ public class AddRemoveDeviceIntegrationTest {
|
||||
clientPublicKeysManager,
|
||||
accountLockExecutor,
|
||||
clientPresenceExecutor,
|
||||
CLOCK);
|
||||
CLOCK,
|
||||
dynamicConfigurationManager);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
|
||||
+1
-3
@@ -32,11 +32,9 @@ import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
|
||||
import org.whispersystems.textsecuregcm.redis.RedisClusterExtension;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamoDbExtensionSchema.Tables;
|
||||
import org.whispersystems.textsecuregcm.tests.util.DevicesHelper;
|
||||
|
||||
import reactor.core.scheduler.Scheduler;
|
||||
import reactor.core.scheduler.Schedulers;
|
||||
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
|
||||
@@ -85,7 +83,7 @@ class MessagePersisterIntegrationTest {
|
||||
messagesManager = new MessagesManager(messagesDynamoDb, messagesCache, mock(ReportMessageManager.class),
|
||||
messageDeletionExecutorService);
|
||||
messagePersister = new MessagePersister(messagesCache, messagesManager, accountsManager,
|
||||
mock(ClientPresenceManager.class), mock(KeysManager.class), dynamicConfigurationManager, PERSIST_DELAY, 1);
|
||||
dynamicConfigurationManager, PERSIST_DELAY, 1);
|
||||
|
||||
account = mock(Account.class);
|
||||
|
||||
|
||||
+2
-8
@@ -46,7 +46,6 @@ import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.stubbing.Answer;
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
|
||||
import org.whispersystems.textsecuregcm.redis.RedisClusterExtension;
|
||||
import org.whispersystems.textsecuregcm.tests.util.DevicesHelper;
|
||||
import reactor.core.scheduler.Scheduler;
|
||||
@@ -66,8 +65,6 @@ class MessagePersisterTest {
|
||||
private MessagesDynamoDb messagesDynamoDb;
|
||||
private MessagePersister messagePersister;
|
||||
private AccountsManager accountsManager;
|
||||
private ClientPresenceManager clientPresenceManager;
|
||||
private KeysManager keysManager;
|
||||
private MessagesManager messagesManager;
|
||||
private Account destinationAccount;
|
||||
|
||||
@@ -87,8 +84,6 @@ class MessagePersisterTest {
|
||||
|
||||
messagesDynamoDb = mock(MessagesDynamoDb.class);
|
||||
accountsManager = mock(AccountsManager.class);
|
||||
clientPresenceManager = mock(ClientPresenceManager.class);
|
||||
keysManager = mock(KeysManager.class);
|
||||
destinationAccount = mock(Account.class);;
|
||||
|
||||
when(accountsManager.getByAccountIdentifier(DESTINATION_ACCOUNT_UUID)).thenReturn(Optional.of(destinationAccount));
|
||||
@@ -105,11 +100,10 @@ class MessagePersisterTest {
|
||||
messageDeliveryScheduler = Schedulers.newBoundedElastic(10, 10_000, "messageDelivery");
|
||||
messagesCache = new MessagesCache(REDIS_CLUSTER_EXTENSION.getRedisCluster(), sharedExecutorService,
|
||||
messageDeliveryScheduler, sharedExecutorService, Clock.systemUTC(), dynamicConfigurationManager);
|
||||
messagePersister = new MessagePersister(messagesCache, messagesManager, accountsManager, clientPresenceManager,
|
||||
keysManager, dynamicConfigurationManager, PERSIST_DELAY, 1);
|
||||
messagePersister = new MessagePersister(messagesCache, messagesManager, accountsManager,
|
||||
dynamicConfigurationManager, PERSIST_DELAY, 1);
|
||||
|
||||
when(messagesManager.clear(any(UUID.class), anyByte())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
when(keysManager.deleteSingleUsePreKeys(any(), anyByte())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
|
||||
when(messagesManager.persistMessages(any(UUID.class), any(), any())).thenAnswer(invocation -> {
|
||||
final UUID destinationUuid = invocation.getArgument(0);
|
||||
|
||||
+26
-4
@@ -6,7 +6,9 @@
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
import io.lettuce.core.RedisCommandExecutionException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
@@ -14,11 +16,13 @@ import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.redis.RedisClusterExtension;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
|
||||
@@ -29,7 +33,7 @@ class MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScriptTest {
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void testInsert(final int count, final Map<AciServiceIdentifier, List<Byte>> destinations) throws Exception {
|
||||
void testInsert(final int count, final Map<ServiceIdentifier, List<Byte>> destinations) throws Exception {
|
||||
|
||||
final MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript insertMrmScript = new MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript(
|
||||
REDIS_CLUSTER_EXTENSION.getRedisCluster());
|
||||
@@ -41,11 +45,12 @@ class MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScriptTest {
|
||||
final int totalDevices = destinations.values().stream().mapToInt(List::size).sum();
|
||||
final long hashFieldCount = REDIS_CLUSTER_EXTENSION.getRedisCluster()
|
||||
.withBinaryCluster(conn -> conn.sync().hlen(sharedMrmKey));
|
||||
assertEquals(totalDevices + 1, hashFieldCount);
|
||||
// + 1 because of "data" field
|
||||
assertEquals(1 + totalDevices, hashFieldCount);
|
||||
}
|
||||
|
||||
public static List<Arguments> testInsert() {
|
||||
final Map<AciServiceIdentifier, List<Byte>> singleAccount = Map.of(
|
||||
final Map<ServiceIdentifier, List<Byte>> singleAccount = Map.of(
|
||||
new AciServiceIdentifier(UUID.randomUUID()), List.of((byte) 1, (byte) 2));
|
||||
|
||||
final List<Arguments> testCases = new ArrayList<>();
|
||||
@@ -54,7 +59,7 @@ class MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScriptTest {
|
||||
for (int j = 1000; j <= 30000; j += 1000) {
|
||||
|
||||
final Map<Integer, List<Byte>> deviceLists = new HashMap<>();
|
||||
final Map<AciServiceIdentifier, List<Byte>> manyAccounts = IntStream.range(0, j)
|
||||
final Map<ServiceIdentifier, List<Byte>> manyAccounts = IntStream.range(0, j)
|
||||
.mapToObj(i -> {
|
||||
final int deviceCount = 1 + i % 5;
|
||||
final List<Byte> devices = deviceLists.computeIfAbsent(deviceCount, count -> IntStream.rangeClosed(1, count)
|
||||
@@ -71,4 +76,21 @@ class MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScriptTest {
|
||||
return testCases;
|
||||
}
|
||||
|
||||
@Test
|
||||
void testInsertDuplicateKey() throws Exception {
|
||||
final MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript insertMrmScript = new MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript(
|
||||
REDIS_CLUSTER_EXTENSION.getRedisCluster());
|
||||
|
||||
final byte[] sharedMrmKey = MessagesCache.getSharedMrmKey(UUID.randomUUID());
|
||||
insertMrmScript.execute(sharedMrmKey,
|
||||
MessagesCacheTest.generateRandomMrmMessage(new AciServiceIdentifier(UUID.randomUUID()), Device.PRIMARY_ID));
|
||||
|
||||
final RedisCommandExecutionException e = assertThrows(RedisCommandExecutionException.class,
|
||||
() -> insertMrmScript.execute(sharedMrmKey,
|
||||
MessagesCacheTest.generateRandomMrmMessage(new AciServiceIdentifier(UUID.randomUUID()),
|
||||
Device.PRIMARY_ID)));
|
||||
|
||||
assertEquals(MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript.ERROR_KEY_EXISTS, e.getMessage());
|
||||
}
|
||||
|
||||
}
|
||||
+11
-10
@@ -22,6 +22,7 @@ import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.redis.RedisClusterExtension;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import reactor.core.publisher.Flux;
|
||||
@@ -34,7 +35,7 @@ class MessagesCacheRemoveRecipientViewFromMrmDataScriptTest {
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void testUpdateSingleKey(final Map<AciServiceIdentifier, List<Byte>> destinations) throws Exception {
|
||||
void testUpdateSingleKey(final Map<ServiceIdentifier, List<Byte>> destinations) throws Exception {
|
||||
|
||||
final MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript insertMrmScript = new MessagesCacheInsertSharedMultiRecipientPayloadAndViewsScript(
|
||||
REDIS_CLUSTER_EXTENSION.getRedisCluster());
|
||||
@@ -48,8 +49,8 @@ class MessagesCacheRemoveRecipientViewFromMrmDataScriptTest {
|
||||
|
||||
final long keysRemoved = Objects.requireNonNull(Flux.fromIterable(destinations.entrySet())
|
||||
.flatMap(e -> Flux.fromStream(e.getValue().stream().map(deviceId -> Tuples.of(e.getKey(), deviceId))))
|
||||
.flatMap(aciServiceIdentifierByteTuple -> removeRecipientViewFromMrmDataScript.execute(List.of(sharedMrmKey),
|
||||
aciServiceIdentifierByteTuple.getT1(), aciServiceIdentifierByteTuple.getT2()))
|
||||
.flatMap(serviceIdentifierByteTuple -> removeRecipientViewFromMrmDataScript.execute(List.of(sharedMrmKey),
|
||||
serviceIdentifierByteTuple.getT1(), serviceIdentifierByteTuple.getT2()))
|
||||
.reduce(Long::sum)
|
||||
.block(Duration.ofSeconds(35)));
|
||||
|
||||
@@ -60,18 +61,18 @@ class MessagesCacheRemoveRecipientViewFromMrmDataScriptTest {
|
||||
assertEquals(0, keyExists);
|
||||
}
|
||||
|
||||
public static List<Map<AciServiceIdentifier, List<Byte>>> testUpdateSingleKey() {
|
||||
final Map<AciServiceIdentifier, List<Byte>> singleAccount = Map.of(
|
||||
public static List<Map<ServiceIdentifier, List<Byte>>> testUpdateSingleKey() {
|
||||
final Map<ServiceIdentifier, List<Byte>> singleAccount = Map.of(
|
||||
new AciServiceIdentifier(UUID.randomUUID()), List.of((byte) 1, (byte) 2));
|
||||
|
||||
final List<Map<AciServiceIdentifier, List<Byte>>> testCases = new ArrayList<>();
|
||||
final List<Map<ServiceIdentifier, List<Byte>>> testCases = new ArrayList<>();
|
||||
testCases.add(singleAccount);
|
||||
|
||||
// Generate a more, from smallish to very large
|
||||
for (int j = 1000; j <= 81000; j *= 3) {
|
||||
|
||||
final Map<Integer, List<Byte>> deviceLists = new HashMap<>();
|
||||
final Map<AciServiceIdentifier, List<Byte>> manyAccounts = IntStream.range(0, j)
|
||||
final Map<ServiceIdentifier, List<Byte>> manyAccounts = IntStream.range(0, j)
|
||||
.mapToObj(i -> {
|
||||
final int deviceCount = 1 + i % 5;
|
||||
final List<Byte> devices = deviceLists.computeIfAbsent(deviceCount, count -> IntStream.rangeClosed(1, count)
|
||||
@@ -93,7 +94,7 @@ class MessagesCacheRemoveRecipientViewFromMrmDataScriptTest {
|
||||
void testUpdateManyKeys(int keyCount) throws Exception {
|
||||
|
||||
final List<byte[]> sharedMrmKeys = new ArrayList<>(keyCount);
|
||||
final AciServiceIdentifier aciServiceIdentifier = new AciServiceIdentifier(UUID.randomUUID());
|
||||
final ServiceIdentifier serviceIdentifier = new AciServiceIdentifier(UUID.randomUUID());
|
||||
final byte deviceId = 1;
|
||||
|
||||
for (int i = 0; i < keyCount; i++) {
|
||||
@@ -103,7 +104,7 @@ class MessagesCacheRemoveRecipientViewFromMrmDataScriptTest {
|
||||
|
||||
final byte[] sharedMrmKey = MessagesCache.getSharedMrmKey(UUID.randomUUID());
|
||||
insertMrmScript.execute(sharedMrmKey,
|
||||
MessagesCacheTest.generateRandomMrmMessage(aciServiceIdentifier, deviceId));
|
||||
MessagesCacheTest.generateRandomMrmMessage(serviceIdentifier, deviceId));
|
||||
|
||||
sharedMrmKeys.add(sharedMrmKey);
|
||||
}
|
||||
@@ -114,7 +115,7 @@ class MessagesCacheRemoveRecipientViewFromMrmDataScriptTest {
|
||||
final long keysRemoved = Objects.requireNonNull(Flux.fromIterable(sharedMrmKeys)
|
||||
.collectMultimap(SlotHash::getSlot)
|
||||
.flatMapMany(slotsAndKeys -> Flux.fromIterable(slotsAndKeys.values()))
|
||||
.flatMap(keys -> removeRecipientViewFromMrmDataScript.execute(keys, aciServiceIdentifier, deviceId))
|
||||
.flatMap(keys -> removeRecipientViewFromMrmDataScript.execute(keys, serviceIdentifier, deviceId))
|
||||
.reduce(Long::sum)
|
||||
.block(Duration.ofSeconds(5)));
|
||||
|
||||
|
||||
+96
-44
@@ -71,6 +71,7 @@ import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfigurati
|
||||
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicMessagesConfiguration;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
|
||||
import org.whispersystems.textsecuregcm.redis.RedisClusterExtension;
|
||||
import org.whispersystems.textsecuregcm.tests.util.RedisClusterHelper;
|
||||
@@ -206,8 +207,7 @@ class MessagesCacheTest {
|
||||
.collect(Collectors.toList())).get(5, TimeUnit.SECONDS);
|
||||
|
||||
assertEquals(messagesToRemove.stream().map(RemovedMessage::fromEnvelope).toList(), removedMessages);
|
||||
assertEquals(messagesToPreserve,
|
||||
messagesCache.getMessagesToPersist(DESTINATION_UUID, DESTINATION_DEVICE_ID, messageCount));
|
||||
assertEquals(messagesToPreserve, get(DESTINATION_UUID, DESTINATION_DEVICE_ID, messageCount));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -566,22 +566,82 @@ class MessagesCacheTest {
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {true, false})
|
||||
void testMultiRecipientMessage(final boolean sharedMrmKeyPresent) throws Exception {
|
||||
final UUID destinationUuid = UUID.randomUUID();
|
||||
final ServiceIdentifier destinationServiceId = new AciServiceIdentifier(UUID.randomUUID());
|
||||
final byte deviceId = 1;
|
||||
|
||||
final UUID mrmGuid = UUID.randomUUID();
|
||||
final SealedSenderMultiRecipientMessage mrm = generateRandomMrmMessage(
|
||||
new AciServiceIdentifier(destinationUuid), deviceId);
|
||||
final SealedSenderMultiRecipientMessage mrm = generateRandomMrmMessage(destinationServiceId, deviceId);
|
||||
|
||||
final byte[] sharedMrmDataKey;
|
||||
if (sharedMrmKeyPresent) {
|
||||
sharedMrmDataKey = messagesCache.insertSharedMultiRecipientMessagePayload(mrmGuid, mrm);
|
||||
sharedMrmDataKey = messagesCache.insertSharedMultiRecipientMessagePayload(mrm);
|
||||
} else {
|
||||
sharedMrmDataKey = new byte[]{1};
|
||||
}
|
||||
|
||||
final UUID guid = UUID.randomUUID();
|
||||
final MessageProtos.Envelope message = generateRandomMessage(guid, true)
|
||||
final MessageProtos.Envelope message = generateRandomMessage(guid, destinationServiceId, true)
|
||||
.toBuilder()
|
||||
// clear some things added by the helper
|
||||
.clearServerGuid()
|
||||
// mrm views phase 1: messages have content
|
||||
.setContent(
|
||||
ByteString.copyFrom(mrm.messageForRecipient(mrm.getRecipients().get(destinationServiceId.toLibsignal()))))
|
||||
.setSharedMrmKey(ByteString.copyFrom(sharedMrmDataKey))
|
||||
.build();
|
||||
messagesCache.insert(guid, destinationServiceId.uuid(), deviceId, message);
|
||||
|
||||
assertEquals(sharedMrmKeyPresent ? 1 : 0, (long) REDIS_CLUSTER_EXTENSION.getRedisCluster()
|
||||
.withBinaryCluster(conn -> conn.sync().exists(sharedMrmDataKey)));
|
||||
|
||||
final List<MessageProtos.Envelope> messages = get(destinationServiceId.uuid(), deviceId, 1);
|
||||
assertEquals(1, messages.size());
|
||||
assertEquals(guid, UUID.fromString(messages.getFirst().getServerGuid()));
|
||||
assertFalse(messages.getFirst().hasSharedMrmKey());
|
||||
|
||||
final SealedSenderMultiRecipientMessage.Recipient recipient = mrm.getRecipients()
|
||||
.get(destinationServiceId.toLibsignal());
|
||||
assertArrayEquals(mrm.messageForRecipient(recipient), messages.getFirst().getContent().toByteArray());
|
||||
|
||||
final Optional<RemovedMessage> removedMessage = messagesCache.remove(destinationServiceId.uuid(), deviceId, guid)
|
||||
.join();
|
||||
|
||||
assertTrue(removedMessage.isPresent());
|
||||
assertEquals(guid, UUID.fromString(removedMessage.get().serverGuid().toString()));
|
||||
assertTrue(get(destinationServiceId.uuid(), deviceId, 1).isEmpty());
|
||||
|
||||
// updating the shared MRM data is purely async, so we just wait for it
|
||||
assertTimeoutPreemptively(Duration.ofSeconds(1), () -> {
|
||||
boolean exists;
|
||||
do {
|
||||
exists = 1 == REDIS_CLUSTER_EXTENSION.getRedisCluster()
|
||||
.withBinaryCluster(conn -> conn.sync().exists(sharedMrmDataKey));
|
||||
} while (exists);
|
||||
}, "Shared MRM data should be deleted asynchronously");
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {true, false})
|
||||
void testGetMessagesToPersist(final boolean sharedMrmKeyPresent) throws Exception {
|
||||
final UUID destinationUuid = UUID.randomUUID();
|
||||
final byte deviceId = 1;
|
||||
|
||||
final UUID messageGuid = UUID.randomUUID();
|
||||
final MessageProtos.Envelope message = generateRandomMessage(destinationUuid, true);
|
||||
|
||||
messagesCache.insert(messageGuid, destinationUuid, deviceId, message);
|
||||
|
||||
final SealedSenderMultiRecipientMessage mrm = generateRandomMrmMessage(
|
||||
new AciServiceIdentifier(destinationUuid), deviceId);
|
||||
|
||||
final byte[] sharedMrmDataKey;
|
||||
if (sharedMrmKeyPresent) {
|
||||
sharedMrmDataKey = messagesCache.insertSharedMultiRecipientMessagePayload(mrm);
|
||||
} else {
|
||||
sharedMrmDataKey = new byte[]{1};
|
||||
}
|
||||
|
||||
final UUID mrmMessageGuid = UUID.randomUUID();
|
||||
final MessageProtos.Envelope mrmMessage = generateRandomMessage(mrmMessageGuid, true)
|
||||
.toBuilder()
|
||||
// clear some things added by the helper
|
||||
.clearServerGuid()
|
||||
@@ -590,35 +650,22 @@ class MessagesCacheTest {
|
||||
ByteString.copyFrom(mrm.messageForRecipient(mrm.getRecipients().get(new ServiceId.Aci(destinationUuid)))))
|
||||
.setSharedMrmKey(ByteString.copyFrom(sharedMrmDataKey))
|
||||
.build();
|
||||
messagesCache.insert(guid, destinationUuid, deviceId, message);
|
||||
messagesCache.insert(mrmMessageGuid, destinationUuid, deviceId, mrmMessage);
|
||||
|
||||
assertEquals(sharedMrmKeyPresent ? 1 : 0, (long) REDIS_CLUSTER_EXTENSION.getRedisCluster()
|
||||
.withBinaryCluster(conn -> conn.sync().exists(MessagesCache.getSharedMrmKey(mrmGuid))));
|
||||
final List<MessageProtos.Envelope> messages = get(destinationUuid, deviceId, 100);
|
||||
|
||||
final List<MessageProtos.Envelope> messages = get(destinationUuid, deviceId, 1);
|
||||
assertEquals(1, messages.size());
|
||||
assertEquals(guid, UUID.fromString(messages.getFirst().getServerGuid()));
|
||||
assertFalse(messages.getFirst().hasSharedMrmKey());
|
||||
assertEquals(2, messages.size());
|
||||
|
||||
final SealedSenderMultiRecipientMessage.Recipient recipient = mrm.getRecipients()
|
||||
.get(new ServiceId.Aci(destinationUuid));
|
||||
assertArrayEquals(mrm.messageForRecipient(recipient), messages.getFirst().getContent().toByteArray());
|
||||
assertEquals(message.toBuilder()
|
||||
.setServerGuid(messageGuid.toString())
|
||||
.build(),
|
||||
messages.getFirst());
|
||||
|
||||
final Optional<RemovedMessage> removedMessage = messagesCache.remove(destinationUuid, deviceId, guid)
|
||||
.join();
|
||||
|
||||
assertTrue(removedMessage.isPresent());
|
||||
assertEquals(guid, UUID.fromString(removedMessage.get().serverGuid().toString()));
|
||||
assertTrue(get(destinationUuid, deviceId, 1).isEmpty());
|
||||
|
||||
// updating the shared MRM data is purely async, so we just wait for it
|
||||
assertTimeoutPreemptively(Duration.ofSeconds(1), () -> {
|
||||
boolean exists;
|
||||
do {
|
||||
exists = 1 == REDIS_CLUSTER_EXTENSION.getRedisCluster()
|
||||
.withBinaryCluster(conn -> conn.sync().exists(MessagesCache.getSharedMrmKey(mrmGuid)));
|
||||
} while (exists);
|
||||
});
|
||||
assertEquals(mrmMessage.toBuilder().
|
||||
clearSharedMrmKey().
|
||||
setServerGuid(mrmMessageGuid.toString())
|
||||
.build(),
|
||||
messages.getLast());
|
||||
}
|
||||
|
||||
private List<MessageProtos.Envelope> get(final UUID destinationUuid, final byte destinationDeviceId,
|
||||
@@ -628,7 +675,6 @@ class MessagesCacheTest {
|
||||
.collectList()
|
||||
.block();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Nested
|
||||
@@ -828,10 +874,17 @@ class MessagesCacheTest {
|
||||
}
|
||||
|
||||
private MessageProtos.Envelope generateRandomMessage(final UUID messageGuid, final boolean sealedSender) {
|
||||
return generateRandomMessage(messageGuid, sealedSender, serialTimestamp++);
|
||||
return generateRandomMessage(messageGuid, new AciServiceIdentifier(UUID.randomUUID()), sealedSender,
|
||||
serialTimestamp++);
|
||||
}
|
||||
|
||||
private MessageProtos.Envelope generateRandomMessage(final UUID messageGuid, final boolean sealedSender,
|
||||
private MessageProtos.Envelope generateRandomMessage(final UUID messageGuid,
|
||||
final ServiceIdentifier destinationServiceId, final boolean sealedSender) {
|
||||
return generateRandomMessage(messageGuid, destinationServiceId, sealedSender, serialTimestamp++);
|
||||
}
|
||||
|
||||
private MessageProtos.Envelope generateRandomMessage(final UUID messageGuid,
|
||||
final ServiceIdentifier destinationServiceId, final boolean sealedSender,
|
||||
final long timestamp) {
|
||||
final MessageProtos.Envelope.Builder envelopeBuilder = MessageProtos.Envelope.newBuilder()
|
||||
.setClientTimestamp(timestamp)
|
||||
@@ -839,7 +892,7 @@ class MessagesCacheTest {
|
||||
.setContent(ByteString.copyFromUtf8(RandomStringUtils.randomAlphanumeric(256)))
|
||||
.setType(MessageProtos.Envelope.Type.CIPHERTEXT)
|
||||
.setServerGuid(messageGuid.toString())
|
||||
.setDestinationServiceId(UUID.randomUUID().toString());
|
||||
.setDestinationServiceId(destinationServiceId.toServiceIdentifierString());
|
||||
|
||||
if (!sealedSender) {
|
||||
envelopeBuilder.setSourceDevice(random.nextInt(Device.MAXIMUM_DEVICE_ID) + 1)
|
||||
@@ -850,8 +903,7 @@ class MessagesCacheTest {
|
||||
}
|
||||
|
||||
static SealedSenderMultiRecipientMessage generateRandomMrmMessage(
|
||||
Map<AciServiceIdentifier, List<Byte>> destinations) {
|
||||
|
||||
Map<ServiceIdentifier, List<Byte>> destinations) {
|
||||
|
||||
try {
|
||||
final ByteBuffer prefix = ByteBuffer.allocate(7);
|
||||
@@ -861,10 +913,10 @@ class MessagesCacheTest {
|
||||
|
||||
List<ByteBuffer> recipients = new ArrayList<>(destinations.size());
|
||||
|
||||
for (Map.Entry<AciServiceIdentifier, List<Byte>> aciServiceIdentifierAndDeviceIds : destinations.entrySet()) {
|
||||
for (Map.Entry<ServiceIdentifier, List<Byte>> serviceIdentifierAndDeviceIds : destinations.entrySet()) {
|
||||
|
||||
final AciServiceIdentifier destination = aciServiceIdentifierAndDeviceIds.getKey();
|
||||
final List<Byte> deviceIds = aciServiceIdentifierAndDeviceIds.getValue();
|
||||
final ServiceIdentifier destination = serviceIdentifierAndDeviceIds.getKey();
|
||||
final List<Byte> deviceIds = serviceIdentifierAndDeviceIds.getValue();
|
||||
|
||||
assert deviceIds.size() < 255;
|
||||
|
||||
@@ -900,10 +952,10 @@ class MessagesCacheTest {
|
||||
}
|
||||
}
|
||||
|
||||
static SealedSenderMultiRecipientMessage generateRandomMrmMessage(AciServiceIdentifier destination,
|
||||
static SealedSenderMultiRecipientMessage generateRandomMrmMessage(ServiceIdentifier destination,
|
||||
byte... deviceIds) {
|
||||
|
||||
final Map<AciServiceIdentifier, List<Byte>> destinations = new HashMap<>();
|
||||
final Map<ServiceIdentifier, List<Byte>> destinations = new HashMap<>();
|
||||
destinations.put(destination, Arrays.asList(ArrayUtils.toObject(deviceIds)));
|
||||
return generateRandomMrmMessage(destinations);
|
||||
}
|
||||
|
||||
@@ -367,6 +367,10 @@ subscription: # configuration for Stripe subscriptions
|
||||
backupExpiration: P30D
|
||||
backupGracePeriod: P15D
|
||||
backupFreeTierMediaDuration: P30D
|
||||
backupLevels:
|
||||
201:
|
||||
playProductId: EXAMPLE
|
||||
prices: {}
|
||||
levels:
|
||||
500:
|
||||
badge: EXAMPLE
|
||||
|
||||
+1
-1
Submodule spam-filter updated: 7c8ead1bd4...ae611a4f9c.
Reference in new issue
Block a user