Compare commits

...
9 Commits
Author SHA1 Message Date
Jon Chambers fdf7b69996 Remove a temporary workaround for incorrect envelope types from iOS clients 2022-07-13 11:30:52 -04:00
Jon Chambers 92d36b725f Allow presence keys to expire if not periodically renewed 2022-07-13 11:28:55 -04:00
Jon Chambers 4e131858ca Generalize scope of and expand size of websocket scheduled executor service 2022-07-13 11:28:55 -04:00
Ravi Khadiwala a45d95905e Be permissive in account-create accept-language
Currently, if we fail to parse a user's accept-language in account
creation, creation will fail. While it's a suboptimal experience to get
a verify code in the wrong language, it might be better than not being
able to sign up at all.
2022-07-13 11:22:31 -04:00
Ehren Kret 0fdfdabf2a merge GroupController into CertificateController 2022-07-01 13:04:24 -05:00
Jon Chambers a25e967978 Remove spurious mocking 2022-07-01 12:26:22 -05:00
Jon Chambers 38e30c7513 Allow callers to get an expiring profile key credential 2022-07-01 12:26:22 -05:00
Jon Chambers e38e5fa17d Allow callers to request a combined group auth credential 2022-07-01 12:26:22 -05:00
Jon Chambers c1f9bedf2f Update to libsignal-server 0.18 2022-06-23 14:25:28 -04:00
18 changed files with 528 additions and 102 deletions

No files matched your search

+1 -1
View File
@@ -275,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>
@@ -372,7 +372,7 @@ 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();
@@ -604,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);
@@ -624,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),
@@ -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);
@@ -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);
}
}
@@ -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);
@@ -8,6 +8,7 @@ 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;
@@ -19,8 +20,10 @@ 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;
@@ -66,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;
@@ -86,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;
@@ -129,8 +134,12 @@ public class ProfileController {
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");
@@ -285,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();
}
}
@@ -415,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,
@@ -514,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);
@@ -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;
}
}
@@ -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);
}
}
}
}
@@ -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) {
@@ -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");
@@ -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
@@ -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 {
@@ -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;
@@ -31,6 +31,7 @@ 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;
@@ -64,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;
@@ -86,6 +88,7 @@ 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;
@@ -1131,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);
@@ -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);
@@ -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
@@ -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))
);
}
}