mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-11-30 15:16:47 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fdf7b69996 | ||
|
|
92d36b725f | ||
|
|
4e131858ca | ||
|
|
a45d95905e | ||
|
|
0fdfdabf2a | ||
|
|
a25e967978 | ||
|
|
38e30c7513 | ||
|
|
e38e5fa17d | ||
|
|
c1f9bedf2f | ||
|
|
dd5d0ea2b3 | ||
|
|
42fd29d38b | ||
|
|
bf6d3aa324 | ||
|
|
023ccc6563 | ||
|
|
da49db5b9e | ||
|
|
cc8dda28cc | ||
|
|
47300c1d44 | ||
|
|
d31550d444 |
No files matched your search
+1
-1
Submodule abusive-message-filter updated: 6094634b57...d9fc2a79b8.
@@ -67,6 +67,7 @@
|
||||
<semver4j.version>3.1.0</semver4j.version>
|
||||
<slf4j.version>1.7.30</slf4j.version>
|
||||
<stripe.version>20.79.0</stripe.version>
|
||||
<vavr.version>0.10.4</vavr.version>
|
||||
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
</properties>
|
||||
@@ -179,6 +180,11 @@
|
||||
<artifactId>lettuce-core</artifactId>
|
||||
<version>${lettuce.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.vavr</groupId>
|
||||
<artifactId>vavr</artifactId>
|
||||
<version>${vavr.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.xml.bind</groupId>
|
||||
<artifactId>jaxb-api</artifactId>
|
||||
@@ -269,7 +275,7 @@
|
||||
<dependency>
|
||||
<groupId>org.signal</groupId>
|
||||
<artifactId>libsignal-server</artifactId>
|
||||
<version>0.16.0</version>
|
||||
<version>0.18.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.logging.log4j</groupId>
|
||||
|
||||
@@ -373,6 +373,10 @@
|
||||
<artifactId>reactor-core</artifactId>
|
||||
<version>3.3.16.RELEASE</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.vavr</groupId>
|
||||
<artifactId>vavr</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
|
||||
@@ -11,7 +11,6 @@ import com.amazonaws.auth.InstanceProfileCredentialsProvider;
|
||||
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
|
||||
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder;
|
||||
import com.codahale.metrics.SharedMetricRegistries;
|
||||
import com.codahale.metrics.jdbi3.strategies.DefaultNameStrategy;
|
||||
import com.fasterxml.jackson.annotation.JsonAutoDetect;
|
||||
import com.fasterxml.jackson.annotation.PropertyAccessor;
|
||||
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||
@@ -24,8 +23,6 @@ import io.dropwizard.auth.PolymorphicAuthDynamicFeature;
|
||||
import io.dropwizard.auth.PolymorphicAuthValueFactoryProvider;
|
||||
import io.dropwizard.auth.basic.BasicCredentialAuthFilter;
|
||||
import io.dropwizard.auth.basic.BasicCredentials;
|
||||
import io.dropwizard.db.PooledDataSourceFactory;
|
||||
import io.dropwizard.jdbi3.JdbiFactory;
|
||||
import io.dropwizard.setup.Bootstrap;
|
||||
import io.dropwizard.setup.Environment;
|
||||
import io.lettuce.core.resource.ClientResources;
|
||||
@@ -55,7 +52,6 @@ import javax.servlet.FilterRegistration;
|
||||
import javax.servlet.ServletRegistration;
|
||||
import org.eclipse.jetty.servlets.CrossOriginFilter;
|
||||
import org.glassfish.jersey.server.ServerProperties;
|
||||
import org.jdbi.v3.core.Jdbi;
|
||||
import org.signal.i18n.HeaderControlledResourceBundleLookup;
|
||||
import org.signal.libsignal.zkgroup.ServerSecretParams;
|
||||
import org.signal.libsignal.zkgroup.auth.ServerZkAuthOperations;
|
||||
@@ -178,7 +174,6 @@ import org.whispersystems.textsecuregcm.storage.DeletedAccountsTableCrawler;
|
||||
import org.whispersystems.textsecuregcm.storage.DirectoryReconciler;
|
||||
import org.whispersystems.textsecuregcm.storage.DirectoryReconciliationClient;
|
||||
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
|
||||
import org.whispersystems.textsecuregcm.storage.FaultTolerantDatabase;
|
||||
import org.whispersystems.textsecuregcm.storage.IssuedReceiptsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Keys;
|
||||
import org.whispersystems.textsecuregcm.storage.MessagePersister;
|
||||
@@ -377,12 +372,15 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
|
||||
ScheduledExecutorService recurringJobExecutor = environment.lifecycle()
|
||||
.scheduledExecutorService(name(getClass(), "recurringJob-%d")).threads(6).build();
|
||||
ScheduledExecutorService retrySchedulingExecutor = environment.lifecycle().scheduledExecutorService(name(getClass(), "retry-%d")).threads(2).build();
|
||||
ScheduledExecutorService websocketScheduledExecutor = environment.lifecycle().scheduledExecutorService(name(getClass(), "websocket-%d")).threads(8).build();
|
||||
ExecutorService keyspaceNotificationDispatchExecutor = environment.lifecycle().executorService(name(getClass(), "keyspaceNotification-%d")).maxThreads(16).workQueue(keyspaceNotificationDispatchQueue).build();
|
||||
ExecutorService apnSenderExecutor = environment.lifecycle().executorService(name(getClass(), "apnSender-%d")).maxThreads(1).minThreads(1).build();
|
||||
ExecutorService gcmSenderExecutor = environment.lifecycle().executorService(name(getClass(), "gcmSender-%d")).maxThreads(1).minThreads(1).build();
|
||||
ExecutorService backupServiceExecutor = environment.lifecycle().executorService(name(getClass(), "backupService-%d")).maxThreads(1).minThreads(1).build();
|
||||
ExecutorService storageServiceExecutor = environment.lifecycle().executorService(name(getClass(), "storageService-%d")).maxThreads(1).minThreads(1).build();
|
||||
|
||||
// TODO: generally speaking this is a DynamoDB I/O executor for the accounts table; we should eventually have a general executor for speaking to the accounts table, but most of the server is still synchronous so this isn't widely useful yet
|
||||
ExecutorService batchIdentityCheckExecutor = environment.lifecycle().executorService(name(getClass(), "batchIdentityCheck-%d")).minThreads(32).maxThreads(32).build();
|
||||
ExecutorService multiRecipientMessageExecutor = environment.lifecycle()
|
||||
.executorService(name(getClass(), "multiRecipientMessage-%d")).minThreads(64).maxThreads(64).build();
|
||||
ExecutorService stripeExecutor = environment.lifecycle().executorService(name(getClass(), "stripe-%d")).
|
||||
@@ -606,7 +604,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
webSocketEnvironment.setAuthenticator(new WebSocketAccountAuthenticator(accountAuthenticator));
|
||||
webSocketEnvironment.setConnectListener(
|
||||
new AuthenticatedConnectListener(receiptSender, messagesManager, messageSender, apnFallbackManager,
|
||||
clientPresenceManager, retrySchedulingExecutor));
|
||||
clientPresenceManager, websocketScheduledExecutor));
|
||||
webSocketEnvironment.jersey().register(new WebsocketRefreshApplicationEventListener(accountsManager, clientPresenceManager));
|
||||
webSocketEnvironment.jersey().register(new ContentLengthFilter(TrafficSource.WEBSOCKET));
|
||||
webSocketEnvironment.jersey().register(MultiDeviceMessageListProvider.class);
|
||||
@@ -626,7 +624,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
new AttachmentControllerV1(rateLimiters, config.getAwsAttachmentsConfiguration().getAccessKey(), config.getAwsAttachmentsConfiguration().getAccessSecret(), config.getAwsAttachmentsConfiguration().getBucket()),
|
||||
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),
|
||||
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),
|
||||
@@ -636,7 +634,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
|
||||
new MessageController(rateLimiters, messageSender, receiptSender, accountsManager, deletedAccountsManager,
|
||||
messagesManager, apnFallbackManager, reportMessageManager, multiRecipientMessageExecutor),
|
||||
new PaymentsController(currencyManager, paymentsCredentialsGenerator),
|
||||
new ProfileController(clock, rateLimiters, accountsManager, profilesManager, dynamicConfigurationManager, profileBadgeConverter, config.getBadges(), cdnS3Client, profileCdnPolicyGenerator, profileCdnPolicySigner, config.getCdnConfiguration().getBucket(), zkProfileOperations),
|
||||
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, config.getRemoteConfigConfiguration().getAuthorizedTokens(), config.getRemoteConfigConfiguration().getGlobalConfig()),
|
||||
new SecureBackupController(backupCredentialsGenerator),
|
||||
|
||||
+11
-3
@@ -74,6 +74,7 @@ import org.whispersystems.textsecuregcm.entities.RegistrationLock;
|
||||
import org.whispersystems.textsecuregcm.entities.RegistrationLockFailure;
|
||||
import org.whispersystems.textsecuregcm.entities.StaleDevices;
|
||||
import org.whispersystems.textsecuregcm.limits.RateLimiters;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
|
||||
import org.whispersystems.textsecuregcm.push.APNSender;
|
||||
import org.whispersystems.textsecuregcm.push.ApnMessage;
|
||||
@@ -121,6 +122,8 @@ public class AccountController {
|
||||
|
||||
private static final String TWILIO_VERIFY_ERROR_COUNTER_NAME = name(AccountController.class, "twilioVerifyError");
|
||||
|
||||
private static final String INVALID_ACCEPT_LANGUAGE_COUNTER_NAME = name(AccountController.class, "invalidAcceptLanguage");
|
||||
|
||||
private static final String CHALLENGE_PRESENT_TAG_NAME = "present";
|
||||
private static final String CHALLENGE_MATCH_TAG_NAME = "matches";
|
||||
private static final String COUNTRY_CODE_TAG_NAME = "countryCode";
|
||||
@@ -266,12 +269,17 @@ public class AccountController {
|
||||
|
||||
pendingAccounts.store(number, storedVerificationCode);
|
||||
|
||||
final List<Locale.LanguageRange> languageRanges;
|
||||
|
||||
List<Locale.LanguageRange> languageRanges;
|
||||
try {
|
||||
languageRanges = acceptLanguage.map(Locale.LanguageRange::parse).orElse(Collections.emptyList());
|
||||
} catch (final IllegalArgumentException e) {
|
||||
return Response.status(400).build();
|
||||
logger.debug("Could not get acceptable languages; Accept-Language: {}; User-Agent: {}",
|
||||
acceptLanguage.orElse(""),
|
||||
userAgent,
|
||||
e);
|
||||
|
||||
Metrics.counter(INVALID_ACCEPT_LANGUAGE_COUNTER_NAME, Tags.of(UserAgentTagUtil.getPlatformTag(userAgent))).increment();
|
||||
languageRanges = Collections.emptyList();
|
||||
}
|
||||
|
||||
final boolean enrolledInVerifyExperiment = verifyExperimentEnrollmentManager.isEnrolled(client, number, languageRanges, transport);
|
||||
|
||||
+62
-7
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2013-2021 Signal Messenger, LLC
|
||||
* Copyright 2013-2022 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
@@ -8,13 +8,22 @@ package org.whispersystems.textsecuregcm.controllers;
|
||||
import static com.codahale.metrics.MetricRegistry.name;
|
||||
|
||||
import com.codahale.metrics.annotation.Timed;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import java.security.InvalidKeyException;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import javax.annotation.Nonnull;
|
||||
import javax.ws.rs.BadRequestException;
|
||||
import javax.ws.rs.GET;
|
||||
import javax.ws.rs.Path;
|
||||
import javax.ws.rs.PathParam;
|
||||
@@ -34,15 +43,22 @@ import org.whispersystems.textsecuregcm.util.Util;
|
||||
@Path("/v1/certificate")
|
||||
public class CertificateController {
|
||||
|
||||
private final CertificateGenerator certificateGenerator;
|
||||
private final CertificateGenerator certificateGenerator;
|
||||
private final ServerZkAuthOperations serverZkAuthOperations;
|
||||
private final Clock clock;
|
||||
|
||||
@VisibleForTesting
|
||||
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";
|
||||
|
||||
public CertificateController(CertificateGenerator certificateGenerator, ServerZkAuthOperations serverZkAuthOperations) {
|
||||
this.certificateGenerator = certificateGenerator;
|
||||
this.serverZkAuthOperations = serverZkAuthOperations;
|
||||
public CertificateController(
|
||||
@Nonnull CertificateGenerator certificateGenerator,
|
||||
@Nonnull ServerZkAuthOperations serverZkAuthOperations,
|
||||
@Nonnull Clock clock) {
|
||||
this.certificateGenerator = Objects.requireNonNull(certificateGenerator);
|
||||
this.serverZkAuthOperations = Objects.requireNonNull(serverZkAuthOperations);
|
||||
this.clock = Objects.requireNonNull(clock);
|
||||
}
|
||||
|
||||
@Timed
|
||||
@@ -76,10 +92,11 @@ public class CertificateController {
|
||||
if (startRedemptionTime > endRedemptionTime) {
|
||||
throw new WebApplicationException(Response.Status.BAD_REQUEST);
|
||||
}
|
||||
if (endRedemptionTime > Util.currentDaysSinceEpoch() + 7) {
|
||||
final int currentDaysSinceEpoch = Util.currentDaysSinceEpoch(clock);
|
||||
if (endRedemptionTime > currentDaysSinceEpoch + 7) {
|
||||
throw new WebApplicationException(Response.Status.BAD_REQUEST);
|
||||
}
|
||||
if (startRedemptionTime < Util.currentDaysSinceEpoch()) {
|
||||
if (startRedemptionTime < currentDaysSinceEpoch) {
|
||||
throw new WebApplicationException(Response.Status.BAD_REQUEST);
|
||||
}
|
||||
|
||||
@@ -98,4 +115,42 @@ public class CertificateController {
|
||||
return new GroupCredentials(credentials);
|
||||
}
|
||||
|
||||
@Timed
|
||||
@GET
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Path("/auth/group")
|
||||
public GroupCredentials getGroupAuthenticationCredentials(
|
||||
@Auth AuthenticatedAccount auth,
|
||||
@QueryParam("redemptionStartSeconds") int startSeconds,
|
||||
@QueryParam("redemptionEndSeconds") int endSeconds) {
|
||||
|
||||
final Instant startOfDay = clock.instant().truncatedTo(ChronoUnit.DAYS);
|
||||
final Instant redemptionStart = Instant.ofEpochSecond(startSeconds);
|
||||
final Instant redemptionEnd = Instant.ofEpochSecond(endSeconds);
|
||||
|
||||
if (redemptionStart.isAfter(redemptionEnd) ||
|
||||
redemptionStart.isBefore(startOfDay) ||
|
||||
redemptionEnd.isAfter(startOfDay.plus(MAX_REDEMPTION_DURATION)) ||
|
||||
!redemptionStart.equals(redemptionStart.truncatedTo(ChronoUnit.DAYS)) ||
|
||||
!redemptionEnd.equals(redemptionEnd.truncatedTo(ChronoUnit.DAYS))) {
|
||||
|
||||
throw new BadRequestException();
|
||||
}
|
||||
|
||||
final List<GroupCredentials.GroupCredential> credentials = new ArrayList<>();
|
||||
|
||||
Instant redemption = redemptionStart;
|
||||
|
||||
UUID aci = auth.getAccount().getUuid();
|
||||
UUID pni = auth.getAccount().getPhoneNumberIdentifier();
|
||||
while (!redemption.isAfter(redemptionEnd)) {
|
||||
credentials.add(new GroupCredentials.GroupCredential(
|
||||
serverZkAuthOperations.issueAuthCredentialWithPni(aci, pni, redemption).serialize(),
|
||||
(int) redemption.getEpochSecond()));
|
||||
|
||||
redemption = redemption.plus(Duration.ofDays(1));
|
||||
}
|
||||
|
||||
return new GroupCredentials(credentials);
|
||||
}
|
||||
}
|
||||
+1
-26
@@ -9,7 +9,6 @@ import static com.codahale.metrics.MetricRegistry.name;
|
||||
import com.codahale.metrics.annotation.Timed;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.protobuf.ByteString;
|
||||
import com.vdurmont.semver4j.Semver;
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.dropwizard.util.DataSize;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
@@ -93,9 +92,7 @@ import org.whispersystems.textsecuregcm.storage.ReportMessageManager;
|
||||
import org.whispersystems.textsecuregcm.util.MessageValidation;
|
||||
import org.whispersystems.textsecuregcm.util.Pair;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
|
||||
import org.whispersystems.textsecuregcm.util.ua.UnrecognizedUserAgentException;
|
||||
import org.whispersystems.textsecuregcm.util.ua.UserAgent;
|
||||
import org.whispersystems.textsecuregcm.util.ua.UserAgentUtil;
|
||||
import org.whispersystems.textsecuregcm.websocket.WebSocketConnection;
|
||||
|
||||
@@ -115,12 +112,6 @@ public class MessageController {
|
||||
private final ReportMessageManager reportMessageManager;
|
||||
private final ExecutorService multiRecipientMessageExecutor;
|
||||
|
||||
@VisibleForTesting
|
||||
static final Semver FIRST_IOS_VERSION_WITH_INCORRECT_ENVELOPE_TYPE = new Semver("5.22.0");
|
||||
|
||||
@VisibleForTesting
|
||||
static final Semver IOS_VERSION_WITH_FIXED_ENVELOPE_TYPE = new Semver("5.25.0");
|
||||
|
||||
private static final String REJECT_OVERSIZE_MESSAGE_COUNTER = name(MessageController.class, "rejectOversizeMessage");
|
||||
private static final String SENT_MESSAGE_COUNTER_NAME = name(MessageController.class, "sentMessages");
|
||||
private static final String CONTENT_SIZE_DISTRIBUTION_NAME = name(MessageController.class, "messageContentSize");
|
||||
@@ -610,23 +601,7 @@ public class MessageController {
|
||||
Optional<byte[]> messageContent = getMessageContent(incomingMessage);
|
||||
Envelope.Builder messageBuilder = Envelope.newBuilder();
|
||||
|
||||
int envelopeTypeNumber = incomingMessage.getType();
|
||||
|
||||
// Some versions of the iOS app incorrectly use the reserved envelope type 7 for PLAINTEXT_CONTENT instead of type
|
||||
// 8. This check can be removed safely after 2022-03-01.
|
||||
if (envelopeTypeNumber == 7) {
|
||||
try {
|
||||
final UserAgent userAgent = UserAgentUtil.parseUserAgentString(userAgentString);
|
||||
if (userAgent.getPlatform() == ClientPlatform.IOS &&
|
||||
FIRST_IOS_VERSION_WITH_INCORRECT_ENVELOPE_TYPE.isLowerThanOrEqualTo(userAgent.getVersion()) &&
|
||||
userAgent.getVersion().isLowerThan(IOS_VERSION_WITH_FIXED_ENVELOPE_TYPE)) {
|
||||
envelopeTypeNumber = Type.PLAINTEXT_CONTENT.getNumber();
|
||||
}
|
||||
} catch (final UnrecognizedUserAgentException ignored2) {
|
||||
}
|
||||
}
|
||||
|
||||
final Envelope.Type envelopeType = Envelope.Type.forNumber(envelopeTypeNumber);
|
||||
final Envelope.Type envelopeType = Envelope.Type.forNumber(incomingMessage.getType());
|
||||
|
||||
if (envelopeType == null) {
|
||||
logger.warn("Received bad envelope type {} from {}", incomingMessage.getType(), userAgentString);
|
||||
|
||||
+96
-46
@@ -8,17 +8,22 @@ package org.whispersystems.textsecuregcm.controllers;
|
||||
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
|
||||
|
||||
import com.codahale.metrics.annotation.Timed;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import com.google.common.base.Preconditions;
|
||||
import io.dropwizard.auth.Auth;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.Tags;
|
||||
import io.vavr.Tuple;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.SecureRandom;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Base64;
|
||||
@@ -32,6 +37,7 @@ import java.util.Map.Entry;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
import javax.validation.Valid;
|
||||
@@ -63,6 +69,7 @@ import org.apache.commons.codec.binary.Hex;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.signal.libsignal.zkgroup.VerificationFailedException;
|
||||
import org.signal.libsignal.zkgroup.profiles.ExpiringProfileKeyCredentialResponse;
|
||||
import org.signal.libsignal.zkgroup.profiles.PniCredentialResponse;
|
||||
import org.signal.libsignal.zkgroup.profiles.ProfileKeyCommitment;
|
||||
import org.signal.libsignal.zkgroup.profiles.ProfileKeyCredentialRequest;
|
||||
@@ -83,6 +90,7 @@ import org.whispersystems.textsecuregcm.entities.BatchIdentityCheckRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.BatchIdentityCheckResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.CreateProfileRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.CredentialProfileResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.ExpiringProfileKeyCredentialProfileResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.PniCredentialProfileResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.ProfileAvatarUploadAttributes;
|
||||
import org.whispersystems.textsecuregcm.entities.ProfileKeyCredentialProfileResponse;
|
||||
@@ -124,8 +132,14 @@ public class ProfileController {
|
||||
private final S3Client s3client;
|
||||
private final String bucket;
|
||||
|
||||
private final Executor batchIdentityCheckExecutor;
|
||||
|
||||
@VisibleForTesting
|
||||
static final Duration EXPIRING_PROFILE_KEY_CREDENTIAL_EXPIRATION = Duration.ofDays(7);
|
||||
|
||||
private static final String PROFILE_KEY_CREDENTIAL_TYPE = "profileKey";
|
||||
private static final String PNI_CREDENTIAL_TYPE = "pni";
|
||||
private static final String EXPIRING_PROFILE_KEY_CREDENTIAL_TYPE = "expiringProfileKey";
|
||||
|
||||
private static final Counter VERSION_NOT_FOUND_COUNTER = Metrics.counter(name(ProfileController.class, "versionNotFound"));
|
||||
private static final String INVALID_ACCEPT_LANGUAGE_COUNTER_NAME = name(ProfileController.class, "invalidAcceptLanguage");
|
||||
@@ -142,7 +156,8 @@ public class ProfileController {
|
||||
PostPolicyGenerator policyGenerator,
|
||||
PolicySigner policySigner,
|
||||
String bucket,
|
||||
ServerZkProfileOperations zkProfileOperations) {
|
||||
ServerZkProfileOperations zkProfileOperations,
|
||||
Executor batchIdentityCheckExecutor) {
|
||||
this.clock = clock;
|
||||
this.rateLimiters = rateLimiters;
|
||||
this.accountsManager = accountsManager;
|
||||
@@ -156,6 +171,7 @@ public class ProfileController {
|
||||
this.s3client = s3client;
|
||||
this.policyGenerator = policyGenerator;
|
||||
this.policySigner = policySigner;
|
||||
this.batchIdentityCheckExecutor = Preconditions.checkNotNull(batchIdentityCheckExecutor);
|
||||
}
|
||||
|
||||
@Timed
|
||||
@@ -278,6 +294,15 @@ public class ProfileController {
|
||||
containerRequestContext);
|
||||
}
|
||||
|
||||
case EXPIRING_PROFILE_KEY_CREDENTIAL_TYPE -> {
|
||||
return buildExpiringProfileKeyCredentialProfileResponse(targetAccount,
|
||||
version,
|
||||
credentialRequest,
|
||||
isSelf,
|
||||
Instant.now().plus(EXPIRING_PROFILE_KEY_CREDENTIAL_EXPIRATION).truncatedTo(ChronoUnit.DAYS),
|
||||
containerRequestContext);
|
||||
}
|
||||
|
||||
default -> throw new BadRequestException();
|
||||
}
|
||||
}
|
||||
@@ -330,59 +355,51 @@ public class ProfileController {
|
||||
@Path("/identity_check/batch")
|
||||
public CompletableFuture<BatchIdentityCheckResponse> runBatchIdentityCheck(@NotNull @Valid BatchIdentityCheckRequest request) {
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
List<BatchIdentityCheckResponse.Element> responseElements = Collections.synchronizedList(new ArrayList<>());
|
||||
BatchIdentityCheckResponse response = new BatchIdentityCheckResponse(responseElements);
|
||||
List<BatchIdentityCheckResponse.Element> responseElements = Collections.synchronizedList(new ArrayList<>());
|
||||
|
||||
// for small requests only run one batch
|
||||
if (request.elements().size() <= 30) {
|
||||
MessageDigest sha256;
|
||||
try {
|
||||
sha256 = MessageDigest.getInstance("SHA-256");
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new AssertionError(e);
|
||||
}
|
||||
for (final BatchIdentityCheckRequest.Element element : request.elements()) {
|
||||
checkFingerprintAndAdd(element, responseElements, sha256);
|
||||
}
|
||||
} else {
|
||||
final int batchCount = 10;
|
||||
final int batchSize = request.elements().size() / batchCount;
|
||||
@SuppressWarnings("rawtypes") CompletableFuture[] futures = new CompletableFuture[batchCount];
|
||||
final int targetBatchCount = 10;
|
||||
// clamp the amount per batch to be in the closed range [30, 100]
|
||||
final int batchSize = Math.min(Math.max(request.elements().size() / targetBatchCount, 30), 100);
|
||||
// add 1 extra batch if there is any remainder to consume the final non-full batch
|
||||
final int batchCount =
|
||||
request.elements().size() / batchSize + (request.elements().size() % batchSize != 0 ? 1 : 0);
|
||||
|
||||
for (int i = 0; i < batchCount; i++) {
|
||||
List<BatchIdentityCheckRequest.Element> batch = request.elements()
|
||||
.subList(i * batchSize, Math.min((i + 1) * batchSize, request.elements().size()));
|
||||
futures[i] = CompletableFuture.runAsync(() -> {
|
||||
MessageDigest sha256;
|
||||
try {
|
||||
sha256 = MessageDigest.getInstance("SHA-256");
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new AssertionError(e);
|
||||
}
|
||||
for (final BatchIdentityCheckRequest.Element element : batch) {
|
||||
checkFingerprintAndAdd(element, responseElements, sha256);
|
||||
}
|
||||
});
|
||||
}
|
||||
@SuppressWarnings("rawtypes") CompletableFuture[] futures = new CompletableFuture[batchCount];
|
||||
for (int i = 0; i < batchCount; ++i) {
|
||||
List<BatchIdentityCheckRequest.Element> batch = request.elements()
|
||||
.subList(i * batchSize, Math.min((i + 1) * batchSize, request.elements().size()));
|
||||
futures[i] = CompletableFuture.runAsync(() -> {
|
||||
MessageDigest sha256;
|
||||
try {
|
||||
sha256 = MessageDigest.getInstance("SHA-256");
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new AssertionError(e);
|
||||
}
|
||||
for (final BatchIdentityCheckRequest.Element element : batch) {
|
||||
checkFingerprintAndAdd(element, responseElements, sha256);
|
||||
}
|
||||
}, batchIdentityCheckExecutor);
|
||||
}
|
||||
|
||||
CompletableFuture.allOf(futures).join();
|
||||
}
|
||||
return response;
|
||||
});
|
||||
return Tuple.of(futures, responseElements);
|
||||
}).thenCompose(tuple2 -> CompletableFuture.allOf(tuple2._1).thenApply((ignored) -> new BatchIdentityCheckResponse(tuple2._2)));
|
||||
}
|
||||
|
||||
private void checkFingerprintAndAdd(BatchIdentityCheckRequest.Element element, Collection<BatchIdentityCheckResponse.Element> responseElements, MessageDigest md) {
|
||||
private void checkFingerprintAndAdd(BatchIdentityCheckRequest.Element element,
|
||||
Collection<BatchIdentityCheckResponse.Element> responseElements, MessageDigest md) {
|
||||
accountsManager.getByAccountIdentifier(element.aci()).ifPresent(account -> {
|
||||
byte[] identityKeyBytes;
|
||||
try {
|
||||
byte[] identityKeyBytes = Base64.getDecoder().decode(account.getIdentityKey());
|
||||
md.reset();
|
||||
byte[] digest = md.digest(identityKeyBytes);
|
||||
byte[] fingerprint = Util.truncate(digest, 4);
|
||||
|
||||
if (!Arrays.equals(fingerprint, element.fingerprint())) {
|
||||
responseElements.add(new BatchIdentityCheckResponse.Element(element.aci(), identityKeyBytes));
|
||||
}
|
||||
identityKeyBytes = Base64.getDecoder().decode(account.getIdentityKey());
|
||||
} catch (IllegalArgumentException ignored) {
|
||||
return;
|
||||
}
|
||||
md.reset();
|
||||
byte[] digest = md.digest(identityKeyBytes);
|
||||
byte[] fingerprint = Util.truncate(digest, 4);
|
||||
|
||||
if (!Arrays.equals(fingerprint, element.fingerprint())) {
|
||||
responseElements.add(new BatchIdentityCheckResponse.Element(element.aci(), identityKeyBytes));
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -416,6 +433,23 @@ public class ProfileController {
|
||||
pniCredentialResponse);
|
||||
}
|
||||
|
||||
private ExpiringProfileKeyCredentialProfileResponse buildExpiringProfileKeyCredentialProfileResponse(
|
||||
final Account account,
|
||||
final String version,
|
||||
final String encodedCredentialRequest,
|
||||
final boolean isSelf,
|
||||
final Instant expiration,
|
||||
final ContainerRequestContext containerRequestContext) {
|
||||
|
||||
final ExpiringProfileKeyCredentialResponse expiringProfileKeyCredentialResponse = profilesManager.get(account.getUuid(), version)
|
||||
.map(profile -> getExpiringProfileKeyCredentialResponse(encodedCredentialRequest, profile, account.getUuid(), expiration))
|
||||
.orElse(null);
|
||||
|
||||
return new ExpiringProfileKeyCredentialProfileResponse(
|
||||
buildVersionedProfileResponse(account, version, isSelf, containerRequestContext),
|
||||
expiringProfileKeyCredentialResponse);
|
||||
}
|
||||
|
||||
private VersionedProfileResponse buildVersionedProfileResponse(final Account account,
|
||||
final String version,
|
||||
final boolean isSelf,
|
||||
@@ -515,6 +549,22 @@ public class ProfileController {
|
||||
}
|
||||
}
|
||||
|
||||
private ExpiringProfileKeyCredentialResponse getExpiringProfileKeyCredentialResponse(
|
||||
final String encodedCredentialRequest,
|
||||
final VersionedProfile profile,
|
||||
final UUID accountIdentifier,
|
||||
final Instant expiration) {
|
||||
|
||||
try {
|
||||
final ProfileKeyCommitment commitment = new ProfileKeyCommitment(profile.getCommitment());
|
||||
final ProfileKeyCredentialRequest request = new ProfileKeyCredentialRequest(Hex.decodeHex(encodedCredentialRequest));
|
||||
|
||||
return zkProfileOperations.issueExpiringProfileKeyCredential(request, accountIdentifier, commitment, expiration);
|
||||
} catch (DecoderException | VerificationFailedException | InvalidInputException e) {
|
||||
throw new WebApplicationException(e, Response.status(Response.Status.BAD_REQUEST).build());
|
||||
}
|
||||
}
|
||||
|
||||
private ProfileAvatarUploadAttributes generateAvatarUploadForm(String objectName) {
|
||||
ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC);
|
||||
Pair<String, String> policy = policyGenerator.createFor(now, objectName, 10 * 1024 * 1024);
|
||||
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
/*
|
||||
* Copyright 2013-2022 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
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 javax.annotation.Nullable;
|
||||
import org.signal.libsignal.zkgroup.profiles.ExpiringProfileKeyCredentialResponse;
|
||||
|
||||
public class ExpiringProfileKeyCredentialProfileResponse extends CredentialProfileResponse {
|
||||
|
||||
@JsonProperty
|
||||
@JsonSerialize(using = ExpiringProfileKeyCredentialResponseAdapter.Serializing.class)
|
||||
@JsonDeserialize(using = ExpiringProfileKeyCredentialResponseAdapter.Deserializing.class)
|
||||
@Nullable
|
||||
private ExpiringProfileKeyCredentialResponse credential;
|
||||
|
||||
public ExpiringProfileKeyCredentialProfileResponse() {
|
||||
}
|
||||
|
||||
public ExpiringProfileKeyCredentialProfileResponse(final VersionedProfileResponse versionedProfileResponse,
|
||||
@Nullable final ExpiringProfileKeyCredentialResponse credential) {
|
||||
|
||||
super(versionedProfileResponse);
|
||||
this.credential = credential;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public ExpiringProfileKeyCredentialResponse getCredential() {
|
||||
return credential;
|
||||
}
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
/*
|
||||
* Copyright 2013-2022 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.entities;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonGenerator;
|
||||
import com.fasterxml.jackson.core.JsonParser;
|
||||
import com.fasterxml.jackson.databind.DeserializationContext;
|
||||
import com.fasterxml.jackson.databind.JsonDeserializer;
|
||||
import com.fasterxml.jackson.databind.JsonSerializer;
|
||||
import com.fasterxml.jackson.databind.SerializerProvider;
|
||||
import java.io.IOException;
|
||||
import java.util.Base64;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.signal.libsignal.zkgroup.profiles.ExpiringProfileKeyCredentialResponse;
|
||||
|
||||
public class ExpiringProfileKeyCredentialResponseAdapter {
|
||||
|
||||
public static class Serializing extends JsonSerializer<ExpiringProfileKeyCredentialResponse> {
|
||||
@Override
|
||||
public void serialize(ExpiringProfileKeyCredentialResponse response, JsonGenerator jsonGenerator, SerializerProvider serializerProvider)
|
||||
throws IOException {
|
||||
if (response == null) jsonGenerator.writeNull();
|
||||
else jsonGenerator.writeString(Base64.getEncoder().encodeToString(response.serialize()));
|
||||
}
|
||||
}
|
||||
|
||||
public static class Deserializing extends JsonDeserializer<ExpiringProfileKeyCredentialResponse> {
|
||||
@Override
|
||||
public ExpiringProfileKeyCredentialResponse deserialize(JsonParser jsonParser, DeserializationContext deserializationContext)
|
||||
throws IOException {
|
||||
try {
|
||||
return new ExpiringProfileKeyCredentialResponse(Base64.getDecoder().decode(jsonParser.getValueAsString()));
|
||||
} catch (InvalidInputException e) {
|
||||
throw new IOException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+17
-5
@@ -55,6 +55,7 @@ public class ClientPresenceManager extends RedisClusterPubSubAdapter<String, Str
|
||||
private final FaultTolerantPubSubConnection<String, String> pubSubConnection;
|
||||
|
||||
private final ClusterLuaScript clearPresenceScript;
|
||||
private final ClusterLuaScript renewPresenceScript;
|
||||
|
||||
private final ExecutorService keyspaceNotificationExecutorService;
|
||||
private final ScheduledExecutorService scheduledExecutorService;
|
||||
@@ -71,6 +72,7 @@ public class ClientPresenceManager extends RedisClusterPubSubAdapter<String, Str
|
||||
private final Meter pubSubMessageMeter;
|
||||
|
||||
private static final int PRUNE_PEERS_INTERVAL_SECONDS = (int) Duration.ofSeconds(30).toSeconds();
|
||||
private static final int PRESENCE_EXPIRATION_SECONDS = (int) Duration.ofMinutes(11).toSeconds();
|
||||
|
||||
static final String MANAGER_SET_KEY = "presence::managers";
|
||||
|
||||
@@ -81,8 +83,8 @@ public class ClientPresenceManager extends RedisClusterPubSubAdapter<String, Str
|
||||
final ExecutorService keyspaceNotificationExecutorService) throws IOException {
|
||||
this.presenceCluster = presenceCluster;
|
||||
this.pubSubConnection = this.presenceCluster.createPubSubConnection();
|
||||
this.clearPresenceScript = ClusterLuaScript.fromResource(presenceCluster, "lua/clear_presence.lua",
|
||||
ScriptOutputType.INTEGER);
|
||||
this.clearPresenceScript = ClusterLuaScript.fromResource(presenceCluster, "lua/clear_presence.lua", ScriptOutputType.INTEGER);
|
||||
this.renewPresenceScript = ClusterLuaScript.fromResource(presenceCluster, "lua/renew_presence.lua", ScriptOutputType.VALUE);
|
||||
this.scheduledExecutorService = scheduledExecutorService;
|
||||
this.keyspaceNotificationExecutorService = keyspaceNotificationExecutorService;
|
||||
|
||||
@@ -151,8 +153,8 @@ public class ClientPresenceManager extends RedisClusterPubSubAdapter<String, Str
|
||||
connection -> connection.sync().upstream().commands().unsubscribe(getManagerPresenceChannel(managerId)));
|
||||
}
|
||||
|
||||
public void setPresent(final UUID accountUuid, final long deviceId,
|
||||
final DisplacedPresenceListener displacementListener) {
|
||||
public void setPresent(final UUID accountUuid, final long deviceId, final DisplacedPresenceListener displacementListener) {
|
||||
|
||||
try (final Timer.Context ignored = setPresenceTimer.time()) {
|
||||
final String presenceKey = getPresenceKey(accountUuid, deviceId);
|
||||
|
||||
@@ -164,13 +166,18 @@ public class ClientPresenceManager extends RedisClusterPubSubAdapter<String, Str
|
||||
final RedisAdvancedClusterCommands<String, String> commands = connection.sync();
|
||||
|
||||
commands.sadd(connectedClientSetKey, presenceKey);
|
||||
commands.set(presenceKey, managerId);
|
||||
commands.setex(presenceKey, PRESENCE_EXPIRATION_SECONDS, managerId);
|
||||
});
|
||||
|
||||
subscribeForRemotePresenceChanges(presenceKey);
|
||||
}
|
||||
}
|
||||
|
||||
public void renewPresence(final UUID accountUuid, final long deviceId) {
|
||||
renewPresenceScript.execute(List.of(getPresenceKey(accountUuid, deviceId)),
|
||||
List.of(managerId, String.valueOf(PRESENCE_EXPIRATION_SECONDS)));
|
||||
}
|
||||
|
||||
public void disconnectPresence(final UUID accountUuid, final long deviceId) {
|
||||
final String presenceKey = getPresenceKey(accountUuid, deviceId);
|
||||
|
||||
@@ -295,6 +302,11 @@ public class ClientPresenceManager extends RedisClusterPubSubAdapter<String, Str
|
||||
}
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
String getManagerId() {
|
||||
return managerId;
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
static String getPresenceKey(final UUID accountUuid, final long deviceId) {
|
||||
return "presence::{" + accountUuid.toString() + "::" + deviceId + "}";
|
||||
|
||||
@@ -27,6 +27,7 @@ import java.util.Optional;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import javax.annotation.Nonnull;
|
||||
|
||||
public class Util {
|
||||
|
||||
@@ -166,8 +167,18 @@ public class Util {
|
||||
return (int) value;
|
||||
}
|
||||
|
||||
public static int currentDaysSinceEpoch(@Nonnull Clock clock) {
|
||||
return toIntExact(clock.millis() / 1000 / 60/ 60 / 24);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the current number of days since the epoch.
|
||||
*
|
||||
* @deprecated use {@link #currentDaysSinceEpoch(Clock)} instead
|
||||
*/
|
||||
@Deprecated
|
||||
public static int currentDaysSinceEpoch() {
|
||||
return Util.toIntExact(System.currentTimeMillis() / 1000 / 60 / 60 / 24);
|
||||
return currentDaysSinceEpoch(Clock.systemUTC());
|
||||
}
|
||||
|
||||
public static void sleep(long i) {
|
||||
|
||||
+23
-4
@@ -12,6 +12,9 @@ import com.codahale.metrics.MetricRegistry;
|
||||
import com.codahale.metrics.SharedMetricRegistries;
|
||||
import com.codahale.metrics.Timer;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.ScheduledFuture;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
|
||||
@@ -33,6 +36,8 @@ public class AuthenticatedConnectListener implements WebSocketConnectListener {
|
||||
private static final Timer unauthenticatedDurationTimer = metricRegistry.timer(name(WebSocketConnection.class, "unauthenticated_connection_duration"));
|
||||
private static final Counter openWebsocketCounter = metricRegistry.counter(name(WebSocketConnection.class, "open_websockets"));
|
||||
|
||||
private static final long RENEW_PRESENCE_INTERVAL_MINUTES = 5;
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(AuthenticatedConnectListener.class);
|
||||
|
||||
private final ReceiptSender receiptSender;
|
||||
@@ -40,20 +45,20 @@ public class AuthenticatedConnectListener implements WebSocketConnectListener {
|
||||
private final MessageSender messageSender;
|
||||
private final ApnFallbackManager apnFallbackManager;
|
||||
private final ClientPresenceManager clientPresenceManager;
|
||||
private final ScheduledExecutorService retrySchedulingExecutor;
|
||||
private final ScheduledExecutorService scheduledExecutorService;
|
||||
|
||||
public AuthenticatedConnectListener(ReceiptSender receiptSender,
|
||||
MessagesManager messagesManager,
|
||||
final MessageSender messageSender, ApnFallbackManager apnFallbackManager,
|
||||
ClientPresenceManager clientPresenceManager,
|
||||
ScheduledExecutorService retrySchedulingExecutor)
|
||||
ScheduledExecutorService scheduledExecutorService)
|
||||
{
|
||||
this.receiptSender = receiptSender;
|
||||
this.messagesManager = messagesManager;
|
||||
this.messageSender = messageSender;
|
||||
this.apnFallbackManager = apnFallbackManager;
|
||||
this.clientPresenceManager = clientPresenceManager;
|
||||
this.retrySchedulingExecutor = retrySchedulingExecutor;
|
||||
this.scheduledExecutorService = scheduledExecutorService;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -65,17 +70,25 @@ public class AuthenticatedConnectListener implements WebSocketConnectListener {
|
||||
final WebSocketConnection connection = new WebSocketConnection(receiptSender,
|
||||
messagesManager, auth, device,
|
||||
context.getClient(),
|
||||
retrySchedulingExecutor);
|
||||
scheduledExecutorService);
|
||||
|
||||
openWebsocketCounter.inc();
|
||||
RedisOperation.unchecked(() -> apnFallbackManager.cancel(auth.getAccount(), device));
|
||||
|
||||
final AtomicReference<ScheduledFuture<?>> renewPresenceFutureReference = new AtomicReference<>();
|
||||
|
||||
context.addListener(new WebSocketSessionContext.WebSocketEventListener() {
|
||||
@Override
|
||||
public void onWebSocketClose(WebSocketSessionContext context, int statusCode, String reason) {
|
||||
openWebsocketCounter.dec();
|
||||
timer.stop();
|
||||
|
||||
final ScheduledFuture<?> renewPresenceFuture = renewPresenceFutureReference.get();
|
||||
|
||||
if (renewPresenceFuture != null) {
|
||||
renewPresenceFuture.cancel(false);
|
||||
}
|
||||
|
||||
connection.stop();
|
||||
|
||||
RedisOperation.unchecked(
|
||||
@@ -94,6 +107,12 @@ public class AuthenticatedConnectListener implements WebSocketConnectListener {
|
||||
connection.start();
|
||||
clientPresenceManager.setPresent(auth.getAccount().getUuid(), device.getId(), connection);
|
||||
messagesManager.addMessageAvailabilityListener(auth.getAccount().getUuid(), device.getId(), connection);
|
||||
|
||||
renewPresenceFutureReference.set(scheduledExecutorService.scheduleAtFixedRate(() -> RedisOperation.unchecked(() ->
|
||||
clientPresenceManager.renewPresence(auth.getAccount().getUuid(), device.getId())),
|
||||
RENEW_PRESENCE_INTERVAL_MINUTES,
|
||||
RENEW_PRESENCE_INTERVAL_MINUTES,
|
||||
TimeUnit.MINUTES));
|
||||
} catch (final Exception e) {
|
||||
log.warn("Failed to initialize websocket", e);
|
||||
context.getClient().close(1011, "Unexpected error initializing connection");
|
||||
|
||||
+6
-6
@@ -101,7 +101,7 @@ public class WebSocketConnection implements MessageAvailabilityListener, Displac
|
||||
|
||||
private final int sendFuturesTimeoutMillis;
|
||||
|
||||
private final ScheduledExecutorService retrySchedulingExecutor;
|
||||
private final ScheduledExecutorService scheduledExecutorService;
|
||||
|
||||
private final boolean isDesktopClient;
|
||||
|
||||
@@ -127,7 +127,7 @@ public class WebSocketConnection implements MessageAvailabilityListener, Displac
|
||||
AuthenticatedAccount auth,
|
||||
Device device,
|
||||
WebSocketClient client,
|
||||
ScheduledExecutorService retrySchedulingExecutor) {
|
||||
ScheduledExecutorService scheduledExecutorService) {
|
||||
|
||||
this(receiptSender,
|
||||
messagesManager,
|
||||
@@ -135,7 +135,7 @@ public class WebSocketConnection implements MessageAvailabilityListener, Displac
|
||||
device,
|
||||
client,
|
||||
DEFAULT_SEND_FUTURES_TIMEOUT_MILLIS,
|
||||
retrySchedulingExecutor);
|
||||
scheduledExecutorService);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
@@ -145,7 +145,7 @@ public class WebSocketConnection implements MessageAvailabilityListener, Displac
|
||||
Device device,
|
||||
WebSocketClient client,
|
||||
int sendFuturesTimeoutMillis,
|
||||
ScheduledExecutorService retrySchedulingExecutor) {
|
||||
ScheduledExecutorService scheduledExecutorService) {
|
||||
|
||||
this.receiptSender = receiptSender;
|
||||
this.messagesManager = messagesManager;
|
||||
@@ -153,7 +153,7 @@ public class WebSocketConnection implements MessageAvailabilityListener, Displac
|
||||
this.device = device;
|
||||
this.client = client;
|
||||
this.sendFuturesTimeoutMillis = sendFuturesTimeoutMillis;
|
||||
this.retrySchedulingExecutor = retrySchedulingExecutor;
|
||||
this.scheduledExecutorService = scheduledExecutorService;
|
||||
|
||||
Optional<ClientPlatform> maybePlatform;
|
||||
|
||||
@@ -294,7 +294,7 @@ public class WebSocketConnection implements MessageAvailabilityListener, Displac
|
||||
|
||||
final long delay = RETRY_DELAY_MILLIS + random.nextInt(RETRY_DELAY_JITTER_MILLIS);
|
||||
retryFuture
|
||||
.set(retrySchedulingExecutor.schedule(this::processStoredMessages, delay, TimeUnit.MILLISECONDS));
|
||||
.set(scheduledExecutorService.schedule(this::processStoredMessages, delay, TimeUnit.MILLISECONDS));
|
||||
}
|
||||
} else {
|
||||
logger.debug("Client disconnected before queue cleared");
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
local presenceKey = KEYS[1]
|
||||
local presenceUuid = ARGV[1]
|
||||
local expireSeconds = ARGV[2]
|
||||
|
||||
if redis.call("GET", presenceKey) == presenceUuid then
|
||||
redis.call("EXPIRE", presenceKey, expireSeconds)
|
||||
end
|
||||
@@ -16,16 +16,16 @@ TEST3_name = Test Badge Gamma
|
||||
TEST3_description = {short_name} is testing the gamma test badge.
|
||||
|
||||
R_LOW_name = Signal Star
|
||||
R_LOW_description = {short_name} is a Sustainer. Signal is a nonprofit with no advertisers or investors, supported only by people like you.
|
||||
R_LOW_description = {short_name} supports Signal with a monthly donation. Signal is a nonprofit with no advertisers or investors, supported only by people like you.
|
||||
|
||||
R_MED_name = Signal Planet
|
||||
R_MED_description = {short_name} is a Sustainer. Signal is a nonprofit with no advertisers or investors, supported only by people like you.
|
||||
R_MED_description = {short_name} supports Signal with a monthly donation. Signal is a nonprofit with no advertisers or investors, supported only by people like you.
|
||||
|
||||
R_HIGH_name = Signal Sun
|
||||
R_HIGH_description = {short_name} is a Sustainer. Signal is a nonprofit with no advertisers or investors, supported only by people like you.
|
||||
R_HIGH_description = {short_name} supports Signal with a monthly donation. Signal is a nonprofit with no advertisers or investors, supported only by people like you.
|
||||
|
||||
BOOST_name = Signal Boost
|
||||
BOOST_description = {short_name} supported Signal with a boost. Signal is a nonprofit with no advertisers or investors, supported only by people like you.
|
||||
BOOST_description = {short_name} supported Signal with a donation. Signal is a nonprofit with no advertisers or investors, supported only by people like you.
|
||||
|
||||
GIFT_name = Signal Gift
|
||||
GIFT_description = {short_name} received a gift from a Signal supporter. Signal is a nonprofit with no advertisers or investors, supported only by people like you.
|
||||
-33
@@ -229,39 +229,6 @@ class MessageControllerTest {
|
||||
assertTrue(captor.getValue().hasSourceDevice());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void testSingleDeviceCurrentBadType(final String userAgentString, final boolean expectAcceptMessage) throws Exception {
|
||||
Response response =
|
||||
resources.getJerseyTest()
|
||||
.target(String.format("/v1/messages/%s", SINGLE_DEVICE_UUID))
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.header("User-Agent", userAgentString)
|
||||
.put(Entity.entity(SystemMapper.getMapper().readValue(jsonFixture("fixtures/current_message_single_device_bad_type.json"), IncomingMessageList.class),
|
||||
MediaType.APPLICATION_JSON_TYPE));
|
||||
|
||||
if (expectAcceptMessage) {
|
||||
assertEquals(200, response.getStatus());
|
||||
|
||||
final ArgumentCaptor<Envelope> captor = ArgumentCaptor.forClass(Envelope.class);
|
||||
verify(messageSender).sendMessage(any(Account.class), any(Device.class), captor.capture(), eq(false));
|
||||
} else {
|
||||
assertEquals(400, response.getStatus());
|
||||
verify(messageSender, never()).sendMessage(any(), any(), any(), anyBoolean());
|
||||
}
|
||||
}
|
||||
|
||||
private static Stream<Arguments> testSingleDeviceCurrentBadType() {
|
||||
return Stream.of(
|
||||
Arguments.of(String.format("Signal-iOS/%s iOS/14.2", MessageController.FIRST_IOS_VERSION_WITH_INCORRECT_ENVELOPE_TYPE), true),
|
||||
Arguments.of(String.format("Signal-iOS/%s iOS/14.2", MessageController.FIRST_IOS_VERSION_WITH_INCORRECT_ENVELOPE_TYPE.nextPatch()), true),
|
||||
Arguments.of(String.format("Signal-iOS/%s iOS/14.2", new Semver("5.22.0.38")), true),
|
||||
Arguments.of(String.format("Signal-iOS/%s iOS/14.2", MessageController.IOS_VERSION_WITH_FIXED_ENVELOPE_TYPE.withIncMinor(-1)), true),
|
||||
Arguments.of(String.format("Signal-iOS/%s iOS/14.2", MessageController.IOS_VERSION_WITH_FIXED_ENVELOPE_TYPE), false)
|
||||
);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("currentMessageSingleDevicePayloads")
|
||||
void testSingleDeviceCurrentByPni(Entity<?> payload) throws Exception {
|
||||
|
||||
+158
-3
@@ -1,9 +1,9 @@
|
||||
/*
|
||||
* Copyright 2013-2021 Signal Messenger, LLC
|
||||
* Copyright 2013-2022 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.tests.controllers;
|
||||
package org.whispersystems.textsecuregcm.controllers;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatNoException;
|
||||
@@ -25,16 +25,22 @@ import io.dropwizard.auth.PolymorphicAuthValueFactoryProvider;
|
||||
import io.dropwizard.testing.junit5.DropwizardExtensionsSupport;
|
||||
import io.dropwizard.testing.junit5.ResourceExtension;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.SecureRandom;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Base64;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.stream.Stream;
|
||||
import javax.ws.rs.client.Entity;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
@@ -44,6 +50,7 @@ import javax.ws.rs.core.Response;
|
||||
import org.apache.commons.codec.binary.Hex;
|
||||
import org.apache.commons.lang3.RandomStringUtils;
|
||||
import org.assertj.core.api.Condition;
|
||||
import org.glassfish.jersey.server.ServerProperties;
|
||||
import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
@@ -58,6 +65,7 @@ import org.signal.libsignal.zkgroup.ServerPublicParams;
|
||||
import org.signal.libsignal.zkgroup.ServerSecretParams;
|
||||
import org.signal.libsignal.zkgroup.VerificationFailedException;
|
||||
import org.signal.libsignal.zkgroup.profiles.ClientZkProfileOperations;
|
||||
import org.signal.libsignal.zkgroup.profiles.ExpiringProfileKeyCredentialResponse;
|
||||
import org.signal.libsignal.zkgroup.profiles.PniCredentialResponse;
|
||||
import org.signal.libsignal.zkgroup.profiles.ProfileKey;
|
||||
import org.signal.libsignal.zkgroup.profiles.ProfileKeyCommitment;
|
||||
@@ -77,7 +85,10 @@ import org.whispersystems.textsecuregcm.controllers.RateLimitExceededException;
|
||||
import org.whispersystems.textsecuregcm.entities.Badge;
|
||||
import org.whispersystems.textsecuregcm.entities.BadgeSvg;
|
||||
import org.whispersystems.textsecuregcm.entities.BaseProfileResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.BatchIdentityCheckRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.BatchIdentityCheckResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.CreateProfileRequest;
|
||||
import org.whispersystems.textsecuregcm.entities.ExpiringProfileKeyCredentialProfileResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.PniCredentialProfileResponse;
|
||||
import org.whispersystems.textsecuregcm.entities.ProfileAvatarUploadAttributes;
|
||||
import org.whispersystems.textsecuregcm.entities.ProfileKeyCredentialProfileResponse;
|
||||
@@ -96,6 +107,7 @@ import org.whispersystems.textsecuregcm.storage.VersionedProfile;
|
||||
import org.whispersystems.textsecuregcm.tests.util.AccountsHelper;
|
||||
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
import org.whispersystems.textsecuregcm.util.Util;
|
||||
import software.amazon.awssdk.services.s3.S3Client;
|
||||
import software.amazon.awssdk.services.s3.model.DeleteObjectRequest;
|
||||
|
||||
@@ -123,6 +135,7 @@ class ProfileControllerTest {
|
||||
private Account profileAccount;
|
||||
|
||||
private static final ResourceExtension resources = ResourceExtension.builder()
|
||||
.addProperty(ServerProperties.UNWRAP_COMPLETION_STAGE_IN_WRITER_ENABLE, Boolean.TRUE)
|
||||
.addProvider(AuthHelper.getAuthFilter())
|
||||
.addProvider(new PolymorphicAuthValueFactoryProvider.Binder<>(
|
||||
ImmutableSet.of(AuthenticatedAccount.class, DisabledPermittedAuthenticatedAccount.class)))
|
||||
@@ -148,7 +161,8 @@ class ProfileControllerTest {
|
||||
postPolicyGenerator,
|
||||
policySigner,
|
||||
"profilesBucket",
|
||||
zkProfileOperations))
|
||||
zkProfileOperations,
|
||||
Executors.newSingleThreadExecutor()))
|
||||
.build();
|
||||
|
||||
@BeforeEach
|
||||
@@ -207,6 +221,8 @@ class ProfileControllerTest {
|
||||
when(profilesManager.get(eq(AuthHelper.VALID_UUID_TWO), eq("validversion"))).thenReturn(Optional.of(new VersionedProfile(
|
||||
"validversion", "validname", "profiles/validavatar", "emoji", "about", null, "validcommitmnet".getBytes())));
|
||||
|
||||
when(accountsManager.getByAccountIdentifier(AuthHelper.INVALID_UUID)).thenReturn(Optional.empty());
|
||||
|
||||
clearInvocations(rateLimiter);
|
||||
clearInvocations(accountsManager);
|
||||
clearInvocations(usernameRateLimiter);
|
||||
@@ -1118,6 +1134,76 @@ class ProfileControllerTest {
|
||||
verify(zkProfileOperations, never()).issuePniCredential(any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void testGetProfileWithExpiringProfileKeyCredential(final MultivaluedMap<String, Object> authHeaders)
|
||||
throws VerificationFailedException, InvalidInputException {
|
||||
final String version = "version";
|
||||
final byte[] unidentifiedAccessKey = "test-uak".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
final ServerSecretParams serverSecretParams = ServerSecretParams.generate();
|
||||
final ServerPublicParams serverPublicParams = serverSecretParams.getPublicParams();
|
||||
|
||||
final ServerZkProfileOperations serverZkProfile = new ServerZkProfileOperations(serverSecretParams);
|
||||
final ClientZkProfileOperations clientZkProfile = new ClientZkProfileOperations(serverPublicParams);
|
||||
|
||||
final byte[] profileKeyBytes = new byte[32];
|
||||
new SecureRandom().nextBytes(profileKeyBytes);
|
||||
|
||||
final ProfileKey profileKey = new ProfileKey(profileKeyBytes);
|
||||
final ProfileKeyCommitment profileKeyCommitment = profileKey.getCommitment(AuthHelper.VALID_UUID);
|
||||
|
||||
final VersionedProfile versionedProfile = mock(VersionedProfile.class);
|
||||
when(versionedProfile.getCommitment()).thenReturn(profileKeyCommitment.serialize());
|
||||
|
||||
final ProfileKeyCredentialRequestContext profileKeyCredentialRequestContext =
|
||||
clientZkProfile.createProfileKeyCredentialRequestContext(AuthHelper.VALID_UUID, profileKey);
|
||||
|
||||
final ProfileKeyCredentialRequest credentialRequest = profileKeyCredentialRequestContext.getRequest();
|
||||
|
||||
final Account account = mock(Account.class);
|
||||
when(account.getUuid()).thenReturn(AuthHelper.VALID_UUID);
|
||||
when(account.getCurrentProfileVersion()).thenReturn(Optional.of(version));
|
||||
when(account.isEnabled()).thenReturn(true);
|
||||
when(account.getUnidentifiedAccessKey()).thenReturn(Optional.of(unidentifiedAccessKey));
|
||||
|
||||
final Instant expiration = Instant.now().plus(ProfileController.EXPIRING_PROFILE_KEY_CREDENTIAL_EXPIRATION)
|
||||
.truncatedTo(ChronoUnit.DAYS);
|
||||
|
||||
final ExpiringProfileKeyCredentialResponse credentialResponse =
|
||||
serverZkProfile.issueExpiringProfileKeyCredential(credentialRequest, AuthHelper.VALID_UUID, profileKeyCommitment, expiration);
|
||||
|
||||
when(accountsManager.getByAccountIdentifier(AuthHelper.VALID_UUID)).thenReturn(Optional.of(account));
|
||||
when(profilesManager.get(AuthHelper.VALID_UUID, version)).thenReturn(Optional.of(versionedProfile));
|
||||
when(zkProfileOperations.issueExpiringProfileKeyCredential(credentialRequest, AuthHelper.VALID_UUID, profileKeyCommitment, expiration))
|
||||
.thenReturn(credentialResponse);
|
||||
|
||||
final ExpiringProfileKeyCredentialProfileResponse profile = resources.getJerseyTest()
|
||||
.target(String.format("/v1/profile/%s/%s/%s", AuthHelper.VALID_UUID, version, Hex.encodeHexString(credentialRequest.serialize())))
|
||||
.queryParam("credentialType", "expiringProfileKey")
|
||||
.request()
|
||||
.headers(authHeaders)
|
||||
.get(ExpiringProfileKeyCredentialProfileResponse.class);
|
||||
|
||||
assertThat(profile.getVersionedProfileResponse().getBaseProfileResponse().getUuid()).isEqualTo(AuthHelper.VALID_UUID);
|
||||
assertThat(profile.getCredential()).isEqualTo(credentialResponse);
|
||||
|
||||
verify(zkProfileOperations).issueExpiringProfileKeyCredential(credentialRequest, AuthHelper.VALID_UUID, profileKeyCommitment, expiration);
|
||||
verify(zkProfileOperations, never()).issuePniCredential(any(), any(), any(), any());
|
||||
|
||||
final ClientZkProfileOperations clientZkProfileCipher = new ClientZkProfileOperations(serverPublicParams);
|
||||
assertThatNoException().isThrownBy(() ->
|
||||
clientZkProfileCipher.receiveExpiringProfileKeyCredential(profileKeyCredentialRequestContext, profile.getCredential()));
|
||||
}
|
||||
|
||||
private static Stream<Arguments> testGetProfileWithExpiringProfileKeyCredential() {
|
||||
return Stream.of(
|
||||
Arguments.of(new MultivaluedHashMap<>(Map.of(OptionalAccess.UNIDENTIFIED, Base64.getEncoder().encodeToString(UNIDENTIFIED_ACCESS_KEY)))),
|
||||
Arguments.of(new MultivaluedHashMap<>(Map.of("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD)))),
|
||||
Arguments.of(new MultivaluedHashMap<>(Map.of("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID_TWO, AuthHelper.VALID_PASSWORD_TWO))))
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetProfileWithPniCredentialVersionNotFound() throws VerificationFailedException {
|
||||
final Account account = mock(Account.class);
|
||||
@@ -1180,4 +1266,73 @@ class ProfileControllerTest {
|
||||
|
||||
verify(AuthHelper.VALID_ACCOUNT_TWO).setBadges(refEq(clock), eq(List.of(new AccountBadge("TEST", Instant.ofEpochSecond(42 + 86400), true))));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testBatchIdentityCheck() {
|
||||
try (Response response = resources.getJerseyTest().target("/v1/profile/identity_check/batch").request()
|
||||
.post(Entity.json(new BatchIdentityCheckRequest(List.of(
|
||||
new BatchIdentityCheckRequest.Element(AuthHelper.VALID_UUID, convertStringToFingerprint("barz")),
|
||||
new BatchIdentityCheckRequest.Element(AuthHelper.VALID_UUID_TWO, convertStringToFingerprint("bar")),
|
||||
new BatchIdentityCheckRequest.Element(AuthHelper.INVALID_UUID, convertStringToFingerprint("baz"))
|
||||
))))) {
|
||||
assertThat(response).isNotNull();
|
||||
assertThat(response.getStatus()).isEqualTo(200);
|
||||
BatchIdentityCheckResponse identityCheckResponse = response.readEntity(BatchIdentityCheckResponse.class);
|
||||
assertThat(identityCheckResponse).isNotNull();
|
||||
assertThat(identityCheckResponse.elements()).isNotNull().isEmpty();
|
||||
}
|
||||
|
||||
Condition<BatchIdentityCheckResponse.Element> isEitherUuid1orUuid2 = new Condition<>(element -> {
|
||||
if (AuthHelper.VALID_UUID.equals(element.aci())) {
|
||||
return Arrays.equals(Base64.getDecoder().decode("barz"), element.identityKey());
|
||||
} else if (AuthHelper.VALID_UUID_TWO.equals(element.aci())) {
|
||||
return Arrays.equals(Base64.getDecoder().decode("bar"), element.identityKey());
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}, "is either UUID 1 or UUID 2 with the correct identity key");
|
||||
|
||||
try (Response response = resources.getJerseyTest().target("/v1/profile/identity_check/batch").request()
|
||||
.post(Entity.json(new BatchIdentityCheckRequest(List.of(
|
||||
new BatchIdentityCheckRequest.Element(AuthHelper.VALID_UUID, convertStringToFingerprint("else1234")),
|
||||
new BatchIdentityCheckRequest.Element(AuthHelper.VALID_UUID_TWO, convertStringToFingerprint("another1")),
|
||||
new BatchIdentityCheckRequest.Element(AuthHelper.INVALID_UUID, convertStringToFingerprint("456"))
|
||||
))))) {
|
||||
assertThat(response).isNotNull();
|
||||
assertThat(response.getStatus()).isEqualTo(200);
|
||||
BatchIdentityCheckResponse identityCheckResponse = response.readEntity(BatchIdentityCheckResponse.class);
|
||||
assertThat(identityCheckResponse).isNotNull();
|
||||
assertThat(identityCheckResponse.elements()).isNotNull().hasSize(2);
|
||||
assertThat(identityCheckResponse.elements()).element(0).isNotNull().is(isEitherUuid1orUuid2);
|
||||
assertThat(identityCheckResponse.elements()).element(1).isNotNull().is(isEitherUuid1orUuid2);
|
||||
}
|
||||
|
||||
List<BatchIdentityCheckRequest.Element> largeElementList = new ArrayList<>(List.of(
|
||||
new BatchIdentityCheckRequest.Element(AuthHelper.VALID_UUID, convertStringToFingerprint("else1234")),
|
||||
new BatchIdentityCheckRequest.Element(AuthHelper.VALID_UUID_TWO, convertStringToFingerprint("another1")),
|
||||
new BatchIdentityCheckRequest.Element(AuthHelper.INVALID_UUID, convertStringToFingerprint("456"))));
|
||||
for (int i = 0; i < 900; i++) {
|
||||
largeElementList.add(new BatchIdentityCheckRequest.Element(UUID.randomUUID(), convertStringToFingerprint("abcd")));
|
||||
}
|
||||
try (Response response = resources.getJerseyTest().target("/v1/profile/identity_check/batch").request()
|
||||
.post(Entity.json(new BatchIdentityCheckRequest(largeElementList)))) {
|
||||
assertThat(response).isNotNull();
|
||||
assertThat(response.getStatus()).isEqualTo(200);
|
||||
BatchIdentityCheckResponse identityCheckResponse = response.readEntity(BatchIdentityCheckResponse.class);
|
||||
assertThat(identityCheckResponse).isNotNull();
|
||||
assertThat(identityCheckResponse.elements()).isNotNull().hasSize(2);
|
||||
assertThat(identityCheckResponse.elements()).element(0).isNotNull().is(isEitherUuid1orUuid2);
|
||||
assertThat(identityCheckResponse.elements()).element(1).isNotNull().is(isEitherUuid1orUuid2);
|
||||
}
|
||||
}
|
||||
|
||||
private byte[] convertStringToFingerprint(String base64) {
|
||||
MessageDigest sha256;
|
||||
try {
|
||||
sha256 = MessageDigest.getInstance("SHA-256");
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new AssertionError(e);
|
||||
}
|
||||
return Util.truncate(sha256.digest(Base64.getDecoder().decode(base64)), 4);
|
||||
}
|
||||
}
|
||||
+58
@@ -196,6 +196,64 @@ class ClientPresenceManagerTest {
|
||||
.sismember(ClientPresenceManager.MANAGER_SET_KEY, missingPeerId)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testInitialPresenceExpiration() {
|
||||
final UUID accountUuid = UUID.randomUUID();
|
||||
final long deviceId = 1;
|
||||
|
||||
clientPresenceManager.setPresent(accountUuid, deviceId, NO_OP);
|
||||
|
||||
{
|
||||
final int ttl = REDIS_CLUSTER_EXTENSION.getRedisCluster().withCluster(connection ->
|
||||
connection.sync().ttl(ClientPresenceManager.getPresenceKey(accountUuid, deviceId)).intValue());
|
||||
|
||||
assertTrue(ttl > 0);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRenewPresence() {
|
||||
final UUID accountUuid = UUID.randomUUID();
|
||||
final long deviceId = 1;
|
||||
|
||||
final String presenceKey = ClientPresenceManager.getPresenceKey(accountUuid, deviceId);
|
||||
|
||||
REDIS_CLUSTER_EXTENSION.getRedisCluster().useCluster(connection ->
|
||||
connection.sync().set(presenceKey, clientPresenceManager.getManagerId()));
|
||||
|
||||
{
|
||||
final int ttl = REDIS_CLUSTER_EXTENSION.getRedisCluster().withCluster(connection ->
|
||||
connection.sync().ttl(presenceKey).intValue());
|
||||
|
||||
assertEquals(-1, ttl);
|
||||
}
|
||||
|
||||
clientPresenceManager.renewPresence(accountUuid, deviceId);
|
||||
|
||||
{
|
||||
final int ttl = REDIS_CLUSTER_EXTENSION.getRedisCluster().withCluster(connection ->
|
||||
connection.sync().ttl(presenceKey).intValue());
|
||||
|
||||
assertTrue(ttl > 0);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void testExpiredPresence() {
|
||||
final UUID accountUuid = UUID.randomUUID();
|
||||
final long deviceId = 1;
|
||||
|
||||
clientPresenceManager.setPresent(accountUuid, deviceId, NO_OP);
|
||||
|
||||
assertTrue(clientPresenceManager.isPresent(accountUuid, deviceId));
|
||||
|
||||
// Hackily set this key to expire immediately
|
||||
REDIS_CLUSTER_EXTENSION.getRedisCluster().useCluster(connection ->
|
||||
connection.sync().expire(ClientPresenceManager.getPresenceKey(accountUuid, deviceId), 0));
|
||||
|
||||
assertFalse(clientPresenceManager.isPresent(accountUuid, deviceId));
|
||||
}
|
||||
|
||||
private void addClientPresence(final String managerId) {
|
||||
final String clientPresenceKey = ClientPresenceManager.getPresenceKey(UUID.randomUUID(), 7);
|
||||
|
||||
|
||||
+18
-6
@@ -636,8 +636,17 @@ class AccountControllerTest {
|
||||
verify(abusiveHostRules).isBlocked(eq(NICE_HOST));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSendCodeVoiceInvalidLocale() throws Exception {
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void testSendCodeVoiceInvalidLocale(boolean enrolledInVerifyExperiment) throws Exception {
|
||||
when(verifyExperimentEnrollmentManager.isEnrolled(any(), anyString(), anyList(), anyString()))
|
||||
.thenReturn(enrolledInVerifyExperiment);
|
||||
|
||||
if (enrolledInVerifyExperiment) {
|
||||
when(smsSender.deliverVoxVerificationWithTwilioVerify(anyString(), anyString(), anyList()))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of("VerificationSid")));
|
||||
}
|
||||
|
||||
Response response =
|
||||
resources.getJerseyTest()
|
||||
.target(String.format("/v1/accounts/voice/code/%s", SENDER))
|
||||
@@ -647,11 +656,14 @@ class AccountControllerTest {
|
||||
.header("X-Forwarded-For", NICE_HOST)
|
||||
.get();
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(400);
|
||||
// Should still send a code, just with no accept language
|
||||
assertThat(response.getStatus()).isEqualTo(200);
|
||||
|
||||
verify(smsSender, never()).deliverVoxVerification(eq(SENDER), anyString(), any());
|
||||
verify(smsSender, never()).deliverVoxVerificationWithTwilioVerify(eq(SENDER), anyString(), any());
|
||||
verify(abusiveHostRules).isBlocked(eq(NICE_HOST));
|
||||
if (enrolledInVerifyExperiment) {
|
||||
verify(smsSender).deliverVoxVerificationWithTwilioVerify(eq(SENDER), anyString(), eq(Collections.emptyList()));
|
||||
} else {
|
||||
verify(smsSender).deliverVoxVerification(eq(SENDER), anyString(), eq(Collections.emptyList()));
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
|
||||
+106
-5
@@ -9,26 +9,35 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatCode;
|
||||
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import io.dropwizard.auth.PolymorphicAuthValueFactoryProvider;
|
||||
import io.dropwizard.testing.junit5.DropwizardExtensionsSupport;
|
||||
import io.dropwizard.testing.junit5.ResourceExtension;
|
||||
import java.io.IOException;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneId;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.Base64;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Stream;
|
||||
import javax.ws.rs.core.Response;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.signal.libsignal.protocol.ecc.Curve;
|
||||
import org.signal.libsignal.zkgroup.ServerSecretParams;
|
||||
import org.signal.libsignal.zkgroup.VerificationFailedException;
|
||||
import org.signal.libsignal.zkgroup.auth.AuthCredentialResponse;
|
||||
import org.signal.libsignal.zkgroup.auth.AuthCredentialWithPniResponse;
|
||||
import org.signal.libsignal.zkgroup.auth.ClientZkAuthOperations;
|
||||
import org.signal.libsignal.zkgroup.auth.ServerZkAuthOperations;
|
||||
import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
|
||||
@@ -58,6 +67,7 @@ class CertificateControllerTest {
|
||||
private static final ServerSecretParams serverSecretParams = ServerSecretParams.generate();
|
||||
private static final CertificateGenerator certificateGenerator;
|
||||
private static final ServerZkAuthOperations serverZkAuthOperations;
|
||||
private static final Clock clock = Clock.fixed(Instant.now(), ZoneId.systemDefault());
|
||||
|
||||
static {
|
||||
try {
|
||||
@@ -75,7 +85,7 @@ class CertificateControllerTest {
|
||||
ImmutableSet.of(AuthenticatedAccount.class, DisabledPermittedAuthenticatedAccount.class)))
|
||||
.setMapper(SystemMapper.getMapper())
|
||||
.setTestContainerFactory(new GrizzlyWebTestContainerFactory())
|
||||
.addResource(new CertificateController(certificateGenerator, serverZkAuthOperations))
|
||||
.addResource(new CertificateController(certificateGenerator, serverZkAuthOperations, clock))
|
||||
.build();
|
||||
|
||||
@Test
|
||||
@@ -219,8 +229,6 @@ class CertificateControllerTest {
|
||||
|
||||
@Test
|
||||
void testGetSingleAuthCredentialByPni() {
|
||||
when(AuthHelper.VALID_ACCOUNT.getPhoneNumberIdentifier()).thenReturn(UUID.randomUUID());
|
||||
|
||||
GroupCredentials credentials = resources.getJerseyTest()
|
||||
.target("/v1/certificate/group/" + Util.currentDaysSinceEpoch() + "/" + Util.currentDaysSinceEpoch())
|
||||
.queryParam("identity", "pni")
|
||||
@@ -293,4 +301,97 @@ class CertificateControllerTest {
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(401);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetSingleGroupCredential() {
|
||||
final Instant startOfDay = clock.instant().truncatedTo(ChronoUnit.DAYS);
|
||||
|
||||
final GroupCredentials credentials = resources.getJerseyTest()
|
||||
.target("/v1/certificate/auth/group")
|
||||
.queryParam("redemptionStartSeconds", startOfDay.getEpochSecond())
|
||||
.queryParam("redemptionEndSeconds", startOfDay.getEpochSecond())
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.get(GroupCredentials.class);
|
||||
|
||||
assertEquals(1, credentials.getCredentials().size());
|
||||
assertEquals(startOfDay.getEpochSecond(), credentials.getCredentials().get(0).getRedemptionTime());
|
||||
|
||||
final ClientZkAuthOperations clientZkAuthOperations =
|
||||
new ClientZkAuthOperations(serverSecretParams.getPublicParams());
|
||||
|
||||
assertDoesNotThrow(() -> {
|
||||
clientZkAuthOperations.receiveAuthCredentialWithPni(
|
||||
AuthHelper.VALID_UUID,
|
||||
AuthHelper.VALID_PNI,
|
||||
(int) startOfDay.getEpochSecond(),
|
||||
new AuthCredentialWithPniResponse(credentials.getCredentials().get(0).getCredential()));
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetWeekLongGroupCredentials() {
|
||||
final Instant startOfDay = clock.instant().truncatedTo(ChronoUnit.DAYS);
|
||||
|
||||
final GroupCredentials credentials = resources.getJerseyTest()
|
||||
.target("/v1/certificate/auth/group")
|
||||
.queryParam("redemptionStartSeconds", startOfDay.getEpochSecond())
|
||||
.queryParam("redemptionEndSeconds", startOfDay.plus(Duration.ofDays(7)).getEpochSecond())
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.get(GroupCredentials.class);
|
||||
|
||||
assertEquals(8, credentials.getCredentials().size());
|
||||
|
||||
final ClientZkAuthOperations clientZkAuthOperations =
|
||||
new ClientZkAuthOperations(serverSecretParams.getPublicParams());
|
||||
|
||||
for (int i = 0; i < 8; i++) {
|
||||
final Instant redemptionTime = startOfDay.plus(Duration.ofDays(i));
|
||||
assertEquals(redemptionTime.getEpochSecond(), credentials.getCredentials().get(i).getRedemptionTime());
|
||||
|
||||
final int index = i;
|
||||
|
||||
assertDoesNotThrow(() -> {
|
||||
clientZkAuthOperations.receiveAuthCredentialWithPni(
|
||||
AuthHelper.VALID_UUID,
|
||||
AuthHelper.VALID_PNI,
|
||||
redemptionTime.getEpochSecond(),
|
||||
new AuthCredentialWithPniResponse(credentials.getCredentials().get(index).getCredential()));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void testBadRedemptionTimes(final Instant redemptionStart, final Instant redemptionEnd) {
|
||||
final Response response = resources.getJerseyTest()
|
||||
.target("/v1/certificate/auth/group")
|
||||
.queryParam("redemptionStartSeconds", redemptionStart.getEpochSecond())
|
||||
.queryParam("redemptionEndSeconds", redemptionEnd.getEpochSecond())
|
||||
.request()
|
||||
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
|
||||
.get();
|
||||
|
||||
assertEquals(400, response.getStatus());
|
||||
}
|
||||
|
||||
private static Stream<Arguments> testBadRedemptionTimes() {
|
||||
return Stream.of(
|
||||
// Start is after end
|
||||
Arguments.of(clock.instant().plus(Duration.ofDays(1)), clock.instant()),
|
||||
|
||||
// Start is in the past
|
||||
Arguments.of(clock.instant().minus(Duration.ofDays(1)), clock.instant()),
|
||||
|
||||
// End is too far in the future
|
||||
Arguments.of(clock.instant(), clock.instant().plus(CertificateController.MAX_REDEMPTION_DURATION).plus(Duration.ofDays(1))),
|
||||
|
||||
// Start is not at a day boundary
|
||||
Arguments.of(clock.instant().plusSeconds(17), clock.instant().plus(Duration.ofDays(1))),
|
||||
|
||||
// End is not at a day boundary
|
||||
Arguments.of(clock.instant(), clock.instant().plusSeconds(17))
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user