Compare commits

...
5 Commits
19 changed files with 78 additions and 542 deletions

No files matched your search

-5
View File
@@ -229,11 +229,6 @@ unidentifiedDelivery:
privateKey: ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789AAAAAAA
expiresDays: 7
voiceVerification:
url: https://cdn-ca.signal.org/verification/
locales:
- en
recaptcha:
projectPath: projects/example
credentialConfigurationJson: "{ }" # service account configuration for backend authentication
@@ -49,7 +49,6 @@ import org.whispersystems.textsecuregcm.configuration.SubscriptionConfiguration;
import org.whispersystems.textsecuregcm.configuration.TestDeviceConfiguration;
import org.whispersystems.textsecuregcm.configuration.UnidentifiedDeliveryConfiguration;
import org.whispersystems.textsecuregcm.configuration.UsernameConfiguration;
import org.whispersystems.textsecuregcm.configuration.VoiceVerificationConfiguration;
import org.whispersystems.textsecuregcm.configuration.ZkConfig;
import org.whispersystems.websocket.configuration.WebSocketConfiguration;
@@ -191,11 +190,6 @@ public class WhisperServerConfiguration extends Configuration {
@JsonProperty
private UnidentifiedDeliveryConfiguration unidentifiedDelivery;
@Valid
@NotNull
@JsonProperty
private VoiceVerificationConfiguration voiceVerification;
@Valid
@NotNull
@JsonProperty
@@ -303,10 +297,6 @@ public class WhisperServerConfiguration extends Configuration {
return hCaptcha;
}
public VoiceVerificationConfiguration getVoiceVerificationConfiguration() {
return voiceVerification;
}
public WebSocketConfiguration getWebSocketConfiguration() {
return webSocket;
}
@@ -70,11 +70,6 @@ import org.signal.libsignal.zkgroup.receipts.ServerZkReceiptOperations;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.dispatch.DispatchManager;
import org.whispersystems.textsecuregcm.spam.SpamFilter;
import org.whispersystems.textsecuregcm.spam.FilterSpam;
import org.whispersystems.textsecuregcm.spam.RateLimitChallengeListener;
import org.whispersystems.textsecuregcm.spam.ReportSpamTokenHandler;
import org.whispersystems.textsecuregcm.spam.ReportSpamTokenProvider;
import org.whispersystems.textsecuregcm.auth.AccountAuthenticator;
import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
import org.whispersystems.textsecuregcm.auth.CertificateGenerator;
@@ -112,7 +107,6 @@ import org.whispersystems.textsecuregcm.controllers.SecureStorageController;
import org.whispersystems.textsecuregcm.controllers.SecureValueRecovery2Controller;
import org.whispersystems.textsecuregcm.controllers.StickerController;
import org.whispersystems.textsecuregcm.controllers.SubscriptionController;
import org.whispersystems.textsecuregcm.controllers.VoiceVerificationController;
import org.whispersystems.textsecuregcm.currency.CoinMarketCapClient;
import org.whispersystems.textsecuregcm.currency.CurrencyConversionManager;
import org.whispersystems.textsecuregcm.currency.FixerClient;
@@ -168,6 +162,10 @@ import org.whispersystems.textsecuregcm.s3.PolicySigner;
import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
import org.whispersystems.textsecuregcm.securebackup.SecureBackupClient;
import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
import org.whispersystems.textsecuregcm.spam.FilterSpam;
import org.whispersystems.textsecuregcm.spam.RateLimitChallengeListener;
import org.whispersystems.textsecuregcm.spam.ReportSpamTokenProvider;
import org.whispersystems.textsecuregcm.spam.SpamFilter;
import org.whispersystems.textsecuregcm.sqs.DirectoryQueue;
import org.whispersystems.textsecuregcm.storage.AccountCleaner;
import org.whispersystems.textsecuregcm.storage.AccountDatabaseCrawler;
@@ -651,8 +649,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
ImmutableSet.of(AuthenticatedAccount.class, DisabledPermittedAuthenticatedAccount.class)));
environment.jersey().register(new WebsocketRefreshApplicationEventListener(accountsManager, clientPresenceManager));
environment.jersey().register(new TimestampResponseFilter());
environment.jersey().register(new VoiceVerificationController(config.getVoiceVerificationConfiguration().getUrl(),
config.getVoiceVerificationConfiguration().getLocales()));
///
WebSocketEnvironment<AuthenticatedAccount> webSocketEnvironment = new WebSocketEnvironment<>(environment,
@@ -679,7 +675,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
boolean registeredSpamFilter = false;
ReportSpamTokenProvider reportSpamTokenProvider = null;
ReportSpamTokenHandler reportSpamTokenHandler = null;
for (final SpamFilter filter : ServiceLoader.load(SpamFilter.class)) {
if (filter.getClass().isAnnotationPresent(FilterSpam.class)) {
@@ -693,12 +688,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
log.info("Multiple spam report token providers found. Using the first.");
}
ReportSpamTokenHandler thisHandler = filter.getReportSpamTokenHandler();
if (reportSpamTokenHandler == null) {
reportSpamTokenHandler = thisHandler;
} else if (thisProvider != null) {
log.info("Multiple spam report token handlers found. Using the first.");
}
filter.getReportedMessageListeners().forEach(reportMessageManager::addListener);
environment.lifecycle().manage(filter);
environment.jersey().register(filter);
@@ -728,10 +718,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
reportSpamTokenProvider = ReportSpamTokenProvider.noop();
}
if (reportSpamTokenHandler == null) {
reportSpamTokenHandler = ReportSpamTokenHandler.noop();
}
final List<Object> commonControllers = Lists.newArrayList(
new ArtController(rateLimiters, artCredentialsGenerator),
new AttachmentControllerV2(rateLimiters, config.getAwsAttachmentsConfiguration().getAccessKey(), config.getAwsAttachmentsConfiguration().getAccessSecret(), config.getAwsAttachmentsConfiguration().getRegion(), config.getAwsAttachmentsConfiguration().getBucket()),
@@ -744,7 +730,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
new DonationController(clock, zkReceiptOperations, redeemedReceiptsManager, accountsManager, config.getBadges(),
ReceiptCredentialPresentation::new),
new MessageController(rateLimiters, messageSender, receiptSender, accountsManager, deletedAccountsManager, messagesManager, pushNotificationManager, reportMessageManager, multiRecipientMessageExecutor,
reportSpamTokenProvider, reportSpamTokenHandler),
reportSpamTokenProvider),
new PaymentsController(currencyManager, paymentsCredentialsGenerator),
new ProfileController(clock, rateLimiters, accountsManager, profilesManager, dynamicConfigurationManager,
profileBadgeConverter, config.getBadges(), cdnS3Client, profileCdnPolicyGenerator, profileCdnPolicySigner,
@@ -1,35 +0,0 @@
/*
* Copyright 2013-2020 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.configuration;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
public class VoiceVerificationConfiguration {
@JsonProperty
@Valid
@NotEmpty
private String url;
@JsonProperty
@Valid
@NotNull
private List<String> locales;
public String getUrl() {
return url;
}
public Set<String> getLocales() {
return new HashSet<>(locales);
}
}
@@ -62,9 +62,6 @@ import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.spam.FilterSpam;
import org.whispersystems.textsecuregcm.spam.ReportSpamTokenHandler;
import org.whispersystems.textsecuregcm.spam.ReportSpamTokenProvider;
import org.whispersystems.textsecuregcm.auth.Anonymous;
import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
import org.whispersystems.textsecuregcm.auth.CombinedUnidentifiedSenderAccessKeys;
@@ -92,6 +89,8 @@ import org.whispersystems.textsecuregcm.push.MessageSender;
import org.whispersystems.textsecuregcm.push.NotPushRegisteredException;
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
import org.whispersystems.textsecuregcm.push.ReceiptSender;
import org.whispersystems.textsecuregcm.spam.FilterSpam;
import org.whispersystems.textsecuregcm.spam.ReportSpamTokenProvider;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.DeletedAccountsManager;
@@ -123,7 +122,6 @@ public class MessageController {
private final ReportMessageManager reportMessageManager;
private final ExecutorService multiRecipientMessageExecutor;
private final ReportSpamTokenProvider reportSpamTokenProvider;
private final ReportSpamTokenHandler reportSpamTokenHandler;
private static final String REJECT_OVERSIZE_MESSAGE_COUNTER = name(MessageController.class, "rejectOversizeMessage");
private static final String SENT_MESSAGE_COUNTER_NAME = name(MessageController.class, "sentMessages");
@@ -131,7 +129,6 @@ public class MessageController {
private static final String OUTGOING_MESSAGE_LIST_SIZE_BYTES_DISTRIBUTION_NAME = name(MessageController.class, "outgoingMessageListSizeBytes");
private static final String RATE_LIMITED_MESSAGE_COUNTER_NAME = name(MessageController.class, "rateLimitedMessage");
private static final String REJECT_INVALID_ENVELOPE_TYPE = name(MessageController.class, "rejectInvalidEnvelopeType");
private static final String REPORT_SPAM_TOKENS_RECEIVED_COUNTER_NAME = name(MessageController.class, "reportSpamTokensReceived");
private static final String EPHEMERAL_TAG_NAME = "ephemeral";
private static final String SENDER_TYPE_TAG_NAME = "senderType";
@@ -156,8 +153,7 @@ public class MessageController {
PushNotificationManager pushNotificationManager,
ReportMessageManager reportMessageManager,
@Nonnull ExecutorService multiRecipientMessageExecutor,
@Nonnull ReportSpamTokenProvider reportSpamTokenProvider,
@Nonnull ReportSpamTokenHandler reportSpamTokenHandler) {
@Nonnull ReportSpamTokenProvider reportSpamTokenProvider) {
this.rateLimiters = rateLimiters;
this.messageSender = messageSender;
this.receiptSender = receiptSender;
@@ -168,8 +164,6 @@ public class MessageController {
this.reportMessageManager = reportMessageManager;
this.multiRecipientMessageExecutor = Objects.requireNonNull(multiRecipientMessageExecutor);
this.reportSpamTokenProvider = reportSpamTokenProvider;
this.reportSpamTokenHandler = reportSpamTokenHandler;
}
@Timed
@@ -643,22 +637,10 @@ public class MessageController {
UUID spamReporterUuid = auth.getAccount().getUuid();
// spam report token is optional, but if provided ensure it is valid base64.
byte[] spamReportToken = null;
if (spamReport != null) {
try {
spamReportToken = Base64.getDecoder().decode(spamReport.token());
Metrics.counter(REPORT_SPAM_TOKENS_RECEIVED_COUNTER_NAME).increment();
} catch (IllegalArgumentException e) {
logger.error("Invalid report spam token provided", e);
throw new WebApplicationException(Response.status(400).build());
}
}
final Optional<byte[]> maybeSpamReportToken =
spamReport != null ? Optional.of(spamReport.token()) : Optional.empty();
// fire-and-forget: we don't want to block the response on this action.
CompletableFuture<Boolean> ignored =
reportSpamTokenHandler.handle(sourceNumber, sourceAci, sourcePni, messageGuid, spamReporterUuid, spamReportToken);
reportMessageManager.report(sourceNumber, sourceAci, sourcePni, messageGuid, spamReporterUuid);
reportMessageManager.report(sourceNumber, sourceAci, sourcePni, messageGuid, spamReporterUuid, maybeSpamReportToken);
return Response.status(Status.ACCEPTED)
.build();
@@ -1,131 +0,0 @@
/*
* Copyright 2013-2020 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.controllers;
import java.util.Collections;
import java.util.List;
import java.util.Locale.LanguageRange;
import java.util.Set;
import java.util.stream.Collectors;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.whispersystems.textsecuregcm.util.Util;
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
@Path("/v1/voice/")
public class VoiceVerificationController {
private static final String PLAY_TWIML = """
<?xml version="1.0" encoding="UTF-8"?>
<Response>
<Play>%s</Play>
<Play>%s</Play>
<Play>%s</Play>
<Play>%s</Play>
<Play>%s</Play>
<Play>%s</Play>
<Play>%s</Play>
<Pause length="1"/>
<Play>%s</Play>
<Play>%s</Play>
<Play>%s</Play>
<Play>%s</Play>
<Play>%s</Play>
<Play>%s</Play>
<Play>%s</Play>
<Pause length="1"/>
<Play>%s</Play>
<Play>%s</Play>
<Play>%s</Play>
<Play>%s</Play>
<Play>%s</Play>
<Play>%s</Play>
<Play>%s</Play>
</Response>
""";
private static final String DEFAULT_LOCALE = "en-US";
private final String baseUrl;
private final Set<String> supportedLocales;
public VoiceVerificationController(String baseUrl, Set<String> supportedLocales) {
this.baseUrl = baseUrl;
this.supportedLocales = supportedLocales;
}
@POST
@Path("/description/{code}")
@Produces(MediaType.APPLICATION_XML)
public Response getDescription(@PathParam("code") String code, @QueryParam("l") List<String> locales) {
code = code.replaceAll("[^0-9]", "");
if (code.length() != 6) {
return Response.status(400).build();
}
if (locales == null) {
locales = Collections.emptyList();
}
final List<LanguageRange> priorityList;
try {
priorityList = locales.stream()
.map(LanguageRange::new)
.collect(Collectors.toList());
} catch (final IllegalArgumentException e) {
return Response.status(400).build();
}
final String localeMatch = Util.findBestLocale(priorityList, supportedLocales).orElse(DEFAULT_LOCALE);
return getLocalizedDescription(code, localeMatch);
}
private Response getLocalizedDescription(String code, String locale) {
String path = constructUrlForLocale(baseUrl, locale);
return Response.ok()
.entity(String.format(PLAY_TWIML,
path + "verification.mp3",
path + code.charAt(0) + "_middle.mp3",
path + code.charAt(1) + "_middle.mp3",
path + code.charAt(2) + "_middle.mp3",
path + code.charAt(3) + "_middle.mp3",
path + code.charAt(4) + "_middle.mp3",
path + code.charAt(5) + "_falling.mp3",
path + "verification.mp3",
path + code.charAt(0) + "_middle.mp3",
path + code.charAt(1) + "_middle.mp3",
path + code.charAt(2) + "_middle.mp3",
path + code.charAt(3) + "_middle.mp3",
path + code.charAt(4) + "_middle.mp3",
path + code.charAt(5) + "_falling.mp3",
path + "verification.mp3",
path + code.charAt(0) + "_middle.mp3",
path + code.charAt(1) + "_middle.mp3",
path + code.charAt(2) + "_middle.mp3",
path + code.charAt(3) + "_middle.mp3",
path + code.charAt(4) + "_middle.mp3",
path + code.charAt(5) + "_falling.mp3"))
.build();
}
private String constructUrlForLocale(String baseUrl, String locale) {
if (!baseUrl.endsWith("/")) {
baseUrl += "/";
}
return baseUrl + locale + "/";
}
}
@@ -1,7 +1,12 @@
package org.whispersystems.textsecuregcm.entities;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
public record SpamReport(@JsonProperty("token") @NotEmpty String token) {}
public record SpamReport(@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
@NotEmpty byte[] token) {}
@@ -9,6 +9,7 @@ import static com.codahale.metrics.MetricRegistry.name;
import io.micrometer.core.instrument.Metrics;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import net.logstash.logback.marker.Markers;
import org.slf4j.Logger;
@@ -35,7 +36,9 @@ public class ReportedMessageMetricsListener implements ReportedMessageListener {
}
@Override
public void handleMessageReported(final String sourceNumber, final UUID messageGuid, final UUID reporterUuid) {
public void handleMessageReported(final String sourceNumber, final UUID messageGuid, final UUID reporterUuid,
final Optional<byte[]> reportSpamToken) {
final String sourceCountryCode = Util.getCountryCode(sourceNumber);
Metrics.counter(REPORTED_COUNTER_NAME, COUNTRY_CODE_TAG_NAME, sourceCountryCode).increment();
@@ -1,47 +0,0 @@
package org.whispersystems.textsecuregcm.spam;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
/**
* Handles ReportSpamTokens during spam reports.
*/
public interface ReportSpamTokenHandler {
/**
* Handle spam reports using the given ReportSpamToken and other provided parameters.
*
* @param reportSpamToken binary data representing a spam report token.
* @return true if the token could be handled (and was), false otherwise.
*/
CompletableFuture<Boolean> handle(
Optional<String> sourceNumber,
Optional<UUID> sourceAci,
Optional<UUID> sourcePni,
UUID messageGuid,
UUID spamReporterUuid,
byte[] reportSpamToken);
/**
* Handler which does nothing.
*
* @return the handler
*/
static ReportSpamTokenHandler noop() {
return new ReportSpamTokenHandler() {
@Override
public CompletableFuture<Boolean> handle(
final Optional<String> sourceNumber,
final Optional<UUID> sourceAci,
final Optional<UUID> sourcePni,
final UUID messageGuid,
final UUID spamReporterUuid,
final byte[] reportSpamToken) {
return CompletableFuture.completedFuture(false);
}
};
}
}
@@ -6,8 +6,10 @@
package org.whispersystems.textsecuregcm.spam;
import io.dropwizard.lifecycle.Managed;
import org.whispersystems.textsecuregcm.storage.ReportedMessageListener;
import javax.ws.rs.container.ContainerRequestFilter;
import java.io.IOException;
import java.util.List;
/**
* A spam filter is a {@link ContainerRequestFilter} that filters requests to message-sending endpoints to
@@ -39,10 +41,10 @@ public interface SpamFilter extends ContainerRequestFilter, Managed {
ReportSpamTokenProvider getReportSpamTokenProvider();
/**
* Builds a spam report token handler. This will handle tokens received by the spam reporting system.
* Return any and all reported message listeners controlled by the spam filter. Listeners will be registered with the
* {@link org.whispersystems.textsecuregcm.storage.ReportMessageManager}.
*
* @return the configured spam report token handler
* @return a list of reported message listeners controlled by the spam filter
*/
ReportSpamTokenHandler getReportSpamTokenHandler();
List<ReportedMessageListener> getReportedMessageListeners();
}
@@ -15,8 +15,10 @@ import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
import io.micrometer.core.instrument.Metrics;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
import org.whispersystems.textsecuregcm.util.UUIDUtil;
@@ -29,6 +31,10 @@ public class ReportMessageManager {
private final List<ReportedMessageListener> reportedMessageListeners = new ArrayList<>();
private static final String REPORT_MESSAGE_COUNTER_NAME = MetricsUtil.name(ReportMessageManager.class);
private static final String FOUND_MESSAGE_TAG = "foundMessage";
private static final String TOKEN_PRESENT_TAG = "hasReportSpamToken";
private static final Logger logger = LoggerFactory.getLogger(ReportMessageManager.class);
public ReportMessageManager(final ReportMessageDynamoDb reportMessageDynamoDb,
@@ -56,12 +62,21 @@ public class ReportMessageManager {
}
}
public void report(Optional<String> sourceNumber, Optional<UUID> sourceAci, Optional<UUID> sourcePni,
UUID messageGuid, UUID reporterUuid) {
public void report(final Optional<String> sourceNumber,
final Optional<UUID> sourceAci,
final Optional<UUID> sourcePni,
final UUID messageGuid,
final UUID reporterUuid,
final Optional<byte[]> reportSpamToken) {
final boolean found = sourceAci.map(uuid -> reportMessageDynamoDb.remove(hash(messageGuid, uuid.toString())))
.orElse(false);
Metrics.counter(REPORT_MESSAGE_COUNTER_NAME,
FOUND_MESSAGE_TAG, String.valueOf(found),
TOKEN_PRESENT_TAG, String.valueOf(reportSpamToken.isPresent()))
.increment();
if (found) {
rateLimitCluster.useCluster(connection -> {
sourcePni.ifPresent(pni -> {
@@ -80,7 +95,7 @@ public class ReportMessageManager {
sourceNumber.ifPresent(number ->
reportedMessageListeners.forEach(listener -> {
try {
listener.handleMessageReported(number, messageGuid, reporterUuid);
listener.handleMessageReported(number, messageGuid, reporterUuid, reportSpamToken);
} catch (final Exception e) {
logger.error("Failed to notify listener of reported message", e);
}
@@ -5,9 +5,10 @@
package org.whispersystems.textsecuregcm.storage;
import java.util.Optional;
import java.util.UUID;
public interface ReportedMessageListener {
void handleMessageReported(String sourceNumber, UUID messageGuid, UUID reporterUuid);
void handleMessageReported(String sourceNumber, UUID messageGuid, UUID reporterUuid, Optional<byte[]> reportSpamToken);
}
@@ -8,17 +8,16 @@ package org.whispersystems.textsecuregcm.controllers;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
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.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.anyBoolean;
import static org.mockito.Mockito.anyString;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.clearInvocations;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.reset;
@@ -67,8 +66,6 @@ import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.mockito.ArgumentCaptor;
import org.whispersystems.textsecuregcm.spam.ReportSpamTokenHandler;
import org.whispersystems.textsecuregcm.spam.ReportSpamTokenProvider;
import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
import org.whispersystems.textsecuregcm.auth.DisabledPermittedAuthenticatedAccount;
import org.whispersystems.textsecuregcm.auth.OptionalAccess;
@@ -92,6 +89,7 @@ import org.whispersystems.textsecuregcm.providers.MultiRecipientMessageProvider;
import org.whispersystems.textsecuregcm.push.MessageSender;
import org.whispersystems.textsecuregcm.push.PushNotificationManager;
import org.whispersystems.textsecuregcm.push.ReceiptSender;
import org.whispersystems.textsecuregcm.spam.ReportSpamTokenProvider;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.DeletedAccountsManager;
@@ -142,7 +140,6 @@ class MessageControllerTest {
private static final PushNotificationManager pushNotificationManager = mock(PushNotificationManager.class);
private static final ReportMessageManager reportMessageManager = mock(ReportMessageManager.class);
private static final ExecutorService multiRecipientMessageExecutor = mock(ExecutorService.class);
private static final ReportSpamTokenHandler REPORT_SPAM_TOKEN_HANDLER = mock(ReportSpamTokenHandler.class);
private static final ResourceExtension resources = ResourceExtension.builder()
.addProperty(ServerProperties.UNWRAP_COMPLETION_STAGE_IN_WRITER_ENABLE, Boolean.TRUE)
@@ -155,7 +152,7 @@ class MessageControllerTest {
.addResource(
new MessageController(rateLimiters, messageSender, receiptSender, accountsManager, deletedAccountsManager,
messagesManager, pushNotificationManager, reportMessageManager, multiRecipientMessageExecutor,
ReportSpamTokenProvider.noop(), REPORT_SPAM_TOKEN_HANDLER))
ReportSpamTokenProvider.noop()))
.build();
@BeforeEach
@@ -182,8 +179,6 @@ class MessageControllerTest {
when(accountsManager.getByAccountIdentifier(INTERNATIONAL_UUID)).thenReturn(Optional.of(internationalAccount));
when(rateLimiters.getMessagesLimiter()).thenReturn(rateLimiter);
when(REPORT_SPAM_TOKEN_HANDLER.handle(any(), any(), any(), any(), any(), any())).thenReturn(CompletableFuture.completedFuture(false));
}
private static Device generateTestDevice(final long id, final int registrationId, final int pniRegistrationId, final SignedPreKey signedPreKey, final long createdAt, final long lastSeen) {
@@ -212,8 +207,7 @@ class MessageControllerTest {
rateLimiter,
pushNotificationManager,
reportMessageManager,
multiRecipientMessageExecutor,
REPORT_SPAM_TOKEN_HANDLER
multiRecipientMessageExecutor
);
}
@@ -634,7 +628,7 @@ class MessageControllerTest {
assertThat(response.getStatus(), is(equalTo(202)));
verify(reportMessageManager).report(Optional.of(senderNumber), Optional.of(senderAci), Optional.of(senderPni),
messageGuid, AuthHelper.VALID_UUID);
messageGuid, AuthHelper.VALID_UUID, Optional.empty());
verify(deletedAccountsManager, never()).findDeletedAccountE164(any(UUID.class));
verify(accountsManager, never()).getPhoneNumberIdentifier(anyString());
@@ -651,7 +645,7 @@ class MessageControllerTest {
assertThat(response.getStatus(), is(equalTo(202)));
verify(reportMessageManager).report(Optional.of(senderNumber), Optional.of(senderAci), Optional.of(senderPni),
messageGuid, AuthHelper.VALID_UUID);
messageGuid, AuthHelper.VALID_UUID, Optional.empty());
}
@Test
@@ -681,7 +675,7 @@ class MessageControllerTest {
assertThat(response.getStatus(), is(equalTo(202)));
verify(reportMessageManager).report(Optional.of(senderNumber), Optional.of(senderAci), Optional.of(senderPni),
messageGuid, AuthHelper.VALID_UUID);
messageGuid, AuthHelper.VALID_UUID, Optional.empty());
verify(deletedAccountsManager, never()).findDeletedAccountE164(any(UUID.class));
verify(accountsManager, never()).getPhoneNumberIdentifier(anyString());
@@ -699,7 +693,7 @@ class MessageControllerTest {
assertThat(response.getStatus(), is(equalTo(202)));
verify(reportMessageManager).report(Optional.of(senderNumber), Optional.of(senderAci), Optional.of(senderPni),
messageGuid, AuthHelper.VALID_UUID);
messageGuid, AuthHelper.VALID_UUID, Optional.empty());
}
@Test
@@ -718,12 +712,8 @@ class MessageControllerTest {
when(accountsManager.getByAccountIdentifier(senderAci)).thenReturn(Optional.of(account));
when(deletedAccountsManager.findDeletedAccountE164(senderAci)).thenReturn(Optional.of(senderNumber));
when(accountsManager.getPhoneNumberIdentifier(senderNumber)).thenReturn(senderPni);
when(REPORT_SPAM_TOKEN_HANDLER.handle(any(), any(), any(), any(), any(), any())).thenReturn(CompletableFuture.completedFuture(true));
ArgumentCaptor<byte[]> captor = ArgumentCaptor.forClass(byte[].class);
String token = Base64.getEncoder().encodeToString(new byte[3]);
Entity<SpamReport> entity = Entity.entity(new SpamReport(token), "application/json");
Entity<SpamReport> entity = Entity.entity(new SpamReport(new byte[3]), "application/json");
Response response =
resources.getJerseyTest()
.target(String.format("/v1/messages/report/%s/%s", senderAci, messageGuid))
@@ -732,20 +722,19 @@ class MessageControllerTest {
.post(entity);
assertThat(response.getStatus(), is(equalTo(202)));
verify(REPORT_SPAM_TOKEN_HANDLER).handle(any(), any(), any(), any(), any(), captor.capture());
assertArrayEquals(new byte[3], captor.getValue());
verify(reportMessageManager).report(Optional.of(senderNumber), Optional.of(senderAci), Optional.of(senderPni),
messageGuid, AuthHelper.VALID_UUID);
verify(reportMessageManager).report(eq(Optional.of(senderNumber)),
eq(Optional.of(senderAci)),
eq(Optional.of(senderPni)),
eq(messageGuid),
eq(AuthHelper.VALID_UUID),
argThat(maybeBytes -> maybeBytes.map(bytes -> Arrays.equals(bytes, new byte[3])).orElse(false)));
verify(deletedAccountsManager, never()).findDeletedAccountE164(any(UUID.class));
verify(accountsManager, never()).getPhoneNumberIdentifier(anyString());
when(accountsManager.getByAccountIdentifier(senderAci)).thenReturn(Optional.empty());
clearInvocations(REPORT_SPAM_TOKEN_HANDLER);
messageGuid = UUID.randomUUID();
token = Base64.getEncoder().encodeToString(new byte[5]);
entity = Entity.entity(new SpamReport(token), "application/json");
entity = Entity.entity(new SpamReport(new byte[5]), "application/json");
response =
resources.getJerseyTest()
.target(String.format("/v1/messages/report/%s/%s", senderAci, messageGuid))
@@ -754,10 +743,12 @@ class MessageControllerTest {
.post(entity);
assertThat(response.getStatus(), is(equalTo(202)));
verify(REPORT_SPAM_TOKEN_HANDLER).handle(any(), any(), any(), any(), any(), captor.capture());
assertArrayEquals(new byte[5], captor.getValue());
verify(reportMessageManager).report(Optional.of(senderNumber), Optional.of(senderAci), Optional.of(senderPni),
messageGuid, AuthHelper.VALID_UUID);
verify(reportMessageManager).report(eq(Optional.of(senderNumber)),
eq(Optional.of(senderAci)),
eq(Optional.of(senderPni)),
eq(messageGuid),
eq(AuthHelper.VALID_UUID),
argThat(maybeBytes -> maybeBytes.map(bytes -> Arrays.equals(bytes, new byte[5])).orElse(false)));
}
@Test
@@ -81,16 +81,16 @@ class ReportMessageManagerTest {
when(reportMessageDynamoDb.remove(any())).thenReturn(false);
reportMessageManager.report(Optional.of(sourceNumber), Optional.of(sourceAci), Optional.of(sourcePni), messageGuid,
reporterUuid);
reporterUuid, Optional.empty());
assertEquals(0, reportMessageManager.getRecentReportCount(sourceAccount));
when(reportMessageDynamoDb.remove(any())).thenReturn(true);
reportMessageManager.report(Optional.of(sourceNumber), Optional.of(sourceAci), Optional.of(sourcePni), messageGuid,
reporterUuid);
reporterUuid, Optional.empty());
assertEquals(1, reportMessageManager.getRecentReportCount(sourceAccount));
verify(listener).handleMessageReported(sourceNumber, messageGuid, reporterUuid);
verify(listener).handleMessageReported(sourceNumber, messageGuid, reporterUuid, Optional.empty());
}
@Test
@@ -100,7 +100,7 @@ class ReportMessageManagerTest {
for (int i = 0; i < 100; i++) {
reportMessageManager.report(Optional.of(sourceNumber), Optional.of(sourceAci), Optional.of(sourcePni),
messageGuid, UUID.randomUUID());
messageGuid, UUID.randomUUID(), Optional.empty());
}
assertTrue(reportMessageManager.getRecentReportCount(sourceAccount) > 10);
@@ -114,7 +114,7 @@ class ReportMessageManagerTest {
for (int i = 0; i < 100; i++) {
reportMessageManager.report(Optional.of(sourceNumber), Optional.of(sourceAci), Optional.of(sourcePni),
messageGuid,
reporterUuid);
reporterUuid, Optional.empty());
}
assertEquals(1, reportMessageManager.getRecentReportCount(sourceAccount));
@@ -127,11 +127,11 @@ class ReportMessageManagerTest {
for (int i = 0; i < 100; i++) {
reportMessageManager.report(Optional.empty(), Optional.of(sourceAci), Optional.of(sourcePni),
messageGuid, UUID.randomUUID());
messageGuid, UUID.randomUUID(), Optional.empty());
}
reportMessageManager.report(Optional.empty(), Optional.of(sourceAci), Optional.empty(),
messageGuid, UUID.randomUUID());
messageGuid, UUID.randomUUID(), Optional.empty());
final int recentReportCount = reportMessageManager.getRecentReportCount(sourceAccount);
assertTrue(recentReportCount > 10);
@@ -1,143 +0,0 @@
/*
* Copyright 2013-2021 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.tests.controllers;
import static org.assertj.core.api.Assertions.assertThat;
import com.google.common.collect.ImmutableSet;
import io.dropwizard.auth.PolymorphicAuthValueFactoryProvider;
import io.dropwizard.testing.FixtureHelpers;
import io.dropwizard.testing.junit5.DropwizardExtensionsSupport;
import io.dropwizard.testing.junit5.ResourceExtension;
import java.util.Arrays;
import java.util.HashSet;
import javax.ws.rs.core.Response;
import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
import org.whispersystems.textsecuregcm.auth.DisabledPermittedAuthenticatedAccount;
import org.whispersystems.textsecuregcm.controllers.VoiceVerificationController;
import org.whispersystems.textsecuregcm.mappers.RateLimitExceededExceptionMapper;
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
import org.whispersystems.textsecuregcm.util.SystemMapper;
@ExtendWith(DropwizardExtensionsSupport.class)
class VoiceVerificationControllerTest {
private static final ResourceExtension resources = ResourceExtension.builder()
.addProvider(AuthHelper.getAuthFilter())
.addProvider(new PolymorphicAuthValueFactoryProvider.Binder<>(
ImmutableSet.of(AuthenticatedAccount.class, DisabledPermittedAuthenticatedAccount.class)))
.addProvider(new RateLimitExceededExceptionMapper())
.setMapper(SystemMapper.getMapper())
.setTestContainerFactory(new GrizzlyWebTestContainerFactory())
.addResource(new VoiceVerificationController("https://foo.com/bar",
new HashSet<>(Arrays.asList("pt-BR", "ru"))))
.build();
@Test
void testTwimlLocale() {
Response response =
resources.getJerseyTest()
.target("/v1/voice/description/123456")
.queryParam("l", "pt-BR")
.request()
.post(null);
assertThat(response.getStatus()).isEqualTo(200);
assertThat(response.readEntity(String.class)).isXmlEqualTo(FixtureHelpers.fixture("fixtures/voice_verification_pt_br.xml"));
}
@Test
void testTwimlSplitLocale() {
Response response =
resources.getJerseyTest()
.target("/v1/voice/description/123456")
.queryParam("l", "ru-RU")
.request()
.post(null);
assertThat(response.getStatus()).isEqualTo(200);
assertThat(response.readEntity(String.class)).isXmlEqualTo(FixtureHelpers.fixture("fixtures/voice_verification_ru.xml"));
}
@Test
void testTwimlUnsupportedLocale() {
Response response =
resources.getJerseyTest()
.target("/v1/voice/description/123456")
.queryParam("l", "es-MX")
.request()
.post(null);
assertThat(response.getStatus()).isEqualTo(200);
assertThat(response.readEntity(String.class)).isXmlEqualTo(FixtureHelpers.fixture("fixtures/voice_verification_en_us.xml"));
}
@Test
void testTwimlMultipleLocales() {
Response response =
resources.getJerseyTest()
.target("/v1/voice/description/123456")
.queryParam("l", "es-MX")
.queryParam("l", "ru-RU")
.request()
.post(null);
assertThat(response.getStatus()).isEqualTo(200);
assertThat(response.readEntity(String.class)).isXmlEqualTo(FixtureHelpers.fixture("fixtures/voice_verification_ru.xml"));
}
@Test
void testTwimlMissingLocale() {
Response response =
resources.getJerseyTest()
.target("/v1/voice/description/123456")
.request()
.post(null);
assertThat(response.getStatus()).isEqualTo(200);
assertThat(response.readEntity(String.class)).isXmlEqualTo(FixtureHelpers.fixture("fixtures/voice_verification_en_us.xml"));
}
@Test
void testTwimlMalformedCode() {
Response response =
resources.getJerseyTest()
.target("/v1/voice/description/1234...56")
.request()
.post(null);
assertThat(response.getStatus()).isEqualTo(200);
assertThat(response.readEntity(String.class)).isXmlEqualTo(FixtureHelpers.fixture("fixtures/voice_verification_en_us.xml"));
}
@Test
void testTwimlBadCodeLength() {
Response response =
resources.getJerseyTest()
.target("/v1/voice/description/1234567")
.request()
.post(null);
assertThat(response.getStatus()).isEqualTo(400);
}
@Test
void testTwimlMalformedLocale() {
Response response =
resources.getJerseyTest()
.target("/v1/voice/description/123456")
.queryParam("l", "it IT ,")
.request()
.post(null);
assertThat(response.getStatus()).isEqualTo(400);
}
}
@@ -1,26 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<Response>
<Play>https://foo.com/bar/en-US/verification.mp3</Play>
<Play>https://foo.com/bar/en-US/1_middle.mp3</Play>
<Play>https://foo.com/bar/en-US/2_middle.mp3</Play>
<Play>https://foo.com/bar/en-US/3_middle.mp3</Play>
<Play>https://foo.com/bar/en-US/4_middle.mp3</Play>
<Play>https://foo.com/bar/en-US/5_middle.mp3</Play>
<Play>https://foo.com/bar/en-US/6_falling.mp3</Play>
<Pause length="1"/>
<Play>https://foo.com/bar/en-US/verification.mp3</Play>
<Play>https://foo.com/bar/en-US/1_middle.mp3</Play>
<Play>https://foo.com/bar/en-US/2_middle.mp3</Play>
<Play>https://foo.com/bar/en-US/3_middle.mp3</Play>
<Play>https://foo.com/bar/en-US/4_middle.mp3</Play>
<Play>https://foo.com/bar/en-US/5_middle.mp3</Play>
<Play>https://foo.com/bar/en-US/6_falling.mp3</Play>
<Pause length="1"/>
<Play>https://foo.com/bar/en-US/verification.mp3</Play>
<Play>https://foo.com/bar/en-US/1_middle.mp3</Play>
<Play>https://foo.com/bar/en-US/2_middle.mp3</Play>
<Play>https://foo.com/bar/en-US/3_middle.mp3</Play>
<Play>https://foo.com/bar/en-US/4_middle.mp3</Play>
<Play>https://foo.com/bar/en-US/5_middle.mp3</Play>
<Play>https://foo.com/bar/en-US/6_falling.mp3</Play>
</Response>
@@ -1,26 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<Response>
<Play>https://foo.com/bar/pt-BR/verification.mp3</Play>
<Play>https://foo.com/bar/pt-BR/1_middle.mp3</Play>
<Play>https://foo.com/bar/pt-BR/2_middle.mp3</Play>
<Play>https://foo.com/bar/pt-BR/3_middle.mp3</Play>
<Play>https://foo.com/bar/pt-BR/4_middle.mp3</Play>
<Play>https://foo.com/bar/pt-BR/5_middle.mp3</Play>
<Play>https://foo.com/bar/pt-BR/6_falling.mp3</Play>
<Pause length="1"/>
<Play>https://foo.com/bar/pt-BR/verification.mp3</Play>
<Play>https://foo.com/bar/pt-BR/1_middle.mp3</Play>
<Play>https://foo.com/bar/pt-BR/2_middle.mp3</Play>
<Play>https://foo.com/bar/pt-BR/3_middle.mp3</Play>
<Play>https://foo.com/bar/pt-BR/4_middle.mp3</Play>
<Play>https://foo.com/bar/pt-BR/5_middle.mp3</Play>
<Play>https://foo.com/bar/pt-BR/6_falling.mp3</Play>
<Pause length="1"/>
<Play>https://foo.com/bar/pt-BR/verification.mp3</Play>
<Play>https://foo.com/bar/pt-BR/1_middle.mp3</Play>
<Play>https://foo.com/bar/pt-BR/2_middle.mp3</Play>
<Play>https://foo.com/bar/pt-BR/3_middle.mp3</Play>
<Play>https://foo.com/bar/pt-BR/4_middle.mp3</Play>
<Play>https://foo.com/bar/pt-BR/5_middle.mp3</Play>
<Play>https://foo.com/bar/pt-BR/6_falling.mp3</Play>
</Response>
@@ -1,26 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<Response>
<Play>https://foo.com/bar/ru/verification.mp3</Play>
<Play>https://foo.com/bar/ru/1_middle.mp3</Play>
<Play>https://foo.com/bar/ru/2_middle.mp3</Play>
<Play>https://foo.com/bar/ru/3_middle.mp3</Play>
<Play>https://foo.com/bar/ru/4_middle.mp3</Play>
<Play>https://foo.com/bar/ru/5_middle.mp3</Play>
<Play>https://foo.com/bar/ru/6_falling.mp3</Play>
<Pause length="1"/>
<Play>https://foo.com/bar/ru/verification.mp3</Play>
<Play>https://foo.com/bar/ru/1_middle.mp3</Play>
<Play>https://foo.com/bar/ru/2_middle.mp3</Play>
<Play>https://foo.com/bar/ru/3_middle.mp3</Play>
<Play>https://foo.com/bar/ru/4_middle.mp3</Play>
<Play>https://foo.com/bar/ru/5_middle.mp3</Play>
<Play>https://foo.com/bar/ru/6_falling.mp3</Play>
<Pause length="1"/>
<Play>https://foo.com/bar/ru/verification.mp3</Play>
<Play>https://foo.com/bar/ru/1_middle.mp3</Play>
<Play>https://foo.com/bar/ru/2_middle.mp3</Play>
<Play>https://foo.com/bar/ru/3_middle.mp3</Play>
<Play>https://foo.com/bar/ru/4_middle.mp3</Play>
<Play>https://foo.com/bar/ru/5_middle.mp3</Play>
<Play>https://foo.com/bar/ru/6_falling.mp3</Play>
</Response>