Compare commits

..
7 Commits
15 changed files with 593 additions and 124 deletions

No files matched your search

+3
View File
@@ -26,3 +26,6 @@ deployer.log
!/service/src/main/resources/org/signal/badges/Badges_en.properties
/service/src/main/resources/org/signal/subscriptions/Subscriptions_*.properties
!/service/src/main/resources/org/signal/subscriptions/Subscriptions_en.properties
.project
.classpath
.settings
@@ -73,6 +73,8 @@ import org.whispersystems.dispatch.DispatchManager;
import org.whispersystems.textsecuregcm.abuse.AbusiveMessageFilter;
import org.whispersystems.textsecuregcm.abuse.FilterAbusiveMessages;
import org.whispersystems.textsecuregcm.abuse.RateLimitChallengeListener;
import org.whispersystems.textsecuregcm.abuse.ReportSpamTokenHandler;
import org.whispersystems.textsecuregcm.abuse.ReportSpamTokenProvider;
import org.whispersystems.textsecuregcm.auth.AccountAuthenticator;
import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
import org.whispersystems.textsecuregcm.auth.CertificateGenerator;
@@ -678,50 +680,29 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
environment.jersey().register(new KeysController(rateLimiters, keys, accountsManager));
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()),
new AttachmentControllerV3(rateLimiters, config.getGcpAttachmentsConfiguration().getDomain(), config.getGcpAttachmentsConfiguration().getEmail(), config.getGcpAttachmentsConfiguration().getMaxSizeInBytes(), config.getGcpAttachmentsConfiguration().getPathPrefix(), config.getGcpAttachmentsConfiguration().getRsaSigningKey()),
new CertificateController(new CertificateGenerator(config.getDeliveryCertificate().getCertificate(), config.getDeliveryCertificate().getPrivateKey(), config.getDeliveryCertificate().getExpiresDays()), zkAuthOperations, clock),
new ChallengeController(rateLimitChallengeManager),
new DeviceController(pendingDevicesManager, accountsManager, messagesManager, keys, rateLimiters, config.getMaxDevices()),
new DirectoryController(directoryCredentialsGenerator),
new DirectoryV2Controller(directoryV2CredentialsGenerator),
new DonationController(clock, zkReceiptOperations, redeemedReceiptsManager, accountsManager, config.getBadges(),
ReceiptCredentialPresentation::new),
new MessageController(rateLimiters, messageSender, receiptSender, accountsManager, deletedAccountsManager, messagesManager, pushNotificationManager, reportMessageManager, multiRecipientMessageExecutor),
new PaymentsController(currencyManager, paymentsCredentialsGenerator),
new ProfileController(clock, rateLimiters, accountsManager, profilesManager, dynamicConfigurationManager,
profileBadgeConverter, config.getBadges(), cdnS3Client, profileCdnPolicyGenerator, profileCdnPolicySigner,
config.getCdnConfiguration().getBucket(), zkProfileOperations, batchIdentityCheckExecutor),
new ProvisioningController(rateLimiters, provisioningManager),
new RemoteConfigController(remoteConfigsManager, adminEventLogger,
config.getRemoteConfigConfiguration().getAuthorizedTokens(),
config.getRemoteConfigConfiguration().getGlobalConfig()),
new SecureBackupController(backupCredentialsGenerator),
new SecureStorageController(storageCredentialsGenerator),
new StickerController(rateLimiters, config.getCdnConfiguration().getAccessKey(),
config.getCdnConfiguration().getAccessSecret(), config.getCdnConfiguration().getRegion(),
config.getCdnConfiguration().getBucket())
);
if (config.getSubscription() != null && config.getOneTimeDonations() != null) {
commonControllers.add(new SubscriptionController(clock, config.getSubscription(), config.getOneTimeDonations(),
subscriptionManager, stripeManager, braintreeManager, zkReceiptOperations, issuedReceiptsManager, profileBadgeConverter,
resourceBundleLevelTranslator));
}
for (Object controller : commonControllers) {
environment.jersey().register(controller);
webSocketEnvironment.jersey().register(controller);
}
boolean registeredAbusiveMessageFilter = false;
ReportSpamTokenProvider reportSpamTokenProvider = null;
ReportSpamTokenHandler reportSpamTokenHandler = null;
for (final AbusiveMessageFilter filter : ServiceLoader.load(AbusiveMessageFilter.class)) {
if (filter.getClass().isAnnotationPresent(FilterAbusiveMessages.class)) {
try {
filter.configure(config.getAbusiveMessageFilterConfiguration().getEnvironment());
ReportSpamTokenProvider thisProvider = filter.getReportSpamTokenProvider();
if (reportSpamTokenProvider == null) {
reportSpamTokenProvider = thisProvider;
} else if (thisProvider != null) {
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.");
}
environment.lifecycle().manage(filter);
environment.jersey().register(filter);
webSocketEnvironment.jersey().register(filter);
@@ -746,6 +727,52 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
log.warn("No abusive message filters installed");
}
if (reportSpamTokenProvider == null) {
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()),
new AttachmentControllerV3(rateLimiters, config.getGcpAttachmentsConfiguration().getDomain(), config.getGcpAttachmentsConfiguration().getEmail(), config.getGcpAttachmentsConfiguration().getMaxSizeInBytes(), config.getGcpAttachmentsConfiguration().getPathPrefix(), config.getGcpAttachmentsConfiguration().getRsaSigningKey()),
new CertificateController(new CertificateGenerator(config.getDeliveryCertificate().getCertificate(), config.getDeliveryCertificate().getPrivateKey(), config.getDeliveryCertificate().getExpiresDays()), zkAuthOperations, clock),
new ChallengeController(rateLimitChallengeManager),
new DeviceController(pendingDevicesManager, accountsManager, messagesManager, keys, rateLimiters, config.getMaxDevices()),
new DirectoryController(directoryCredentialsGenerator),
new DirectoryV2Controller(directoryV2CredentialsGenerator),
new DonationController(clock, zkReceiptOperations, redeemedReceiptsManager, accountsManager, config.getBadges(),
ReceiptCredentialPresentation::new),
new MessageController(rateLimiters, messageSender, receiptSender, accountsManager, deletedAccountsManager, messagesManager, pushNotificationManager, reportMessageManager, multiRecipientMessageExecutor,
reportSpamTokenProvider, reportSpamTokenHandler),
new PaymentsController(currencyManager, paymentsCredentialsGenerator),
new ProfileController(clock, rateLimiters, accountsManager, profilesManager, dynamicConfigurationManager,
profileBadgeConverter, config.getBadges(), cdnS3Client, profileCdnPolicyGenerator, profileCdnPolicySigner,
config.getCdnConfiguration().getBucket(), zkProfileOperations, batchIdentityCheckExecutor),
new ProvisioningController(rateLimiters, provisioningManager),
new RemoteConfigController(remoteConfigsManager, adminEventLogger,
config.getRemoteConfigConfiguration().getAuthorizedTokens(),
config.getRemoteConfigConfiguration().getGlobalConfig()),
new SecureBackupController(backupCredentialsGenerator),
new SecureStorageController(storageCredentialsGenerator),
new StickerController(rateLimiters, config.getCdnConfiguration().getAccessKey(),
config.getCdnConfiguration().getAccessSecret(), config.getCdnConfiguration().getRegion(),
config.getCdnConfiguration().getBucket())
);
if (config.getSubscription() != null && config.getOneTimeDonations() != null) {
commonControllers.add(new SubscriptionController(clock, config.getSubscription(), config.getOneTimeDonations(),
subscriptionManager, stripeManager, braintreeManager, zkReceiptOperations, issuedReceiptsManager, profileBadgeConverter,
resourceBundleLevelTranslator));
}
for (Object controller : commonControllers) {
environment.jersey().register(controller);
webSocketEnvironment.jersey().register(controller);
}
WebSocketEnvironment<AuthenticatedAccount> provisioningEnvironment = new WebSocketEnvironment<>(environment,
webSocketEnvironment.getRequestLog(), 60000);
provisioningEnvironment.jersey().register(new WebsocketRefreshApplicationEventListener(accountsManager, clientPresenceManager));
@@ -30,4 +30,19 @@ public interface AbusiveMessageFilter extends ContainerRequestFilter, Managed {
* @throws IOException if the filter could not read its configuration source for any reason
*/
void configure(String environmentName) throws IOException;
/**
* Builds a spam report token provider. This will generate tokens used by the spam reporting system.
*
* @return the configured spam report token provider.
*/
ReportSpamTokenProvider getReportSpamTokenProvider();
/**
* Builds a spam report token handler. This will handle tokens received by the spam reporting system.
*
* @return the configured spam report token handler
*/
ReportSpamTokenHandler getReportSpamTokenHandler();
}
@@ -0,0 +1,47 @@
package org.whispersystems.textsecuregcm.abuse;
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);
}
};
}
}
@@ -0,0 +1,38 @@
package org.whispersystems.textsecuregcm.abuse;
import javax.ws.rs.container.ContainerRequestContext;
import java.util.Optional;
import java.util.function.Function;
/**
* Generates ReportSpamTokens to be used for spam reports.
*/
public interface ReportSpamTokenProvider {
/**
* Generate a new ReportSpamToken
*
* @param context the message request context
* @return either a generated token or nothing
*/
Optional<byte[]> makeReportSpamToken(ContainerRequestContext context);
/**
* Provider which generates nothing
*
* @return the provider
*/
static ReportSpamTokenProvider noop() {
return create(c -> Optional.empty());
}
/**
* Provider which generates ReportSpamTokens using the given function
*
* @param fn function from message requests to optional tokens
* @return the provider
*/
static ReportSpamTokenProvider create(Function<ContainerRequestContext, Optional<byte[]>> fn) {
return fn::apply;
}
}
@@ -361,11 +361,7 @@ public class AccountController {
final byte[] sessionId = maybeStoredVerificationCode.isPresent() && maybeStoredVerificationCode.get().sessionId() != null ?
maybeStoredVerificationCode.get().sessionId() : createRegistrationSession(phoneNumber);
registrationServiceClient.sendRegistrationCode(sessionId,
messageTransport,
clientType,
acceptLanguage.orElse(null),
REGISTRATION_RPC_TIMEOUT).join();
sendVerificationCode(sessionId, messageTransport, clientType, acceptLanguage);
final StoredVerificationCode storedVerificationCode = new StoredVerificationCode(null,
clock.millis(),
@@ -405,10 +401,14 @@ public class AccountController {
// Note that successful verification depends on being able to find a stored verification code for the given number.
// We check that numbers are normalized before we store verification codes, and so don't need to re-assert
// normalization here.
final boolean codeVerified = pendingAccounts.getCodeForNumber(number).map(storedVerificationCode ->
registrationServiceClient.checkVerificationCode(storedVerificationCode.sessionId(),
verificationCode, REGISTRATION_RPC_TIMEOUT).join())
.orElse(false);
final boolean codeVerified;
final Optional<StoredVerificationCode> maybeStoredVerificationCode = pendingAccounts.getCodeForNumber(number);
if (maybeStoredVerificationCode.isPresent()) {
codeVerified = checkVerificationCode(maybeStoredVerificationCode.get().sessionId(), verificationCode);
} else {
codeVerified = false;
}
if (!codeVerified) {
throw new WebApplicationException(Response.status(403).build());
@@ -471,10 +471,14 @@ public class AccountController {
rateLimiters.getVerifyLimiter().validate(number);
final boolean codeVerified = pendingAccounts.getCodeForNumber(number).map(storedVerificationCode ->
registrationServiceClient.checkVerificationCode(storedVerificationCode.sessionId(),
request.code(), REGISTRATION_RPC_TIMEOUT).join())
.orElse(false);
final boolean codeVerified;
final Optional<StoredVerificationCode> maybeStoredVerificationCode = pendingAccounts.getCodeForNumber(number);
if (maybeStoredVerificationCode.isPresent()) {
codeVerified = checkVerificationCode(maybeStoredVerificationCode.get().sessionId(), request.code());
} else {
codeVerified = false;
}
if (!codeVerified) {
throw new ForbiddenException();
@@ -964,17 +968,50 @@ public class AccountController {
try {
return registrationServiceClient.createRegistrationSession(phoneNumber, REGISTRATION_RPC_TIMEOUT).join();
} catch (final CompletionException e) {
Throwable cause = e;
while (cause instanceof CompletionException) {
cause = cause.getCause();
}
if (cause instanceof RateLimitExceededException rateLimitExceededException) {
throw rateLimitExceededException;
}
rethrowRateLimitException(e);
throw e;
}
}
private void sendVerificationCode(final byte[] sessionId,
final MessageTransport messageTransport,
final ClientType clientType,
final Optional<String> acceptLanguage) throws RateLimitExceededException {
try {
registrationServiceClient.sendRegistrationCode(sessionId,
messageTransport,
clientType,
acceptLanguage.orElse(null),
REGISTRATION_RPC_TIMEOUT).join();
} catch (final CompletionException e) {
rethrowRateLimitException(e);
throw e;
}
}
private boolean checkVerificationCode(final byte[] sessionId, final String verificationCode)
throws RateLimitExceededException {
try {
return registrationServiceClient.checkVerificationCode(sessionId, verificationCode, REGISTRATION_RPC_TIMEOUT).join();
} catch (final CompletionException e) {
rethrowRateLimitException(e);
throw e;
}
}
private void rethrowRateLimitException(final CompletionException completionException)
throws RateLimitExceededException {
Throwable cause = completionException;
while (cause instanceof CompletionException) {
cause = cause.getCause();
}
if (cause instanceof RateLimitExceededException rateLimitExceededException) {
throw rateLimitExceededException;
}
}
}
@@ -55,12 +55,16 @@ import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
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.abuse.FilterAbusiveMessages;
import org.whispersystems.textsecuregcm.abuse.ReportSpamTokenHandler;
import org.whispersystems.textsecuregcm.abuse.ReportSpamTokenProvider;
import org.whispersystems.textsecuregcm.auth.Anonymous;
import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
import org.whispersystems.textsecuregcm.auth.CombinedUnidentifiedSenderAccessKeys;
@@ -78,6 +82,7 @@ import org.whispersystems.textsecuregcm.entities.OutgoingMessageEntity;
import org.whispersystems.textsecuregcm.entities.OutgoingMessageEntityList;
import org.whispersystems.textsecuregcm.entities.SendMessageResponse;
import org.whispersystems.textsecuregcm.entities.SendMultiRecipientMessageResponse;
import org.whispersystems.textsecuregcm.entities.SpamReport;
import org.whispersystems.textsecuregcm.entities.StaleDevices;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.metrics.MessageMetrics;
@@ -117,6 +122,8 @@ public class MessageController {
private final PushNotificationManager pushNotificationManager;
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");
@@ -124,6 +131,7 @@ 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";
@@ -147,7 +155,9 @@ public class MessageController {
MessagesManager messagesManager,
PushNotificationManager pushNotificationManager,
ReportMessageManager reportMessageManager,
@Nonnull ExecutorService multiRecipientMessageExecutor) {
@Nonnull ExecutorService multiRecipientMessageExecutor,
@Nonnull ReportSpamTokenProvider reportSpamTokenProvider,
@Nonnull ReportSpamTokenHandler reportSpamTokenHandler) {
this.rateLimiters = rateLimiters;
this.messageSender = messageSender;
this.receiptSender = receiptSender;
@@ -157,6 +167,9 @@ public class MessageController {
this.pushNotificationManager = pushNotificationManager;
this.reportMessageManager = reportMessageManager;
this.multiRecipientMessageExecutor = Objects.requireNonNull(multiRecipientMessageExecutor);
this.reportSpamTokenProvider = reportSpamTokenProvider;
this.reportSpamTokenHandler = reportSpamTokenHandler;
}
@Timed
@@ -171,7 +184,9 @@ public class MessageController {
@HeaderParam(HttpHeaders.X_FORWARDED_FOR) String forwardedFor,
@PathParam("destination") UUID destinationUuid,
@QueryParam("story") boolean isStory,
@NotNull @Valid IncomingMessageList messages)
@NotNull @Valid IncomingMessageList messages,
@Context ContainerRequestContext context
)
throws RateLimitExceededException {
if (source.isEmpty() && accessKey.isEmpty() && !isStory) {
@@ -190,6 +205,13 @@ public class MessageController {
senderType = SENDER_TYPE_UNIDENTIFIED;
}
final Optional<byte[]> spamReportToken;
if (senderType.equals(SENDER_TYPE_IDENTIFIED)) {
spamReportToken = reportSpamTokenProvider.makeReportSpamToken(context);
} else {
spamReportToken = Optional.empty();
}
for (final IncomingMessage message : messages.messages()) {
int contentLength = 0;
@@ -267,7 +289,18 @@ public class MessageController {
if (destinationDevice.isPresent()) {
Metrics.counter(SENT_MESSAGE_COUNTER_NAME, tags).increment();
sendIndividualMessage(source, destination.get(), destinationDevice.get(), destinationUuid, messages.timestamp(), messages.online(), isStory, messages.urgent(), incomingMessage, userAgent);
sendIndividualMessage(
source,
destination.get(),
destinationDevice.get(),
destinationUuid,
messages.timestamp(),
messages.online(),
isStory,
messages.urgent(),
incomingMessage,
userAgent,
spamReportToken);
}
}
@@ -570,9 +603,14 @@ public class MessageController {
@Timed
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Path("/report/{source}/{messageGuid}")
public Response reportMessage(@Auth AuthenticatedAccount auth, @PathParam("source") String source,
@PathParam("messageGuid") UUID messageGuid) {
public Response reportSpamMessage(
@Auth AuthenticatedAccount auth,
@PathParam("source") String source,
@PathParam("messageGuid") UUID messageGuid,
@Nullable @Valid SpamReport spamReport
) {
final Optional<String> sourceNumber;
final Optional<UUID> sourceAci;
@@ -602,13 +640,32 @@ public class MessageController {
}
}
reportMessageManager.report(sourceNumber, sourceAci, sourcePni, messageGuid, auth.getAccount().getUuid());
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());
}
}
// 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);
return Response.status(Status.ACCEPTED)
.build();
}
private void sendIndividualMessage(Optional<AuthenticatedAccount> source,
private void sendIndividualMessage(
Optional<AuthenticatedAccount> source,
Account destinationAccount,
Device destinationDevice,
UUID destinationUuid,
@@ -617,18 +674,23 @@ public class MessageController {
boolean story,
boolean urgent,
IncomingMessage incomingMessage,
String userAgentString)
String userAgentString,
Optional<byte[]> spamReportToken)
throws NoSuchUserException {
try {
final Envelope envelope;
try {
envelope = incomingMessage.toEnvelope(destinationUuid,
source.map(AuthenticatedAccount::getAccount).orElse(null),
source.map(authenticatedAccount -> authenticatedAccount.getAuthenticatedDevice().getId()).orElse(null),
Account sourceAccount = source.map(AuthenticatedAccount::getAccount).orElse(null);
Long sourceDeviceId = source.map(account -> account.getAuthenticatedDevice().getId()).orElse(null);
envelope = incomingMessage.toEnvelope(
destinationUuid,
sourceAccount,
sourceDeviceId,
timestamp == 0 ? System.currentTimeMillis() : timestamp,
story,
urgent);
urgent,
spamReportToken.orElse(null));
} catch (final IllegalArgumentException e) {
logger.warn("Received bad envelope type {} from {}", incomingMessage.type(), userAgentString);
throw new BadRequestException(e);
@@ -18,7 +18,8 @@ public record IncomingMessage(int type, long destinationDeviceId, int destinatio
@Nullable Long sourceDeviceId,
final long timestamp,
final boolean story,
final boolean urgent) {
final boolean urgent,
@Nullable byte[] reportSpamToken) {
final MessageProtos.Envelope.Type envelopeType = MessageProtos.Envelope.Type.forNumber(type());
@@ -36,10 +37,15 @@ public record IncomingMessage(int type, long destinationDeviceId, int destinatio
.setUrgent(urgent);
if (sourceAccount != null && sourceDeviceId != null) {
envelopeBuilder.setSourceUuid(sourceAccount.getUuid().toString())
envelopeBuilder
.setSourceUuid(sourceAccount.getUuid().toString())
.setSourceDevice(sourceDeviceId.intValue());
}
if (reportSpamToken != null) {
envelopeBuilder.setReportSpamToken(ByteString.copyFrom(reportSpamToken));
}
if (StringUtils.isNotEmpty(content())) {
envelopeBuilder.setContent(ByteString.copyFrom(Base64.getDecoder().decode(content())));
}
@@ -0,0 +1,7 @@
package org.whispersystems.textsecuregcm.entities;
import com.fasterxml.jackson.annotation.JsonProperty;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
public record SpamReport(@JsonProperty("token") @NotEmpty String token) {}
@@ -69,7 +69,8 @@ public class RegistrationServiceClient implements Managed {
case ERROR -> {
switch (response.getError().getErrorType()) {
case ERROR_TYPE_RATE_LIMITED -> throw new CompletionException(new RateLimitExceededException(Duration.ofSeconds(response.getError().getRetryAfterSeconds())));
case CREATE_REGISTRATION_SESSION_ERROR_TYPE_RATE_LIMITED -> throw new CompletionException(new RateLimitExceededException(Duration.ofSeconds(response.getError().getRetryAfterSeconds())));
case CREATE_REGISTRATION_SESSION_ERROR_TYPE_ILLEGAL_PHONE_NUMBER -> throw new IllegalArgumentException();
default -> throw new RuntimeException("Unrecognized error type from registration service: " + response.getError().getErrorType());
}
}
@@ -95,7 +96,18 @@ public class RegistrationServiceClient implements Managed {
return toCompletableFuture(stub.withDeadline(toDeadline(timeout))
.sendVerificationCode(requestBuilder.build()))
.thenApply(response -> response.getSessionId().toByteArray());
.thenApply(response -> {
if (response.hasError()) {
switch (response.getError().getErrorType()) {
case SEND_VERIFICATION_CODE_ERROR_TYPE_RATE_LIMITED ->
throw new CompletionException(new RateLimitExceededException(Duration.ofSeconds(response.getError().getRetryAfterSeconds())));
default -> throw new CompletionException(new RuntimeException("Failed to send verification code: " + response.getError().getErrorType()));
}
} else {
return response.getSessionId().toByteArray();
}
});
}
public CompletableFuture<Boolean> checkVerificationCode(final byte[] sessionId,
@@ -107,7 +119,18 @@ public class RegistrationServiceClient implements Managed {
.setSessionId(ByteString.copyFrom(sessionId))
.setVerificationCode(verificationCode)
.build()))
.thenApply(CheckVerificationCodeResponse::getVerified);
.thenApply(response -> {
if (response.hasError()) {
switch (response.getError().getErrorType()) {
case CHECK_VERIFICATION_CODE_ERROR_TYPE_RATE_LIMITED ->
throw new CompletionException(new RateLimitExceededException(Duration.ofSeconds(response.getError().getRetryAfterSeconds())));
default -> throw new CompletionException(new RuntimeException("Failed to check verification code: " + response.getError().getErrorType()));
}
} else {
return response.getVerified() || response.getSessionMetadata().getVerified();
}
});
}
private static Deadline toDeadline(final Duration timeout) {
@@ -297,32 +297,17 @@ public class BraintreeManager implements SubscriptionProcessorManager {
.filter(Subscription::neverExpires)
.findAny();
final CompletableFuture<Plan> planFuture = maybeExistingSubscription.map(sub ->
findPlan(sub.getPlanId()).thenApply(plan -> {
if (getLevelForPlan(plan) != level) {
// if this happens, the likely cause is retrying an apparently failed request (likely some sort of timeout or network interruption)
// with a different level.
// In this case, it’s safer and easier to recover by returning this subscription, rather than
// returning an error
logger.warn("existing subscription had unexpected level");
}
return plan;
})).orElseGet(() -> findPlan(planId));
return maybeExistingSubscription
.map(subscription -> {
return findPlan(subscription.getPlanId())
.thenApply(plan -> {
if (getLevelForPlan(plan) != level) {
// if this happens, the likely cause is retrying an apparently failed request (likely some sort of timeout or network interruption)
// with a different level.
// In this case, it’s safer and easier to recover by returning this subscription, rather than
// returning an error
logger.warn("existing subscription had unexpected level");
}
return subscription;
});
})
return maybeExistingSubscription.map(subscription -> findPlan(subscription.getPlanId())
.thenApply(plan -> {
if (getLevelForPlan(plan) != level) {
// if this happens, the likely cause is retrying an apparently failed request (likely some sort of timeout or network interruption)
// with a different level.
// In this case, it’s safer and easier to recover by returning this subscription, rather than
// returning an error
logger.warn("existing subscription had unexpected level");
}
return subscription;
}))
.orElseGet(() -> findPlan(planId).thenApplyAsync(plan -> {
final Result<Subscription> result = braintreeGateway.subscription().create(new SubscriptionRequest()
.planId(planId)
+164 -14
View File
@@ -50,6 +50,12 @@ message RegistrationSessionMetadata {
* session associated with this registration attempt.
*/
bytes session_id = 1;
/**
* Indicates whether a valid verification code has been submitted in the scope
* of this session.
*/
bool verified = 2;
}
message CreateRegistrationSessionError {
@@ -59,37 +65,39 @@ message CreateRegistrationSessionError {
CreateRegistrationSessionErrorType error_type = 1;
/**
* Indicates that this error is fatal and should not be retried without
* modification. Non-fatal errors may be retried without modification after
* the duration indicated by `retry_after_seconds`.
* Indicates that this error may succeed if retried without modification after
* a delay indicated by `retry_after_seconds`. If false, callers should not
* retry the request without modification.
*/
bool fatal = 2;
bool may_retry = 2;
/**
* If this error is not fatal (see `fatal`), indicates the duration in seconds
* from the present after which the request may be retried without
* modification. This value has no meaning otherwise.
* If this error may be retried,, indicates the duration in seconds from the
* present after which the request may be retried without modification. This
* value has no meaning otherwise.
*/
uint64 retry_after_seconds = 3;
}
enum CreateRegistrationSessionErrorType {
ERROR_TYPE_UNSPECIFIED = 0;
CREATE_REGISTRATION_SESSION_ERROR_TYPE_UNSPECIFIED = 0;
/**
* Indicates that a session could not be created because too many requests to
* create a session for the given phone number have been received in some
* window of time. Callers should wait and try again later.
*/
ERROR_TYPE_RATE_LIMITED = 1;
CREATE_REGISTRATION_SESSION_ERROR_TYPE_RATE_LIMITED = 1;
/**
* Indicates that the provided phone number could not be parsed.
*/
CREATE_REGISTRATION_SESSION_ERROR_TYPE_ILLEGAL_PHONE_NUMBER = 2;
}
message SendVerificationCodeRequest {
/**
* The phone number to which to send a verification code. Ignored (and may be
* null if `session_id` is set.
*/
uint64 e164 = 1;
reserved 1;
/**
* The message transport to use to send a verification code to the destination
@@ -112,6 +120,12 @@ message SendVerificationCodeRequest {
* The ID of a session within which to send (or re-send) a verification code.
*/
bytes session_id = 5;
/**
* If provided, always attempt to use the specified sender to send
* this message.
*/
string sender_name = 6;
}
enum MessageTransport {
@@ -133,6 +147,76 @@ message SendVerificationCodeResponse {
* session associated with this registration attempt.
*/
bytes session_id = 1;
/**
* Metadata for the named session. May be absent if the session could not be
* found or has expired.
*/
RegistrationSessionMetadata session_metadata = 2;
/**
* If a code could not be sent, explains the underlying error. Will be absent
* if a code was sent successfully. Note that both an error and session
* metadata may be present in the same response because the session metadata
* may include information helpful for resolving the underlying error (i.e.
* "next attempt" times).
*/
SendVerificationCodeError error = 3;
}
message SendVerificationCodeError {
/**
* The type of error that prevented a verification code from being sent.
*/
SendVerificationCodeErrorType error_type = 1;
/**
* Indicates that this error may succeed if retried without modification after
* a delay indicated by `retry_after_seconds`. If false, callers should not
* retry the request without modification.
*/
bool may_retry = 2;
/**
* If this error may be retried,, indicates the duration in seconds from the
* present after which the request may be retried without modification. This
* value has no meaning otherwise.
*/
uint64 retry_after_seconds = 3;
}
enum SendVerificationCodeErrorType {
SEND_VERIFICATION_CODE_ERROR_TYPE_UNSPECIFIED = 0;
/**
* The sender received and understood the request to send a verification code,
* but declined to do so (i.e. due to rate limits or suspected fraud).
*/
SEND_VERIFICATION_CODE_ERROR_TYPE_SENDER_REJECTED = 1;
/**
* The sender could not process or would not accept some part of a request
* (e.g. a valid phone number that cannot receive SMS messages).
*/
SEND_VERIFICATION_CODE_ERROR_TYPE_SENDER_ILLEGAL_ARGUMENT = 2;
/**
* A verification could could not be sent via the requested channel due to
* timing/rate restrictions. The response object containing this error should
* include session metadata that indicates when the next attempt is allowed.
*/
SEND_VERIFICATION_CODE_ERROR_TYPE_RATE_LIMITED = 3;
/**
* No session was found with the given ID.
*/
SEND_VERIFICATION_CODE_ERROR_TYPE_SESSION_NOT_FOUND = 4;
/**
* A new verification could could not be sent because the session has already
* been verified.
*/
SEND_VERIFICATION_CODE_ERROR_TYPE_SESSION_ALREADY_VERIFIED = 5;
}
message CheckVerificationCodeRequest {
@@ -153,4 +237,70 @@ message CheckVerificationCodeResponse {
* matched the expected code or false otherwise.
*/
bool verified = 1;
/**
* Metadata for the named session. May be absent if the session could not be
* found or has expired.
*/
RegistrationSessionMetadata session_metadata = 2;
/**
* If a code could not be checked, explains the underlying error. Will be
* absent if no error occurred. Note that both an error and session
* metadata may be present in the same response because the session metadata
* may include information helpful for resolving the underlying error (i.e.
* "next attempt" times).
*/
CheckVerificationCodeError error = 3;
}
message CheckVerificationCodeError {
/**
* The type of error that prevented a verification code from being checked.
*/
CheckVerificationCodeErrorType error_type = 1;
/**
* Indicates that this error may succeed if retried without modification after
* a delay indicated by `retry_after_seconds`. If false, callers should not
* retry the request without modification.
*/
bool may_retry = 2;
/**
* If this error may be retried,, indicates the duration in seconds from the
* present after which the request may be retried without modification. This
* value has no meaning otherwise.
*/
uint64 retry_after_seconds = 3;
}
enum CheckVerificationCodeErrorType {
CHECK_VERIFICATION_CODE_ERROR_TYPE_UNSPECIFIED = 0;
/**
* The caller has made too many incorrect guesses within the scope of this
* session and may not make any further guesses.
*/
CHECK_VERIFICATION_CODE_ERROR_TYPE_ATTEMPTS_EXHAUSTED = 1;
/**
* The caller has attempted to submit a verification code even though no
* verification codes have been sent within the scope of this session. The
* caller must issue a "send code" request before trying again.
*/
CHECK_VERIFICATION_CODE_ERROR_TYPE_NO_CODE_SENT = 2;
/**
* The caller has made too many guesses within some period of time. Callers
* should wait for the duration prescribed in the session metadata object
* elsewhere in the response before trying again.
*/
CHECK_VERIFICATION_CODE_ERROR_TYPE_RATE_LIMITED = 3;
/**
* The session identified in this request could not be found (possibly due to
* session expiration).
*/
CHECK_VERIFICATION_CODE_ERROR_TYPE_SESSION_NOT_FOUND = 4;
}
+2 -1
View File
@@ -33,7 +33,8 @@ message Envelope {
optional bool urgent = 14 [default=true];
optional string updated_pni = 15;
optional bool story = 16; // indicates that the content is a story.
// next: 17
optional bytes report_spam_token = 17; // token sent when reporting spam
// next: 18
}
message ProvisioningUuid {
@@ -8,6 +8,7 @@ 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;
@@ -17,6 +18,7 @@ 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;
@@ -65,6 +67,8 @@ 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.abuse.ReportSpamTokenHandler;
import org.whispersystems.textsecuregcm.abuse.ReportSpamTokenProvider;
import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
import org.whispersystems.textsecuregcm.auth.DisabledPermittedAuthenticatedAccount;
import org.whispersystems.textsecuregcm.auth.OptionalAccess;
@@ -79,6 +83,7 @@ import org.whispersystems.textsecuregcm.entities.OutgoingMessageEntity;
import org.whispersystems.textsecuregcm.entities.OutgoingMessageEntityList;
import org.whispersystems.textsecuregcm.entities.SendMultiRecipientMessageResponse;
import org.whispersystems.textsecuregcm.entities.SignedPreKey;
import org.whispersystems.textsecuregcm.entities.SpamReport;
import org.whispersystems.textsecuregcm.entities.StaleDevices;
import org.whispersystems.textsecuregcm.limits.RateLimiter;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
@@ -124,8 +129,6 @@ class MessageControllerTest {
private static final String INTERNATIONAL_RECIPIENT = "+61123456789";
private static final UUID INTERNATIONAL_UUID = UUID.fromString("33333333-3333-3333-3333-333333333333");
private Account internationalAccount;
@SuppressWarnings("unchecked")
private static final RedisAdvancedClusterCommands<String, String> redisCommands = mock(RedisAdvancedClusterCommands.class);
@@ -139,6 +142,7 @@ 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)
@@ -150,7 +154,8 @@ class MessageControllerTest {
.setTestContainerFactory(new GrizzlyWebTestContainerFactory())
.addResource(
new MessageController(rateLimiters, messageSender, receiptSender, accountsManager, deletedAccountsManager,
messagesManager, pushNotificationManager, reportMessageManager, multiRecipientMessageExecutor))
messagesManager, pushNotificationManager, reportMessageManager, multiRecipientMessageExecutor,
ReportSpamTokenProvider.noop(), REPORT_SPAM_TOKEN_HANDLER))
.build();
@BeforeEach
@@ -167,7 +172,8 @@ class MessageControllerTest {
Account singleDeviceAccount = AccountsHelper.generateTestAccount(SINGLE_DEVICE_RECIPIENT, SINGLE_DEVICE_UUID, SINGLE_DEVICE_PNI, singleDeviceList, UNIDENTIFIED_ACCESS_BYTES);
Account multiDeviceAccount = AccountsHelper.generateTestAccount(MULTI_DEVICE_RECIPIENT, MULTI_DEVICE_UUID, MULTI_DEVICE_PNI, multiDeviceList, UNIDENTIFIED_ACCESS_BYTES);
internationalAccount = AccountsHelper.generateTestAccount(INTERNATIONAL_RECIPIENT, INTERNATIONAL_UUID, UUID.randomUUID(), singleDeviceList, UNIDENTIFIED_ACCESS_BYTES);
Account internationalAccount = AccountsHelper.generateTestAccount(INTERNATIONAL_RECIPIENT, INTERNATIONAL_UUID,
UUID.randomUUID(), singleDeviceList, UNIDENTIFIED_ACCESS_BYTES);
when(accountsManager.getByAccountIdentifier(eq(SINGLE_DEVICE_UUID))).thenReturn(Optional.of(singleDeviceAccount));
when(accountsManager.getByPhoneNumberIdentifier(SINGLE_DEVICE_PNI)).thenReturn(Optional.of(singleDeviceAccount));
@@ -176,6 +182,8 @@ 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) {
@@ -198,12 +206,14 @@ class MessageControllerTest {
messageSender,
receiptSender,
accountsManager,
deletedAccountsManager,
messagesManager,
rateLimiters,
rateLimiter,
pushNotificationManager,
reportMessageManager,
multiRecipientMessageExecutor
multiRecipientMessageExecutor,
REPORT_SPAM_TOKEN_HANDLER
);
}
@@ -692,6 +702,64 @@ class MessageControllerTest {
messageGuid, AuthHelper.VALID_UUID);
}
@Test
void testReportMessageByAciWithSpamReportToken() {
final String senderNumber = "+12125550001";
final UUID senderAci = UUID.randomUUID();
final UUID senderPni = UUID.randomUUID();
UUID messageGuid = UUID.randomUUID();
final Account account = mock(Account.class);
when(account.getUuid()).thenReturn(senderAci);
when(account.getNumber()).thenReturn(senderNumber);
when(account.getPhoneNumberIdentifier()).thenReturn(senderPni);
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");
Response response =
resources.getJerseyTest()
.target(String.format("/v1/messages/report/%s/%s", senderAci, messageGuid))
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.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(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");
response =
resources.getJerseyTest()
.target(String.format("/v1/messages/report/%s/%s", senderAci, messageGuid))
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.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);
}
@Test
void testValidateContentLength() throws Exception {
final int contentLength = Math.toIntExact(MessageController.MAX_MESSAGE_SIZE + 1);