mirror of
https://github.com/signalapp/Signal-Server.git
synced 2026-12-01 11:16:47 +00:00
Compare commits
29
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4577a4aa9b | ||
|
|
8fac5de9af | ||
|
|
1dd7383af0 | ||
|
|
5f66f1c51d | ||
|
|
867ec4a3df | ||
|
|
a5f2f7f3e5 | ||
|
|
4c2cd0c999 | ||
|
|
14fb2fb29d | ||
|
|
c612bd4b73 | ||
|
|
4157cadf44 | ||
|
|
0cabb53aed | ||
|
|
f04e716347 | ||
|
|
558649ba65 | ||
|
|
43dc9d11fd | ||
|
|
9547655a9c | ||
|
|
547bde4869 | ||
|
|
fe1082d8ba | ||
|
|
7c77dd20bc | ||
|
|
f0370b75af | ||
|
|
ed08d1dc23 | ||
|
|
369ca0b514 | ||
|
|
218a1cd75f | ||
|
|
b04e41803a | ||
|
|
e92c3bb8aa | ||
|
|
2bcecc7f7d | ||
|
|
e8979082a7 | ||
|
|
5c99b03eb2 | ||
|
|
9814fee556 | ||
|
|
5b18ecafaa |
No files matched your search
@@ -19,6 +19,23 @@ updates:
|
||||
update-types:
|
||||
- version-update:semver-major
|
||||
- version-update:semver-minor
|
||||
# Ignore the latest pre-release version
|
||||
versions: ["<=7.3.79"]
|
||||
|
||||
# Temporary exclusions, pending upstream fixes
|
||||
# https://github.com/dropwizard/dropwizard/pull/11273
|
||||
- dependency-name: "ch.qos.logback:*"
|
||||
versions: [">=1.6.0"]
|
||||
# https://github.com/jetty/jetty.project/issues/15657
|
||||
- dependency-name: "org.eclipse.jetty:*"
|
||||
versions: ["<=12.1.12"]
|
||||
- dependency-name: "org.eclipse.jetty.ee10:*"
|
||||
versions: ["<=12.1.12"]
|
||||
|
||||
# Dependency convergence sentinels, pinned to specific versions
|
||||
- dependency-name: "tools.jackson.core:jackson-databind"
|
||||
- dependency-name: "com.squareup.okio:okio-jvm"
|
||||
|
||||
groups:
|
||||
minor-java-dependencies:
|
||||
# Java: Only group minor and patch updates (we want to carefully review major updates)
|
||||
|
||||
@@ -10,10 +10,6 @@
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>integration-tests</artifactId>
|
||||
|
||||
<properties>
|
||||
<jetty.http2-client.version>12.1.12</jetty.http2-client.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.whispersystems.textsecure</groupId>
|
||||
@@ -39,7 +35,6 @@
|
||||
<dependency>
|
||||
<groupId>org.eclipse.jetty.http2</groupId>
|
||||
<artifactId>jetty-http2-client-transport</artifactId>
|
||||
<version>${jetty.http2-client.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
|
||||
@@ -61,7 +61,7 @@ public class MessagingTest {
|
||||
assertDoesNotThrow(() -> WebsocketClientSession.decode(SendMessageResponse.class, responseMessage));
|
||||
|
||||
final WebsocketClientSession websocketB = Operations.authenticatedWebsocket(userB, Device.PRIMARY_ID);
|
||||
assertTimeoutPreemptively(Duration.ofSeconds(5), websocketB::waitForQueueEmpty);
|
||||
assertTimeoutPreemptively(Duration.ofSeconds(15), websocketB::waitForQueueEmpty);
|
||||
|
||||
assertEquals(1, websocketB.getReceivedEnvelopes().size());
|
||||
final MessageProtos.Envelope envelope = websocketB.getReceivedEnvelopes().getFirst();
|
||||
|
||||
@@ -51,24 +51,24 @@
|
||||
<commons-io.version>2.22.0</commons-io.version>
|
||||
<dropwizard.version>5.0.2</dropwizard.version>
|
||||
<!-- Note: We use x86_64 builds without AVX instructions enabled (i.e. FoundationDB versions with even-numbered
|
||||
patch versions). Also when updating FoundationDB, make sure to update the version of FoundationDBused by GitHub
|
||||
Actions. -->
|
||||
<foundationdb.version>7.3.68</foundationdb.version>
|
||||
patch versions). -->
|
||||
<foundationdb.version>7.3.76</foundationdb.version>
|
||||
<foundationdb.api-version>730</foundationdb.api-version>
|
||||
<foundationdb.client-library-sha256>8c96a1f7ab561cd38e16e4c269c5e50ae0fd8063854e0d72c89339a7ac1b6873</foundationdb.client-library-sha256>
|
||||
<foundationdb.client-library-sha256>af099848721d08904ff9e5d38fade0de24d92e86451ea491d9ab5ce84adcf62a</foundationdb.client-library-sha256>
|
||||
<google-cloud-libraries.version>26.86.0</google-cloud-libraries.version>
|
||||
<grpc.version>1.76.3</grpc.version> <!-- should be kept in sync with the value from Google libraries-bom -->
|
||||
<gson.version>2.14.0</gson.version>
|
||||
<guava.version>33.6.0-jre</guava.version>
|
||||
<guava.version>33.7.0-jre</guava.version>
|
||||
<!-- several libraries (AWS, Google Cloud) use Apache http components transitively, and we need to align them -->
|
||||
<httpcore.version>4.4.16</httpcore.version>
|
||||
<httpclient.version>4.5.14</httpclient.version>
|
||||
<jackson.version>2.22.2</jackson.version>
|
||||
<java-otp.version>1.0.0</java-otp.version>
|
||||
<jetty.version>12.1.9</jetty.version>
|
||||
<junit-pioneer.version>2.3.0</junit-pioneer.version>
|
||||
<jsr305.version>3.0.2</jsr305.version>
|
||||
<kotlin.version>2.4.10</kotlin.version>
|
||||
<!-- dropwizard references a constant removed in 1.6 -->
|
||||
<!-- dropwizard references a constant removed in 1.6. See also: dependabot.yml -->
|
||||
<logback.version>1.5.38</logback.version>
|
||||
<logback-access-common.version>2.0.15</logback-access-common.version>
|
||||
<lettuce.version>7.6.0.RELEASE</lettuce.version>
|
||||
@@ -88,7 +88,7 @@
|
||||
<simple-grpc.version>0.2.1</simple-grpc.version>
|
||||
<slf4j.version>2.0.18</slf4j.version>
|
||||
<stripe.version>33.3.0</stripe.version>
|
||||
<swagger.version>2.2.46</swagger.version>
|
||||
<swagger.version>2.2.53</swagger.version>
|
||||
<testcontainers.version>2.0.5</testcontainers.version>
|
||||
|
||||
<!-- images to use in tests via testcontainers -->
|
||||
@@ -97,7 +97,7 @@
|
||||
<redis.image>redis:7.4-alpine@sha256:6ab0b6e7381779332f97b8ca76193e45b0756f38d4c0dcda72dbb3c32061ab99</redis.image>
|
||||
<redis-cluster.image>docker.io/bitnamilegacy/redis-cluster:7.4.3@sha256:a53d023fdfaf8a8d7ddc58da040d3494e4cb45772644618ffa44c42dcd32b9af</redis-cluster.image>
|
||||
|
||||
<docker.image>eclipse-temurin:25-jre-resolute@sha256:17ddcc32b1f296155738c4b2f689208e46bf0cf4eb0b215c717717deb8b74b90</docker.image>
|
||||
<docker.image>eclipse-temurin:25-jre-resolute@sha256:71bfb73662d4146bdc9ee2f97418a764d5ab4e83f4e90baec3b3dcda14071007</docker.image>
|
||||
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
</properties>
|
||||
@@ -107,7 +107,9 @@
|
||||
<version>JGITVER</version>
|
||||
|
||||
<dependencyManagement>
|
||||
<!-- note: order matters, and earlier declarations take precedence -->
|
||||
<dependencies>
|
||||
<!-- use a pinned version of jackson, rather than Dropwizard's BOM -->
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson</groupId>
|
||||
<artifactId>jackson-bom</artifactId>
|
||||
@@ -115,19 +117,21 @@
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
<!-- use a pinned version of jetty, rather than Dropwizard's BOM -->
|
||||
<dependency>
|
||||
<groupId>io.dropwizard</groupId>
|
||||
<artifactId>dropwizard-dependencies</artifactId>
|
||||
<version>${dropwizard.version}</version>
|
||||
<groupId>org.eclipse.jetty</groupId>
|
||||
<artifactId>jetty-bom</artifactId>
|
||||
<version>${jetty.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
<!-- Needed for gRPC with Java 9+ -->
|
||||
<!-- use a pinned version of jetty, rather than Dropwizard's BOM -->
|
||||
<dependency>
|
||||
<groupId>org.apache.tomcat</groupId>
|
||||
<artifactId>annotations-api</artifactId>
|
||||
<version>6.0.53</version>
|
||||
<scope>provided</scope>
|
||||
<groupId>org.eclipse.jetty.ee10</groupId>
|
||||
<artifactId>jetty-ee10-bom</artifactId>
|
||||
<version>${jetty.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.netty</groupId>
|
||||
@@ -136,13 +140,6 @@
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>software.amazon.awssdk</groupId>
|
||||
<artifactId>bom</artifactId>
|
||||
<version>${aws.sdk2.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.protobuf</groupId>
|
||||
<artifactId>protobuf-bom</artifactId>
|
||||
@@ -157,6 +154,27 @@
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>software.amazon.awssdk</groupId>
|
||||
<artifactId>bom</artifactId>
|
||||
<version>${aws.sdk2.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.dropwizard</groupId>
|
||||
<artifactId>dropwizard-dependencies</artifactId>
|
||||
<version>${dropwizard.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
<!-- Needed for gRPC with Java 9+ -->
|
||||
<dependency>
|
||||
<groupId>org.apache.tomcat</groupId>
|
||||
<artifactId>annotations-api</artifactId>
|
||||
<version>6.0.53</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.github.resilience4j</groupId>
|
||||
<artifactId>resilience4j-bom</artifactId>
|
||||
|
||||
+2
-14
@@ -23,7 +23,6 @@
|
||||
<opentelemetry-logback-appender-1.0.version>2.30.0-alpha</opentelemetry-logback-appender-1.0.version>
|
||||
<storekit.version>5.2.0</storekit.version>
|
||||
<webauthn4j.version>0.31.9.RELEASE</webauthn4j.version>
|
||||
<jetty.http2-client.version>12.1.12</jetty.http2-client.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
@@ -147,7 +146,6 @@
|
||||
<groupId>org.eclipse.jetty.http2</groupId>
|
||||
<artifactId>jetty-http2-client-transport</artifactId>
|
||||
<scope>test</scope>
|
||||
<version>${jetty.http2-client.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.dropwizard</groupId>
|
||||
@@ -190,6 +188,7 @@
|
||||
<dependency>
|
||||
<groupId>tools.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
<!-- update dependabot.yml when this dependency is removed -->
|
||||
<version>3.2.1</version>
|
||||
</dependency>
|
||||
|
||||
@@ -311,18 +310,6 @@
|
||||
</exclusions>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.google.cloud</groupId>
|
||||
<artifactId>google-cloud-firestore</artifactId>
|
||||
<exclusions>
|
||||
<!-- incubator packages aren't included in the opentelemetry BOM, and we don't use them -->
|
||||
<exclusion>
|
||||
<groupId>io.opentelemetry.instrumentation</groupId>
|
||||
<artifactId>opentelemetry-instrumentation-api-incubator</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.google.code.findbugs</groupId>
|
||||
<artifactId>jsr305</artifactId>
|
||||
@@ -653,6 +640,7 @@
|
||||
<dependency>
|
||||
<groupId>com.squareup.okio</groupId>
|
||||
<artifactId>okio-jvm</artifactId>
|
||||
<!-- update dependabot.yml when this dependency is removed -->
|
||||
<version>3.17.0</version>
|
||||
</dependency>
|
||||
|
||||
|
||||
+1
@@ -18,6 +18,7 @@ public record OpenTelemetryConfiguration(
|
||||
@JsonProperty Duration shutdownWaitDuration,
|
||||
@JsonProperty int maxBucketCount,
|
||||
@JsonProperty Map<String, Integer> maxBucketsPerMeter,
|
||||
@JsonProperty boolean publishMaxGaugeForHistograms,
|
||||
@JsonAnyGetter @JsonAnySetter Map<String, String> otlpConfig
|
||||
) implements OtlpConfig {
|
||||
|
||||
|
||||
+5
-5
@@ -226,8 +226,6 @@ public class RegistrationController {
|
||||
throw new WebApplicationException("PNI keys and registration ID must be provided", 422);
|
||||
}
|
||||
|
||||
rateLimiters.getRegistrationLimiter().validate(number);
|
||||
|
||||
final PhoneVerificationRequest.VerificationType verificationType;
|
||||
try {
|
||||
verificationType = phoneVerificationTokenManager.verify(
|
||||
@@ -247,6 +245,8 @@ public class RegistrationController {
|
||||
throw new ForbiddenException("recovery password could not be verified");
|
||||
}
|
||||
|
||||
rateLimiters.getRegistrationLimiter().validate(number);
|
||||
|
||||
// There can be at most one existing account for a set of numbers in the same equivalence class, so it's sufficient
|
||||
// to find the first one.
|
||||
final Optional<Account> existingAccount = Util.getAlternateForms(number)
|
||||
@@ -334,9 +334,9 @@ public class RegistrationController {
|
||||
throw new BadRequestException("login purchases are not enabled");
|
||||
}
|
||||
|
||||
if (registrationRequest.accountAttributes().recoveryPassword().isEmpty()) {
|
||||
throw new WebApplicationException("Account recovery password is required", 422);
|
||||
}
|
||||
registrationRequest.accountAttributes().recoveryPassword()
|
||||
.filter(ArrayUtils::isNotEmpty)
|
||||
.orElseThrow(() -> new WebApplicationException("Account recovery password is required", 422));
|
||||
|
||||
final ReceiptCredentialPresentation receiptCredentialPresentation;
|
||||
try {
|
||||
|
||||
+2
-1
@@ -14,6 +14,7 @@ import jakarta.validation.constraints.AssertTrue;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import javax.annotation.Nullable;
|
||||
import org.apache.commons.lang3.ArrayUtils;
|
||||
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
|
||||
import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
|
||||
@@ -103,7 +104,7 @@ public class AccountAttributes {
|
||||
}
|
||||
|
||||
public Optional<byte[]> recoveryPassword() {
|
||||
return Optional.ofNullable(recoveryPassword);
|
||||
return Optional.ofNullable(recoveryPassword).filter(ArrayUtils::isNotEmpty);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
|
||||
+18
-7
@@ -577,7 +577,7 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
|
||||
|
||||
@Override
|
||||
public ConfirmTotpKeyResponse confirmTotpKey(final ConfirmTotpKeyRequest request) {
|
||||
final Optional<Integer> maybeConfirmedTotpKeyId =
|
||||
final Optional<Byte> maybeConfirmedTotpKeyId =
|
||||
accountsManager.confirmPendingTotpKey(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier(),
|
||||
request.getOneTimePassword(),
|
||||
clock.instant(),
|
||||
@@ -610,17 +610,18 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
|
||||
|
||||
@Override
|
||||
public SetTotpKeyMetadataResponse setTotpKeyMetadata(final SetTotpKeyMetadataRequest request) {
|
||||
final byte keyId = validateTotpKeyId(request.getKeyId());
|
||||
|
||||
try {
|
||||
accountsManager.update(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier(), account -> {
|
||||
final Map<Integer, AnnotatedTotpKey> totpKeys = new HashMap<>(account.getTotpKeys());
|
||||
@Nullable final AnnotatedTotpKey existingKey = totpKeys.get(request.getKeyId());
|
||||
final Map<Byte, AnnotatedTotpKey> totpKeys = new HashMap<>(account.getTotpKeys());
|
||||
@Nullable final AnnotatedTotpKey existingKey = totpKeys.get(keyId);
|
||||
|
||||
if (existingKey == null) {
|
||||
throw new TotpKeyNotFoundException();
|
||||
}
|
||||
|
||||
totpKeys.put(request.getKeyId(),
|
||||
new AnnotatedTotpKey(existingKey.totpKey(), request.getMetadataCiphertext().toByteArray()));
|
||||
totpKeys.put(keyId, new AnnotatedTotpKey(existingKey.totpKey(), request.getMetadataCiphertext().toByteArray()));
|
||||
|
||||
account.setTotpKeys(totpKeys);
|
||||
});
|
||||
@@ -637,9 +638,11 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
|
||||
|
||||
@Override
|
||||
public RemoveTotpKeyResponse removeTotpKey(final RemoveTotpKeyRequest request) {
|
||||
final byte keyId = validateTotpKeyId(request.getKeyId());
|
||||
|
||||
accountsManager.update(AuthenticationUtil.requireAuthenticatedDevice().accountIdentifier(), account -> {
|
||||
final Map<Integer, AnnotatedTotpKey> totpKeys = new HashMap<>(account.getTotpKeys());
|
||||
totpKeys.remove(request.getKeyId());
|
||||
final Map<Byte, AnnotatedTotpKey> totpKeys = new HashMap<>(account.getTotpKeys());
|
||||
totpKeys.remove(keyId);
|
||||
|
||||
account.setTotpKeys(totpKeys);
|
||||
});
|
||||
@@ -647,6 +650,14 @@ public class AccountsGrpcService extends SimpleAccountsGrpc.AccountsImplBase {
|
||||
return RemoveTotpKeyResponse.getDefaultInstance();
|
||||
}
|
||||
|
||||
private byte validateTotpKeyId(final int keyId) {
|
||||
if (keyId < 0 || keyId > Account.MAX_TOTP_KEY_ID) {
|
||||
throw GrpcExceptions.invalidArguments("TOTP key ID out of range");
|
||||
}
|
||||
|
||||
return (byte) keyId;
|
||||
}
|
||||
|
||||
private static TotpParameters toGrpcTotpParameters(final org.whispersystems.textsecuregcm.storage.TotpParameters totpParameters) {
|
||||
return TotpParameters.newBuilder()
|
||||
.setAlgorithm(totpParameters.algorithm())
|
||||
|
||||
@@ -16,11 +16,11 @@ import java.util.HexFormat;
|
||||
import java.util.Optional;
|
||||
import org.bouncycastle.crypto.digests.TupleHash;
|
||||
import org.signal.chat.common.S3UploadForm;
|
||||
import org.signal.chat.profile.AccountInfo;
|
||||
import org.signal.chat.profile.GetExpiringProfileKeyCredentialResult;
|
||||
import org.signal.chat.profile.LegacyProfileResult;
|
||||
import org.signal.chat.profile.ProfileResult;
|
||||
import org.signal.chat.profile.ProfileResultOrBuilder;
|
||||
import org.signal.chat.profile.LegacyProfileResult;
|
||||
import org.signal.chat.profile.AccountInfo;
|
||||
import org.signal.libsignal.protocol.ServiceId;
|
||||
import org.signal.libsignal.zkgroup.InvalidInputException;
|
||||
import org.signal.libsignal.zkgroup.VerificationFailedException;
|
||||
@@ -30,7 +30,6 @@ import org.signal.libsignal.zkgroup.profiles.ProfileKeyCredentialRequest;
|
||||
import org.signal.libsignal.zkgroup.profiles.ServerZkProfileOperations;
|
||||
import org.whispersystems.textsecuregcm.auth.UnidentifiedAccessChecksum;
|
||||
import org.whispersystems.textsecuregcm.badges.ProfileBadgeConverter;
|
||||
import org.whispersystems.textsecuregcm.identity.IdentityType;
|
||||
import org.whispersystems.textsecuregcm.s3.PostPolicyGenerator;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.DeviceCapability;
|
||||
@@ -60,12 +59,20 @@ public class ProfileGrpcHelper {
|
||||
final VersionedProfileV1 v1Profile = maybeV1Profile.get();
|
||||
|
||||
final LegacyProfileResult.Builder builder = LegacyProfileResult.newBuilder()
|
||||
.setAccountInfo(buildAccountInfo(profileBadgeConverter, account))
|
||||
.setName(ByteString.copyFrom(v1Profile.name()))
|
||||
.setAbout(ByteString.copyFrom(v1Profile.about()))
|
||||
.setAboutEmoji(ByteString.copyFrom(v1Profile.aboutEmoji()))
|
||||
.setPhoneNumberSharing(ByteString.copyFrom(v1Profile.phoneNumberSharing()));
|
||||
.setAccountInfo(buildAccountInfo(profileBadgeConverter, account));
|
||||
|
||||
if (v1Profile.name() != null) {
|
||||
builder.setName(ByteString.copyFrom(v1Profile.name()));
|
||||
}
|
||||
if (v1Profile.about() != null) {
|
||||
builder.setAbout(ByteString.copyFrom(v1Profile.about()));
|
||||
}
|
||||
if (v1Profile.aboutEmoji() != null) {
|
||||
builder.setAboutEmoji(ByteString.copyFrom(v1Profile.aboutEmoji()));
|
||||
}
|
||||
if (v1Profile.phoneNumberSharing() != null) {
|
||||
builder.setPhoneNumberSharing(ByteString.copyFrom(v1Profile.phoneNumberSharing()));
|
||||
}
|
||||
if (v1Profile.avatar() != null) {
|
||||
builder.setAvatar(v1Profile.avatar());
|
||||
}
|
||||
|
||||
+33
-2
@@ -31,6 +31,8 @@ import org.signal.chat.profile.SetProfileRequest;
|
||||
import org.signal.chat.profile.SetProfileResponse;
|
||||
import org.signal.chat.profile.SetProfileResult;
|
||||
import org.signal.chat.profile.SetProfileV1Request.AvatarChange;
|
||||
import org.signal.chat.profile.SetV1AvatarRequest;
|
||||
import org.signal.chat.profile.SetV1AvatarResponse;
|
||||
import org.signal.chat.profile.SimpleProfileGrpc;
|
||||
import org.signal.libsignal.protocol.ServiceId;
|
||||
import org.signal.libsignal.zkgroup.GenericServerSecretParams;
|
||||
@@ -107,7 +109,7 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
|
||||
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
|
||||
|
||||
final Account account = accountsManager.getByAccountIdentifier(authenticatedDevice.accountIdentifier())
|
||||
.orElseThrow(() -> GrpcExceptions.invalidArguments("Account not found"));
|
||||
.orElseThrow(() -> GrpcExceptions.invalidCredentials("invalid credentials"));
|
||||
|
||||
if (!account.hasCapability(DeviceCapability.PROFILES_V2)) {
|
||||
return SetProfileResponse.newBuilder()
|
||||
@@ -224,7 +226,7 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
|
||||
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
|
||||
|
||||
final Account account = accountsManager.getByAccountIdentifier(authenticatedDevice.accountIdentifier())
|
||||
.orElseThrow(() -> GrpcExceptions.invalidCredentials("account not found"));
|
||||
.orElseThrow(() -> GrpcExceptions.invalidCredentials("invalid credentials"));
|
||||
|
||||
if (account.getZkCredentialKey().isEmpty()) {
|
||||
return GetAvatarCredentialsResponse.newBuilder()
|
||||
@@ -275,6 +277,35 @@ public class ProfileGrpcService extends SimpleProfileGrpc.ProfileImplBase {
|
||||
.orElseGet(() -> GetProfileResponse.newBuilder().setNotFound(NotFound.getDefaultInstance()).build());
|
||||
}
|
||||
|
||||
@Override
|
||||
public SetV1AvatarResponse setV1Avatar(final SetV1AvatarRequest request) {
|
||||
|
||||
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
|
||||
|
||||
final String version = request.getVersion();
|
||||
final Optional<VersionedProfileV1> maybeV1Profile = profilesManager.getV1(authenticatedDevice.accountIdentifier(),
|
||||
version);
|
||||
|
||||
if (maybeV1Profile.isEmpty() && request.getCommitment().isEmpty()) {
|
||||
throw GrpcExceptions.fieldViolation("commitment", "Commitment is required for new profile versions");
|
||||
}
|
||||
|
||||
maybeV1Profile.map(VersionedProfileV1::avatar).filter(a -> a.startsWith("profiles/"))
|
||||
.ifPresent(profilesManager::deleteAvatar);
|
||||
|
||||
final byte[] commitment = maybeV1Profile.map(VersionedProfileV1::commitment).orElseGet(request.getCommitment()::toByteArray);
|
||||
|
||||
final String updateAvatarObjectName = ProfileHelper.generateAvatarObjectName();
|
||||
|
||||
profilesManager.setV1Avatar(authenticatedDevice.accountIdentifier(), version, updateAvatarObjectName, commitment);
|
||||
|
||||
return SetV1AvatarResponse.newBuilder()
|
||||
.setForm(ProfileGrpcHelper.generateAvatarUploadForm(updateAvatarObjectName,
|
||||
ProfileHelper.MAX_PROFILE_AVATAR_SIZE_BYTES,
|
||||
policyGenerator, clock))
|
||||
.build();
|
||||
}
|
||||
|
||||
private Optional<Account> validateRateLimitAndGetAccount(final UUID requesterUuid,
|
||||
final ServiceIdentifier targetIdentifier) throws RateLimitExceededException {
|
||||
rateLimiters.getProfileLimiter().validate(requesterUuid);
|
||||
|
||||
+3
-1
@@ -4,6 +4,7 @@
|
||||
*/
|
||||
package org.whispersystems.textsecuregcm.grpc.net;
|
||||
|
||||
import com.google.common.net.InetAddresses;
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import io.netty.channel.ChannelInboundHandlerAdapter;
|
||||
import io.netty.handler.codec.haproxy.HAProxyMessage;
|
||||
@@ -30,7 +31,8 @@ class ProxyMessageAttributeSetterHandler extends ChannelInboundHandlerAdapter {
|
||||
try {
|
||||
final String sourceAddress = proxyMessage.sourceAddress();
|
||||
if (sourceAddress != null) {
|
||||
ctx.channel().attr(PROXY_REMOTE_ADDRESS).set(InetAddress.getByName(sourceAddress));
|
||||
// Assume that the server has been configured to only allow access from a trusted PPv2 provider
|
||||
ctx.channel().attr(PROXY_REMOTE_ADDRESS).set(InetAddresses.forString(sourceAddress));
|
||||
} else {
|
||||
logger.warn("PROXY protocol message has no source address");
|
||||
}
|
||||
|
||||
+16
-2
@@ -5,17 +5,17 @@
|
||||
|
||||
package org.whispersystems.textsecuregcm.jetty;
|
||||
|
||||
import org.eclipse.jetty.http.HttpHeader;
|
||||
import org.eclipse.jetty.http2.server.HTTP2ServerConnectionFactory;
|
||||
import org.eclipse.jetty.server.ConnectionFactory;
|
||||
import org.eclipse.jetty.server.Connector;
|
||||
import org.eclipse.jetty.server.ForwardedRequestCustomizer;
|
||||
import org.eclipse.jetty.server.HttpConfiguration;
|
||||
import org.eclipse.jetty.server.HttpConnectionFactory;
|
||||
import org.eclipse.jetty.util.component.Container;
|
||||
import org.eclipse.jetty.util.component.LifeCycle;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import io.micrometer.core.instrument.binder.jetty.JettyConnectionMetrics;
|
||||
|
||||
/**
|
||||
* Uses {@link Container.Listener} to update {@link org.eclipse.jetty.server.HttpConfiguration}
|
||||
@@ -38,6 +38,20 @@ public class JettyHttpConfigurationCustomizer implements Container.Listener, Lif
|
||||
// see https://github.com/jetty/jetty.project/issues/1891
|
||||
logger.info("setNotifyRemoteAsyncErrors(false) for {}", cf);
|
||||
httpConfiguration.setNotifyRemoteAsyncErrors(false);
|
||||
|
||||
httpConfiguration.getCustomizers().stream()
|
||||
.filter(ForwardedRequestCustomizer.class::isInstance)
|
||||
.map(ForwardedRequestCustomizer.class::cast)
|
||||
.forEach(forwardedRequestCustomizer -> {
|
||||
// If this http configuration supports using proxy-supplied headers, only use X-Forwarded-For
|
||||
|
||||
// Disable all headers except for 'Forwarded'
|
||||
forwardedRequestCustomizer.setForwardedOnly(true);
|
||||
// Disable 'Forwarded'
|
||||
forwardedRequestCustomizer.setForwardedHeader(null);
|
||||
// Enable 'X-Forwarded-For'
|
||||
forwardedRequestCustomizer.setForwardedForHeader(HttpHeader.X_FORWARDED_FOR.toString());
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,12 +22,15 @@ import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.Collections;
|
||||
import java.util.HashSet;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.IntStream;
|
||||
import javax.annotation.Nullable;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.signal.libsignal.protocol.IdentityKey;
|
||||
@@ -46,6 +49,8 @@ import org.whispersystems.textsecuregcm.util.ZkCredentialPublicKeyAdapter;
|
||||
@JsonFilter("Account")
|
||||
public class Account {
|
||||
|
||||
public static final int MAX_TOTP_KEY_ID = Byte.MAX_VALUE;
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(Account.class);
|
||||
|
||||
@JsonProperty
|
||||
@@ -161,7 +166,7 @@ public class Account {
|
||||
private TotpKey pendingTotpKey;
|
||||
|
||||
@JsonProperty("totp")
|
||||
private Map<Integer, AnnotatedTotpKey> totpKeys = Collections.emptyMap();
|
||||
private Map<Byte, AnnotatedTotpKey> totpKeys = Collections.emptyMap();
|
||||
|
||||
@JsonIgnore
|
||||
private boolean stale;
|
||||
@@ -668,21 +673,23 @@ public class Account {
|
||||
return Optional.ofNullable(pendingTotpKey);
|
||||
}
|
||||
|
||||
public int getNextTotpKeyId() {
|
||||
public byte getNextTotpKeyId() {
|
||||
requireNotStale();
|
||||
|
||||
return totpKeys.keySet().stream()
|
||||
.mapToInt(i -> i)
|
||||
.max()
|
||||
.orElse(-1) + 1;
|
||||
final Set<Byte> usedKeys = new HashSet<>(totpKeys.keySet());
|
||||
|
||||
return (byte) IntStream.range(0, MAX_TOTP_KEY_ID + 1)
|
||||
.filter(b -> !usedKeys.contains((byte) b))
|
||||
.findFirst()
|
||||
.orElseThrow(IllegalStateException::new);
|
||||
}
|
||||
|
||||
public Map<Integer, AnnotatedTotpKey> getTotpKeys() {
|
||||
public Map<Byte, AnnotatedTotpKey> getTotpKeys() {
|
||||
requireNotStale();
|
||||
return totpKeys;
|
||||
}
|
||||
|
||||
public void setTotpKeys(final Map<Integer, AnnotatedTotpKey> totpKeys) {
|
||||
public void setTotpKeys(final Map<Byte, AnnotatedTotpKey> totpKeys) {
|
||||
requireNotStale();
|
||||
this.totpKeys = totpKeys;
|
||||
}
|
||||
|
||||
@@ -61,7 +61,6 @@ import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
import javax.annotation.Nullable;
|
||||
import javax.crypto.KeyGenerator;
|
||||
import javax.crypto.Mac;
|
||||
@@ -2060,7 +2059,7 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
/// otherwise
|
||||
///
|
||||
/// @see [#generatePendingTotpKey(UUID)
|
||||
public Optional<Integer> confirmPendingTotpKey(final UUID accountIdentifier,
|
||||
public Optional<Byte> confirmPendingTotpKey(final UUID accountIdentifier,
|
||||
final int oneTimePassword,
|
||||
final Instant timestamp,
|
||||
final byte[] metadataCiphertext) {
|
||||
@@ -2081,18 +2080,18 @@ public class AccountsManager extends RedisPubSubAdapter<String, String> implemen
|
||||
final AtomicInteger keyId = new AtomicInteger();
|
||||
|
||||
update(accountIdentifier, account -> {
|
||||
final Map<Integer, AnnotatedTotpKey> updatedTotpKeys = new HashMap<>(account.getTotpKeys());
|
||||
final Map<Byte, AnnotatedTotpKey> updatedTotpKeys = new HashMap<>(account.getTotpKeys());
|
||||
|
||||
keyId.set(account.getNextTotpKeyId());
|
||||
|
||||
updatedTotpKeys.put(keyId.get(),
|
||||
updatedTotpKeys.put((byte) keyId.get(),
|
||||
new AnnotatedTotpKey(new TotpKey(pendingTotpKey.totpParameters(), pendingTotpKey.encodedKey()), metadataCiphertext));
|
||||
|
||||
account.setPendingTotpKey(null);
|
||||
account.setTotpKeys(updatedTotpKeys);
|
||||
});
|
||||
|
||||
return Optional.of(keyId.get());
|
||||
return Optional.of((byte) keyId.get());
|
||||
}
|
||||
} catch (final InvalidKeyException e) {
|
||||
ImpossibleEvents.logImpossible(logger, "Invalid pending TOTP key for account {}", accountIdentifier, e);
|
||||
|
||||
@@ -29,9 +29,11 @@ import software.amazon.awssdk.services.dynamodb.model.DeleteItemRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.GetItemRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.GetItemResponse;
|
||||
import software.amazon.awssdk.services.dynamodb.model.QueryRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.ReturnValue;
|
||||
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem;
|
||||
import software.amazon.awssdk.services.dynamodb.model.Update;
|
||||
import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest;
|
||||
import software.amazon.awssdk.services.dynamodb.model.UpdateItemResponse;
|
||||
|
||||
public class Profiles {
|
||||
|
||||
@@ -282,4 +284,28 @@ public class Profiles {
|
||||
.doOnError(ignored -> sample.stop(Metrics.timer(DELETE_PROFILES_TIMER_NAME, "outcome", "error")))
|
||||
.toFuture();
|
||||
}
|
||||
|
||||
/**
|
||||
* Upserts the avatar for a v1 profile
|
||||
*/
|
||||
public VersionedProfileV1 setAvatar(UUID accountIdentifier, String version, String avatar, byte[] commitment) {
|
||||
final UpdateItemResponse response = SET_PROFILES_TIMER.record(() ->
|
||||
dynamoDbClient.updateItem(UpdateItemRequest.builder()
|
||||
.tableName(tableName)
|
||||
.key(buildPrimaryKey(accountIdentifier, version))
|
||||
.updateExpression("SET #avatar = :avatar, #commitment = if_not_exists(#commitment, :commitment)")
|
||||
.expressionAttributeNames(Map.of(
|
||||
"#avatar", ATTR_AVATAR,
|
||||
"#commitment", ATTR_COMMITMENT
|
||||
))
|
||||
.expressionAttributeValues(Map.of(
|
||||
":avatar", AttributeValues.s(avatar),
|
||||
":commitment", AttributeValues.b(commitment)
|
||||
))
|
||||
.returnValues(ReturnValue.ALL_NEW)
|
||||
.build())
|
||||
);
|
||||
|
||||
return fromItem(response.attributes());
|
||||
}
|
||||
}
|
||||
@@ -338,4 +338,14 @@ public class ProfilesManager {
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public void setV1Avatar(UUID accountIdentifier, String version, String avatar, byte[] commitment) {
|
||||
ResilienceUtil.getGeneralRedisRetry(RETRY_NAME)
|
||||
.executeRunnable(() -> cacheCluster.withBinaryCluster(
|
||||
connection -> connection.sync().del(getCacheKeyV1(accountIdentifier))));
|
||||
|
||||
final VersionedProfileV1 versionedProfileV1 = profilesV1.setAvatar(accountIdentifier, version, avatar, commitment);
|
||||
|
||||
redisSet(accountIdentifier, null, versionedProfileV1);
|
||||
}
|
||||
}
|
||||
+8
-3
@@ -85,7 +85,7 @@ public class FoundationDbMessageStore {
|
||||
private static final byte[] SERVER_ID = UUIDUtil.toBytes(UUID.randomUUID());
|
||||
private static final int PRESENCE_VALUE_LENGTH = 28;
|
||||
|
||||
private static final Subspace MESSAGES_SUBSPACE = new Subspace(Tuple.from("M"));
|
||||
public static final Subspace MESSAGES_SUBSPACE = new Subspace(Tuple.from("M"));
|
||||
|
||||
@VisibleForTesting
|
||||
static final Duration PRESENCE_STALE_THRESHOLD = Duration.ofMinutes(5);
|
||||
@@ -717,8 +717,13 @@ public class FoundationDbMessageStore {
|
||||
});
|
||||
}
|
||||
|
||||
private static Subspace getAccountSubspace(final AciServiceIdentifier aci) {
|
||||
return MESSAGES_SUBSPACE.get(aci.uuid());
|
||||
@VisibleForTesting
|
||||
public static Subspace getAccountSubspace(final AciServiceIdentifier aci) {
|
||||
return getAccountSubspace(MESSAGES_SUBSPACE, aci);
|
||||
}
|
||||
|
||||
public static Subspace getAccountSubspace(final Subspace messagesSubspace, final AciServiceIdentifier aci) {
|
||||
return messagesSubspace.get(aci.uuid());
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
|
||||
+295
@@ -0,0 +1,295 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.workers;
|
||||
|
||||
import static org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStore.getAccountSubspace;
|
||||
|
||||
import com.apple.foundationdb.Database;
|
||||
import com.apple.foundationdb.FDB;
|
||||
import com.apple.foundationdb.KeySelector;
|
||||
import com.apple.foundationdb.Range;
|
||||
import com.apple.foundationdb.ReadTransaction;
|
||||
import com.apple.foundationdb.async.AsyncUtil;
|
||||
import com.apple.foundationdb.subspace.Subspace;
|
||||
import com.apple.foundationdb.tuple.ByteArrayUtil;
|
||||
import com.google.common.annotations.VisibleForTesting;
|
||||
import io.dropwizard.core.Application;
|
||||
import io.dropwizard.core.setup.Environment;
|
||||
import io.micrometer.core.instrument.Metrics;
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Stream;
|
||||
import net.sourceforge.argparse4j.inf.Namespace;
|
||||
import net.sourceforge.argparse4j.inf.Subparser;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStore;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.util.retry.Retry;
|
||||
|
||||
public class ClearOrphanedFoundationDbQueuesCommand extends AbstractCommandWithDependencies {
|
||||
|
||||
private final Logger logger = LoggerFactory.getLogger(getClass());
|
||||
|
||||
private final Subspace messagesSubspace;
|
||||
|
||||
private static final String DRY_RUN_ARGUMENT = "dry-run";
|
||||
|
||||
private static final String CONCURRENCY_ARGUMENT = "concurrency";
|
||||
private static final int DEFAULT_CONCURRENCY = 16;
|
||||
|
||||
private static final String MAX_ACIS_PER_TRANSACTION_ARGUMENT = "max-acis-per-transaction";
|
||||
private static final int DEFAULT_MAX_ACIS_PER_TRANSACTION = 128;
|
||||
|
||||
private static final String CHUNKS_PER_SHARD_ARGUMENT = "chunks-per-shard";
|
||||
private static final int DEFAULT_CHUNKS_PER_SHARD = 100;
|
||||
|
||||
private static final String ACCOUNTS_CRAWLED_COUNTER = MetricsUtil.name(ClearOrphanedFoundationDbQueuesCommand.class,
|
||||
"accountsCrawled");
|
||||
private static final String ORPHANED_QUEUES_CLEARED = MetricsUtil.name(ClearOrphanedFoundationDbQueuesCommand.class,
|
||||
"orphanedQueuesCleared");
|
||||
|
||||
|
||||
public ClearOrphanedFoundationDbQueuesCommand() {
|
||||
this(FoundationDbMessageStore.MESSAGES_SUBSPACE);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
public ClearOrphanedFoundationDbQueuesCommand(final Subspace messagesSubspace) {
|
||||
super(new Application<>() {
|
||||
@Override
|
||||
public void run(final WhisperServerConfiguration configuration, final Environment environment) {
|
||||
}
|
||||
}, "clear-orphaned-foundationdb-queues", "Clear FoundationDB queues that have no active account");
|
||||
this.messagesSubspace = messagesSubspace;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void configure(final Subparser subparser) {
|
||||
super.configure(subparser);
|
||||
|
||||
subparser.addArgument("--concurrency")
|
||||
.type(Integer.class)
|
||||
.dest(CONCURRENCY_ARGUMENT)
|
||||
.required(false)
|
||||
.setDefault(DEFAULT_CONCURRENCY)
|
||||
.help("The maximum number of parallel dynamodb operations to process concurrently");
|
||||
|
||||
subparser.addArgument("--dry-run")
|
||||
.type(Boolean.class)
|
||||
.dest(DRY_RUN_ARGUMENT)
|
||||
.required(false)
|
||||
.setDefault(true)
|
||||
.help("If true, don't actually clear orphaned queues");
|
||||
|
||||
subparser.addArgument("--max-acis-per-transaction")
|
||||
.type(Integer.class)
|
||||
.dest(MAX_ACIS_PER_TRANSACTION_ARGUMENT)
|
||||
.required(false)
|
||||
.setDefault(DEFAULT_MAX_ACIS_PER_TRANSACTION)
|
||||
.help("The maximum number of ACIs to read per FoundationDB transaction");
|
||||
|
||||
subparser.addArgument("--chunks-per-shard")
|
||||
.type(Integer.class)
|
||||
.dest(CHUNKS_PER_SHARD_ARGUMENT)
|
||||
.required(false)
|
||||
.setDefault(DEFAULT_CHUNKS_PER_SHARD)
|
||||
.help("The number of chunks to split the the key-space into, each of which will be crawled in parallel");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void run(final Environment environment, final Namespace namespace,
|
||||
final WhisperServerConfiguration configuration, final CommandDependencies commandDependencies) throws Exception {
|
||||
|
||||
final int concurrency = Objects.requireNonNull(namespace.getInt(CONCURRENCY_ARGUMENT));
|
||||
final boolean dryRun = Objects.requireNonNull(namespace.getBoolean(DRY_RUN_ARGUMENT));
|
||||
final int maxAcisPerTransaction = Objects.requireNonNull(namespace.getInt(MAX_ACIS_PER_TRANSACTION_ARGUMENT));
|
||||
final int chunksPerShard = Objects.requireNonNull(namespace.getInt(CHUNKS_PER_SHARD_ARGUMENT));
|
||||
|
||||
final FDB fdb = commandDependencies.fdb();
|
||||
|
||||
final Stream<Database> databases = configuration.getFoundationDbMessagesConfiguration().clusters().values().stream()
|
||||
.map(databaseFactory -> {
|
||||
try {
|
||||
return databaseFactory.build(fdb);
|
||||
} catch (final IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
});
|
||||
clearOrphanedQueues(databases, commandDependencies.accountsManager(), concurrency, dryRun, maxAcisPerTransaction,
|
||||
configuration.getFoundationDbMessagesConfiguration().batchPriorityTransactionRetryLimit(),
|
||||
configuration.getFoundationDbMessagesConfiguration().batchPriorityTransactionTimeout(),
|
||||
chunksPerShard);
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
void clearOrphanedQueues(final Stream<Database> databases, final AccountsManager accountsManager,
|
||||
final int concurrency, final boolean dryRun, final int maxAcisPerTransaction, final long transactionRetryLimit,
|
||||
final Duration transactionTimeout, final int numChunks) {
|
||||
Flux.fromStream(databases)
|
||||
.flatMap(database -> crawlAcisInShard(database, accountsManager, concurrency, dryRun, maxAcisPerTransaction,
|
||||
transactionRetryLimit, transactionTimeout, numChunks))
|
||||
.then()
|
||||
.block();
|
||||
}
|
||||
|
||||
private Mono<Void> crawlAcisInShard(final Database database, final AccountsManager accountsManager,
|
||||
final int concurrency, final boolean dryRun, final int maxAcisPerTransaction, final long transactionRetryLimit,
|
||||
final Duration transactionTimeout, final int numChunks) {
|
||||
return getAcisInShard(database, maxAcisPerTransaction, transactionRetryLimit, transactionTimeout, numChunks)
|
||||
.doOnNext(_ -> Metrics.counter(ACCOUNTS_CRAWLED_COUNTER, "dryRun", String.valueOf(dryRun)).increment())
|
||||
.flatMap(aci -> Mono.fromFuture(() -> accountsManager.getByAccountIdentifierAsync(aci.uuid()))
|
||||
.flatMap(maybeAccount -> {
|
||||
if (maybeAccount.isEmpty()) {
|
||||
return Mono.just(aci);
|
||||
}
|
||||
return Mono.empty();
|
||||
})
|
||||
.retryWhen(Retry.backoff(2, Duration.ofSeconds(1)))
|
||||
.onErrorResume(t -> {
|
||||
logger.warn("Failed to fetch account by ACI", t);
|
||||
return Mono.empty();
|
||||
})
|
||||
, concurrency)
|
||||
.flatMap(aci -> {
|
||||
if (dryRun) {
|
||||
logger.info("Would have cleared queue for ACI: {}", aci.uuid());
|
||||
return Mono.just(true);
|
||||
}
|
||||
return clearQueue(database, aci, transactionRetryLimit, transactionTimeout)
|
||||
.thenReturn(true)
|
||||
.onErrorResume(t -> {
|
||||
logger.error("Failed to clear orphaned queue for ACI: {}", aci.uuid(), t);
|
||||
return Mono.just(false);
|
||||
});
|
||||
})
|
||||
.doOnNext(success -> Metrics.counter(ORPHANED_QUEUES_CLEARED,
|
||||
"dryRun", String.valueOf(dryRun),
|
||||
"success", String.valueOf(success)).increment())
|
||||
.then();
|
||||
}
|
||||
|
||||
private Mono<Void> clearQueue(final Database database, final AciServiceIdentifier aci,
|
||||
final long transactionRetryLimit, final Duration transactionTimeout) {
|
||||
return Mono.fromFuture(() -> database.runAsync(transaction -> {
|
||||
transaction.options().setPriorityBatch();
|
||||
transaction.options().setRetryLimit(transactionRetryLimit);
|
||||
transaction.options().setTimeout(transactionTimeout.toMillis());
|
||||
transaction.clear(getAccountSubspace(messagesSubspace, aci).range());
|
||||
return CompletableFuture.completedFuture(null);
|
||||
}));
|
||||
}
|
||||
|
||||
@VisibleForTesting
|
||||
Flux<AciServiceIdentifier> getAcisInShard(final Database database, final int maxAcisPerTransaction,
|
||||
final long transactionRetryLimit, final Duration transactionTimeout, final int numChunks) {
|
||||
return Mono.fromFuture(() -> splitSubspace(database, numChunks))
|
||||
.flatMapIterable(Function.identity())
|
||||
.flatMap(
|
||||
range -> getAcisInChunk(database, maxAcisPerTransaction, transactionRetryLimit, transactionTimeout, range));
|
||||
}
|
||||
|
||||
/// Split the messages subspace into roughly equally sized \`numChunks\` chunks, each of which can be crawled in
|
||||
/// parallel
|
||||
///
|
||||
/// @param database the FDB instance
|
||||
/// @param numChunks the number of chunks to split the subspace into
|
||||
/// @return a list of key [Range]s representing chunk boundaries
|
||||
CompletableFuture<List<Range>> splitSubspace(final Database database, final int numChunks) {
|
||||
return database.runAsync(transaction -> transaction.getEstimatedRangeSizeBytes(messagesSubspace.range())
|
||||
.thenCompose(rangeSize -> {
|
||||
final int chunkSize = Math.toIntExact(Math.ceilDiv(rangeSize, numChunks));
|
||||
return transaction.getRangeSplitPoints(messagesSubspace.range(), chunkSize);
|
||||
}))
|
||||
.thenApply(result -> splitPointsToRanges(result.getKeys()));
|
||||
}
|
||||
|
||||
private static List<Range> splitPointsToRanges(final List<byte[]> splitPoints) {
|
||||
if (splitPoints.size() < 2) {
|
||||
throw new IllegalArgumentException("Expected at least two split points");
|
||||
}
|
||||
final int numSplitPoints = splitPoints.size();
|
||||
final List<Range> ranges = new ArrayList<>();
|
||||
for (int i = 0; i < numSplitPoints - 1; i++) {
|
||||
ranges.add(new Range(splitPoints.get(i), splitPoints.get(i + 1)));
|
||||
}
|
||||
return ranges;
|
||||
}
|
||||
|
||||
Flux<AciServiceIdentifier> getAcisInChunk(final Database database, final int maxAcisPerTransaction,
|
||||
final long transactionRetryLimit, final Duration transactionTimeout, final Range range) {
|
||||
return readAciBatch(database, range.begin, range.end, maxAcisPerTransaction, transactionRetryLimit,
|
||||
transactionTimeout)
|
||||
.expand(result -> {
|
||||
if (result.acis().isEmpty()) {
|
||||
return Mono.empty();
|
||||
}
|
||||
return readAciBatch(database, result.cursor(), range.end, maxAcisPerTransaction, transactionRetryLimit,
|
||||
transactionTimeout);
|
||||
})
|
||||
.limitRate(1)
|
||||
.flatMapIterable(BatchReadResult::acis);
|
||||
}
|
||||
|
||||
private record BatchReadResult(List<AciServiceIdentifier> acis, byte[] cursor) {}
|
||||
|
||||
private Mono<BatchReadResult> readAciBatch(
|
||||
final Database database,
|
||||
final byte[] beginInclusive,
|
||||
final byte[] endExclusive,
|
||||
final int maxAcisPerTransaction,
|
||||
final long transactionRetryLimit,
|
||||
final Duration transactionTimeout) {
|
||||
|
||||
final AtomicReference<byte[]> cursor = new AtomicReference<>(beginInclusive);
|
||||
final AtomicInteger numAcisRead = new AtomicInteger();
|
||||
return Mono.fromFuture(() -> database.readAsync(transaction -> {
|
||||
final ReadTransaction readTransaction = transaction.snapshot();
|
||||
readTransaction.options().setPriorityBatch();
|
||||
readTransaction.options().setRetryLimit(transactionRetryLimit);
|
||||
readTransaction.options().setTimeout(transactionTimeout.toMillis());
|
||||
final List<AciServiceIdentifier> acis = new ArrayList<>();
|
||||
return AsyncUtil.whileTrue(() -> {
|
||||
if (ByteArrayUtil.compareUnsigned(cursor.get(), endExclusive) >= 0) {
|
||||
return CompletableFuture.completedFuture(false);
|
||||
}
|
||||
return readTransaction.getKey(KeySelector.firstGreaterOrEqual(cursor.get())).thenApply(key -> {
|
||||
if (ByteArrayUtil.compareUnsigned(key, endExclusive) >= 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
final AciServiceIdentifier aci = getAciFromKey(key);
|
||||
acis.add(aci);
|
||||
// Skip the specified ACI's entire subspace by incrementing the account prefix; this way,
|
||||
// [KeySelector#firstGreaterOrEqual] should resolve to the next available ACI (if one exists)
|
||||
cursor.set(ByteArrayUtil.strinc(getAccountSubspace(messagesSubspace, aci).getKey()));
|
||||
return numAcisRead.incrementAndGet() < maxAcisPerTransaction;
|
||||
});
|
||||
})
|
||||
.thenApply(_ -> acis);
|
||||
})
|
||||
.thenApply(acis -> new BatchReadResult(acis, cursor.get()))
|
||||
);
|
||||
}
|
||||
|
||||
public AciServiceIdentifier getAciFromKey(final byte[] key) {
|
||||
return new AciServiceIdentifier(messagesSubspace.unpack(key).getUUID(0));
|
||||
}
|
||||
|
||||
}
|
||||
+4
-2
@@ -125,7 +125,8 @@ public record CommandDependencies(
|
||||
DynamoDbAsyncClient dynamoDbAsyncClient,
|
||||
DynamoDbClient dynamoDbClient,
|
||||
PhoneNumberIdentifiers phoneNumberIdentifiers,
|
||||
DynamoDbRecoveryManager dynamoDbRecoveryManager) {
|
||||
DynamoDbRecoveryManager dynamoDbRecoveryManager,
|
||||
FDB fdb) {
|
||||
|
||||
static CommandDependencies build(
|
||||
final String name,
|
||||
@@ -458,7 +459,8 @@ public record CommandDependencies(
|
||||
dynamoDbAsyncClient,
|
||||
dynamoDbClient,
|
||||
phoneNumberIdentifiers,
|
||||
dynamoDbRecoveryManager
|
||||
dynamoDbRecoveryManager,
|
||||
fdb
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -549,7 +549,7 @@ message ConfirmTotpKeyRequest {
|
||||
message ConfirmTotpKeyResponse {
|
||||
message KeyConfirmed {
|
||||
// The account-specific identifier for the newly-confirmed TOTP key
|
||||
uint32 key_id = 1;
|
||||
uint32 key_id = 1 [(require.range) = {min: 0, max: 127}];
|
||||
}
|
||||
|
||||
oneof response {
|
||||
@@ -568,18 +568,18 @@ message ListTotpKeysRequest {}
|
||||
message ListTotpKeysResponse {
|
||||
message TotpKeyMetadata {
|
||||
// The user-provided ciphertext for metadata associated with this TOTP key
|
||||
bytes metadata_ciphertext = 1;
|
||||
bytes metadata_ciphertext = 1 [(require.exactlySize) = 160];
|
||||
|
||||
// The TOTP parameters associated with this key
|
||||
TotpParameters totp_parameters = 2;
|
||||
}
|
||||
|
||||
map<int32, TotpKeyMetadata> keys = 1;
|
||||
map<uint32, TotpKeyMetadata> keys = 1;
|
||||
}
|
||||
|
||||
message SetTotpKeyMetadataRequest {
|
||||
// The account-specific identifier of the TOTP key to modify
|
||||
uint32 key_id = 1;
|
||||
uint32 key_id = 1 [(require.range) = {min: 0, max: 127}];
|
||||
|
||||
// The ciphertext of the new user-provided metadata to be attached to the
|
||||
// identified key
|
||||
@@ -601,7 +601,7 @@ message SetTotpKeyMetadataResponse {
|
||||
|
||||
message RemoveTotpKeyRequest {
|
||||
// The account-specific identifier of the TOTP key to remove
|
||||
uint32 key_id = 1;
|
||||
uint32 key_id = 1 [(require.range) = {min: 0, max: 127}];
|
||||
}
|
||||
|
||||
message RemoveTotpKeyResponse {
|
||||
|
||||
@@ -31,6 +31,17 @@ service Profile {
|
||||
//
|
||||
// Note: `Accounts.SetZkCredentialKey` is a pre-requisite for this RPC
|
||||
rpc GetAvatarCredentials(GetAvatarCredentialsRequest) returns (GetAvatarCredentialsResponse) {}
|
||||
|
||||
// Returns credentials used by clients to upload a v1 avatar, deleting any current avatar.
|
||||
//
|
||||
// This RPC streamlines avatar changes during the v1 -> v2 transition by minimizing uploads:
|
||||
// 1. SetV1Avatar
|
||||
// 2. Upload to CDN
|
||||
// 3. SetProfile with v1 `AVATAR_CHANGE_UNCHANGED` and the v1 avatar in the v2 profile body
|
||||
//
|
||||
// Clients that do this will be required to upload current avatars using `ProfilesAnonymous.GetAvatarUploadFormRequest`
|
||||
// once v1 Profile APIs are no longer supported.
|
||||
rpc SetV1Avatar(SetV1AvatarRequest) returns (SetV1AvatarResponse) {}
|
||||
}
|
||||
|
||||
// Provides methods for working with profiles and profile-related data using "unidentified access"
|
||||
@@ -90,6 +101,19 @@ message SetProfileV1Request {
|
||||
bytes phone_number_sharing = 6 [(require.exactlySize) = 29];
|
||||
}
|
||||
|
||||
message SetV1AvatarRequest {
|
||||
// The profile version. Required.
|
||||
string version = 1 [(require.exactlySize) = 64];
|
||||
|
||||
// The profile key commitment. Required if this is a new profile version.
|
||||
bytes commitment = 2 [(require.exactlySize) = 0, (require.exactlySize) = 97];
|
||||
}
|
||||
|
||||
message SetV1AvatarResponse {
|
||||
// the policy and credential used by clients to upload an avatar to the CDN
|
||||
common.S3UploadForm form = 1;
|
||||
}
|
||||
|
||||
message SetProfileRequest {
|
||||
|
||||
// The profile version. Required.
|
||||
@@ -374,6 +398,7 @@ message GetAvatarUploadFormRequest {
|
||||
|
||||
message GetAvatarUploadFormResponse {
|
||||
oneof response {
|
||||
// the policy and credential used by clients to upload an avatar to the CDN
|
||||
common.S3UploadForm avatar_upload_form = 1;
|
||||
|
||||
errors.FailedZkAuthentication invalid_credentials_presentation = 2 [(tag.reason) = "invalid_credentials_presentation"];
|
||||
|
||||
+18
-17
@@ -31,9 +31,7 @@ import org.eclipse.jetty.client.HttpClient;
|
||||
import org.eclipse.jetty.http2.client.HTTP2Client;
|
||||
import org.eclipse.jetty.http2.client.transport.HttpClientTransportOverHTTP2;
|
||||
import org.eclipse.jetty.io.ClientConnector;
|
||||
import org.eclipse.jetty.util.component.LifeCycle;
|
||||
import org.eclipse.jetty.websocket.api.Session;
|
||||
import org.eclipse.jetty.websocket.api.StatusCode;
|
||||
import org.eclipse.jetty.websocket.client.WebSocketClient;
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
@@ -87,7 +85,9 @@ class WhisperServerServiceTest {
|
||||
public static final DynamoDbExtension DYNAMO_DB_EXTENSION = new DynamoDbExtension(DynamoDbExtensionSchema.Tables.values());
|
||||
|
||||
@AfterAll
|
||||
static void teardown() {
|
||||
static void teardown() throws Exception {
|
||||
h2WebSocketClient.stop();
|
||||
webSocketClient.stop();
|
||||
System.clearProperty("secrets.bundle.filename");
|
||||
}
|
||||
|
||||
@@ -132,23 +132,24 @@ class WhisperServerServiceTest {
|
||||
|
||||
final TestWebsocketListener testWebsocketListener = new TestWebsocketListener();
|
||||
|
||||
// Session is Closeable, but we intentionally keep it open so that we can confirm the container Lifecycle behavior
|
||||
final Session session = (useH2 ? h2WebSocketClient : webSocketClient).connect(testWebsocketListener,
|
||||
try(Session session = (useH2 ? h2WebSocketClient : webSocketClient).connect(testWebsocketListener,
|
||||
URI.create(String.format("ws://localhost:%d/v1/websocket/", EXTENSION.getLocalPort())))
|
||||
.join();
|
||||
final long sessionTimestamp = Long.parseLong(session.getUpgradeResponse().getHeader(HeaderUtils.TIMESTAMP_HEADER));
|
||||
assertTrue(sessionTimestamp >= start);
|
||||
.join()) {
|
||||
final long sessionTimestamp = Long.parseLong(
|
||||
session.getUpgradeResponse().getHeader(HeaderUtils.TIMESTAMP_HEADER));
|
||||
assertTrue(sessionTimestamp >= start);
|
||||
|
||||
final WebSocketResponseMessage keepAlive = testWebsocketListener.doGet("/v1/keepalive").join();
|
||||
assertEquals(200, keepAlive.getStatus());
|
||||
final long keepAliveTimestamp = Long.parseLong(
|
||||
keepAlive.getHeaders().get(HeaderUtils.TIMESTAMP_HEADER.toLowerCase()));
|
||||
assertTrue(keepAliveTimestamp >= start);
|
||||
final WebSocketResponseMessage keepAlive = testWebsocketListener.doGet("/v1/keepalive").join();
|
||||
assertEquals(200, keepAlive.getStatus());
|
||||
final long keepAliveTimestamp = Long.parseLong(
|
||||
keepAlive.getHeaders().get(HeaderUtils.TIMESTAMP_HEADER.toLowerCase()));
|
||||
assertTrue(keepAliveTimestamp >= start);
|
||||
|
||||
final WebSocketResponseMessage whoami = testWebsocketListener.doGet("/v1/accounts/whoami").join();
|
||||
assertEquals(401, whoami.getStatus());
|
||||
final long whoamiTimestamp = Long.parseLong(whoami.getHeaders().get(HeaderUtils.TIMESTAMP_HEADER.toLowerCase()));
|
||||
assertTrue(whoamiTimestamp >= start);
|
||||
final WebSocketResponseMessage whoami = testWebsocketListener.doGet("/v1/accounts/whoami").join();
|
||||
assertEquals(401, whoami.getStatus());
|
||||
final long whoamiTimestamp = Long.parseLong(whoami.getHeaders().get(HeaderUtils.TIMESTAMP_HEADER.toLowerCase()));
|
||||
assertTrue(whoamiTimestamp >= start);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+12
-5
@@ -46,6 +46,7 @@ import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.stream.Stream;
|
||||
import org.apache.commons.lang3.ArrayUtils;
|
||||
import org.glassfish.jersey.server.ServerProperties;
|
||||
import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
@@ -881,10 +882,13 @@ class AccountControllerTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void testAccountsAttributesUpdateRecoveryPassword() {
|
||||
final byte[] recoveryPassword = TestRandomUtil.nextBytes(32);
|
||||
static Stream<byte[]> testAccountsAttributesUpdateRecoveryPassword() {
|
||||
return Stream.of(null, new byte[]{}, TestRandomUtil.nextBytes(32));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void testAccountsAttributesUpdateRecoveryPassword(final byte[] recoveryPassword) {
|
||||
try (final Response response = resources.getJerseyTest()
|
||||
.target("/v1/accounts/attributes/")
|
||||
.request()
|
||||
@@ -893,9 +897,12 @@ class AccountControllerTest {
|
||||
.setUnidentifiedAccessKey(new byte[16])
|
||||
.setRecoveryPassword(recoveryPassword)))) {
|
||||
|
||||
final int expectedRrpUpdates = ArrayUtils.isEmpty(recoveryPassword) ? 0 : 1;
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(204);
|
||||
verify(accountsManager).update(eq(AuthHelper.UNDISCOVERABLE_UUID), any(), argThat(additionWriteItems -> additionWriteItems.size() == 1));
|
||||
verify(AuthHelper.UNDISCOVERABLE_ACCOUNT).setAccountRecoveryPassword(recoveryPassword);
|
||||
verify(accountsManager).update(eq(AuthHelper.UNDISCOVERABLE_UUID), any(), argThat(additionWriteItems -> additionWriteItems.size() == expectedRrpUpdates));
|
||||
|
||||
verify(AuthHelper.UNDISCOVERABLE_ACCOUNT, times(expectedRrpUpdates)).setAccountRecoveryPassword(recoveryPassword);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+8
-4
@@ -60,6 +60,7 @@ import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.junit.jupiter.params.provider.NullSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.junitpioneer.jupiter.cartesian.ArgumentSets;
|
||||
import org.junitpioneer.jupiter.cartesian.CartesianTest;
|
||||
@@ -1022,19 +1023,22 @@ class RegistrationControllerTest {
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
void registerAccountMissingRecoveryPassword() throws Exception {
|
||||
@ParameterizedTest
|
||||
@NullSource
|
||||
@ValueSource(ints = 0)
|
||||
void registerAccountMissingRecoveryPassword(@Nullable final Integer recoveryPasswordLength) throws Exception {
|
||||
final ECKeyPair aciIdentityKeyPair = ECKeyPair.generate();
|
||||
final IdentityKey aciIdentityKey = new IdentityKey(aciIdentityKeyPair.getPublicKey());
|
||||
|
||||
final AccountAttributes accountAttributes =
|
||||
new AccountAttributes(true, 1, null, "test".getBytes(StandardCharsets.UTF_8), null, false,
|
||||
DeviceCapability.CAPABILITIES_REQUIRED_FOR_NEW_DEVICES, null)
|
||||
DeviceCapability.CAPABILITIES_REQUIRED_FOR_NEW_DEVICES,
|
||||
recoveryPasswordLength == null ? null : new byte[recoveryPasswordLength])
|
||||
.setUnidentifiedAccessKey(TestRandomUtil.nextBytes(16));
|
||||
|
||||
final RegistrationRequest registrationRequest = new RegistrationRequest(null,
|
||||
new byte[0],
|
||||
receiptPresentation(CLOCK.instant().plus(Duration.ofDays(30)), 1).serialize(),
|
||||
receiptPresentation(CLOCK.instant().plus(Duration.ofDays(30)), ReceiptLevel.LOGIN.getValue()).serialize(),
|
||||
null,
|
||||
accountAttributes,
|
||||
true,
|
||||
|
||||
+80
-1
@@ -6,11 +6,14 @@
|
||||
package org.whispersystems.textsecuregcm.filters;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assumptions.assumeTrue;
|
||||
|
||||
import com.google.common.net.HttpHeaders;
|
||||
import io.dropwizard.core.Application;
|
||||
import io.dropwizard.core.Configuration;
|
||||
import io.dropwizard.core.setup.Environment;
|
||||
import io.dropwizard.testing.ConfigOverride;
|
||||
import io.dropwizard.testing.junit5.DropwizardAppExtension;
|
||||
import io.dropwizard.testing.junit5.DropwizardExtensionsSupport;
|
||||
import jakarta.ws.rs.GET;
|
||||
@@ -36,6 +39,7 @@ import org.eclipse.jetty.ee10.websocket.server.config.JettyWebSocketServletConta
|
||||
import org.eclipse.jetty.util.HostPort;
|
||||
import org.eclipse.jetty.websocket.api.Callback;
|
||||
import org.eclipse.jetty.websocket.api.Session;
|
||||
import org.eclipse.jetty.websocket.client.ClientUpgradeRequest;
|
||||
import org.eclipse.jetty.websocket.client.WebSocketClient;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
@@ -44,6 +48,7 @@ import org.junit.jupiter.api.Timeout;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.whispersystems.textsecuregcm.jetty.JettyHttpConfigurationCustomizer;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
import org.whispersystems.websocket.WebSocketResourceProviderFactory;
|
||||
import org.whispersystems.websocket.configuration.WebSocketConfiguration;
|
||||
@@ -64,7 +69,9 @@ class RemoteAddressFilterIntegrationTest {
|
||||
// in jersey-test-framework-provider-jetty doesn’t easily support @Context HttpServletRequest, so this test runs a
|
||||
// full Jetty server in a separate process
|
||||
private static final DropwizardAppExtension<Configuration> EXTENSION = new DropwizardAppExtension<>(
|
||||
TestApplication.class);
|
||||
TestApplication.class, null,
|
||||
ConfigOverride.config("server.applicationConnectors[0].type", "h2c"),
|
||||
ConfigOverride.config("server.applicationConnectors[0].useForwardedHeaders", "true"));
|
||||
|
||||
@Nested
|
||||
class Rest {
|
||||
@@ -87,6 +94,37 @@ class RemoteAddressFilterIntegrationTest {
|
||||
|
||||
assertEquals(ip, response.remoteAddress());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"127.0.0.3", "0:0:0:0:0:0:dead:beef"})
|
||||
void testForwardedForHeader(final String ip) throws Exception {
|
||||
final Client client = EXTENSION.client();
|
||||
|
||||
final RemoteAddressFilterIntegrationTest.TestResponse response = client.target(
|
||||
String.format("http://%s:%d%s", "localhost", EXTENSION.getLocalPort(), REMOTE_ADDRESS_PATH))
|
||||
.request("application/json")
|
||||
.header(HttpHeaders.X_FORWARDED_FOR, ip)
|
||||
.get(RemoteAddressFilterIntegrationTest.TestResponse.class);
|
||||
|
||||
assertEquals(ip, response.remoteAddress());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"Forwarded", "X-Forwarded-Host", "X-Forwarded-Server", "X-Forwarded-Proto"})
|
||||
void testOtherHeadersIgnored(final String header) throws Exception {
|
||||
final Client client = EXTENSION.client();
|
||||
|
||||
final String ip = "127.0.0.3";
|
||||
|
||||
final RemoteAddressFilterIntegrationTest.TestResponse response = client.target(
|
||||
String.format("http://%s:%d%s", "localhost", EXTENSION.getLocalPort(), REMOTE_ADDRESS_PATH))
|
||||
.request("application/json")
|
||||
.header(header, ip)
|
||||
.get(RemoteAddressFilterIntegrationTest.TestResponse.class);
|
||||
|
||||
assertNotEquals(ip, response.remoteAddress(), "header " + header + " should be ignored");
|
||||
assertEquals("127.0.0.1", response.remoteAddress());
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
@@ -128,6 +166,45 @@ class RemoteAddressFilterIntegrationTest {
|
||||
|
||||
assertEquals(ip, response.remoteAddress());
|
||||
}
|
||||
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"127.0.0.3", "0:0:0:0:0:0:dead:beef"})
|
||||
void testForwardedForHeader(final String ip) throws Exception {
|
||||
final CompletableFuture<byte[]> responseFuture = new CompletableFuture<>();
|
||||
final ClientEndpoint clientEndpoint = new ClientEndpoint(WS_REQUEST_PATH, responseFuture);
|
||||
final ClientUpgradeRequest upgradeRequest = new ClientUpgradeRequest(URI.create(String.format("ws://%s:%d%s",
|
||||
"localhost",
|
||||
EXTENSION.getLocalPort(),
|
||||
WEBSOCKET_PREFIX + REMOTE_ADDRESS_PATH)));
|
||||
upgradeRequest.setHeader(HttpHeaders.X_FORWARDED_FOR, ip);
|
||||
client.connect(clientEndpoint, upgradeRequest);
|
||||
|
||||
final byte[] responseBytes = responseFuture.get(1, TimeUnit.SECONDS);
|
||||
final TestResponse response = SystemMapper.jsonMapper().readValue(responseBytes, TestResponse.class);
|
||||
assertEquals(ip, response.remoteAddress());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"Forwarded", "X-Forwarded-Host", "X-Forwarded-Server", "X-Forwarded-Proto"})
|
||||
void testOtherHeadersIgnored(final String header) throws Exception {
|
||||
final String ip = "127.0.0.3";
|
||||
|
||||
final CompletableFuture<byte[]> responseFuture = new CompletableFuture<>();
|
||||
final ClientEndpoint clientEndpoint = new ClientEndpoint(WS_REQUEST_PATH, responseFuture);
|
||||
final ClientUpgradeRequest upgradeRequest = new ClientUpgradeRequest(URI.create(String.format("ws://%s:%d%s",
|
||||
"localhost",
|
||||
EXTENSION.getLocalPort(),
|
||||
WEBSOCKET_PREFIX + REMOTE_ADDRESS_PATH)));
|
||||
upgradeRequest.setHeader(header, ip);
|
||||
client.connect(clientEndpoint, upgradeRequest);
|
||||
|
||||
final byte[] responseBytes = responseFuture.get(1, TimeUnit.SECONDS);
|
||||
final TestResponse response = SystemMapper.jsonMapper().readValue(responseBytes, TestResponse.class);
|
||||
|
||||
assertNotEquals(ip, response.remoteAddress(), "header " + header + " should be ignored");
|
||||
assertEquals("127.0.0.1", response.remoteAddress());
|
||||
}
|
||||
}
|
||||
|
||||
public static class ClientEndpoint implements Session.Listener.AutoDemanding {
|
||||
@@ -216,6 +293,8 @@ class RemoteAddressFilterIntegrationTest {
|
||||
webSocketEnvironment, TestPrincipal.class,
|
||||
RemoteAddressFilter.REMOTE_ADDRESS_ATTRIBUTE_NAME);
|
||||
|
||||
environment.lifecycle().addEventListener(new JettyHttpConfigurationCustomizer());
|
||||
|
||||
JettyWebSocketServletContainerInitializer.configure(environment.getApplicationContext(), (servletContext, container) -> {
|
||||
container.addMapping(WEBSOCKET_PREFIX + REMOTE_ADDRESS_PATH, webSocketServlet);
|
||||
PriorityFilter.ensureFilter(servletContext, new RemoteAddressFilter());
|
||||
|
||||
+28
-11
@@ -1148,7 +1148,7 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
|
||||
|
||||
@Test
|
||||
void confirmTotpKey() {
|
||||
final int keyId = 17;
|
||||
final byte keyId = 17;
|
||||
final int oneTimePassword = 123456;
|
||||
final byte[] metadataCiphertext = TestRandomUtil.nextBytes(TOTP_KEY_METADATA_SIZE);
|
||||
|
||||
@@ -1188,9 +1188,9 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
|
||||
|
||||
@Test
|
||||
void listTotpKeys() {
|
||||
final Map<Integer, AnnotatedTotpKey> totpKeys = Map.of(
|
||||
1, generateRandomAnnotatedTotpKey(),
|
||||
2, generateRandomAnnotatedTotpKey());
|
||||
final Map<Byte, AnnotatedTotpKey> totpKeys = Map.of(
|
||||
(byte) 1, generateRandomAnnotatedTotpKey(),
|
||||
(byte) 2, generateRandomAnnotatedTotpKey());
|
||||
|
||||
final Account account = mock(Account.class);
|
||||
when(account.getTotpKeys()).thenReturn(totpKeys);
|
||||
@@ -1208,7 +1208,7 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
|
||||
.build();
|
||||
|
||||
final Map<Integer, ListTotpKeysResponse.TotpKeyMetadata> expectedTotpKeys = totpKeys.entrySet().stream()
|
||||
.collect(Collectors.toMap(Map.Entry::getKey, entry -> ListTotpKeysResponse.TotpKeyMetadata.newBuilder()
|
||||
.collect(Collectors.toMap(entry -> entry.getKey().intValue(), entry -> ListTotpKeysResponse.TotpKeyMetadata.newBuilder()
|
||||
.setTotpParameters(expectedTotpParameters)
|
||||
.setMetadataCiphertext(ByteString.copyFrom(entry.getValue().metadataCiphertext()))
|
||||
.build()));
|
||||
@@ -1218,7 +1218,7 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
|
||||
|
||||
@Test
|
||||
void setTotpKeyMetadata() {
|
||||
final int keyId = ThreadLocalRandom.current().nextInt();
|
||||
final byte keyId = (byte) ThreadLocalRandom.current().nextInt(Account.MAX_TOTP_KEY_ID);
|
||||
final byte[] updatedMetadata = TestRandomUtil.nextBytes(TOTP_KEY_METADATA_SIZE);
|
||||
final AnnotatedTotpKey existingTotpKey = generateRandomAnnotatedTotpKey();
|
||||
|
||||
@@ -1248,7 +1248,7 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
|
||||
|
||||
final SetTotpKeyMetadataResponse response =
|
||||
authenticatedServiceStub().setTotpKeyMetadata(SetTotpKeyMetadataRequest.newBuilder()
|
||||
.setKeyId(ThreadLocalRandom.current().nextInt())
|
||||
.setKeyId(ThreadLocalRandom.current().nextInt(Account.MAX_TOTP_KEY_ID))
|
||||
.setMetadataCiphertext(ByteString.copyFrom(TestRandomUtil.nextBytes(TOTP_KEY_METADATA_SIZE)))
|
||||
.build());
|
||||
|
||||
@@ -1265,11 +1265,20 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
|
||||
}
|
||||
|
||||
@Test
|
||||
void removeTotpKey() {
|
||||
final int retainedKeyId = 1;
|
||||
final int removedKeyId = 2;
|
||||
void setTotpKeyMetadataKeyIdOutOfRange() {
|
||||
GrpcTestUtils.assertStatusInvalidArgument(
|
||||
() -> authenticatedServiceStub().setTotpKeyMetadata(SetTotpKeyMetadataRequest.newBuilder()
|
||||
.setKeyId(Account.MAX_TOTP_KEY_ID + 1)
|
||||
.setMetadataCiphertext(ByteString.copyFrom(TestRandomUtil.nextBytes(TOTP_KEY_METADATA_SIZE)))
|
||||
.build()));
|
||||
}
|
||||
|
||||
final Map<Integer, AnnotatedTotpKey> initialKeys = Map.of(
|
||||
@Test
|
||||
void removeTotpKey() {
|
||||
final byte retainedKeyId = 1;
|
||||
final byte removedKeyId = 2;
|
||||
|
||||
final Map<Byte, AnnotatedTotpKey> initialKeys = Map.of(
|
||||
retainedKeyId, generateRandomAnnotatedTotpKey(),
|
||||
removedKeyId, generateRandomAnnotatedTotpKey());
|
||||
|
||||
@@ -1287,6 +1296,14 @@ class AccountsGrpcServiceTest extends SimpleBaseGrpcTest<AccountsGrpcService, Ac
|
||||
verify(account).setTotpKeys(Map.of(retainedKeyId, initialKeys.get(retainedKeyId)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void removeTotpKeyIdOutOfRange() {
|
||||
GrpcTestUtils.assertStatusInvalidArgument(
|
||||
() -> authenticatedServiceStub().removeTotpKey(RemoveTotpKeyRequest.newBuilder()
|
||||
.setKeyId(Account.MAX_TOTP_KEY_ID + 1)
|
||||
.build()));
|
||||
}
|
||||
|
||||
private static AnnotatedTotpKey generateRandomAnnotatedTotpKey() {
|
||||
return new AnnotatedTotpKey(new TotpKey(AccountsManager.TOTP_PARAMETERS, TestRandomUtil.nextBytes(32)),
|
||||
TestRandomUtil.nextBytes(TOTP_KEY_METADATA_SIZE));
|
||||
|
||||
+87
-4
@@ -8,6 +8,7 @@ package org.whispersystems.textsecuregcm.grpc;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.AdditionalMatchers.aryEq;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
@@ -41,6 +42,7 @@ import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
@@ -57,6 +59,7 @@ import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Mock;
|
||||
import org.signal.chat.common.IdentityType;
|
||||
import org.signal.chat.common.ServiceIdentifier;
|
||||
import org.signal.chat.profile.AccountInfo;
|
||||
import org.signal.chat.profile.GetAvatarCredentialsRequest;
|
||||
import org.signal.chat.profile.GetAvatarCredentialsResponse;
|
||||
import org.signal.chat.profile.GetProfileRequest;
|
||||
@@ -64,12 +67,13 @@ import org.signal.chat.profile.GetProfileResponse;
|
||||
import org.signal.chat.profile.LegacyProfileResult;
|
||||
import org.signal.chat.profile.ProfileGrpc;
|
||||
import org.signal.chat.profile.ProfileResult;
|
||||
import org.signal.chat.profile.AccountInfo;
|
||||
import org.signal.chat.profile.SetProfileRequest;
|
||||
import org.signal.chat.profile.SetProfileResponse;
|
||||
import org.signal.chat.profile.SetProfileResult;
|
||||
import org.signal.chat.profile.SetProfileV1Request;
|
||||
import org.signal.chat.profile.SetProfileV1Request.AvatarChange;
|
||||
import org.signal.chat.profile.SetV1AvatarRequest;
|
||||
import org.signal.chat.profile.SetV1AvatarResponse;
|
||||
import org.signal.chat.profile.test.PlaintextProfileData;
|
||||
import org.signal.libsignal.protocol.IdentityKey;
|
||||
import org.signal.libsignal.protocol.ServiceId;
|
||||
@@ -195,8 +199,6 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
|
||||
when(accountsManager.getByAccountIdentifier(AUTHENTICATED_ACI)).thenReturn(Optional.of(account));
|
||||
when(accountsManager.getByServiceIdentifier(new AciServiceIdentifier(AUTHENTICATED_ACI))).thenReturn(Optional.of(account));
|
||||
|
||||
when(profilesManager.getV1(any(), any())).thenReturn(Optional.of(profile));
|
||||
|
||||
when(dynamicConfigurationManager.getConfiguration()).thenReturn(dynamicConfiguration);
|
||||
when(dynamicConfiguration.getPaymentsConfiguration()).thenReturn(dynamicPaymentsConfiguration);
|
||||
when(dynamicPaymentsConfiguration.disallowedPrefixes()).thenReturn(Collections.emptyList());
|
||||
@@ -376,6 +378,23 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
|
||||
assertTrue(response.hasProfilesV2CapabilityRequired());
|
||||
}
|
||||
|
||||
@Test
|
||||
void setProfileUnauthenticated() {
|
||||
|
||||
when(accountsManager.getByAccountIdentifier(AUTHENTICATED_ACI)).thenReturn(Optional.empty());
|
||||
|
||||
final SetProfileRequest request = SetProfileRequest.newBuilder()
|
||||
.setVersion(ByteString.copyFrom(VERSION))
|
||||
.setData(ByteString.copyFrom(VALID_DATA))
|
||||
.setExpectedCurrentDataHash(ByteString.copyFrom(TestRandomUtil.nextBytes(32)))
|
||||
.setV1Request(V1_REQUEST)
|
||||
.build();
|
||||
|
||||
final StatusRuntimeException statusRuntimeException = assertStatusException(Status.UNAUTHENTICATED,
|
||||
() -> authenticatedServiceStub().setProfile(request));
|
||||
assertEquals("invalid credentials", statusRuntimeException.getStatus().getDescription());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void setProfileUpload(final AvatarChange avatarChange, final boolean hasPreviousProfile,
|
||||
@@ -862,7 +881,7 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
|
||||
|
||||
final StatusRuntimeException statusRuntimeException = assertStatusException(Status.UNAUTHENTICATED,
|
||||
() -> authenticatedServiceStub().getAvatarCredentials(GetAvatarCredentialsRequest.getDefaultInstance()));
|
||||
assertEquals("account not found", statusRuntimeException.getStatus().getDescription());
|
||||
assertEquals("invalid credentials", statusRuntimeException.getStatus().getDescription());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -902,6 +921,70 @@ public class ProfileGrpcServiceTest extends SimpleBaseGrpcTest<ProfileGrpcServic
|
||||
assertEquals("invalid credential request", statusRuntimeException.getStatus().getDescription());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {true, false})
|
||||
void setV1Avatar(boolean hasAvatar) {
|
||||
final String version = HexFormat.of().formatHex(TestRandomUtil.nextBytes(32));
|
||||
|
||||
final VersionedProfileV1 profile = new VersionedProfileV1(version,
|
||||
TestRandomUtil.nextBytes(81),
|
||||
hasAvatar ? "profiles/old-avatar" : null,
|
||||
null,
|
||||
TestRandomUtil.nextBytes(156),
|
||||
null,
|
||||
TestRandomUtil.nextBytes(582),
|
||||
TestRandomUtil.nextBytes(32)
|
||||
);
|
||||
|
||||
when(profilesManager.getV1(AUTHENTICATED_ACI, profile.version()))
|
||||
.thenReturn(Optional.of(profile));
|
||||
|
||||
final SetV1AvatarResponse response = authenticatedServiceStub().setV1Avatar(
|
||||
SetV1AvatarRequest.newBuilder()
|
||||
.setVersion(version)
|
||||
.build());
|
||||
|
||||
verify(profilesManager).setV1Avatar(eq(AUTHENTICATED_ACI), eq(version), anyString(), aryEq(profile.commitment()));
|
||||
|
||||
assertTrue(response.hasForm());
|
||||
assertTrue(response.getForm().getKey().startsWith("profiles/"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void setV1AvatarNewVersion() throws Exception {
|
||||
final ProfileKey profileKey = new ProfileKey(new byte[32]);
|
||||
final byte[] commitment = profileKey.getCommitment(new ServiceId.Aci(AUTHENTICATED_ACI)).serialize();
|
||||
final String version = profileKey.getProfileKeyVersion(new ServiceId.Aci(AUTHENTICATED_ACI)).serialize();
|
||||
|
||||
when(profilesManager.getV1(eq(AUTHENTICATED_ACI), anyString()))
|
||||
.thenReturn(Optional.empty());
|
||||
|
||||
final SetV1AvatarResponse response = authenticatedServiceStub().setV1Avatar(
|
||||
SetV1AvatarRequest.newBuilder()
|
||||
.setVersion(version)
|
||||
.setCommitment(ByteString.copyFrom(commitment))
|
||||
.build());
|
||||
|
||||
verify(profilesManager).setV1Avatar(eq(AUTHENTICATED_ACI), eq(version), anyString(), aryEq(commitment));
|
||||
|
||||
assertTrue(response.hasForm());
|
||||
assertTrue(response.getForm().getKey().startsWith("profiles/"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void setV1AvatarNewVersionMissingCommitment() {
|
||||
when(profilesManager.getV1(eq(AUTHENTICATED_ACI), anyString()))
|
||||
.thenReturn(Optional.empty());
|
||||
|
||||
final StatusRuntimeException statusRuntimeException = assertStatusInvalidArgument(
|
||||
() -> authenticatedServiceStub().setV1Avatar(
|
||||
SetV1AvatarRequest.newBuilder().setVersion(HexFormat.of().formatHex(TestRandomUtil.nextBytes(32)))
|
||||
.build()));
|
||||
|
||||
assertNotNull(statusRuntimeException.getStatus().getDescription());
|
||||
assertTrue(statusRuntimeException.getStatus().getDescription().toLowerCase(Locale.ROOT).contains("commitment"));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(ints = {0, 1, 16, 32})
|
||||
void testProfileSerialized(int aboutEmojiLength) {
|
||||
|
||||
@@ -27,12 +27,16 @@ import java.util.Base64;
|
||||
import java.util.Collections;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.whispersystems.textsecuregcm.tests.util.AccountsHelper;
|
||||
import org.whispersystems.textsecuregcm.util.SystemMapper;
|
||||
import org.whispersystems.textsecuregcm.util.TestClock;
|
||||
@@ -282,21 +286,51 @@ class AccountTest {
|
||||
assertThat(deserializedBase64Cpv.getCurrentProfileVersion()).isPresent().hasValue(version);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getNextTotpKeyId() {
|
||||
assertEquals(0, new Account().getNextTotpKeyId());
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void getNextTotpKeyId(final List<Byte> existingKeyIds, final byte expectedNextKeyId) {
|
||||
final Account account = new Account();
|
||||
account.setTotpKeys(existingKeyIds.stream()
|
||||
.collect(Collectors.toMap(keyId -> keyId, _ -> new AnnotatedTotpKey(new TotpKey(
|
||||
new TotpParameters(
|
||||
TimeBasedOneTimePasswordGenerator.TOTP_ALGORITHM_HMAC_SHA256,
|
||||
HmacOneTimePasswordGenerator.DEFAULT_PASSWORD_LENGTH,
|
||||
TimeBasedOneTimePasswordGenerator.DEFAULT_TIME_STEP),
|
||||
TestRandomUtil.nextBytes(16)),
|
||||
TestRandomUtil.nextBytes(16)))));
|
||||
|
||||
final AnnotatedTotpKey totpKey = new AnnotatedTotpKey(new TotpKey(
|
||||
new TotpParameters(
|
||||
TimeBasedOneTimePasswordGenerator.TOTP_ALGORITHM_HMAC_SHA256,
|
||||
HmacOneTimePasswordGenerator.DEFAULT_PASSWORD_LENGTH,
|
||||
TimeBasedOneTimePasswordGenerator.DEFAULT_TIME_STEP),
|
||||
TestRandomUtil.nextBytes(16)),
|
||||
TestRandomUtil.nextBytes(16));
|
||||
assertEquals(expectedNextKeyId, account.getNextTotpKeyId());
|
||||
}
|
||||
|
||||
final Account accountWithTotpKey = new Account();
|
||||
accountWithTotpKey.setTotpKeys(Map.of(0, totpKey));
|
||||
private static List<Arguments> getNextTotpKeyId() {
|
||||
final byte unclaimedId = 17;
|
||||
|
||||
assertEquals(1, accountWithTotpKey.getNextTotpKeyId());
|
||||
final List<Byte> mostIdsTaken = IntStream.range(0, Account.MAX_TOTP_KEY_ID)
|
||||
.filter(i -> i != unclaimedId)
|
||||
.mapToObj(i -> (byte) i)
|
||||
.toList();
|
||||
|
||||
return List.of(
|
||||
Arguments.argumentSet("No existing keys", List.of(), (byte) 0),
|
||||
Arguments.argumentSet("Single existing key", List.of((byte) 0), (byte) 1),
|
||||
Arguments.argumentSet("Multiple existing keys", List.of((byte) 0, (byte) 1), (byte) 2),
|
||||
Arguments.argumentSet("ID wraparound", List.of((byte) 0, (byte) 255), (byte) 1),
|
||||
Arguments.argumentSet("Most IDs taken", mostIdsTaken, unclaimedId)
|
||||
);
|
||||
}
|
||||
|
||||
void getNextTotpKeyNoneAvailable() {
|
||||
final Account account = new Account();
|
||||
account.setTotpKeys(IntStream.range(0, Account.MAX_TOTP_KEY_ID)
|
||||
.mapToObj(i -> (byte) i)
|
||||
.collect(Collectors.toMap(keyId -> keyId, _ -> new AnnotatedTotpKey(new TotpKey(
|
||||
new TotpParameters(
|
||||
TimeBasedOneTimePasswordGenerator.TOTP_ALGORITHM_HMAC_SHA256,
|
||||
HmacOneTimePasswordGenerator.DEFAULT_PASSWORD_LENGTH,
|
||||
TimeBasedOneTimePasswordGenerator.DEFAULT_TIME_STEP),
|
||||
TestRandomUtil.nextBytes(16)),
|
||||
TestRandomUtil.nextBytes(16)))));
|
||||
|
||||
assertThrows(IllegalStateException.class, account::getNextTotpKeyId);
|
||||
}
|
||||
}
|
||||
+11
-11
@@ -1957,7 +1957,7 @@ class AccountsManagerTest {
|
||||
|
||||
when(account.getTotpKeys()).thenReturn(IntStream.range(0, AccountsManager.MAX_TOTP_KEYS)
|
||||
.boxed()
|
||||
.collect(Collectors.toMap(keyId -> keyId, _ -> new AnnotatedTotpKey(
|
||||
.collect(Collectors.toMap(Integer::byteValue, _ -> new AnnotatedTotpKey(
|
||||
new TotpKey(AccountsManager.TOTP_PARAMETERS, TestRandomUtil.nextBytes(16)),
|
||||
TestRandomUtil.nextBytes(16)))));
|
||||
|
||||
@@ -1979,7 +1979,7 @@ class AccountsManagerTest {
|
||||
.thenReturn(Optional.of(account));
|
||||
|
||||
final TotpKey pendingTotpKey = accountsManager.generatePendingTotpKey(accountIdentifier);
|
||||
final int nextTotpKeyId = ThreadLocalRandom.current().nextInt();
|
||||
final byte nextTotpKeyId = (byte) ThreadLocalRandom.current().nextInt();
|
||||
|
||||
when(account.getPendingTotpKey()).thenReturn(Optional.of(pendingTotpKey));
|
||||
when(account.getNextTotpKeyId()).thenReturn(nextTotpKeyId);
|
||||
@@ -2019,11 +2019,11 @@ class AccountsManagerTest {
|
||||
TestRandomUtil.nextBytes(16));
|
||||
}
|
||||
|
||||
final int keyId = 17;
|
||||
final byte keyId = 17;
|
||||
|
||||
when(account.getPendingTotpKey()).thenReturn(Optional.empty());
|
||||
when(account.getTotpKeys()).thenReturn(Map.of(
|
||||
keyId - 1, confirmedTotpKey,
|
||||
(byte) (keyId - 1), confirmedTotpKey,
|
||||
keyId, confirmedTotpKey));
|
||||
|
||||
final TimeBasedOneTimePasswordGenerator totpGenerator =
|
||||
@@ -2079,7 +2079,7 @@ class AccountsManagerTest {
|
||||
.thenReturn(Optional.of(account));
|
||||
|
||||
final TotpKey pendingTotpKey = accountsManager.generatePendingTotpKey(accountIdentifier);
|
||||
final int nextTotpKeyId = ThreadLocalRandom.current().nextInt();
|
||||
final byte nextTotpKeyId = (byte) ThreadLocalRandom.current().nextInt();
|
||||
|
||||
when(account.getPendingTotpKey()).thenReturn(Optional.of(pendingTotpKey));
|
||||
when(account.getNextTotpKeyId()).thenReturn(nextTotpKeyId);
|
||||
@@ -2103,7 +2103,7 @@ class AccountsManagerTest {
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void verifyTotp(final Map<Integer, AnnotatedTotpKey> totpKeys,
|
||||
void verifyTotp(final Map<Byte, AnnotatedTotpKey> totpKeys,
|
||||
final Instant timestamp,
|
||||
@Nullable final Integer oneTimePassword,
|
||||
final boolean expectVerified) {
|
||||
@@ -2145,16 +2145,16 @@ class AccountsManagerTest {
|
||||
Collections.emptyMap(), timestamp, 123456, false),
|
||||
|
||||
Arguments.argumentSet("Has key, correct password provided",
|
||||
Map.of(1, totpKey), timestamp, totpGenerator.generateOneTimePassword(totpKey, timestamp), true),
|
||||
Map.of((byte) 1, totpKey), timestamp, totpGenerator.generateOneTimePassword(totpKey, timestamp), true),
|
||||
|
||||
Arguments.argumentSet("Has key, incorrect password provided",
|
||||
Map.of(1, totpKey), timestamp, totpGenerator.generateOneTimePassword(totpKey, timestamp) + 1, false),
|
||||
Map.of((byte) 1, totpKey), timestamp, totpGenerator.generateOneTimePassword(totpKey, timestamp) + 1, false),
|
||||
|
||||
Arguments.argumentSet("Has key, no password provided",
|
||||
Map.of(1, totpKey), timestamp, null, false),
|
||||
Map.of((byte) 1, totpKey), timestamp, null, false),
|
||||
|
||||
Arguments.argumentSet("Has multiple keys, correct password provided for one key",
|
||||
Map.of(1, totpKey, 2, secondTotpKey), timestamp, totpGenerator.generateOneTimePassword(totpKey, timestamp), true)
|
||||
Map.of((byte) 1, totpKey, (byte) 2, secondTotpKey), timestamp, totpGenerator.generateOneTimePassword(totpKey, timestamp), true)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2176,7 +2176,7 @@ class AccountsManagerTest {
|
||||
AccountsManager.TOTP_PARAMETERS.algorithm());
|
||||
|
||||
final Account account = mock(Account.class);
|
||||
when(account.getTotpKeys()).thenReturn(Map.of(1, totpKey));
|
||||
when(account.getTotpKeys()).thenReturn(Map.of((byte) 1, totpKey));
|
||||
|
||||
final Instant beginningOfTotpWindow =
|
||||
Instant.ofEpochMilli((Instant.now().toEpochMilli() / AccountsManager.TOTP_PARAMETERS.timeStep().toMillis()) *
|
||||
|
||||
+27
@@ -556,6 +556,33 @@ public class ProfilesManagerTest {
|
||||
verifyNoInteractions(s3Client);
|
||||
}
|
||||
|
||||
@Test
|
||||
void setV1Avatar() {
|
||||
final UUID uuid = UUID.randomUUID();
|
||||
final String version = HexFormat.of().formatHex(TestRandomUtil.nextBytes(32));
|
||||
final String avatar = "avatar";
|
||||
final byte[] commitment = TestRandomUtil.nextBytes(97);
|
||||
|
||||
final VersionedProfileV1 profile = mock(VersionedProfileV1.class);
|
||||
when(profile.version()).thenReturn(version);
|
||||
when(profile.commitment()).thenReturn(commitment);
|
||||
when(profile.avatar()).thenReturn(avatar);
|
||||
|
||||
when(profilesV1.setAvatar(any(UUID.class), anyString(), anyString(), any(byte[].class)))
|
||||
.thenReturn(profile);
|
||||
|
||||
profilesManager.setV1Avatar(uuid, version, avatar, commitment);
|
||||
|
||||
verify(commands).del(aryEq(ProfilesManager.getCacheKeyV1(uuid)));
|
||||
verify(profilesV1).setAvatar(uuid, version, avatar, commitment);
|
||||
verify(setLuaScript).executeBinary(
|
||||
argThat(keys ->
|
||||
Arrays.equals(keys.get(0), ProfilesManager.getCacheKeyV1(uuid))),
|
||||
argThat(args ->
|
||||
Arrays.equals(args.get(0), version.getBytes())));
|
||||
verifyNoMoreInteractions(setLuaScript);
|
||||
}
|
||||
|
||||
@Nested
|
||||
class Redis {
|
||||
|
||||
|
||||
@@ -6,7 +6,9 @@
|
||||
package org.whispersystems.textsecuregcm.storage;
|
||||
|
||||
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -384,4 +386,41 @@ public class ProfilesTest {
|
||||
Map.of(":commitment", AttributeValues.fromByteArray(commitment)))
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void setAvatarInsert() {
|
||||
final String avatar = "avatar";
|
||||
final String version = "version";
|
||||
final byte[] commitment = TestRandomUtil.nextBytes(97);
|
||||
|
||||
final VersionedProfileV1 profile = profiles.setAvatar(UUID.randomUUID(), version, avatar,
|
||||
commitment);
|
||||
|
||||
assertEquals(version, profile.version());
|
||||
assertEquals(avatar, profile.avatar());
|
||||
assertArrayEquals(commitment, profile.commitment());
|
||||
assertNull(profile.name());
|
||||
}
|
||||
|
||||
@Test
|
||||
void setAvatarUpdate() {
|
||||
final String version = "version";
|
||||
final byte[] commitment = TestRandomUtil.nextBytes(97);
|
||||
final byte[] name = TestRandomUtil.nextBytes(81);
|
||||
final UUID uuid = UUID.randomUUID();
|
||||
{
|
||||
final VersionedProfileV1 initialProfile = new VersionedProfileV1(version, name, null, null, null, null, null,
|
||||
commitment);
|
||||
|
||||
profiles.set(uuid, initialProfile);
|
||||
}
|
||||
final String avatar = "avatar";
|
||||
|
||||
final VersionedProfileV1 profile = profiles.setAvatar(uuid, version, avatar, commitment);
|
||||
|
||||
assertEquals(version, profile.version());
|
||||
assertEquals(avatar, profile.avatar());
|
||||
assertArrayEquals(commitment, profile.commitment());
|
||||
assertArrayEquals(name, profile.name());
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -45,7 +45,7 @@ class ClearExpiredFoundationDbMessagesCommandTest {
|
||||
|
||||
super(clock);
|
||||
|
||||
this.commandDependencies = new CommandDependencies(null, null, null, null, messagesManager, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null);
|
||||
this.commandDependencies = new CommandDependencies(null, null, null, null, messagesManager, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null);
|
||||
this.dryRun = dryRun;
|
||||
}
|
||||
|
||||
|
||||
+159
@@ -0,0 +1,159 @@
|
||||
/*
|
||||
* Copyright 2026 Signal Messenger, LLC
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
package org.whispersystems.textsecuregcm.workers;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.apple.foundationdb.Database;
|
||||
import com.apple.foundationdb.KeyValue;
|
||||
import com.apple.foundationdb.Range;
|
||||
import com.apple.foundationdb.async.AsyncUtil;
|
||||
import com.apple.foundationdb.subspace.Subspace;
|
||||
import com.apple.foundationdb.tuple.Tuple;
|
||||
import com.google.protobuf.ByteString;
|
||||
import java.security.SecureRandom;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.stream.IntStream;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.whispersystems.textsecuregcm.entities.MessageProtos;
|
||||
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
|
||||
import org.whispersystems.textsecuregcm.storage.Account;
|
||||
import org.whispersystems.textsecuregcm.storage.AccountsManager;
|
||||
import org.whispersystems.textsecuregcm.storage.Device;
|
||||
import org.whispersystems.textsecuregcm.storage.FoundationDbClusterExtension;
|
||||
import org.whispersystems.textsecuregcm.storage.foundationdb.FoundationDbMessageStore;
|
||||
import org.whispersystems.textsecuregcm.storage.foundationdb.VersionstampUUIDCipher;
|
||||
import org.whispersystems.textsecuregcm.util.TestClock;
|
||||
|
||||
class ClearOrphanedFoundationDbQueuesCommandTest {
|
||||
|
||||
@RegisterExtension
|
||||
static FoundationDbClusterExtension FOUNDATION_DB_EXTENSION = new FoundationDbClusterExtension(2);
|
||||
|
||||
private static final TestClock CLOCK = TestClock.pinned(Instant.ofEpochSecond(500));
|
||||
|
||||
private FoundationDbMessageStore foundationDbMessageStore;
|
||||
|
||||
@BeforeEach
|
||||
void setup() {
|
||||
final byte[] versionstampCipherKey = new byte[16];
|
||||
new SecureRandom().nextBytes(versionstampCipherKey);
|
||||
|
||||
final List<Database> databases = Arrays.asList(FOUNDATION_DB_EXTENSION.getDatabases());
|
||||
|
||||
foundationDbMessageStore = new FoundationDbMessageStore(
|
||||
Map.of(0, databases),
|
||||
0,
|
||||
new VersionstampUUIDCipher(0, versionstampCipherKey),
|
||||
Executors.newSingleThreadScheduledExecutor(),
|
||||
CLOCK,
|
||||
Duration.ofSeconds(5),
|
||||
10);
|
||||
}
|
||||
|
||||
@Test
|
||||
void clearOrphanedQueues() {
|
||||
// Create a few accounts and insert messages into their queues
|
||||
final List<AciServiceIdentifier> accounts = new ArrayList<>();
|
||||
for (int i = 0; i < 16; i++) {
|
||||
final AciServiceIdentifier aci = new AciServiceIdentifier(UUID.randomUUID());
|
||||
foundationDbMessageStore.insert(aci, Map.of(Device.PRIMARY_ID, generateRandomMessage())).join();
|
||||
foundationDbMessageStore.insert(aci, Map.of(Device.PRIMARY_ID, generateRandomMessage())).join();
|
||||
accounts.add(aci);
|
||||
}
|
||||
|
||||
// Assume that a subset of accounts are deleted
|
||||
final Set<AciServiceIdentifier> deletedAccounts = new HashSet<>(accounts.subList(0, 3));
|
||||
|
||||
final AccountsManager accountsManager = mock(AccountsManager.class);
|
||||
when(accountsManager.getByAccountIdentifierAsync(any()))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.of(mock(Account.class))));
|
||||
for (final AciServiceIdentifier deletedAccount : deletedAccounts) {
|
||||
when(accountsManager.getByAccountIdentifierAsync(deletedAccount.uuid()))
|
||||
.thenReturn(CompletableFuture.completedFuture(Optional.empty()));
|
||||
}
|
||||
|
||||
final ClearOrphanedFoundationDbQueuesCommand command = new ClearOrphanedFoundationDbQueuesCommand();
|
||||
command.clearOrphanedQueues(
|
||||
Arrays.stream(FOUNDATION_DB_EXTENSION.getDatabases()), accountsManager, 16, false, 8,
|
||||
3,
|
||||
Duration.ofSeconds(2),
|
||||
2);
|
||||
|
||||
for (final AciServiceIdentifier aci : accounts) {
|
||||
assertEquals(!deletedAccounts.contains(aci), queueExists(FoundationDbMessageStore.getAccountSubspace(aci)));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAcisInShard() {
|
||||
// create accounts in a test subspace that doesn't conflict with the main messages subspace
|
||||
final Subspace testMessagesSubspace = new Subspace(
|
||||
Tuple.from("MT"));
|
||||
final ClearOrphanedFoundationDbQueuesCommand command = new ClearOrphanedFoundationDbQueuesCommand(testMessagesSubspace);
|
||||
final List<AciServiceIdentifier> acis = IntStream.range(0, 128)
|
||||
.mapToObj(_ -> new AciServiceIdentifier(UUID.randomUUID()))
|
||||
.toList();
|
||||
final Database database = FOUNDATION_DB_EXTENSION.getDatabases()[0];
|
||||
database.run(transaction -> {
|
||||
acis.forEach(aci -> {
|
||||
transaction.set(FoundationDbMessageStore.getAccountSubspace(testMessagesSubspace, aci).pack(Tuple.from("foo")), new byte[]{42});
|
||||
transaction.set(FoundationDbMessageStore.getAccountSubspace(testMessagesSubspace, aci).pack(Tuple.from("bar")), new byte[]{43});
|
||||
});
|
||||
return null;
|
||||
});
|
||||
final List<AciServiceIdentifier> fetchedAcis = command.getAcisInShard(database, 2, 3, Duration.ofSeconds(2), 5)
|
||||
.collectList()
|
||||
.block();
|
||||
assertNotNull(fetchedAcis);
|
||||
assertEquals(new HashSet<>(acis), new HashSet<>(fetchedAcis));
|
||||
}
|
||||
|
||||
/// Returns whether any key exists under the account's prefix in any shard
|
||||
private boolean queueExists(final Subspace accountSpace) {
|
||||
final Range accountRange = accountSpace.range();
|
||||
|
||||
for (final Database database : FOUNDATION_DB_EXTENSION.getDatabases()) {
|
||||
final List<KeyValue> keyValues = database.readAsync(transaction ->
|
||||
AsyncUtil.collect(transaction.getRange(accountRange, 1))).join();
|
||||
|
||||
if (!keyValues.isEmpty()) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private static MessageProtos.Envelope generateRandomMessage() {
|
||||
final byte[] content = new byte[16];
|
||||
new SecureRandom().nextBytes(content);
|
||||
|
||||
return MessageProtos.Envelope.newBuilder()
|
||||
.setClientTimestamp(CLOCK.millis())
|
||||
.setServerTimestamp(CLOCK.millis())
|
||||
.setContent(ByteString.copyFrom(content))
|
||||
.setEphemeral(false)
|
||||
.build();
|
||||
}
|
||||
}
|
||||
+1
@@ -87,6 +87,7 @@ class FinishPushNotificationExperimentCommandTest {
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null);
|
||||
|
||||
//noinspection unchecked
|
||||
|
||||
+1
@@ -68,6 +68,7 @@ class NotifyIdleDevicesCommandTest {
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null);
|
||||
|
||||
this.idleDeviceNotificationScheduler = idleDeviceNotificationScheduler;
|
||||
|
||||
+2
-1
@@ -54,7 +54,8 @@ class RegenerateSecondaryDynamoDbTableDataCommandTest {
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
dynamoDbRecoveryManager);
|
||||
dynamoDbRecoveryManager,
|
||||
null);
|
||||
|
||||
namespace = new Namespace(Map.of(
|
||||
RegenerateSecondaryDynamoDbTableDataCommand.DRY_RUN_ARGUMENT, dryRun,
|
||||
|
||||
+1
@@ -76,6 +76,7 @@ class StartPushNotificationExperimentCommandTest {
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null);
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -40,7 +40,7 @@ public class TrimOversizedFoundationDbMessageQueuesCommandTest {
|
||||
final boolean dryRun) {
|
||||
|
||||
super();
|
||||
this.commandDependencies = new CommandDependencies(null, null, null, null, messagesManager, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null);
|
||||
this.commandDependencies = new CommandDependencies(null, null, null, null, messagesManager, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null);
|
||||
this.dryRun = dryRun;
|
||||
}
|
||||
|
||||
|
||||
+1
-1
Submodule spam-filter updated: 098a2bf807...93660f2a68.
Reference in new issue
Block a user