Compare commits

..
41 Commits
Author SHA1 Message Date
Chris Eager d338ba5152 Convert some KeysController methods return CompletableFutures 2023-08-24 11:59:28 -05:00
Chris Eager f181397664 Add test for round-trip AccountsManager JSON serialization 2023-08-24 11:18:01 -05:00
Chris Eager 708f23a2ee Remove deprecated identity key and signed pre-key methods 2023-08-24 11:18:01 -05:00
Chris Eager 2d1a979eba Update libphonenumber to 8.13.19 2023-08-24 11:07:18 -05:00
Chris Eager ee0be92967 Update to the latest version of the spam filter 2023-08-24 11:06:30 -05:00
Chris Eager 7536b75508 Remove unused test fixtures 2023-08-24 11:06:11 -05:00
Jonathan Klabunde Tomer 7237ae6c54 check that pq last-resort prekeys, if submitted, match device list 2023-08-24 09:04:29 -07:00
Sergey Skrobotov ca05753a3e adding 400 response documentation to the API call 2023-08-23 13:20:07 -07:00
Chris Eager 9ca8503eac Downgrade to stripe-java 22.30.0 2023-08-22 16:31:46 -05:00
Jon Chambers 754f71ce00 Add a gRPC service for working with devices 2023-08-22 16:31:02 -05:00
Jon Chambers 619b05e56c Add utility a method for requiring authentication with the account's primary device 2023-08-22 16:31:02 -05:00
Jon Chambers 8b13826949 Convert DeviceInfo and DeviceInfoList to a record 2023-08-22 16:31:02 -05:00
Jon Chambers a96ee57c7e Defer asynchronous actions when deriving Mono instances from futures 2023-08-22 16:28:02 -05:00
Jon Chambers ff1ef90a6d Defer actions taken after rate limit checks 2023-08-22 16:28:02 -05:00
Chris Eager 22905fa8ee Downgrade logstash-logback-encoder to 7.3 2023-08-21 12:44:02 -05:00
Chris Eager 9e218ddd1c Update to the latest version of the spam filter 2023-08-21 11:42:11 -05:00
Chris Eager 6f0462622b Update maven and various plugins 2023-08-21 11:34:08 -05:00
Chris Eager 2f17161163 Update various dependencies 2023-08-21 11:34:08 -05:00
Ravi Khadiwala 17d48b95ac keep lettuce metrics; strip remote tags 2023-08-18 16:28:19 -05:00
Chris Eager eeea97e2fe Return a single OAuth2 credentials JSON 2023-08-18 16:16:31 -05:00
Chris Eager 360e101660 Update to the latest version of the spam filter 2023-08-18 16:13:30 -05:00
Jon Chambers 3501a944a3 Update to the latest version of the spam filter 2023-08-18 11:49:11 -04:00
Jon Chambers 76305190a2 Temporarily restore explicit service/version/environment/host tags 2023-08-17 18:30:59 -04:00
Jon Chambers ab83990170 Send latency metrics as distributions 2023-08-17 17:10:16 -04:00
Jon Chambers 8103a22026 Submit Micrometer metrics via dogstatsd instead of the Datadog API 2023-08-17 17:01:36 -04:00
Jonathan Klabunde Tomer 1f8e4713ef limit concurrency of async DynamoDB ops 2023-08-17 13:56:09 -07:00
Katherine Yen ff9fe2c1be Remove record equality test 2023-08-17 13:55:27 -07:00
Jon Chambers 7f37c8ee5e Retire now-unused HTTP transport configuration for Datadog metric reporter 2023-08-17 16:53:53 -04:00
Jon Chambers ed0a723fef Include underlying exceptions when logging failures to write exit files 2023-08-17 12:32:45 -04:00
Jon Chambers 5c31ef43c9 Send an HTTP/440 response instead of an HTTP/502 if an upstream provider rejects a "send verification code" request 2023-08-17 12:15:00 -04:00
Katherine Yen 43fd8518c0 Add missing java.util.Base64 import to ProfileController 2023-08-16 14:02:53 -07:00
Katherine Yen 19a08f01e8 Write certain profile data as bytes instead of strings to dynamo and represent those fields as byte arrays on VersionedProfile 2023-08-16 13:45:16 -07:00
Jonathan Klabunde Tomer 33498cf147 Update to the latest version of the spam filter 2023-08-16 10:19:00 -07:00
Jon Chambers beeb85cf8d Update to the latest version of the spam filter 2023-08-15 14:21:00 -04:00
Jon Chambers ccd860207b Make MessagesManager#clear asynchronous 2023-08-15 14:08:16 -04:00
Jon Chambers 2c835b5c51 Make message deletion from DynamoDB asynchronous 2023-08-15 14:08:16 -04:00
Jon Chambers 5caa951c61 Make MessagesCache#clear methods asynchronous 2023-08-15 14:08:16 -04:00
Jon Chambers 4d8c4d6693 Also delete APNs VOIP tokens when clearing APNs tokens 2023-08-15 14:08:00 -04:00
Jon Chambers a9d0574ea8 Remove most @Timed annotations 2023-08-15 14:06:31 -04:00
Jonathan Klabunde Tomer 3954494eae Update to the latest version of the spam filter 2023-08-11 15:11:58 -07:00
Ravi Khadiwala ed6a2c55eb adjust lettuce metric denial for post-transform name 2023-08-11 09:43:41 -05:00
99 changed files with 1871 additions and 1111 deletions

No files matched your search

+1 -1
View File
@@ -4,6 +4,6 @@
<extension>
<groupId>fr.brouillard.oss</groupId>
<artifactId>jgitver-maven-plugin</artifactId>
<version>1.7.1</version>
<version>1.9.0</version>
</extension>
</extensions>
+2 -2
View File
@@ -14,5 +14,5 @@
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.6/apache-maven-3.8.6-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.1/maven-wrapper-3.1.1.jar
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.4/apache-maven-3.9.4-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar
+1 -1
View File
@@ -28,7 +28,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M7</version>
<version>3.1.2</version>
<configuration>
<excludes>
<exclude>**</exclude>
+19 -33
View File
@@ -38,38 +38,37 @@
</modules>
<properties>
<aws.sdk2.version>2.20.118</aws.sdk2.version>
<braintree.version>3.19.0</braintree.version>
<aws.sdk2.version>2.20.130</aws.sdk2.version>
<braintree.version>3.25.0</braintree.version>
<commons-csv.version>1.9.0</commons-csv.version>
<commons-io.version>2.9.0</commons-io.version>
<commons-io.version>2.13.0</commons-io.version>
<dropwizard.version>2.1.7</dropwizard.version>
<dropwizard-metrics-datadog.version>1.1.13</dropwizard-metrics-datadog.version>
<google-cloud-libraries.version>26.21.0</google-cloud-libraries.version>
<google-cloud-libraries.version>26.22.0</google-cloud-libraries.version>
<grpc.version>1.56.1</grpc.version> <!-- should be kept in sync with the value from Google libraries-bom -->
<gson.version>2.9.0</gson.version>
<gson.version>2.10.1</gson.version>
<jackson.version>2.13.5</jackson.version>
<jaxb.version>2.3.1</jaxb.version>
<kotlin.version>1.8.0</kotlin.version>
<kotlinx-serialization.version>1.4.1</kotlinx-serialization.version>
<lettuce.version>6.2.4.RELEASE</lettuce.version>
<libphonenumber.version>8.12.54</libphonenumber.version>
<logstash.logback.version>7.2</logstash.logback.version>
<kotlin.version>1.9.0</kotlin.version>
<kotlinx-serialization.version>1.5.1</kotlinx-serialization.version>
<lettuce.version>6.2.6.RELEASE</lettuce.version>
<libphonenumber.version>8.13.19</libphonenumber.version>
<logstash.logback.version>7.3</logstash.logback.version>
<luajava.version>3.4.0</luajava.version>
<micrometer.version>1.10.3</micrometer.version>
<mockito.version>4.11.0</mockito.version>
<micrometer.version>1.10.10</micrometer.version>
<netty.version>4.1.96.Final</netty.version>
<opentest4j.version>1.2.0</opentest4j.version>
<opentest4j.version>1.3.0</opentest4j.version>
<protobuf.version>3.23.2</protobuf.version> <!-- should be kept in sync with the value from Google libraries-bom -->
<pushy.version>0.15.2</pushy.version>
<reactive.grpc.version>1.2.4</reactive.grpc.version>
<resilience4j.version>1.7.0</resilience4j.version>
<semver4j.version>3.1.0</semver4j.version>
<slf4j.version>1.7.30</slf4j.version>
<stripe.version>21.2.0</stripe.version>
<slf4j.version>1.7.36</slf4j.version>
<stripe.version>22.30.0</stripe.version>
<vavr.version>0.10.4</vavr.version>
<!-- 17.0.7_7-jre-jammy -->
<docker.image.sha256>ddf36656dc8920621fddf4928bdcb4b98c0d0e7bc9672f0cea8115c10ad5cbc6</docker.image.sha256>
<!-- 17.0.8_7-jre-jammy -->
<docker.image.sha256>b8af44d6a7e0615a7486d7307dd54bba23ff24e3aea14893fd2795e8c436d44e</docker.image.sha256>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
@@ -144,7 +143,7 @@
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-bom</artifactId>
<version>2022.0.3</version> <!-- 3.5.x, see https://github.com/reactor/reactor#bom-versioning-scheme -->
<version>2022.0.10</version> <!-- 3.5.x, see https://github.com/reactor/reactor#bom-versioning-scheme -->
<type>pom</type>
<scope>import</scope>
</dependency>
@@ -221,18 +220,6 @@
<version>${jaxb.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-inline</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.opentest4j</groupId>
<artifactId>opentest4j</artifactId>
@@ -258,7 +245,7 @@
<dependency>
<groupId>org.ow2.asm</groupId>
<artifactId>asm</artifactId>
<version>9.2</version>
<version>9.5</version>
<scope>test</scope>
</dependency>
<dependency>
@@ -323,7 +310,6 @@
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
<dependency>
@@ -339,7 +325,7 @@
<dependency>
<groupId>org.junit-pioneer</groupId>
<artifactId>junit-pioneer</artifactId>
<version>1.9.1</version>
<version>2.0.1</version>
<scope>test</scope>
</dependency>
+1 -13
View File
@@ -22,8 +22,6 @@ metrics:
tags:
- "env:staging"
- "service:chat"
transport:
apiKey: secret://datadog.apiKey
udpTransport:
statsdHost: localhost
port: 8125
@@ -47,10 +45,6 @@ adminEventLoggingConfiguration:
{
"key": "value"
}
secondaryCredentials: |
{
"key": "value"
}
projectId: some-project-id
logName: some-log-name
@@ -226,8 +220,7 @@ cdn:
bucket: cdn # S3 Bucket name
region: us-west-2 # AWS region
datadog:
apiKey: secret://datadog.apiKey
dogstatsd:
environment: dev
unidentifiedDelivery:
@@ -238,7 +231,6 @@ unidentifiedDelivery:
recaptcha:
projectPath: projects/example
credentialConfigurationJson: "{ }" # service account configuration for backend authentication
secondaryCredentialConfigurationJson: "{ }" # service account configuration for backend authentication
hCaptcha:
apiKey: secret://hCaptcha.apiKey
@@ -403,10 +395,6 @@ registrationService:
{
"example": "example"
}
secondaryCredentialConfigurationJson: |
{
"example": "example"
}
identityTokenAudience: https://registration.example.com
registrationCaCertificate: | # Registration service TLS certificate trust root
-----BEGIN CERTIFICATE-----
+7 -7
View File
@@ -255,7 +255,7 @@
</dependency>
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-datadog</artifactId>
<artifactId>micrometer-registry-statsd</artifactId>
</dependency>
<dependency>
<groupId>org.coursera</groupId>
@@ -429,7 +429,7 @@
<dependency>
<groupId>com.fasterxml.uuid</groupId>
<artifactId>java-uuid-generator</artifactId>
<version>4.0.1</version>
<version>4.2.0</version>
<scope>test</scope>
</dependency>
@@ -470,7 +470,7 @@
<dependency>
<groupId>com.apollographql.apollo3</groupId>
<artifactId>apollo-api-jvm</artifactId>
<version>3.7.1</version>
<version>3.8.2</version>
</dependency>
</dependencies>
@@ -483,7 +483,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.2.4</version>
<version>3.5.0</version>
<configuration>
<createDependencyReducedPom>true</createDependencyReducedPom>
<filters>
@@ -518,7 +518,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>3.3.0</version>
<version>3.6.0</version>
<configuration>
<descriptors>
<descriptor>assembly.xml</descriptor>
@@ -538,7 +538,7 @@
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>properties-maven-plugin</artifactId>
<version>1.0.0</version>
<version>1.2.0</version>
<executions>
<execution>
<id>read-deploy-configuration</id>
@@ -638,7 +638,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M7</version>
<version>3.1.2</version>
<configuration>
<!-- work around PATCH not being a supported method on HttpUrlConnection -->
<argLine>--add-opens=java.base/java.net=ALL-UNNAMED</argLine>
@@ -27,7 +27,7 @@ import org.whispersystems.textsecuregcm.configuration.BraintreeConfiguration;
import org.whispersystems.textsecuregcm.configuration.CdnConfiguration;
import org.whispersystems.textsecuregcm.configuration.ClientReleaseConfiguration;
import org.whispersystems.textsecuregcm.configuration.CommandStopListenerConfiguration;
import org.whispersystems.textsecuregcm.configuration.DatadogConfiguration;
import org.whispersystems.textsecuregcm.configuration.DogstatsdConfiguration;
import org.whispersystems.textsecuregcm.configuration.DirectoryV2Configuration;
import org.whispersystems.textsecuregcm.configuration.DynamoDbClientConfiguration;
import org.whispersystems.textsecuregcm.configuration.DynamoDbTables;
@@ -106,7 +106,7 @@ public class WhisperServerConfiguration extends Configuration {
@NotNull
@Valid
@JsonProperty
private DatadogConfiguration datadog;
private DogstatsdConfiguration dogstatsd = new DogstatsdConfiguration();
@NotNull
@Valid
@@ -416,8 +416,8 @@ public class WhisperServerConfiguration extends Configuration {
return cdn;
}
public DatadogConfiguration getDatadogConfiguration() {
return datadog;
public DogstatsdConfiguration getDatadogConfiguration() {
return dogstatsd;
}
public UnidentifiedDeliveryConfiguration getDeliveryCertificate() {
@@ -39,7 +39,6 @@ import java.time.Duration;
import java.util.Collections;
import java.util.EnumSet;
import java.util.List;
import java.util.Optional;
import java.util.ServiceLoader;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
@@ -116,7 +115,6 @@ import org.whispersystems.textsecuregcm.controllers.VerificationController;
import org.whispersystems.textsecuregcm.currency.CoinMarketCapClient;
import org.whispersystems.textsecuregcm.currency.CurrencyConversionManager;
import org.whispersystems.textsecuregcm.currency.FixerClient;
import org.whispersystems.textsecuregcm.grpc.ProfileGrpcService;
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
import org.whispersystems.textsecuregcm.filters.RemoteDeprecationFilter;
import org.whispersystems.textsecuregcm.filters.RequestStatisticsFilter;
@@ -124,6 +122,7 @@ import org.whispersystems.textsecuregcm.filters.TimestampResponseFilter;
import org.whispersystems.textsecuregcm.grpc.GrpcServerManagedWrapper;
import org.whispersystems.textsecuregcm.grpc.KeysAnonymousGrpcService;
import org.whispersystems.textsecuregcm.grpc.KeysGrpcService;
import org.whispersystems.textsecuregcm.grpc.ProfileGrpcService;
import org.whispersystems.textsecuregcm.grpc.UserAgentInterceptor;
import org.whispersystems.textsecuregcm.limits.CardinalityEstimator;
import org.whispersystems.textsecuregcm.limits.PushChallengeManager;
@@ -283,10 +282,6 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
MetricsUtil.configureRegistries(config, environment);
final boolean useSecondaryCredentialsJson = Optional.ofNullable(
System.getenv("SIGNAL_USE_SECONDARY_CREDENTIALS_JSON"))
.isPresent();
HeaderControlledResourceBundleLookup headerControlledResourceBundleLookup =
new HeaderControlledResourceBundleLookup();
ConfiguredProfileBadgeConverter profileBadgeConverter = new ConfiguredProfileBadgeConverter(
@@ -448,9 +443,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
final AdminEventLogger adminEventLogger = new GoogleCloudAdminEventLogger(
LoggingOptions.newBuilder().setProjectId(config.getAdminEventLoggingConfiguration().projectId())
.setCredentials(GoogleCredentials.fromStream(new ByteArrayInputStream(
useSecondaryCredentialsJson
? config.getAdminEventLoggingConfiguration().secondaryCredentials().getBytes(StandardCharsets.UTF_8)
: config.getAdminEventLoggingConfiguration().credentials().getBytes(StandardCharsets.UTF_8))))
config.getAdminEventLoggingConfiguration().credentials().getBytes(StandardCharsets.UTF_8))))
.build().getService(),
config.getAdminEventLoggingConfiguration().projectId(),
config.getAdminEventLoggingConfiguration().logName());
@@ -489,9 +482,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
RegistrationServiceClient registrationServiceClient = new RegistrationServiceClient(
config.getRegistrationServiceConfiguration().host(),
config.getRegistrationServiceConfiguration().port(),
useSecondaryCredentialsJson
? config.getRegistrationServiceConfiguration().secondaryCredentialConfigurationJson()
: config.getRegistrationServiceConfiguration().credentialConfigurationJson(),
config.getRegistrationServiceConfiguration().credentialConfigurationJson(),
config.getRegistrationServiceConfiguration().identityTokenAudience(),
config.getRegistrationServiceConfiguration().registrationCaCertificate(),
registrationCallbackExecutor);
@@ -574,9 +565,7 @@ public class WhisperServerService extends Application<WhisperServerConfiguration
RecaptchaClient recaptchaClient = new RecaptchaClient(
config.getRecaptchaConfiguration().projectPath(),
useSecondaryCredentialsJson
? config.getRecaptchaConfiguration().secondaryCredentialConfigurationJson()
: config.getRecaptchaConfiguration().credentialConfigurationJson(),
config.getRecaptchaConfiguration().credentialConfigurationJson(),
dynamicConfigurationManager);
HttpClient hcaptchaHttpClient = HttpClient.newBuilder().version(HttpClient.Version.HTTP_2)
.connectTimeout(Duration.ofSeconds(10)).build();
@@ -13,6 +13,7 @@ import org.signal.libsignal.protocol.ecc.Curve;
import org.signal.libsignal.protocol.ecc.ECPrivateKey;
import org.whispersystems.textsecuregcm.entities.MessageProtos.SenderCertificate;
import org.whispersystems.textsecuregcm.entities.MessageProtos.ServerCertificate;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.Device;
@@ -32,11 +33,11 @@ public class CertificateGenerator {
public byte[] createFor(Account account, Device device, boolean includeE164) throws InvalidKeyException {
SenderCertificate.Certificate.Builder builder = SenderCertificate.Certificate.newBuilder()
.setSenderDevice(Math.toIntExact(device.getId()))
.setExpires(System.currentTimeMillis() + TimeUnit.DAYS.toMillis(expiresDays))
.setIdentityKey(ByteString.copyFrom(account.getIdentityKey().serialize()))
.setSigner(serverCertificate)
.setSenderUuid(account.getUuid().toString());
.setSenderDevice(Math.toIntExact(device.getId()))
.setExpires(System.currentTimeMillis() + TimeUnit.DAYS.toMillis(expiresDays))
.setIdentityKey(ByteString.copyFrom(account.getIdentityKey(IdentityType.ACI).serialize()))
.setSigner(serverCertificate)
.setSenderUuid(account.getUuid().toString());
if (includeE164) {
builder.setSender(account.getNumber());
@@ -9,9 +9,7 @@ import io.grpc.Context;
import io.grpc.Status;
import java.util.UUID;
import javax.annotation.Nullable;
import reactor.core.publisher.Mono;
import reactor.util.function.Tuple2;
import reactor.util.function.Tuples;
import org.whispersystems.textsecuregcm.storage.Device;
/**
* Provides utility methods for working with authentication in the context of gRPC calls.
@@ -25,7 +23,7 @@ public class AuthenticationUtil {
* Returns the account/device authenticated in the current gRPC context or throws an "unauthenticated" exception if
* no authenticated account/device is available.
*
* @return the account/device authenticated in the current gRPC context
* @return the account/device identifier authenticated in the current gRPC context
*
* @throws io.grpc.StatusRuntimeException with a status of {@code UNAUTHENTICATED} if no authenticated account/device
* could be retrieved from the current gRPC context
@@ -40,4 +38,25 @@ public class AuthenticationUtil {
throw Status.UNAUTHENTICATED.asRuntimeException();
}
/**
* Returns the account/device authenticated in the current gRPC context or throws an "unauthenticated" exception if
* no authenticated account/device is available or "permission denied" if the authenticated device is not the primary
* device for the account.
*
* @return the account/device identifier authenticated in the current gRPC context
*
* @throws io.grpc.StatusRuntimeException with a status of {@code UNAUTHENTICATED} if no authenticated account/device
* could be retrieved from the current gRPC context or a status of {@code PERMISSION_DENIED} if the authenticated
* device is not the primary device for the authenticated account
*/
public static AuthenticatedDevice requireAuthenticatedPrimaryDevice() {
final AuthenticatedDevice authenticatedDevice = requireAuthenticatedDevice();
if (authenticatedDevice.deviceId() != Device.MASTER_ID) {
throw Status.PERMISSION_DENIED.asRuntimeException();
}
return authenticatedDevice;
}
}
@@ -10,7 +10,6 @@ import javax.validation.constraints.NotEmpty;
public record AdminEventLoggingConfiguration(
@NotBlank String credentials,
@NotBlank String secondaryCredentials,
@NotEmpty String projectId,
@NotEmpty String logName) {
}
@@ -6,18 +6,13 @@
package org.whispersystems.textsecuregcm.configuration;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.micrometer.datadog.DatadogConfig;
import io.micrometer.statsd.StatsdConfig;
import io.micrometer.statsd.StatsdFlavor;
import java.time.Duration;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import org.whispersystems.textsecuregcm.configuration.secrets.SecretString;
public class DatadogConfiguration implements DatadogConfig {
@JsonProperty
@NotNull
private SecretString apiKey;
public class DogstatsdConfiguration implements StatsdConfig {
@JsonProperty
@NotNull
@@ -27,15 +22,6 @@ public class DatadogConfiguration implements DatadogConfig {
@NotBlank
private String environment;
@JsonProperty
@Min(1)
private int batchSize = 5_000;
@Override
public String apiKey() {
return apiKey.value();
}
@Override
public Duration step() {
return step;
@@ -46,17 +32,13 @@ public class DatadogConfiguration implements DatadogConfig {
}
@Override
public int batchSize() {
return batchSize;
}
@Override
public String hostTag() {
return "host";
public StatsdFlavor flavor() {
return StatsdFlavor.DATADOG;
}
@Override
public String get(final String key) {
// We have no Micrometer key/value pairs to report, so always return `null`
return null;
}
}
@@ -7,7 +7,6 @@ package org.whispersystems.textsecuregcm.configuration;
import javax.validation.constraints.NotEmpty;
public record RecaptchaConfiguration(@NotEmpty String projectPath, @NotEmpty String credentialConfigurationJson,
@NotEmpty String secondaryCredentialConfigurationJson) {
public record RecaptchaConfiguration(@NotEmpty String projectPath, @NotEmpty String credentialConfigurationJson) {
}
@@ -5,7 +5,6 @@ import javax.validation.constraints.NotBlank;
public record RegistrationServiceConfiguration(@NotBlank String host,
int port,
@NotBlank String credentialConfigurationJson,
@NotBlank String secondaryCredentialConfigurationJson,
@NotBlank String identityTokenAudience,
@NotBlank String registrationCaCertificate) {
}
@@ -4,7 +4,6 @@
*/
package org.whispersystems.textsecuregcm.controllers;
import com.codahale.metrics.annotation.Timed;
import io.dropwizard.auth.Auth;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
@@ -91,7 +90,6 @@ public class AccountController {
this.usernameHashZkProofVerifier = usernameHashZkProofVerifier;
}
@Timed
@GET
@Path("/turn/")
@Produces(MediaType.APPLICATION_JSON)
@@ -100,7 +98,6 @@ public class AccountController {
return turnTokenGenerator.generate(auth.getAccount().getUuid());
}
@Timed
@PUT
@Path("/gcm/")
@Consumes(MediaType.APPLICATION_JSON)
@@ -124,7 +121,6 @@ public class AccountController {
});
}
@Timed
@DELETE
@Path("/gcm/")
@ChangesDeviceEnabledState
@@ -139,7 +135,6 @@ public class AccountController {
});
}
@Timed
@PUT
@Path("/apn/")
@Consumes(MediaType.APPLICATION_JSON)
@@ -165,7 +160,6 @@ public class AccountController {
});
}
@Timed
@DELETE
@Path("/apn/")
@ChangesDeviceEnabledState
@@ -175,6 +169,7 @@ public class AccountController {
accounts.updateDevice(account, device.getId(), d -> {
d.setApnId(null);
d.setVoipApnId(null);
d.setFetchesMessages(false);
if (d.getId() == 1) {
d.setUserAgent("OWI");
@@ -184,7 +179,6 @@ public class AccountController {
});
}
@Timed
@PUT
@Produces(MediaType.APPLICATION_JSON)
@Path("/registration_lock")
@@ -195,14 +189,12 @@ public class AccountController {
a -> a.setRegistrationLock(credentials.hash(), credentials.salt()));
}
@Timed
@DELETE
@Path("/registration_lock")
public void removeRegistrationLock(@Auth AuthenticatedAccount auth) {
accounts.update(auth.getAccount(), a -> a.setRegistrationLock(null, null));
}
@Timed
@PUT
@Path("/name/")
public void setName(@Auth DisabledPermittedAuthenticatedAccount disabledPermittedAuth, @NotNull @Valid DeviceName deviceName) {
@@ -211,7 +203,6 @@ public class AccountController {
accounts.updateDevice(account, device.getId(), d -> d.setName(deviceName.getDeviceName()));
}
@Timed
@PUT
@Path("/attributes/")
@Consumes(MediaType.APPLICATION_JSON)
@@ -268,7 +259,6 @@ public class AccountController {
auth.getAccount().isStorageSupported());
}
@Timed
@DELETE
@Path("/username_hash")
@Produces(MediaType.APPLICATION_JSON)
@@ -285,7 +275,6 @@ public class AccountController {
accounts.clearUsernameHash(auth.getAccount());
}
@Timed
@PUT
@Path("/username_hash/reserve")
@Produces(MediaType.APPLICATION_JSON)
@@ -325,7 +314,6 @@ public class AccountController {
}
}
@Timed
@PUT
@Path("/username_hash/confirm")
@Produces(MediaType.APPLICATION_JSON)
@@ -370,7 +358,6 @@ public class AccountController {
}
}
@Timed
@GET
@Path("/username_hash/{usernameHash}")
@Produces(MediaType.APPLICATION_JSON)
@@ -408,7 +395,6 @@ public class AccountController {
.orElseThrow(() -> new WebApplicationException(Status.NOT_FOUND));
}
@Timed
@PUT
@Path("/username_link")
@Produces(MediaType.APPLICATION_JSON)
@@ -443,7 +429,6 @@ public class AccountController {
return new UsernameLinkHandle(usernameLinkHandle);
}
@Timed
@DELETE
@Path("/username_link")
@Operation(
@@ -462,7 +447,6 @@ public class AccountController {
clearUsernameLink(auth.getAccount());
}
@Timed
@GET
@Path("/username_link/{uuid}")
@Produces(MediaType.APPLICATION_JSON)
@@ -475,6 +459,7 @@ public class AccountController {
"""
)
@ApiResponse(responseCode = "200", description = "Username link with the given handle was found.", useReturnTypeSchema = true)
@ApiResponse(responseCode = "400", description = "Request must not be authenticated.")
@ApiResponse(responseCode = "404", description = "Username link was not found for the given handle.")
@ApiResponse(responseCode = "422", description = "Invalid request format.")
@ApiResponse(responseCode = "429", description = "Ratelimited.")
@@ -497,7 +482,7 @@ public class AccountController {
"""
)
@ApiResponse(responseCode = "200", description = "An account with the given identifier was found.", useReturnTypeSchema = true)
@ApiResponse(responseCode = "400", description = "A client made an authenticated to this endpoint, and must not provide credentials.")
@ApiResponse(responseCode = "400", description = "Request must not be authenticated.")
@ApiResponse(responseCode = "404", description = "An account was not found for the given identifier.")
@ApiResponse(responseCode = "422", description = "Invalid request format.")
@ApiResponse(responseCode = "429", description = "Rate-limited.")
@@ -518,7 +503,6 @@ public class AccountController {
return Response.status(maybeAccount.map(ignored -> Status.OK).orElse(Status.NOT_FOUND)).build();
}
@Timed
@DELETE
@Path("/me")
public void deleteAccount(@Auth DisabledPermittedAuthenticatedAccount auth) throws InterruptedException {
@@ -7,7 +7,6 @@ package org.whispersystems.textsecuregcm.controllers;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import com.codahale.metrics.annotation.Timed;
import com.google.common.net.HttpHeaders;
import io.dropwizard.auth.Auth;
import io.micrometer.core.instrument.Metrics;
@@ -76,7 +75,6 @@ public class AccountControllerV2 {
this.rateLimiters = rateLimiters;
}
@Timed
@PUT
@Path("/number")
@Consumes(MediaType.APPLICATION_JSON)
@@ -155,7 +153,6 @@ public class AccountControllerV2 {
}
}
@Timed
@PUT
@Path("/phone_number_identity_key_distribution")
@Consumes(MediaType.APPLICATION_JSON)
@@ -208,7 +205,6 @@ public class AccountControllerV2 {
}
}
@Timed
@PUT
@Path("/phone_number_discoverability")
@Consumes(MediaType.APPLICATION_JSON)
@@ -221,7 +217,6 @@ public class AccountControllerV2 {
phoneNumberDiscoverability.discoverableByPhoneNumber()));
}
@Timed
@GET
@Path("/data_report")
@Produces(MediaType.APPLICATION_JSON)
@@ -5,7 +5,6 @@
package org.whispersystems.textsecuregcm.controllers;
import com.codahale.metrics.annotation.Timed;
import io.dropwizard.auth.Auth;
import io.swagger.v3.oas.annotations.tags.Tag;
import java.util.UUID;
@@ -40,7 +39,6 @@ public class ArtController {
this.rateLimiters = rateLimiters;
}
@Timed
@GET
@Path("/auth")
@Produces(MediaType.APPLICATION_JSON)
@@ -7,7 +7,6 @@ package org.whispersystems.textsecuregcm.controllers;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import com.codahale.metrics.annotation.Timed;
import com.google.common.net.HttpHeaders;
import io.dropwizard.auth.Auth;
import io.micrometer.core.instrument.Metrics;
@@ -48,7 +47,6 @@ public class AttachmentControllerV2 {
this.policySigner = new PolicySigner(accessSecret, region);
}
@Timed
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/form/upload")
@@ -5,17 +5,13 @@
package org.whispersystems.textsecuregcm.controllers;
import com.codahale.metrics.annotation.Timed;
import io.dropwizard.auth.Auth;
import io.swagger.v3.oas.annotations.tags.Tag;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.Base64;
import java.util.Map;
import javax.annotation.Nonnull;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
@@ -25,9 +21,6 @@ import org.whispersystems.textsecuregcm.attachments.AttachmentGenerator;
import org.whispersystems.textsecuregcm.attachments.GcsAttachmentGenerator;
import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
import org.whispersystems.textsecuregcm.entities.AttachmentDescriptorV3;
import org.whispersystems.textsecuregcm.gcp.CanonicalRequest;
import org.whispersystems.textsecuregcm.gcp.CanonicalRequestGenerator;
import org.whispersystems.textsecuregcm.gcp.CanonicalRequestSigner;
import org.whispersystems.textsecuregcm.limits.RateLimiter;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
@@ -51,7 +44,6 @@ public class AttachmentControllerV3 {
this.secureRandom = new SecureRandom();
}
@Timed
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/form/upload")
@@ -5,13 +5,11 @@
package org.whispersystems.textsecuregcm.controllers;
import com.codahale.metrics.annotation.Timed;
import io.dropwizard.auth.Auth;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.headers.Header;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import java.security.SecureRandom;
import java.util.Base64;
import java.util.Map;
@@ -20,7 +18,6 @@ import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.whispersystems.textsecuregcm.attachments.AttachmentGenerator;
import org.whispersystems.textsecuregcm.attachments.GcsAttachmentGenerator;
import org.whispersystems.textsecuregcm.attachments.TusAttachmentGenerator;
@@ -62,7 +59,6 @@ public class AttachmentControllerV4 {
);
}
@Timed
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/form/upload")
@@ -1,9 +1,17 @@
package org.whispersystems.textsecuregcm.controllers;
import com.codahale.metrics.annotation.Timed;
import io.dropwizard.auth.Auth;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.ws.rs.BadRequestException;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.signal.libsignal.protocol.ServiceId;
import org.signal.libsignal.zkgroup.GenericServerSecretParams;
import org.signal.libsignal.zkgroup.InvalidInputException;
@@ -12,15 +20,6 @@ import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
import org.whispersystems.textsecuregcm.entities.CreateCallLinkCredential;
import org.whispersystems.textsecuregcm.entities.GetCreateCallLinkCredentialsRequest;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.ws.rs.BadRequestException;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
@Path("/v1/call-link")
@io.swagger.v3.oas.annotations.tags.Tag(name = "CallLink")
@@ -36,7 +35,6 @@ public class CallLinkController {
this.genericServerSecretParams = genericServerSecretParams;
}
@Timed
@POST
@Path("/create-auth")
@Produces(MediaType.APPLICATION_JSON)
@@ -7,7 +7,6 @@ package org.whispersystems.textsecuregcm.controllers;
import static com.codahale.metrics.MetricRegistry.name;
import com.codahale.metrics.annotation.Timed;
import com.google.common.annotations.VisibleForTesting;
import io.dropwizard.auth.Auth;
import io.micrometer.core.instrument.Metrics;
@@ -20,7 +19,6 @@ import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
import javax.annotation.Nonnull;
import javax.ws.rs.BadRequestException;
import javax.ws.rs.DefaultValue;
@@ -31,16 +29,16 @@ import javax.ws.rs.QueryParam;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.signal.libsignal.protocol.ServiceId;
import org.signal.libsignal.zkgroup.GenericServerSecretParams;
import org.signal.libsignal.zkgroup.auth.AuthCredentialWithPniResponse;
import org.signal.libsignal.zkgroup.auth.ServerZkAuthOperations;
import org.signal.libsignal.zkgroup.calllinks.CallLinkAuthCredentialResponse;
import org.signal.libsignal.zkgroup.GenericServerSecretParams;
import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
import org.whispersystems.textsecuregcm.auth.CertificateGenerator;
import org.whispersystems.textsecuregcm.entities.DeliveryCertificate;
import org.whispersystems.textsecuregcm.entities.GroupCredentials;
import org.whispersystems.textsecuregcm.identity.IdentityType;
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
@Path("/v1/certificate")
@@ -68,7 +66,6 @@ public class CertificateController {
this.clock = Objects.requireNonNull(clock);
}
@Timed
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/delivery")
@@ -76,7 +73,7 @@ public class CertificateController {
@QueryParam("includeE164") @DefaultValue("true") boolean includeE164)
throws InvalidKeyException {
if (auth.getAccount().getIdentityKey() == null) {
if (auth.getAccount().getIdentityKey(IdentityType.ACI) == null) {
throw new WebApplicationException(Response.Status.BAD_REQUEST);
}
@@ -87,7 +84,6 @@ public class CertificateController {
certificateGenerator.createFor(auth.getAccount(), auth.getAuthenticatedDevice(), includeE164));
}
@Timed
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/auth/group")
@@ -7,7 +7,6 @@ package org.whispersystems.textsecuregcm.controllers;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import com.codahale.metrics.annotation.Timed;
import com.google.common.net.HttpHeaders;
import io.dropwizard.auth.Auth;
import io.micrometer.core.instrument.Metrics;
@@ -20,7 +19,6 @@ import io.swagger.v3.oas.annotations.parameters.RequestBody;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import java.io.IOException;
import java.util.Optional;
import javax.validation.Valid;
import javax.ws.rs.BadRequestException;
import javax.ws.rs.Consumes;
@@ -53,7 +51,6 @@ public class ChallengeController {
this.rateLimitChallengeManager = rateLimitChallengeManager;
}
@Timed
@PUT
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@@ -110,7 +107,6 @@ public class ChallengeController {
return Response.status(200).build();
}
@Timed
@POST
@Path("/push")
@Operation(
@@ -4,7 +4,6 @@
*/
package org.whispersystems.textsecuregcm.controllers;
import com.codahale.metrics.annotation.Timed;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.net.HttpHeaders;
import io.dropwizard.auth.Auth;
@@ -58,6 +57,7 @@ import org.whispersystems.textsecuregcm.entities.DeviceInfoList;
import org.whispersystems.textsecuregcm.entities.DeviceResponse;
import org.whispersystems.textsecuregcm.entities.LinkDeviceRequest;
import org.whispersystems.textsecuregcm.entities.PreKeySignatureValidator;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
import org.whispersystems.textsecuregcm.storage.Account;
@@ -118,7 +118,6 @@ public class DeviceController {
}
}
@Timed
@GET
@Produces(MediaType.APPLICATION_JSON)
public DeviceInfoList getDevices(@Auth AuthenticatedAccount auth) {
@@ -132,7 +131,6 @@ public class DeviceController {
return new DeviceInfoList(devices);
}
@Timed
@DELETE
@Produces(MediaType.APPLICATION_JSON)
@Path("/{device_id}")
@@ -145,15 +143,14 @@ public class DeviceController {
final CompletableFuture<Void> deleteKeysFuture = keys.delete(account.getUuid(), deviceId);
messages.clear(account.getUuid(), deviceId);
messages.clear(account.getUuid(), deviceId).join();
account = accounts.update(account, a -> a.removeDevice(deviceId));
// ensure any messages that came in after the first clear() are also removed
messages.clear(account.getUuid(), deviceId);
messages.clear(account.getUuid(), deviceId).join();
deleteKeysFuture.join();
}
@Timed
@GET
@Path("/provisioning/code")
@Produces(MediaType.APPLICATION_JSON)
@@ -185,7 +182,6 @@ public class DeviceController {
* @deprecated callers should use {@link #linkDevice(BasicAuthorizationHeader, LinkDeviceRequest, ContainerRequest)}
* instead
*/
@Timed
@PUT
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@@ -210,7 +206,6 @@ public class DeviceController {
return new DeviceResponse(account.getUuid(), account.getPhoneNumberIdentifier(), device.getId());
}
@Timed
@PUT
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@@ -244,7 +239,6 @@ public class DeviceController {
return new DeviceResponse(account.getUuid(), account.getPhoneNumberIdentifier(), device.getId());
}
@Timed
@PUT
@Produces(MediaType.APPLICATION_JSON)
@Path("/unauthenticated_delivery")
@@ -253,7 +247,6 @@ public class DeviceController {
// Deprecated
}
@Timed
@PUT
@Produces(MediaType.APPLICATION_JSON)
@Path("/capabilities")
@@ -367,9 +360,10 @@ public class DeviceController {
assert deviceActivationRequest.aciPqLastResortPreKey().isPresent();
assert deviceActivationRequest.pniPqLastResortPreKey().isPresent();
final boolean allKeysValid = PreKeySignatureValidator.validatePreKeySignatures(account.getIdentityKey(),
final boolean allKeysValid = PreKeySignatureValidator.validatePreKeySignatures(account.getIdentityKey(
IdentityType.ACI),
List.of(deviceActivationRequest.aciSignedPreKey().get(), deviceActivationRequest.aciPqLastResortPreKey().get()))
&& PreKeySignatureValidator.validatePreKeySignatures(account.getPhoneNumberIdentityKey(),
&& PreKeySignatureValidator.validatePreKeySignatures(account.getIdentityKey(IdentityType.PNI),
List.of(deviceActivationRequest.pniSignedPreKey().get(), deviceActivationRequest.pniPqLastResortPreKey().get()));
if (!allKeysValid) {
@@ -427,7 +421,7 @@ public class DeviceController {
keys.delete(a.getUuid(), device.getId()),
keys.delete(a.getPhoneNumberIdentifier(), device.getId()));
messages.clear(a.getUuid(), device.getId());
messages.clear(a.getUuid(), device.getId()).join();
deleteKeysFuture.join();
@@ -4,7 +4,6 @@
*/
package org.whispersystems.textsecuregcm.controllers;
import com.codahale.metrics.annotation.Timed;
import com.google.common.annotations.VisibleForTesting;
import io.dropwizard.auth.Auth;
import io.swagger.v3.oas.annotations.tags.Tag;
@@ -45,7 +44,6 @@ public class DirectoryV2Controller {
this.directoryServiceTokenGenerator = userTokenGenerator;
}
@Timed
@GET
@Path("/auth")
@Produces(MediaType.APPLICATION_JSON)
@@ -5,7 +5,6 @@
package org.whispersystems.textsecuregcm.controllers;
import com.codahale.metrics.annotation.Timed;
import io.dropwizard.auth.Auth;
import io.swagger.v3.oas.annotations.tags.Tag;
import java.time.Clock;
@@ -74,7 +73,6 @@ public class DonationController {
this.receiptCredentialPresentationFactory = Objects.requireNonNull(receiptCredentialPresentationFactory);
}
@Timed
@POST
@Path("/redeem-receipt")
@Consumes(MediaType.APPLICATION_JSON)
@@ -7,7 +7,6 @@ package org.whispersystems.textsecuregcm.controllers;
import static com.codahale.metrics.MetricRegistry.name;
import com.codahale.metrics.annotation.Timed;
import io.dropwizard.auth.Auth;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tags;
@@ -40,7 +39,6 @@ public class KeepAliveController {
this.clientPresenceManager = clientPresenceManager;
}
@Timed
@GET
public Response getKeepAlive(@Auth Optional<AuthenticatedAccount> maybeAuth,
@WebSocketSession WebSocketSessionContext context) {
@@ -63,7 +61,6 @@ public class KeepAliveController {
return Response.ok().build();
}
@Timed
@GET
@Path("/provisioning")
public Response getProvisioningKeepAlive() {
@@ -6,7 +6,6 @@ package org.whispersystems.textsecuregcm.controllers;
import static com.codahale.metrics.MetricRegistry.name;
import com.codahale.metrics.annotation.Timed;
import com.google.common.net.HttpHeaders;
import io.dropwizard.auth.Auth;
import io.micrometer.core.instrument.Metrics;
@@ -57,6 +56,7 @@ import org.whispersystems.textsecuregcm.entities.PreKeyResponse;
import org.whispersystems.textsecuregcm.entities.PreKeyResponseItem;
import org.whispersystems.textsecuregcm.entities.PreKeyState;
import org.whispersystems.textsecuregcm.experiment.Experiment;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.metrics.UserAgentTagUtil;
@@ -64,6 +64,7 @@ import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.KeysManager;
import org.whispersystems.textsecuregcm.util.Util;
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
@Path("/v2/keys")
@@ -95,7 +96,7 @@ public class KeysController {
description = "Gets the number of one-time prekeys uploaded for this device and still available")
@ApiResponse(responseCode = "200", description = "Body contains the number of available one-time prekeys for the device.", useReturnTypeSchema = true)
@ApiResponse(responseCode = "401", description = "Account authentication check failed.")
public PreKeyCount getStatus(@Auth final AuthenticatedAccount auth,
public CompletableFuture<PreKeyCount> getStatus(@Auth final AuthenticatedAccount auth,
@QueryParam("identity") final Optional<String> identityType) {
final CompletableFuture<Integer> ecCountFuture =
@@ -104,10 +105,9 @@ public class KeysController {
final CompletableFuture<Integer> pqCountFuture =
keys.getPqCount(getIdentifier(auth.getAccount(), identityType), auth.getAuthenticatedDevice().getId());
return new PreKeyCount(ecCountFuture.join(), pqCountFuture.join());
return ecCountFuture.thenCombine(pqCountFuture, PreKeyCount::new);
}
@Timed
@PUT
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@@ -121,7 +121,7 @@ public class KeysController {
@ApiResponse(responseCode = "401", description = "Account authentication check failed.")
@ApiResponse(responseCode = "403", description = "Attempt to change identity key from a non-primary device.")
@ApiResponse(responseCode = "422", description = "Invalid request format.")
public void setKeys(@Auth final DisabledPermittedAuthenticatedAccount disabledPermittedAuth,
public CompletableFuture<Void> setKeys(@Auth final DisabledPermittedAuthenticatedAccount disabledPermittedAuth,
@RequestBody @NotNull @Valid final PreKeyState preKeys,
@Parameter(allowEmptyValue=true)
@@ -139,11 +139,13 @@ public class KeysController {
final boolean usePhoneNumberIdentity = usePhoneNumberIdentity(identityType);
if (preKeys.getSignedPreKey() != null &&
!preKeys.getSignedPreKey().equals(usePhoneNumberIdentity ? device.getPhoneNumberIdentitySignedPreKey() : device.getSignedPreKey())) {
!preKeys.getSignedPreKey().equals(usePhoneNumberIdentity ? device.getSignedPreKey(IdentityType.PNI)
: device.getSignedPreKey(IdentityType.ACI))) {
updateAccount = true;
}
final IdentityKey oldIdentityKey = usePhoneNumberIdentity ? account.getPhoneNumberIdentityKey() : account.getIdentityKey();
final IdentityKey oldIdentityKey =
usePhoneNumberIdentity ? account.getIdentityKey(IdentityType.PNI) : account.getIdentityKey(IdentityType.ACI);
if (!Objects.equals(preKeys.getIdentityKey(), oldIdentityKey)) {
updateAccount = true;
@@ -186,13 +188,10 @@ public class KeysController {
});
}
keys.store(
getIdentifier(account, identityType), device.getId(),
preKeys.getPreKeys(), preKeys.getPqPreKeys(), preKeys.getSignedPreKey(), preKeys.getPqLastResortPreKey())
.join();
return keys.store(getIdentifier(account, identityType), device.getId(),
preKeys.getPreKeys(), preKeys.getPqPreKeys(), preKeys.getSignedPreKey(), preKeys.getPqLastResortPreKey());
}
@Timed
@GET
@Path("/{identifier}/{device_id}")
@Produces(MediaType.APPLICATION_JSON)
@@ -241,35 +240,47 @@ public class KeysController {
+ "." + deviceId);
}
List<Device> devices = parseDeviceId(deviceId, target);
List<PreKeyResponseItem> responseItems = new ArrayList<>(devices.size());
final List<Device> devices = parseDeviceId(deviceId, target);
final List<PreKeyResponseItem> responseItems = new ArrayList<>(devices.size());
for (Device device : devices) {
ECSignedPreKey signedECPreKey = switch (targetIdentifier.identityType()) {
case ACI -> device.getSignedPreKey();
case PNI -> device.getPhoneNumberIdentitySignedPreKey();
};
final List<CompletableFuture<Void>> tasks = devices.stream().map(device -> {
ECPreKey unsignedECPreKey = keys.takeEC(targetIdentifier.uuid(), device.getId()).join().orElse(null);
KEMSignedPreKey pqPreKey = returnPqKey ? keys.takePQ(targetIdentifier.uuid(), device.getId()).join().orElse(null) : null;
ECSignedPreKey signedECPreKey = device.getSignedPreKey(targetIdentifier.identityType());
compareSignedEcPreKeysExperiment.compareFutureResult(Optional.ofNullable(signedECPreKey),
keys.getEcSignedPreKey(targetIdentifier.uuid(), device.getId()));
final CompletableFuture<Optional<ECPreKey>> unsignedEcPreKeyFuture = keys.takeEC(targetIdentifier.uuid(),
device.getId());
final CompletableFuture<Optional<KEMSignedPreKey>> pqPreKeyFuture = returnPqKey
? keys.takePQ(targetIdentifier.uuid(), device.getId())
: CompletableFuture.completedFuture(Optional.empty());
if (signedECPreKey != null || unsignedECPreKey != null || pqPreKey != null) {
final int registrationId = switch (targetIdentifier.identityType()) {
case ACI -> device.getRegistrationId();
case PNI -> device.getPhoneNumberIdentityRegistrationId().orElse(device.getRegistrationId());
};
return pqPreKeyFuture.thenCombine(unsignedEcPreKeyFuture,
(maybePqPreKey, maybeUnsignedEcPreKey) -> {
responseItems.add(new PreKeyResponseItem(device.getId(), registrationId, signedECPreKey, unsignedECPreKey, pqPreKey));
}
}
KEMSignedPreKey pqPreKey = pqPreKeyFuture.join().orElse(null);
ECPreKey unsignedECPreKey = unsignedEcPreKeyFuture.join().orElse(null);
final IdentityKey identityKey = switch (targetIdentifier.identityType()) {
case ACI -> target.getIdentityKey();
case PNI -> target.getPhoneNumberIdentityKey();
};
compareSignedEcPreKeysExperiment.compareFutureResult(Optional.ofNullable(signedECPreKey),
keys.getEcSignedPreKey(targetIdentifier.uuid(), device.getId()));
if (signedECPreKey != null || unsignedECPreKey != null || pqPreKey != null) {
final int registrationId = switch (targetIdentifier.identityType()) {
case ACI -> device.getRegistrationId();
case PNI -> device.getPhoneNumberIdentityRegistrationId().orElse(device.getRegistrationId());
};
responseItems.add(
new PreKeyResponseItem(device.getId(), registrationId, signedECPreKey, unsignedECPreKey,
pqPreKey));
}
return null;
}).thenRun(Util.NOOP);
})
.toList();
CompletableFuture.allOf(tasks.toArray(new CompletableFuture[0])).join();
final IdentityKey identityKey = target.getIdentityKey(targetIdentifier.identityType());
if (responseItems.isEmpty()) {
throw new WebApplicationException(Response.Status.NOT_FOUND);
@@ -277,7 +288,6 @@ public class KeysController {
return new PreKeyResponse(identityKey, responseItems);
}
@Timed
@PUT
@Path("/signed")
@Consumes(MediaType.APPLICATION_JSON)
@@ -289,7 +299,7 @@ public class KeysController {
@ApiResponse(responseCode = "200", description = "Indicates that new prekey was successfully stored.")
@ApiResponse(responseCode = "401", description = "Account authentication check failed.")
@ApiResponse(responseCode = "422", description = "Invalid request format.")
public void setSignedKey(@Auth final AuthenticatedAccount auth,
public CompletableFuture<Void> setSignedKey(@Auth final AuthenticatedAccount auth,
@Valid final ECSignedPreKey signedPreKey,
@QueryParam("identity") final Optional<String> identityType) {
@@ -303,7 +313,8 @@ public class KeysController {
}
});
keys.storeEcSignedPreKeys(getIdentifier(auth.getAccount(), identityType), Map.of(device.getId(), signedPreKey)).join();
return keys.storeEcSignedPreKeys(getIdentifier(auth.getAccount(), identityType),
Map.of(device.getId(), signedPreKey));
}
private static boolean usePhoneNumberIdentity(final Optional<String> identityType) {
@@ -5,7 +5,6 @@
package org.whispersystems.textsecuregcm.controllers;
import com.codahale.metrics.annotation.Timed;
import io.dropwizard.auth.Auth;
import io.swagger.v3.oas.annotations.tags.Tag;
import javax.ws.rs.GET;
@@ -40,7 +39,6 @@ public class PaymentsController {
this.paymentsServiceCredentialsGenerator = paymentsServiceCredentialsGenerator;
}
@Timed
@GET
@Path("/auth")
@Produces(MediaType.APPLICATION_JSON)
@@ -48,7 +46,6 @@ public class PaymentsController {
return paymentsServiceCredentialsGenerator.generateForUuid(auth.getAccount().getUuid());
}
@Timed
@GET
@Path("/conversions")
@Produces(MediaType.APPLICATION_JSON)
@@ -7,7 +7,6 @@ package org.whispersystems.textsecuregcm.controllers;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import com.codahale.metrics.annotation.Timed;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import io.dropwizard.auth.Auth;
@@ -18,12 +17,9 @@ import io.swagger.v3.oas.annotations.tags.Tag;
import io.vavr.Tuple;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Arrays;
@@ -31,17 +27,16 @@ import java.util.Base64;
import java.util.Collection;
import java.util.Collections;
import java.util.HexFormat;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.ws.rs.BadRequestException;
@@ -88,11 +83,11 @@ import org.whispersystems.textsecuregcm.entities.BatchIdentityCheckResponse;
import org.whispersystems.textsecuregcm.entities.CreateProfileRequest;
import org.whispersystems.textsecuregcm.entities.CredentialProfileResponse;
import org.whispersystems.textsecuregcm.entities.ExpiringProfileKeyCredentialProfileResponse;
import org.whispersystems.textsecuregcm.entities.ProfileAvatarUploadAttributes;
import org.whispersystems.textsecuregcm.entities.UserCapabilities;
import org.whispersystems.textsecuregcm.entities.VersionedProfileResponse;
import org.whispersystems.textsecuregcm.grpc.ProfileHelper;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
@@ -105,7 +100,6 @@ import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.DynamicConfigurationManager;
import org.whispersystems.textsecuregcm.storage.ProfilesManager;
import org.whispersystems.textsecuregcm.storage.VersionedProfile;
import org.whispersystems.textsecuregcm.util.Pair;
import org.whispersystems.textsecuregcm.util.Util;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.DeleteObjectRequest;
@@ -172,7 +166,6 @@ public class ProfileController {
this.batchIdentityCheckExecutor = Preconditions.checkNotNull(batchIdentityCheckExecutor);
}
@Timed
@PUT
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@@ -186,15 +179,15 @@ public class ProfileController {
dynamicConfigurationManager.getConfiguration().getPaymentsConfiguration().getDisallowedPrefixes().stream()
.anyMatch(prefix -> auth.getAccount().getNumber().startsWith(prefix));
if (hasDisallowedPrefix && currentProfile.map(VersionedProfile::getPaymentAddress).isEmpty()) {
if (hasDisallowedPrefix && currentProfile.map(VersionedProfile::paymentAddress).isEmpty()) {
return Response.status(Response.Status.FORBIDDEN).build();
}
}
Optional<String> currentAvatar = Optional.empty();
if (currentProfile.isPresent() && currentProfile.get().getAvatar() != null && currentProfile.get().getAvatar()
if (currentProfile.isPresent() && currentProfile.get().avatar() != null && currentProfile.get().avatar()
.startsWith("profiles/")) {
currentAvatar = Optional.of(currentProfile.get().getAvatar());
currentAvatar = Optional.of(currentProfile.get().avatar());
}
final String avatar = switch (request.getAvatarChange()) {
@@ -206,11 +199,11 @@ public class ProfileController {
profilesManager.set(auth.getAccount().getUuid(),
new VersionedProfile(
request.getVersion(),
request.getName(),
decodeFromBase64(request.getName()),
avatar,
request.getAboutEmoji(),
request.getAbout(),
request.getPaymentAddress(),
decodeFromBase64(request.getAboutEmoji()),
decodeFromBase64(request.getAbout()),
decodeFromBase64(request.getPaymentAddress()),
request.getCommitment().serialize()));
if (request.getAvatarChange() != CreateProfileRequest.AvatarChange.UNCHANGED) {
@@ -236,7 +229,6 @@ public class ProfileController {
}
}
@Timed
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/{identifier}/{version}")
@@ -257,7 +249,6 @@ public class ProfileController {
containerRequestContext);
}
@Timed
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/{identifier}/{version}/{credentialRequest}")
@@ -289,7 +280,6 @@ public class ProfileController {
// Although clients should generally be using versioned profiles wherever possible, there are still a few lingering
// use cases for getting profiles without a version (e.g. getting a contact's unidentified access key checksum).
@Timed
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/{identifier}")
@@ -332,7 +322,6 @@ public class ProfileController {
};
}
@Timed
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@@ -420,16 +409,17 @@ public class ProfileController {
VERSION_NOT_FOUND_COUNTER.increment();
}
final String name = maybeProfile.map(VersionedProfile::getName).orElse(null);
final String about = maybeProfile.map(VersionedProfile::getAbout).orElse(null);
final String aboutEmoji = maybeProfile.map(VersionedProfile::getAboutEmoji).orElse(null);
final String avatar = maybeProfile.map(VersionedProfile::getAvatar).orElse(null);
final String name = maybeProfile.map(VersionedProfile::name).map(ProfileController::encodeToBase64).orElse(null);
final String about = maybeProfile.map(VersionedProfile::about).map(ProfileController::encodeToBase64).orElse(null);
final String aboutEmoji = maybeProfile.map(VersionedProfile::aboutEmoji).map(ProfileController::encodeToBase64).orElse(null);
final String avatar = maybeProfile.map(VersionedProfile::avatar).orElse(null);
// Allow requests where either the version matches the latest version on Account or the latest version on Account
// is empty to read the payment address.
final String paymentAddress = maybeProfile
.filter(p -> account.getCurrentProfileVersion().map(v -> v.equals(version)).orElse(true))
.map(VersionedProfile::getPaymentAddress)
.map(VersionedProfile::paymentAddress)
.map(ProfileController::encodeToBase64)
.orElse(null);
return new VersionedProfileResponse(
@@ -441,7 +431,7 @@ public class ProfileController {
final boolean isSelf,
final ContainerRequestContext containerRequestContext) {
return new BaseProfileResponse(account.getIdentityKey(),
return new BaseProfileResponse(account.getIdentityKey(IdentityType.ACI),
UnidentifiedAccessChecksum.generateFor(account.getUnidentifiedAccessKey()),
account.isUnrestrictedUnidentifiedAccess(),
UserCapabilities.createForAccount(account),
@@ -453,7 +443,7 @@ public class ProfileController {
}
private BaseProfileResponse buildBaseProfileResponseForPhoneNumberIdentity(final Account account) {
return new BaseProfileResponse(account.getPhoneNumberIdentityKey(),
return new BaseProfileResponse(account.getIdentityKey(IdentityType.PNI),
null,
false,
UserCapabilities.createForAccount(account),
@@ -468,7 +458,7 @@ public class ProfileController {
final Instant expiration) {
try {
final ProfileKeyCommitment commitment = new ProfileKeyCommitment(profile.getCommitment());
final ProfileKeyCommitment commitment = new ProfileKeyCommitment(profile.commitment());
final ProfileKeyCredentialRequest request = new ProfileKeyCredentialRequest(
HexFormat.of().parseHex(encodedCredentialRequest));
@@ -530,4 +520,20 @@ public class ProfileController {
private boolean isSelfProfileRequest(final Optional<Account> maybeRequester, final AciServiceIdentifier targetIdentifier) {
return maybeRequester.map(requester -> requester.getUuid().equals(targetIdentifier.uuid())).orElse(false);
}
@Nullable
private static byte[] decodeFromBase64(@Nullable final String input) {
if (input == null) {
return null;
}
return Base64.getDecoder().decode(input);
}
@Nullable
private static String encodeToBase64(@Nullable final byte[] input) {
if (input == null) {
return null;
}
return Base64.getEncoder().encodeToString(input);
}
}
@@ -5,7 +5,6 @@
package org.whispersystems.textsecuregcm.controllers;
import com.codahale.metrics.annotation.Timed;
import io.dropwizard.auth.Auth;
import io.swagger.v3.oas.annotations.tags.Tag;
import java.util.Base64;
@@ -37,7 +36,6 @@ public class ProvisioningController {
this.provisioningManager = provisioningManager;
}
@Timed
@Path("/{destination}")
@PUT
@Consumes(MediaType.APPLICATION_JSON)
@@ -7,7 +7,6 @@ package org.whispersystems.textsecuregcm.controllers;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import com.codahale.metrics.annotation.Timed;
import com.google.common.net.HttpHeaders;
import io.micrometer.core.instrument.DistributionSummary;
import io.micrometer.core.instrument.Metrics;
@@ -34,8 +33,6 @@ import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.auth.BasicAuthorizationHeader;
import org.whispersystems.textsecuregcm.auth.PhoneVerificationTokenManager;
import org.whispersystems.textsecuregcm.auth.RegistrationLockVerificationManager;
@@ -57,8 +54,6 @@ import org.whispersystems.textsecuregcm.util.Util;
@io.swagger.v3.oas.annotations.tags.Tag(name = "Registration")
public class RegistrationController {
private static final Logger logger = LoggerFactory.getLogger(RegistrationController.class);
private static final DistributionSummary REREGISTRATION_IDLE_DAYS_DISTRIBUTION = DistributionSummary
.builder(name(RegistrationController.class, "reregistrationIdleDays"))
.publishPercentiles(0.75, 0.95, 0.99, 0.999)
@@ -90,7 +85,6 @@ public class RegistrationController {
this.rateLimiters = rateLimiters;
}
@Timed
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@@ -5,7 +5,6 @@
package org.whispersystems.textsecuregcm.controllers;
import com.codahale.metrics.annotation.Timed;
import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken;
import com.google.api.client.googleapis.auth.oauth2.GoogleIdTokenVerifier;
import com.google.common.annotations.VisibleForTesting;
@@ -76,7 +75,6 @@ public class RemoteConfigController {
this.googleIdTokenVerifier = googleIdTokenVerifierBuilder.setAudience(audience).build();
}
@Timed
@GET
@Produces(MediaType.APPLICATION_JSON)
public UserRemoteConfigList getAll(@Auth AuthenticatedAccount auth) {
@@ -98,7 +96,6 @@ public class RemoteConfigController {
}
}
@Timed
@PUT
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@@ -123,7 +120,6 @@ public class RemoteConfigController {
remoteConfigsManager.set(config);
}
@Timed
@DELETE
@Path("/{name}")
public void delete(@HeaderParam("Config-Token") String configToken, @PathParam("name") String name) {
@@ -7,7 +7,6 @@ package org.whispersystems.textsecuregcm.controllers;
import static java.util.Objects.requireNonNull;
import com.codahale.metrics.annotation.Timed;
import io.dropwizard.auth.Auth;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
@@ -69,7 +68,6 @@ public class SecureBackupController {
this.accountsManager = requireNonNull(accountsManager);
}
@Timed
@GET
@Path("/auth")
@Produces(MediaType.APPLICATION_JSON)
@@ -86,7 +84,6 @@ public class SecureBackupController {
return credentialsGenerator.generateForUuid(auth.getAccount().getUuid());
}
@Timed
@POST
@Path("/auth/check")
@Consumes(MediaType.APPLICATION_JSON)
@@ -5,7 +5,6 @@
package org.whispersystems.textsecuregcm.controllers;
import com.codahale.metrics.annotation.Timed;
import io.dropwizard.auth.Auth;
import io.swagger.v3.oas.annotations.tags.Tag;
import javax.ws.rs.GET;
@@ -34,7 +33,6 @@ public class SecureStorageController {
this.storageServiceCredentialsGenerator = storageServiceCredentialsGenerator;
}
@Timed
@GET
@Path("/auth")
@Produces(MediaType.APPLICATION_JSON)
@@ -5,7 +5,6 @@
package org.whispersystems.textsecuregcm.controllers;
import com.codahale.metrics.annotation.Timed;
import io.dropwizard.auth.Auth;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
@@ -66,7 +65,6 @@ public class SecureValueRecovery2Controller {
this.accountsManager = accountsManager;
}
@Timed
@GET
@Path("/auth")
@Produces(MediaType.APPLICATION_JSON)
@@ -84,7 +82,6 @@ public class SecureValueRecovery2Controller {
}
@Timed
@POST
@Path("/auth/check")
@Consumes(MediaType.APPLICATION_JSON)
@@ -7,7 +7,6 @@ package org.whispersystems.textsecuregcm.controllers;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import com.codahale.metrics.annotation.Timed;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
@@ -220,7 +219,6 @@ public class SubscriptionController {
return new GetSubscriptionConfigurationResponse(currencyConfiguration, levels);
}
@Timed
@DELETE
@Path("/{subscriberId}")
@Produces(MediaType.APPLICATION_JSON)
@@ -242,7 +240,6 @@ public class SubscriptionController {
.thenApply(unused -> Response.ok().build());
}
@Timed
@PUT
@Path("/{subscriberId}")
@Consumes(MediaType.APPLICATION_JSON)
@@ -277,7 +274,6 @@ public class SubscriptionController {
}
@Timed
@POST
@Path("/{subscriberId}/create_payment_method")
@Consumes(MediaType.APPLICATION_JSON)
@@ -332,7 +328,6 @@ public class SubscriptionController {
}
@Timed
@POST
@Path("/{subscriberId}/create_payment_method/paypal")
@Consumes(MediaType.APPLICATION_JSON)
@@ -396,7 +391,6 @@ public class SubscriptionController {
};
}
@Timed
@POST
@Path("/{subscriberId}/default_payment_method/{paymentMethodId}")
@Consumes(MediaType.APPLICATION_JSON)
@@ -414,7 +408,6 @@ public class SubscriptionController {
.thenApply(customer -> Response.ok().build());
}
@Timed
@POST
@Path("/{subscriberId}/default_payment_method/{processor}/{paymentMethodToken}")
@Consumes(MediaType.APPLICATION_JSON)
@@ -497,7 +490,6 @@ public class SubscriptionController {
}
}
@Timed
@PUT
@Path("/{subscriberId}/level/{level}/{currency}/{idempotencyKey}")
@Consumes(MediaType.APPLICATION_JSON)
@@ -655,7 +647,6 @@ public class SubscriptionController {
}
@Timed
@GET
@Path("/configuration")
@Produces(MediaType.APPLICATION_JSON)
@@ -666,7 +657,6 @@ public class SubscriptionController {
});
}
@Timed
@GET
@Path("/levels")
@Produces(MediaType.APPLICATION_JSON)
@@ -714,7 +704,6 @@ public class SubscriptionController {
}
}
@Timed
@GET
@Path("/boost/badges")
@Produces(MediaType.APPLICATION_JSON)
@@ -737,7 +726,6 @@ public class SubscriptionController {
});
}
@Timed
@GET
@Path("/boost/amounts")
@Produces(MediaType.APPLICATION_JSON)
@@ -749,7 +737,6 @@ public class SubscriptionController {
.build());
}
@Timed
@GET
@Path("/boost/amounts/gift")
@Produces(MediaType.APPLICATION_JSON)
@@ -801,7 +788,6 @@ public class SubscriptionController {
/**
* Creates a Stripe PaymentIntent with the requested amount and currency
*/
@Timed
@POST
@Path("/boost/create")
@Consumes(MediaType.APPLICATION_JSON)
@@ -855,7 +841,6 @@ public class SubscriptionController {
}
}
@Timed
@POST
@Path("/boost/paypal/create")
@Consumes(MediaType.APPLICATION_JSON)
@@ -898,7 +883,6 @@ public class SubscriptionController {
}
@Timed
@POST
@Path("/boost/paypal/confirm")
@Consumes(MediaType.APPLICATION_JSON)
@@ -945,7 +929,6 @@ public class SubscriptionController {
}
}
@Timed
@POST
@Path("/boost/receipt_credentials")
@Consumes(MediaType.APPLICATION_JSON)
@@ -1158,7 +1141,6 @@ public class SubscriptionController {
}
}
@Timed
@GET
@Path("/{subscriberId}")
@Produces(MediaType.APPLICATION_JSON)
@@ -1236,7 +1218,6 @@ public class SubscriptionController {
}
}
@Timed
@POST
@Path("/{subscriberId}/receipt_credentials")
@Consumes(MediaType.APPLICATION_JSON)
@@ -7,7 +7,6 @@ package org.whispersystems.textsecuregcm.controllers;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import com.codahale.metrics.annotation.Timed;
import com.google.i18n.phonenumbers.NumberParseException;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.Phonenumber;
@@ -78,8 +77,8 @@ import org.whispersystems.textsecuregcm.registration.TransportNotAllowedExceptio
import org.whispersystems.textsecuregcm.registration.VerificationSession;
import org.whispersystems.textsecuregcm.spam.Extract;
import org.whispersystems.textsecuregcm.spam.FilterSpam;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.spam.ScoreThreshold;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.RegistrationRecoveryPasswordsManager;
import org.whispersystems.textsecuregcm.storage.VerificationSessionManager;
import org.whispersystems.textsecuregcm.util.ExceptionUtils;
@@ -137,7 +136,6 @@ public class VerificationController {
this.clock = clock;
}
@Timed
@POST
@Path("/session")
@Consumes(MediaType.APPLICATION_JSON)
@@ -188,7 +186,6 @@ public class VerificationController {
return buildResponse(registrationServiceSession, verificationSession);
}
@Timed
@FilterSpam
@PATCH
@Path("/session/{sessionId}")
@@ -411,7 +408,6 @@ public class VerificationController {
return verificationSession;
}
@Timed
@GET
@Path("/session/{sessionId}")
@Produces(MediaType.APPLICATION_JSON)
@@ -423,7 +419,6 @@ public class VerificationController {
return buildResponse(registrationServiceSession, verificationSession);
}
@Timed
@POST
@Path("/session/{sessionId}/code")
@Consumes(MediaType.APPLICATION_JSON)
@@ -518,7 +513,6 @@ public class VerificationController {
return buildResponse(resultSession, verificationSession);
}
@Timed
@PUT
@Path("/session/{sessionId}/code")
@Consumes(MediaType.APPLICATION_JSON)
@@ -5,25 +5,5 @@
package org.whispersystems.textsecuregcm.entities;
import com.fasterxml.jackson.annotation.JsonProperty;
public class DeviceInfo {
@JsonProperty
private long id;
@JsonProperty
private String name;
@JsonProperty
private long lastSeen;
@JsonProperty
private long created;
public DeviceInfo(long id, String name, long lastSeen, long created) {
this.id = id;
this.name = name;
this.lastSeen = lastSeen;
this.created = created;
}
public record DeviceInfo(long id, String name, long lastSeen, long created) {
}
@@ -5,16 +5,7 @@
package org.whispersystems.textsecuregcm.entities;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
public class DeviceInfoList {
@JsonProperty
private List<DeviceInfo> devices;
public DeviceInfoList(List<DeviceInfo> devices) {
this.devices = devices;
}
public record DeviceInfoList(List<DeviceInfo> devices) {
}
@@ -0,0 +1,212 @@
/*
* Copyright 2023 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.grpc;
import com.google.protobuf.ByteString;
import io.grpc.Status;
import java.util.Base64;
import java.util.Objects;
import javax.annotation.Nullable;
import org.apache.commons.lang3.StringUtils;
import org.signal.chat.device.ClearPushTokenRequest;
import org.signal.chat.device.ClearPushTokenResponse;
import org.signal.chat.device.GetDevicesRequest;
import org.signal.chat.device.GetDevicesResponse;
import org.signal.chat.device.ReactorDevicesGrpc;
import org.signal.chat.device.RemoveDeviceRequest;
import org.signal.chat.device.RemoveDeviceResponse;
import org.signal.chat.device.SetCapabilitiesRequest;
import org.signal.chat.device.SetCapabilitiesResponse;
import org.signal.chat.device.SetDeviceNameRequest;
import org.signal.chat.device.SetDeviceNameResponse;
import org.signal.chat.device.SetPushTokenRequest;
import org.signal.chat.device.SetPushTokenResponse;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticatedDevice;
import org.whispersystems.textsecuregcm.auth.grpc.AuthenticationUtil;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.KeysManager;
import org.whispersystems.textsecuregcm.storage.MessagesManager;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
public class DevicesGrpcService extends ReactorDevicesGrpc.DevicesImplBase {
private final AccountsManager accountsManager;
private final KeysManager keysManager;
private final MessagesManager messagesManager;
private static final int MAX_NAME_LENGTH = 256;
public DevicesGrpcService(final AccountsManager accountsManager,
final KeysManager keysManager,
final MessagesManager messagesManager) {
this.accountsManager = accountsManager;
this.keysManager = keysManager;
this.messagesManager = messagesManager;
}
@Override
public Mono<GetDevicesResponse> getDevices(final GetDevicesRequest request) {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
return Mono.fromFuture(() -> accountsManager.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier()))
.map(maybeAccount -> maybeAccount.orElseThrow(Status.UNAUTHENTICATED::asRuntimeException))
.flatMapMany(account -> Flux.fromIterable(account.getDevices()))
.reduce(GetDevicesResponse.newBuilder(), (builder, device) -> {
final GetDevicesResponse.LinkedDevice.Builder linkedDeviceBuilder = GetDevicesResponse.LinkedDevice.newBuilder();
if (StringUtils.isNotBlank(device.getName())) {
linkedDeviceBuilder.setName(ByteString.copyFrom(Base64.getDecoder().decode(device.getName())));
}
return builder.addDevices(linkedDeviceBuilder
.setId(device.getId())
.setCreated(device.getCreated())
.setLastSeen(device.getLastSeen())
.build());
})
.map(GetDevicesResponse.Builder::build);
}
@Override
public Mono<RemoveDeviceResponse> removeDevice(final RemoveDeviceRequest request) {
if (request.getId() == Device.MASTER_ID) {
throw Status.INVALID_ARGUMENT.withDescription("Cannot remove primary device").asRuntimeException();
}
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedPrimaryDevice();
return Mono.fromFuture(() -> accountsManager.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier()))
.map(maybeAccount -> maybeAccount.orElseThrow(Status.UNAUTHENTICATED::asRuntimeException))
.flatMap(account -> Flux.merge(
Mono.fromFuture(() -> messagesManager.clear(account.getUuid(), request.getId())),
Mono.fromFuture(() -> keysManager.delete(account.getUuid(), request.getId())))
.then(Mono.fromFuture(() -> accountsManager.updateAsync(account, a -> a.removeDevice(request.getId()))))
// Some messages may have arrived while we were performing the other updates; make a best effort to clear
// those out, too
.then(Mono.fromFuture(() -> messagesManager.clear(account.getUuid(), request.getId()))))
.thenReturn(RemoveDeviceResponse.newBuilder().build());
}
@Override
public Mono<SetDeviceNameResponse> setDeviceName(final SetDeviceNameRequest request) {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
if (request.getName().isEmpty()) {
throw Status.INVALID_ARGUMENT.withDescription("Must specify a device name").asRuntimeException();
}
if (request.getName().size() > MAX_NAME_LENGTH) {
throw Status.INVALID_ARGUMENT.withDescription("Device name must be at most " + MAX_NAME_LENGTH + " bytes")
.asRuntimeException();
}
return Mono.fromFuture(() -> accountsManager.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier()))
.map(maybeAccount -> maybeAccount.orElseThrow(Status.UNAUTHENTICATED::asRuntimeException))
.flatMap(account -> Mono.fromFuture(() -> accountsManager.updateDeviceAsync(account, authenticatedDevice.deviceId(),
device -> device.setName(Base64.getEncoder().encodeToString(request.getName().toByteArray())))))
.thenReturn(SetDeviceNameResponse.newBuilder().build());
}
@Override
public Mono<SetPushTokenResponse> setPushToken(final SetPushTokenRequest request) {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
@Nullable final String apnsToken;
@Nullable final String apnsVoipToken;
@Nullable final String fcmToken;
switch (request.getTokenRequestCase()) {
case APNS_TOKEN_REQUEST -> {
final SetPushTokenRequest.ApnsTokenRequest apnsTokenRequest = request.getApnsTokenRequest();
if (StringUtils.isAllBlank(apnsTokenRequest.getApnsToken(), apnsTokenRequest.getApnsVoipToken())) {
throw Status.INVALID_ARGUMENT.withDescription("APNs tokens may not both be blank").asRuntimeException();
}
apnsToken = StringUtils.stripToNull(apnsTokenRequest.getApnsToken());
apnsVoipToken = StringUtils.stripToNull(apnsTokenRequest.getApnsVoipToken());
fcmToken = null;
}
case FCM_TOKEN_REQUEST -> {
final SetPushTokenRequest.FcmTokenRequest fcmTokenRequest = request.getFcmTokenRequest();
if (StringUtils.isBlank(fcmTokenRequest.getFcmToken())) {
throw Status.INVALID_ARGUMENT.withDescription("FCM token must not be blank").asRuntimeException();
}
apnsToken = null;
apnsVoipToken = null;
fcmToken = StringUtils.stripToNull(fcmTokenRequest.getFcmToken());
}
default -> throw Status.INVALID_ARGUMENT.withDescription("No tokens specified").asRuntimeException();
}
return Mono.fromFuture(() -> accountsManager.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier()))
.map(maybeAccount -> maybeAccount.orElseThrow(Status.UNAUTHENTICATED::asRuntimeException))
.flatMap(account -> {
final Device device = account.getDevice(authenticatedDevice.deviceId())
.orElseThrow(Status.UNAUTHENTICATED::asRuntimeException);
final boolean tokenUnchanged =
Objects.equals(device.getApnId(), apnsToken) &&
Objects.equals(device.getVoipApnId(), apnsVoipToken) &&
Objects.equals(device.getGcmId(), fcmToken);
return tokenUnchanged
? Mono.empty()
: Mono.fromFuture(() -> accountsManager.updateDeviceAsync(account, authenticatedDevice.deviceId(), d -> {
d.setApnId(apnsToken);
d.setVoipApnId(apnsVoipToken);
d.setGcmId(fcmToken);
d.setFetchesMessages(false);
}));
})
.thenReturn(SetPushTokenResponse.newBuilder().build());
}
@Override
public Mono<ClearPushTokenResponse> clearPushToken(final ClearPushTokenRequest request) {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
return Mono.fromFuture(() -> accountsManager.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier()))
.map(maybeAccount -> maybeAccount.orElseThrow(Status.UNAUTHENTICATED::asRuntimeException))
.flatMap(account -> Mono.fromFuture(() -> accountsManager.updateDeviceAsync(account, authenticatedDevice.deviceId(), device -> {
if (StringUtils.isNotBlank(device.getApnId()) || StringUtils.isNotBlank(device.getVoipApnId())) {
device.setUserAgent(device.isMaster() ? "OWI" : "OWP");
} else if (StringUtils.isNotBlank(device.getGcmId())) {
device.setUserAgent("OWA");
}
device.setApnId(null);
device.setVoipApnId(null);
device.setGcmId(null);
device.setFetchesMessages(true);
})))
.thenReturn(ClearPushTokenResponse.newBuilder().build());
}
@Override
public Mono<SetCapabilitiesResponse> setCapabilities(final SetCapabilitiesRequest request) {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedDevice();
return Mono.fromFuture(() -> accountsManager.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier()))
.map(maybeAccount -> maybeAccount.orElseThrow(Status.UNAUTHENTICATED::asRuntimeException))
.flatMap(account ->
Mono.fromFuture(() -> accountsManager.updateDeviceAsync(account, authenticatedDevice.deviceId(),
d -> d.setCapabilities(new Device.DeviceCapabilities(
request.getStorage(),
request.getTransfer(),
request.getPni(),
request.getPaymentActivation())))))
.thenReturn(SetCapabilitiesResponse.newBuilder().build());
}
}
@@ -30,7 +30,7 @@ public class KeysAnonymousGrpcService extends ReactorKeysAnonymousGrpc.KeysAnony
final ServiceIdentifier serviceIdentifier =
ServiceIdentifierUtil.fromGrpcServiceIdentifier(request.getRequest().getTargetIdentifier());
return Mono.fromFuture(accountsManager.getByServiceIdentifierAsync(serviceIdentifier))
return Mono.fromFuture(() -> accountsManager.getByServiceIdentifierAsync(serviceIdentifier))
.flatMap(Mono::justOrEmpty)
.switchIfEmpty(Mono.error(Status.UNAUTHENTICATED.asException()))
.flatMap(targetAccount ->
@@ -52,8 +52,8 @@ class KeysGrpcHelper {
.build());
return Flux.merge(
Mono.fromFuture(keysManager.takeEC(targetAccount.getIdentifier(identityType), device.getId())),
Mono.fromFuture(keysManager.takePQ(targetAccount.getIdentifier(identityType), device.getId())))
Mono.fromFuture(() -> keysManager.takeEC(targetAccount.getIdentifier(identityType), device.getId())),
Mono.fromFuture(() -> keysManager.takePQ(targetAccount.getIdentifier(identityType), device.getId())))
.flatMap(Mono::justOrEmpty)
.reduce(preKeyBundleBuilder, (builder, preKey) -> {
if (preKey instanceof ECPreKey ecPreKey) {
@@ -82,7 +82,7 @@ public class KeysGrpcService extends ReactorKeysGrpc.KeysImplBase {
@Override
public Mono<GetPreKeyCountResponse> getPreKeyCount(final GetPreKeyCountRequest request) {
return Mono.fromSupplier(AuthenticationUtil::requireAuthenticatedDevice)
.flatMap(authenticatedDevice -> Mono.fromFuture(accountsManager.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier()))
.flatMap(authenticatedDevice -> Mono.fromFuture(() -> accountsManager.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier()))
.map(maybeAccount -> maybeAccount
.map(account -> Tuples.of(account, authenticatedDevice.deviceId()))
.orElseThrow(Status.UNAUTHENTICATED::asRuntimeException)))
@@ -91,10 +91,10 @@ public class KeysGrpcService extends ReactorKeysGrpc.KeysImplBase {
Tuples.of(IdentityType.PNI, accountAndDeviceId.getT1().getPhoneNumberIdentifier(), accountAndDeviceId.getT2())
))
.flatMap(identityTypeUuidAndDeviceId -> Flux.merge(
Mono.fromFuture(keysManager.getEcCount(identityTypeUuidAndDeviceId.getT2(), identityTypeUuidAndDeviceId.getT3()))
Mono.fromFuture(() -> keysManager.getEcCount(identityTypeUuidAndDeviceId.getT2(), identityTypeUuidAndDeviceId.getT3()))
.map(ecKeyCount -> Tuples.of(identityTypeUuidAndDeviceId.getT1(), PreKeyType.EC, ecKeyCount)),
Mono.fromFuture(keysManager.getPqCount(identityTypeUuidAndDeviceId.getT2(), identityTypeUuidAndDeviceId.getT3()))
Mono.fromFuture(() -> keysManager.getPqCount(identityTypeUuidAndDeviceId.getT2(), identityTypeUuidAndDeviceId.getT3()))
.map(ecKeyCount -> Tuples.of(identityTypeUuidAndDeviceId.getT1(), PreKeyType.KEM, ecKeyCount))
))
.reduce(GetPreKeyCountResponse.newBuilder(), (builder, tuple) -> {
@@ -135,7 +135,7 @@ public class KeysGrpcService extends ReactorKeysGrpc.KeysImplBase {
request.getDeviceId();
return rateLimiters.getPreKeysLimiter().validateReactive(rateLimitKey)
.then(Mono.fromFuture(accountsManager.getByServiceIdentifierAsync(targetIdentifier))
.then(Mono.fromFuture(() -> accountsManager.getByServiceIdentifierAsync(targetIdentifier))
.flatMap(Mono::justOrEmpty))
.switchIfEmpty(Mono.error(Status.NOT_FOUND.asException()))
.flatMap(targetAccount ->
@@ -168,7 +168,7 @@ public class KeysGrpcService extends ReactorKeysGrpc.KeysImplBase {
final BiFunction<R, IdentityKey, K> extractPreKeyFunction,
final BiFunction<UUID, List<K>, CompletableFuture<Void>> storeKeysFunction) {
return Mono.fromFuture(accountsManager.getByAccountIdentifierAsync(authenticatedAccountUuid))
return Mono.fromFuture(() -> accountsManager.getByAccountIdentifierAsync(authenticatedAccountUuid))
.map(maybeAccount -> maybeAccount.orElseThrow(Status.UNAUTHENTICATED::asRuntimeException))
.map(account -> {
final List<K> preKeys = requestPreKeys.stream()
@@ -181,7 +181,7 @@ public class KeysGrpcService extends ReactorKeysGrpc.KeysImplBase {
return Tuples.of(account.getIdentifier(identityType), preKeys);
})
.flatMap(identifierAndPreKeys -> Mono.fromFuture(storeKeysFunction.apply(identifierAndPreKeys.getT1(), identifierAndPreKeys.getT2())))
.flatMap(identifierAndPreKeys -> Mono.fromFuture(() -> storeKeysFunction.apply(identifierAndPreKeys.getT1(), identifierAndPreKeys.getT2())))
.thenReturn(SetPreKeyResponse.newBuilder().build());
}
@@ -203,8 +203,8 @@ public class KeysGrpcService extends ReactorKeysGrpc.KeysImplBase {
final UUID identifier = account.getIdentifier(identityType);
return Flux.merge(
Mono.fromFuture(keysManager.storeEcSignedPreKeys(identifier, Map.of(authenticatedDevice.deviceId(), signedPreKey))),
Mono.fromFuture(accountsManager.updateDeviceAsync(account, authenticatedDevice.deviceId(), deviceUpdater)))
Mono.fromFuture(() -> keysManager.storeEcSignedPreKeys(identifier, Map.of(authenticatedDevice.deviceId(), signedPreKey))),
Mono.fromFuture(() -> accountsManager.updateDeviceAsync(account, authenticatedDevice.deviceId(), deviceUpdater)))
.then();
}));
}
@@ -220,7 +220,7 @@ public class KeysGrpcService extends ReactorKeysGrpc.KeysImplBase {
final UUID identifier =
account.getIdentifier(IdentityTypeUtil.fromGrpcIdentityType(request.getIdentityType()));
return Mono.fromFuture(keysManager.storePqLastResort(identifier, Map.of(authenticatedDevice.deviceId(), lastResortKey)));
return Mono.fromFuture(() -> keysManager.storePqLastResort(identifier, Map.of(authenticatedDevice.deviceId(), lastResortKey)));
}));
}
@@ -230,7 +230,7 @@ public class KeysGrpcService extends ReactorKeysGrpc.KeysImplBase {
final BiFunction<R, IdentityKey, K> extractKeyFunction,
final BiFunction<Account, K, Mono<?>> storeKeyFunction) {
return Mono.fromFuture(accountsManager.getByAccountIdentifierAsync(authenticatedAccountUuid))
return Mono.fromFuture(() -> accountsManager.getByAccountIdentifierAsync(authenticatedAccountUuid))
.map(maybeAccount -> maybeAccount.orElseThrow(Status.UNAUTHENTICATED::asRuntimeException))
.map(account -> {
final IdentityKey identityKey = account.getIdentityKey(IdentityTypeUtil.fromGrpcIdentityType(identityType));
@@ -25,7 +25,6 @@ import software.amazon.awssdk.services.s3.S3AsyncClient;
import software.amazon.awssdk.services.s3.model.DeleteObjectRequest;
import java.time.Clock;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@@ -76,23 +75,23 @@ public class ProfileGrpcService extends ReactorProfileGrpc.ProfileImplBase {
validateRequest(request);
return Mono.fromSupplier(AuthenticationUtil::requireAuthenticatedDevice)
.flatMap(authenticatedDevice -> Mono.zip(
Mono.fromFuture(accountsManager.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier()))
Mono.fromFuture(() -> accountsManager.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifier()))
.map(maybeAccount -> maybeAccount.orElseThrow(Status.UNAUTHENTICATED::asRuntimeException)),
Mono.fromFuture(profilesManager.getAsync(authenticatedDevice.accountIdentifier(), request.getVersion()))
Mono.fromFuture(() -> profilesManager.getAsync(authenticatedDevice.accountIdentifier(), request.getVersion()))
))
.doOnNext(accountAndMaybeProfile -> {
if (!request.getPaymentAddress().isEmpty()) {
final boolean hasDisallowedPrefix =
dynamicConfigurationManager.getConfiguration().getPaymentsConfiguration().getDisallowedPrefixes().stream()
.anyMatch(prefix -> accountAndMaybeProfile.getT1().getNumber().startsWith(prefix));
if (hasDisallowedPrefix && accountAndMaybeProfile.getT2().map(VersionedProfile::getPaymentAddress).isEmpty()) {
if (hasDisallowedPrefix && accountAndMaybeProfile.getT2().map(VersionedProfile::paymentAddress).isEmpty()) {
throw Status.PERMISSION_DENIED.asRuntimeException();
}
}
})
.flatMap(accountAndMaybeProfile -> {
final Account account = accountAndMaybeProfile.getT1();
final Optional<String> currentAvatar = accountAndMaybeProfile.getT2().map(VersionedProfile::getAvatar)
final Optional<String> currentAvatar = accountAndMaybeProfile.getT2().map(VersionedProfile::avatar)
.filter(avatar -> avatar.startsWith("profiles/"));
final AvatarData avatarData = switch (AvatarChangeUtil.fromGrpcAvatarChange(request.getAvatarChange())) {
case AVATAR_CHANGE_UNCHANGED -> new AvatarData(currentAvatar, currentAvatar, Optional.empty());
@@ -104,14 +103,14 @@ public class ProfileGrpcService extends ReactorProfileGrpc.ProfileImplBase {
}
};
final Mono<Void> profileSetMono = Mono.fromFuture(profilesManager.setAsync(account.getUuid(),
final Mono<Void> profileSetMono = Mono.fromFuture(() -> profilesManager.setAsync(account.getUuid(),
new VersionedProfile(
request.getVersion(),
encodeToBase64(request.getName().toByteArray()),
request.getName().toByteArray(),
avatarData.finalAvatar().orElse(null),
encodeToBase64(request.getAboutEmoji().toByteArray()),
encodeToBase64(request.getAbout().toByteArray()),
encodeToBase64(request.getPaymentAddress().toByteArray()),
request.getAboutEmoji().toByteArray(),
request.getAbout().toByteArray(),
request.getPaymentAddress().toByteArray(),
request.getCommitment().toByteArray())));
final List<Mono<?>> updates = new ArrayList<>(2);
@@ -119,12 +118,13 @@ public class ProfileGrpcService extends ReactorProfileGrpc.ProfileImplBase {
.map(badges -> ProfileHelper.mergeBadgeIdsWithExistingAccountBadges(clock, badgeConfigurationMap, badges, account.getBadges()))
.orElseGet(account::getBadges);
updates.add(Mono.fromFuture(accountsManager.updateAsync(account, a -> {
updates.add(Mono.fromFuture(() -> accountsManager.updateAsync(account, a -> {
a.setBadges(clock, updatedBadges);
a.setCurrentProfileVersion(request.getVersion());
})));
if (request.getAvatarChange() != AvatarChange.AVATAR_CHANGE_UNCHANGED && avatarData.currentAvatar().isPresent()) {
updates.add(Mono.fromFuture(asyncS3client.deleteObject(DeleteObjectRequest.builder()
updates.add(Mono.fromFuture(() -> asyncS3client.deleteObject(DeleteObjectRequest.builder()
.bucket(bucket)
.key(avatarData.currentAvatar().get())
.build())));
@@ -163,8 +163,4 @@ public class ProfileGrpcService extends ReactorProfileGrpc.ProfileImplBase {
throw Status.INVALID_ARGUMENT.withDescription(errorMessage).asRuntimeException();
}
private static String encodeToBase64(byte[] input) {
return Base64.getEncoder().encodeToString(input);
}
}
@@ -55,7 +55,7 @@ public interface RateLimiter {
}
default Mono<Void> validateReactive(final String key) {
return Mono.fromFuture(validateAsync(key).toCompletableFuture());
return Mono.fromFuture(() -> validateAsync(key).toCompletableFuture());
}
default Mono<Void> validateReactive(final UUID accountUuid) {
@@ -12,9 +12,11 @@ import org.whispersystems.textsecuregcm.registration.RegistrationServiceSenderEx
public class RegistrationServiceSenderExceptionMapper implements ExceptionMapper<RegistrationServiceSenderException> {
public static int REMOTE_SERVICE_REJECTED_REQUEST_STATUS = 440;
@Override
public Response toResponse(final RegistrationServiceSenderException exception) {
return Response.status(Response.Status.BAD_GATEWAY)
return Response.status(REMOTE_SERVICE_REJECTED_REQUEST_STATUS)
.entity(new SendVerificationCodeFailureResponse(exception.getReason(), exception.isPermanent()))
.build();
}
@@ -7,15 +7,13 @@ package org.whispersystems.textsecuregcm.metrics;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import com.vdurmont.semver4j.Semver;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Timer;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.textsecuregcm.entities.MessageProtos;
@@ -23,7 +21,6 @@ import org.whispersystems.textsecuregcm.entities.OutgoingMessageEntity;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.ClientReleaseManager;
import org.whispersystems.textsecuregcm.util.ua.ClientPlatform;
public final class MessageMetrics {
@@ -32,7 +29,7 @@ public final class MessageMetrics {
private static final String MISMATCHED_ACCOUNT_ENVELOPE_UUID_COUNTER_NAME = name(MessageMetrics.class,
"mismatchedAccountEnvelopeUuid");
private static final String DELIVERY_LATENCY_TIMER_NAME = name(MessageMetrics.class, "deliveryLatency");
public static final String DELIVERY_LATENCY_TIMER_NAME = name(MessageMetrics.class, "deliveryLatency");
public static void measureAccountOutgoingMessageUuidMismatches(final Account account,
final OutgoingMessageEntity outgoingMessage) {
@@ -70,7 +67,10 @@ public final class MessageMetrics {
UserAgentTagUtil.getClientVersionTag(userAgent, clientReleaseManager).ifPresent(tags::add);
Metrics.timer(DELIVERY_LATENCY_TIMER_NAME, tags)
Timer.builder(DELIVERY_LATENCY_TIMER_NAME)
.publishPercentileHistogram(true)
.tags(tags)
.register(Metrics.globalRegistry)
.record(Duration.between(Instant.ofEpochMilli(serverTimestamp), Instant.now()));
}
}
@@ -6,17 +6,19 @@
package org.whispersystems.textsecuregcm.metrics;
import com.codahale.metrics.SharedMetricRegistries;
import com.google.common.annotations.VisibleForTesting;
import io.dropwizard.setup.Environment;
import io.micrometer.core.instrument.Meter;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tags;
import io.micrometer.core.instrument.config.MeterFilter;
import io.micrometer.core.instrument.config.MeterFilterReply;
import io.micrometer.core.instrument.distribution.DistributionStatisticConfig;
import io.micrometer.datadog.DatadogMeterRegistry;
import io.micrometer.statsd.StatsdMeterRegistry;
import java.util.concurrent.TimeUnit;
import org.whispersystems.textsecuregcm.WhisperServerConfiguration;
import org.whispersystems.textsecuregcm.WhisperServerVersion;
import org.whispersystems.textsecuregcm.push.PushLatencyManager;
import org.whispersystems.textsecuregcm.util.Constants;
import org.whispersystems.textsecuregcm.util.HostnameUtil;
@@ -43,54 +45,57 @@ public class MetricsUtil {
public static void configureRegistries(final WhisperServerConfiguration config, final Environment environment) {
SharedMetricRegistries.add(Constants.METRICS_NAME, environment.metrics());
final DistributionStatisticConfig defaultDistributionStatisticConfig = DistributionStatisticConfig.builder()
.percentiles(.75, .95, .99, .999)
.build();
{
final DatadogMeterRegistry datadogMeterRegistry = new DatadogMeterRegistry(
final StatsdMeterRegistry dogstatsdMeterRegistry = new StatsdMeterRegistry(
config.getDatadogConfiguration(), io.micrometer.core.instrument.Clock.SYSTEM);
datadogMeterRegistry.config().commonTags(
Tags.of(
"service", "chat",
"host", HostnameUtil.getLocalHostname(),
"version", WhisperServerVersion.getServerVersion(),
"env", config.getDatadogConfiguration().getEnvironment()))
.meterFilter(new MeterFilter() {
@Override
public DistributionStatisticConfig configure(final Meter.Id id, final DistributionStatisticConfig config) {
return defaultDistributionStatisticConfig.merge(config);
}
});
dogstatsdMeterRegistry.config().commonTags(
Tags.of(
"service", "chat",
"host", HostnameUtil.getLocalHostname(),
"version", WhisperServerVersion.getServerVersion(),
"env", config.getDatadogConfiguration().getEnvironment()));
datadogMeterRegistry.config()
// Deny lettuce metrics, but leave command.completions.max
.meterFilter(MeterFilter.deny(id ->
id.getName().startsWith("lettuce") && !id.getName().contains("command.completions.max")
))
// Remove high-cardinality `command` tags from Lettuce metrics and prepend "chat." to meter names
.meterFilter(new MeterFilter() {
@Override
public Meter.Id map(final Meter.Id id) {
if (id.getName().startsWith("lettuce")) {
return id.withName(PREFIX + "." + id.getName())
.replaceTags(id.getTags().stream()
.filter(tag -> !"command".equals(tag.getKey()))
.toList());
}
return MeterFilter.super.map(id);
}
});
Metrics.addRegistry(datadogMeterRegistry);
configureMeterFilters(dogstatsdMeterRegistry.config());
Metrics.addRegistry(dogstatsdMeterRegistry);
}
environment.lifecycle().manage(new MicrometerRegistryManager(Metrics.globalRegistry));
environment.lifecycle().manage(new ApplicationShutdownMonitor(Metrics.globalRegistry));
}
@VisibleForTesting
static MeterRegistry.Config configureMeterFilters(MeterRegistry.Config config) {
final DistributionStatisticConfig defaultDistributionStatisticConfig = DistributionStatisticConfig.builder()
.percentiles(.75, .95, .99, .999)
.build();
return config
.meterFilter(new MeterFilter() {
@Override
public DistributionStatisticConfig configure(final Meter.Id id, final DistributionStatisticConfig config) {
return defaultDistributionStatisticConfig.merge(config);
}
})
// Remove high-cardinality `command` and `remote` tags from Lettuce metrics and prepend "chat." to meter names
.meterFilter(new MeterFilter() {
@Override
public Meter.Id map(final Meter.Id id) {
if (id.getName().startsWith("lettuce")) {
return id.withName(PREFIX + "." + id.getName())
.replaceTags(id.getTags().stream()
.filter(tag -> !"command".equals(tag.getKey()))
.filter(tag -> !"remote".equals(tag.getKey()))
.toList());
}
return MeterFilter.super.map(id);
}
})
.meterFilter(MeterFilter.denyNameStartsWith(PushLatencyManager.TIMER_NAME + ".percentile"))
.meterFilter(MeterFilter.denyNameStartsWith(MessageMetrics.DELIVERY_LATENCY_TIMER_NAME + ".percentile"));
}
public static void registerSystemResourceMetrics(final Environment environment) {
environment.metrics().register(name(CpuUsageGauge.class, "cpu"), new CpuUsageGauge(3, TimeUnit.SECONDS));
environment.metrics().register(name(FreeMemoryGauge.class, "free_memory"), new FreeMemoryGauge());
@@ -15,11 +15,9 @@ import com.codahale.metrics.ScheduledReporter;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeName;
import io.dropwizard.metrics.BaseReporterFactory;
import io.dropwizard.util.Duration;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
import java.util.Optional;
import javax.validation.Valid;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
@@ -28,11 +26,8 @@ import org.coursera.metrics.datadog.DatadogReporter.Expansion;
import org.coursera.metrics.datadog.DefaultMetricNameFormatterFactory;
import org.coursera.metrics.datadog.DynamicTagsCallbackFactory;
import org.coursera.metrics.datadog.MetricNameFormatterFactory;
import org.coursera.metrics.datadog.transport.HttpTransport;
import org.coursera.metrics.datadog.transport.Transport;
import org.coursera.metrics.datadog.transport.UdpTransport;
import org.whispersystems.textsecuregcm.WhisperServerVersion;
import org.whispersystems.textsecuregcm.configuration.secrets.SecretString;
import org.whispersystems.textsecuregcm.util.HostnameUtil;
@JsonTypeName("signal-datadog")
@@ -53,11 +48,6 @@ public class SignalDatadogReporterFactory extends BaseReporterFactory {
@JsonProperty
private MetricNameFormatterFactory metricNameFormatter = new DefaultMetricNameFormatterFactory();
@Valid
@NotNull
@JsonProperty("transport")
private HttpTransportConfig httpTransportConfig;
@Valid
@NotNull
@JsonProperty("udpTransport")
@@ -89,12 +79,8 @@ public class SignalDatadogReporterFactory extends BaseReporterFactory {
}
}
final boolean useUdpTransport = Optional.ofNullable(System.getenv("SIGNAL_USE_DATADOG_UDP_TRANSPORT")).isPresent();
final Transport transport =
useUdpTransport ? udpTransportConfig.udpTransport() : httpTransportConfig.httpTransport();
return DatadogReporter.forRegistry(registry)
.withTransport(transport)
.withTransport(udpTransportConfig.udpTransport())
.withHost(HostnameUtil.getLocalHostname())
.withTags(tagsWithVersion)
.withPrefix(prefix)
@@ -107,28 +93,6 @@ public class SignalDatadogReporterFactory extends BaseReporterFactory {
.build();
}
public static class HttpTransportConfig {
@JsonProperty
@NotNull
private SecretString apiKey;
@JsonProperty
private Duration connectTimeout = Duration.seconds(5);
@JsonProperty
private Duration socketTimeout = Duration.seconds(5);
public HttpTransport httpTransport() {
return new HttpTransport.Builder()
.withApiKey(apiKey.value())
.withConnectTimeout((int) connectTimeout.toMilliseconds())
.withSocketTimeout((int) socketTimeout.toMilliseconds())
.build();
}
}
public record UdpTransportConfig(@NotNull String statsdHost, @Min(1) int port) {
public UdpTransport udpTransport() {
@@ -11,6 +11,7 @@ import com.google.common.annotations.VisibleForTesting;
import io.lettuce.core.SetArgs;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Timer;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
@@ -43,7 +44,7 @@ public class PushLatencyManager {
private final Clock clock;
private static final String TIMER_NAME = MetricRegistry.name(PushLatencyManager.class, "latency");
public static final String TIMER_NAME = MetricRegistry.name(PushLatencyManager.class, "latency");
private static final int TTL = (int) Duration.ofDays(1).toSeconds();
private static final Logger log = LoggerFactory.getLogger(PushLatencyManager.class);
@@ -103,7 +104,11 @@ public class PushLatencyManager {
pushRecord.urgent().ifPresent(urgent -> tags.add(Tag.of("urgent", String.valueOf(urgent))));
Metrics.timer(TIMER_NAME, tags).record(latency);
Timer.builder(TIMER_NAME)
.publishPercentileHistogram(true)
.tags(tags)
.register(Metrics.globalRegistry)
.record(latency);
}
});
}
@@ -317,24 +317,6 @@ public class Account {
};
}
/**
* @deprecated Please use {@link #getIdentityKey(IdentityType)} instead.
*/
@Deprecated
public IdentityKey getIdentityKey() {
requireNotStale();
return identityKey;
}
/**
* @deprecated Please use {@link #getIdentityKey(IdentityType)} instead.
*/
@Deprecated
public IdentityKey getPhoneNumberIdentityKey() {
return phoneNumberIdentityKey;
}
public void setPhoneNumberIdentityKey(final IdentityKey phoneNumberIdentityKey) {
this.phoneNumberIdentityKey = phoneNumberIdentityKey;
}
@@ -52,6 +52,7 @@ import org.whispersystems.textsecuregcm.entities.AccountAttributes;
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.identity.ServiceIdentifier;
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
@@ -235,7 +236,7 @@ public class AccountsManager {
keysManager.delete(actualUuid),
keysManager.delete(account.getPhoneNumberIdentifier()));
messagesManager.clear(actualUuid);
messagesManager.clear(actualUuid).join();
profilesManager.deleteAll(actualUuid);
deleteKeysFuture.join();
@@ -397,8 +398,8 @@ public class AccountsManager {
throw new IllegalArgumentException("PNI identity key, signed pre-keys, and registration IDs must be all null or all non-null");
}
boolean changed = !Objects.equals(pniIdentityKey, account.getPhoneNumberIdentityKey());
boolean changed = !Objects.equals(pniIdentityKey, account.getIdentityKey(IdentityType.PNI));
for (Device device : account.getDevices()) {
if (!device.isEnabled()) {
continue;
@@ -406,11 +407,11 @@ public class AccountsManager {
ECSignedPreKey signedPreKey = pniSignedPreKeys.get(device.getId());
int registrationId = pniRegistrationIds.get(device.getId());
changed = changed ||
!signedPreKey.equals(device.getPhoneNumberIdentitySignedPreKey()) ||
!signedPreKey.equals(device.getSignedPreKey(IdentityType.PNI)) ||
device.getRegistrationId() != registrationId;
device.setPhoneNumberIdentitySignedPreKey(signedPreKey);
device.setPhoneNumberIdentityRegistrationId(registrationId);
}
}
account.setPhoneNumberIdentityKey(pniIdentityKey);
@@ -434,11 +435,13 @@ public class AccountsManager {
Collections.emptySet());
// Check that all including master ID are in Pq pre-keys
DestinationDeviceValidator.validateCompleteDeviceList(
account,
pniSignedPreKeys.keySet(),
Collections.emptySet());
if (pniPqLastResortPreKeys != null) {
DestinationDeviceValidator.validateCompleteDeviceList(
account,
pniPqLastResortPreKeys.keySet(),
Collections.emptySet());
}
// Check that all devices are accounted for in the map of new PNI registration IDs
DestinationDeviceValidator.validateCompleteDeviceList(
account,
@@ -877,12 +880,15 @@ public class AccountsManager {
keysManager.delete(account.getUuid()),
keysManager.delete(account.getPhoneNumberIdentifier()));
final CompletableFuture<Void> deleteMessagesFuture = CompletableFuture.allOf(
messagesManager.clear(account.getUuid()),
messagesManager.clear(account.getPhoneNumberIdentifier()));
profilesManager.deleteAll(account.getUuid());
messagesManager.clear(account.getUuid());
messagesManager.clear(account.getPhoneNumberIdentifier());
registrationRecoveryPasswordsManager.removeForNumber(account.getNumber());
deleteKeysFuture.join();
deleteMessagesFuture.join();
deleteStorageServiceDataFuture.join();
deleteBackupServiceDataFuture.join();
deleteSecureValueRecoveryServiceDataFuture.join();
@@ -909,7 +915,7 @@ public class AccountsManager {
private void redisSet(Account account) {
try (Timer.Context ignored = redisSetTimer.time()) {
final String accountJson = ACCOUNT_REDIS_JSON_WRITER.writeValueAsString(account);
final String accountJson = writeRedisAccountJson(account);
cacheCluster.useCluster(connection -> {
final RedisAdvancedClusterCommands<String, String> commands = connection.sync();
@@ -930,7 +936,7 @@ public class AccountsManager {
final String accountJson;
try {
accountJson = ACCOUNT_REDIS_JSON_WRITER.writeValueAsString(account);
accountJson = writeRedisAccountJson(account);
} catch (final JsonProcessingException e) {
throw new UncheckedIOException(e);
}
@@ -1041,7 +1047,8 @@ public class AccountsManager {
.toCompletableFuture();
}
private static Optional<Account> parseAccountJson(@Nullable final String accountJson, final UUID uuid) {
@VisibleForTesting
static Optional<Account> parseAccountJson(@Nullable final String accountJson, final UUID uuid) {
try {
if (StringUtils.isNotBlank(accountJson)) {
Account account = SystemMapper.jsonMapper().readValue(accountJson, Account.class);
@@ -1061,6 +1068,11 @@ public class AccountsManager {
}
}
@VisibleForTesting
static String writeRedisAccountJson(final Account account) throws JsonProcessingException {
return ACCOUNT_REDIS_JSON_WRITER.writeValueAsString(account);
}
private void redisDelete(final Account account) {
try (final Timer.Context ignored = redisDeleteTimer.time()) {
cacheCluster.useCluster(connection -> {
@@ -238,26 +238,10 @@ public class Device {
};
}
/**
* @deprecated Please use {@link #getSignedPreKey(IdentityType)} instead.
*/
@Deprecated
public ECSignedPreKey getSignedPreKey() {
return signedPreKey;
}
public void setSignedPreKey(ECSignedPreKey signedPreKey) {
this.signedPreKey = signedPreKey;
}
/**
* @deprecated Please use {@link #getSignedPreKey(IdentityType)} instead.
*/
@Deprecated
public ECSignedPreKey getPhoneNumberIdentitySignedPreKey() {
return phoneNumberIdentitySignedPreKey;
}
public void setPhoneNumberIdentitySignedPreKey(final ECSignedPreKey phoneNumberIdentitySignedPreKey) {
this.phoneNumberIdentitySignedPreKey = phoneNumberIdentitySignedPreKey;
}
@@ -329,21 +329,24 @@ public class MessagesCache extends RedisClusterPubSubAdapter<String, String> imp
});
}
public void clear(final UUID destinationUuid) {
// TODO Remove null check in a fully UUID-based world
if (destinationUuid != null) {
for (int i = 1; i < Device.MAXIMUM_DEVICE_ID; i++) {
clear(destinationUuid, i);
}
public CompletableFuture<Void> clear(final UUID destinationUuid) {
final CompletableFuture<?>[] clearFutures = new CompletableFuture[Device.MAXIMUM_DEVICE_ID];
for (int deviceId = 0; deviceId < Device.MAXIMUM_DEVICE_ID; deviceId++) {
clearFutures[deviceId] = clear(destinationUuid, deviceId);
}
return CompletableFuture.allOf(clearFutures);
}
public void clear(final UUID destinationUuid, final long deviceId) {
clearQueueTimer.record(() ->
removeQueueScript.executeBinary(List.of(getMessageQueueKey(destinationUuid, deviceId),
public CompletableFuture<Void> clear(final UUID destinationUuid, final long deviceId) {
final Timer.Sample sample = Timer.start();
return removeQueueScript.executeBinaryAsync(List.of(getMessageQueueKey(destinationUuid, deviceId),
getMessageQueueMetadataKey(destinationUuid, deviceId),
getQueueIndexKey(destinationUuid, deviceId)),
Collections.emptyList()));
Collections.emptyList())
.thenRun(() -> sample.stop(clearQueueTimer));
}
int getNextSlotToPersist() {
@@ -37,7 +37,6 @@ import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.DeleteItemRequest;
import software.amazon.awssdk.services.dynamodb.model.DeleteRequest;
import software.amazon.awssdk.services.dynamodb.model.PutRequest;
import software.amazon.awssdk.services.dynamodb.model.QueryRequest;
import software.amazon.awssdk.services.dynamodb.model.ReturnValue;
@@ -215,38 +214,59 @@ public class MessagesDynamoDb extends AbstractDynamoDbStore {
}, messageDeletionExecutor);
}
public void deleteAllMessagesForAccount(final UUID destinationAccountUuid) {
deleteByAccount.record(() -> {
final AttributeValue partitionKey = convertPartitionKey(destinationAccountUuid);
final QueryRequest queryRequest = QueryRequest.builder()
.tableName(tableName)
.projectionExpression(KEY_SORT)
.consistentRead(true)
.keyConditionExpression("#part = :part")
.expressionAttributeNames(Map.of("#part", KEY_PARTITION))
.expressionAttributeValues(Map.of(":part", partitionKey))
.build();
deleteRowsMatchingQuery(partitionKey, queryRequest);
});
public CompletableFuture<Void> deleteAllMessagesForAccount(final UUID destinationAccountUuid) {
final Timer.Sample sample = Timer.start();
final AttributeValue partitionKey = convertPartitionKey(destinationAccountUuid);
return Flux.from(dbAsyncClient.queryPaginator(QueryRequest.builder()
.tableName(tableName)
.projectionExpression(KEY_SORT)
.consistentRead(true)
.keyConditionExpression("#part = :part")
.expressionAttributeNames(Map.of("#part", KEY_PARTITION))
.expressionAttributeValues(Map.of(":part", partitionKey))
.build())
.items())
.flatMap(item -> Mono.fromFuture(() -> dbAsyncClient.deleteItem(DeleteItemRequest.builder()
.tableName(tableName)
.key(Map.of(
KEY_PARTITION, partitionKey,
KEY_SORT, item.get(KEY_SORT)))
.build())),
DYNAMO_DB_MAX_BATCH_SIZE)
.doOnComplete(() -> sample.stop(deleteByAccount))
.then()
.toFuture();
}
public void deleteAllMessagesForDevice(final UUID destinationAccountUuid, final long destinationDeviceId) {
deleteByDevice.record(() -> {
final AttributeValue partitionKey = convertPartitionKey(destinationAccountUuid);
final QueryRequest queryRequest = QueryRequest.builder()
.tableName(tableName)
.keyConditionExpression("#part = :part AND begins_with ( #sort , :sortprefix )")
.expressionAttributeNames(Map.of(
"#part", KEY_PARTITION,
"#sort", KEY_SORT))
.expressionAttributeValues(Map.of(
":part", partitionKey,
":sortprefix", convertDestinationDeviceIdToSortKeyPrefix(destinationDeviceId)))
.projectionExpression(KEY_SORT)
.consistentRead(true)
.build();
deleteRowsMatchingQuery(partitionKey, queryRequest);
});
public CompletableFuture<Void> deleteAllMessagesForDevice(final UUID destinationAccountUuid, final long destinationDeviceId) {
final Timer.Sample sample = Timer.start();
final AttributeValue partitionKey = convertPartitionKey(destinationAccountUuid);
return Flux.from(dbAsyncClient.queryPaginator(QueryRequest.builder()
.tableName(tableName)
.keyConditionExpression("#part = :part AND begins_with ( #sort , :sortprefix )")
.expressionAttributeNames(Map.of(
"#part", KEY_PARTITION,
"#sort", KEY_SORT))
.expressionAttributeValues(Map.of(
":part", partitionKey,
":sortprefix", convertDestinationDeviceIdToSortKeyPrefix(destinationDeviceId)))
.projectionExpression(KEY_SORT)
.consistentRead(true)
.build())
.items())
.flatMap(item -> Mono.fromFuture(() -> dbAsyncClient.deleteItem(DeleteItemRequest.builder()
.tableName(tableName)
.key(Map.of(
KEY_PARTITION, partitionKey,
KEY_SORT, item.get(KEY_SORT)))
.build())),
DYNAMO_DB_MAX_BATCH_SIZE)
.doOnComplete(() -> sample.stop(deleteByDevice))
.then()
.toFuture();
}
@VisibleForTesting
@@ -256,21 +276,6 @@ public class MessagesDynamoDb extends AbstractDynamoDbStore {
return MessageProtos.Envelope.parseFrom(item.get(KEY_ENVELOPE_BYTES).b().asByteArray());
}
private void deleteRowsMatchingQuery(AttributeValue partitionKey, QueryRequest querySpec) {
writeInBatches(db().queryPaginator(querySpec).items(), itemBatch -> deleteItems(partitionKey, itemBatch));
}
private void deleteItems(AttributeValue partitionKey, List<Map<String, AttributeValue>> items) {
List<WriteRequest> deletes = items.stream()
.map(item -> WriteRequest.builder()
.deleteRequest(DeleteRequest.builder().key(Map.of(
KEY_PARTITION, partitionKey,
KEY_SORT, item.get(KEY_SORT))).build())
.build())
.toList();
executeTableWriteItemsUntilComplete(Map.of(tableName, deletes));
}
private long getTtlForMessage(MessageProtos.Envelope message) {
return message.getServerTimestamp() / 1000 + timeToLive.getSeconds();
}
@@ -102,14 +102,16 @@ public class MessagesManager {
.tap(Micrometer.metrics(Metrics.globalRegistry));
}
public void clear(UUID destinationUuid) {
messagesCache.clear(destinationUuid);
messagesDynamoDb.deleteAllMessagesForAccount(destinationUuid);
public CompletableFuture<Void> clear(UUID destinationUuid) {
return CompletableFuture.allOf(
messagesCache.clear(destinationUuid),
messagesDynamoDb.deleteAllMessagesForAccount(destinationUuid));
}
public void clear(UUID destinationUuid, long deviceId) {
messagesCache.clear(destinationUuid, deviceId);
messagesDynamoDb.deleteAllMessagesForDevice(destinationUuid, deviceId);
public CompletableFuture<Void> clear(UUID destinationUuid, long deviceId) {
return CompletableFuture.allOf(
messagesCache.clear(destinationUuid, deviceId),
messagesDynamoDb.deleteAllMessagesForDevice(destinationUuid, deviceId));
}
public CompletableFuture<Optional<Envelope>> delete(UUID destinationUuid, long destinationDeviceId, UUID guid,
@@ -11,7 +11,6 @@ import com.google.common.annotations.VisibleForTesting;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Timer;
import java.util.ArrayList;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -47,19 +46,19 @@ public class Profiles {
@VisibleForTesting
static final String ATTR_VERSION = "V";
// User's name; string
// User's name; byte array
private static final String ATTR_NAME = "N";
// Avatar path/filename; string
private static final String ATTR_AVATAR = "A";
// Bio/about text; string
// Bio/about text; byte array
private static final String ATTR_ABOUT = "B";
// Bio/about emoji; string
// Bio/about emoji; byte array
private static final String ATTR_EMOJI = "E";
// Payment address; string
// Payment address; byte array
private static final String ATTR_PAYMENT_ADDRESS = "P";
// Commitment; byte array
@@ -91,7 +90,7 @@ public class Profiles {
SET_PROFILES_TIMER.record(() -> {
dynamoDbClient.updateItem(UpdateItemRequest.builder()
.tableName(tableName)
.key(buildPrimaryKey(uuid, profile.getVersion()))
.key(buildPrimaryKey(uuid, profile.version()))
.updateExpression(buildUpdateExpression(profile))
.expressionAttributeNames(UPDATE_EXPRESSION_ATTRIBUTE_NAMES)
.expressionAttributeValues(buildUpdateExpressionAttributeValues(profile))
@@ -102,7 +101,7 @@ public class Profiles {
public CompletableFuture<Void> setAsync(final UUID uuid, final VersionedProfile profile) {
return AsyncTimerUtil.record(SET_PROFILES_TIMER, () -> dynamoDbAsyncClient.updateItem(UpdateItemRequest.builder()
.tableName(tableName)
.key(buildPrimaryKey(uuid, profile.getVersion()))
.key(buildPrimaryKey(uuid, profile.version()))
.updateExpression(buildUpdateExpression(profile))
.expressionAttributeNames(UPDATE_EXPRESSION_ATTRIBUTE_NAMES)
.expressionAttributeValues(buildUpdateExpressionAttributeValues(profile))
@@ -122,31 +121,31 @@ public class Profiles {
final List<String> updatedAttributes = new ArrayList<>(5);
final List<String> deletedAttributes = new ArrayList<>(5);
if (StringUtils.isNotBlank(profile.getName())) {
if (profile.name() != null) {
updatedAttributes.add("name");
} else {
deletedAttributes.add("name");
}
if (StringUtils.isNotBlank(profile.getAvatar())) {
if (StringUtils.isNotBlank(profile.avatar())) {
updatedAttributes.add("avatar");
} else {
deletedAttributes.add("avatar");
}
if (StringUtils.isNotBlank(profile.getAbout())) {
if (profile.about() != null) {
updatedAttributes.add("about");
} else {
deletedAttributes.add("about");
}
if (StringUtils.isNotBlank(profile.getAboutEmoji())) {
if (profile.aboutEmoji() != null) {
updatedAttributes.add("aboutEmoji");
} else {
deletedAttributes.add("aboutEmoji");
}
if (StringUtils.isNotBlank(profile.getPaymentAddress())) {
if (profile.paymentAddress() != null) {
updatedAttributes.add("paymentAddress");
} else {
deletedAttributes.add("paymentAddress");
@@ -177,26 +176,26 @@ public class Profiles {
static Map<String, AttributeValue> buildUpdateExpressionAttributeValues(final VersionedProfile profile) {
final Map<String, AttributeValue> expressionValues = new HashMap<>();
expressionValues.put(":commitment", AttributeValues.fromByteArray(profile.getCommitment()));
expressionValues.put(":commitment", AttributeValues.fromByteArray(profile.commitment()));
if (StringUtils.isNotBlank(profile.getName())) {
expressionValues.put(":name", AttributeValues.fromString(profile.getName()));
if (profile.name() != null) {
expressionValues.put(":name", AttributeValues.fromByteArray(profile.name()));
}
if (StringUtils.isNotBlank(profile.getAvatar())) {
expressionValues.put(":avatar", AttributeValues.fromString(profile.getAvatar()));
if (StringUtils.isNotBlank(profile.avatar())) {
expressionValues.put(":avatar", AttributeValues.fromString(profile.avatar()));
}
if (StringUtils.isNotBlank(profile.getAbout())) {
expressionValues.put(":about", AttributeValues.fromString(profile.getAbout()));
if (profile.about() != null) {
expressionValues.put(":about", AttributeValues.fromByteArray(profile.about()));
}
if (StringUtils.isNotBlank(profile.getAboutEmoji())) {
expressionValues.put(":aboutEmoji", AttributeValues.fromString(profile.getAboutEmoji()));
if (profile.aboutEmoji() != null) {
expressionValues.put(":aboutEmoji", AttributeValues.fromByteArray(profile.aboutEmoji()));
}
if (StringUtils.isNotBlank(profile.getPaymentAddress())) {
expressionValues.put(":paymentAddress", AttributeValues.fromString(profile.getPaymentAddress()));
if (profile.paymentAddress() != null) {
expressionValues.put(":paymentAddress", AttributeValues.fromByteArray(profile.paymentAddress()));
}
return expressionValues;
@@ -228,21 +227,21 @@ public class Profiles {
private static VersionedProfile fromItem(final Map<String, AttributeValue> item) {
return new VersionedProfile(
AttributeValues.getString(item, ATTR_VERSION, null),
getBase64EncodedBytes(item, ATTR_NAME, PARSE_BYTE_ARRAY_COUNTER_NAME),
getBytes(item, ATTR_NAME),
AttributeValues.getString(item, ATTR_AVATAR, null),
getBase64EncodedBytes(item, ATTR_EMOJI, PARSE_BYTE_ARRAY_COUNTER_NAME),
getBase64EncodedBytes(item, ATTR_ABOUT, PARSE_BYTE_ARRAY_COUNTER_NAME),
getBase64EncodedBytes(item, ATTR_PAYMENT_ADDRESS, PARSE_BYTE_ARRAY_COUNTER_NAME),
getBytes(item, ATTR_EMOJI),
getBytes(item, ATTR_ABOUT),
getBytes(item, ATTR_PAYMENT_ADDRESS),
AttributeValues.getByteArray(item, ATTR_COMMITMENT, null));
}
private static String getBase64EncodedBytes(final Map<String, AttributeValue> item, final String attributeName, final String counterName) {
private static byte[] getBytes(final Map<String, AttributeValue> item, final String attributeName) {
final AttributeValue attributeValue = item.get(attributeName);
if (attributeValue == null) {
return null;
}
return Base64.getEncoder().encodeToString(AttributeValues.extractByteArray(attributeValue, counterName));
return AttributeValues.extractByteArray(attributeValue, PARSE_BYTE_ARRAY_COUNTER_NAME);
}
public void deleteAll(final UUID uuid) {
@@ -77,7 +77,7 @@ public class ProfilesManager {
try {
final String profileJson = mapper.writeValueAsString(profile);
cacheCluster.useCluster(connection -> connection.sync().hset(getCacheKey(uuid), profile.getVersion(), profileJson));
cacheCluster.useCluster(connection -> connection.sync().hset(getCacheKey(uuid), profile.version(), profileJson));
} catch (JsonProcessingException e) {
throw new IllegalArgumentException(e);
}
@@ -93,7 +93,7 @@ public class ProfilesManager {
}
return cacheCluster.withCluster(connection ->
connection.async().hset(getCacheKey(uuid), profile.getVersion(), profileJson))
connection.async().hset(getCacheKey(uuid), profile.version(), profileJson))
.thenRun(Util.NOOP)
.toCompletableFuture();
}
@@ -150,7 +150,7 @@ public abstract class RepeatedUseSignedPreKeyStore<K extends SignedPreKey<?>> {
.tableName(tableName)
.key(getPrimaryKey(identifier, deviceId))
.build())
.flatMap(deleteItemRequest -> Mono.fromFuture(dynamoDbAsyncClient.deleteItem(deleteItemRequest)))
.flatMap(deleteItemRequest -> Mono.fromFuture(() -> dynamoDbAsyncClient.deleteItem(deleteItemRequest)))
// Idiom: wait for everything to finish, but discard the results
.reduce(0, (a, b) -> 0)
.toFuture()
@@ -6,22 +6,19 @@
package org.whispersystems.textsecuregcm.storage;
import static org.whispersystems.textsecuregcm.metrics.MetricsUtil.name;
import static org.whispersystems.textsecuregcm.storage.AbstractDynamoDbStore.DYNAMO_DB_MAX_BATCH_SIZE;
import com.google.common.annotations.VisibleForTesting;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.DistributionSummary;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Timer;
import java.nio.ByteBuffer;
import java.time.Duration;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.commons.lang3.StringUtils;
import org.whispersystems.textsecuregcm.entities.PreKey;
import org.whispersystems.textsecuregcm.util.AttributeValues;
import org.whispersystems.textsecuregcm.util.Util;
@@ -97,11 +94,12 @@ public abstract class SingleUsePreKeyStore<K extends PreKey<?>> {
public CompletableFuture<Void> store(final UUID identifier, final long deviceId, final List<K> preKeys) {
final Timer.Sample sample = Timer.start();
return delete(identifier, deviceId)
.thenCompose(ignored -> CompletableFuture.allOf(preKeys.stream()
.map(preKey -> store(identifier, deviceId, preKey))
.toList()
.toArray(new CompletableFuture[0])))
return Mono.fromFuture(() -> delete(identifier, deviceId))
.thenMany(
Flux.fromIterable(preKeys)
.flatMap(preKey -> Mono.fromFuture(() -> store(identifier, deviceId, preKey)), DYNAMO_DB_MAX_BATCH_SIZE))
.then()
.toFuture()
.thenRun(() -> sample.stop(storeKeyBatchTimer));
}
@@ -149,7 +147,7 @@ public abstract class SingleUsePreKeyStore<K extends PreKey<?>> {
KEY_DEVICE_ID_KEY_ID, item.get(KEY_DEVICE_ID_KEY_ID)))
.returnValues(ReturnValue.ALL_OLD)
.build())
.flatMap(deleteItemRequest -> Mono.fromFuture(dynamoDbAsyncClient.deleteItem(deleteItemRequest)), 1)
.flatMap(deleteItemRequest -> Mono.fromFuture(() -> dynamoDbAsyncClient.deleteItem(deleteItemRequest)), 1)
.doOnNext(deleteItemResponse -> keysConsidered.incrementAndGet())
.filter(DeleteItemResponse::hasAttributes)
.next()
@@ -258,7 +256,7 @@ public abstract class SingleUsePreKeyStore<K extends PreKey<?>> {
KEY_DEVICE_ID_KEY_ID, item.get(KEY_DEVICE_ID_KEY_ID)
))
.build())
.flatMap(deleteItemRequest -> Mono.fromFuture(dynamoDbAsyncClient.deleteItem(deleteItemRequest)))
.flatMap(deleteItemRequest -> Mono.fromFuture(() -> dynamoDbAsyncClient.deleteItem(deleteItemRequest)), DYNAMO_DB_MAX_BATCH_SIZE)
// Idiom: wait for everything to finish, but discard the results
.reduce(0, (a, b) -> 0)
.toFuture()
@@ -10,84 +10,29 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import org.whispersystems.textsecuregcm.util.ByteArrayAdapter;
import org.whispersystems.textsecuregcm.util.ByteArrayBase64WithPaddingAdapter;
import java.util.Arrays;
import java.util.Objects;
public class VersionedProfile {
public record VersionedProfile (String version,
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
byte[] name,
private final String version;
private final String name;
private final String avatar;
private final String aboutEmoji;
private final String about;
private final String paymentAddress;
String avatar,
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
private byte[] commitment;
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
byte[] aboutEmoji,
@JsonCreator
public VersionedProfile(
@JsonProperty("version") final String version,
@JsonProperty("name") final String name,
@JsonProperty("avatar") final String avatar,
@JsonProperty("aboutEmoji") final String aboutEmoji,
@JsonProperty("about") final String about,
@JsonProperty("paymentAddress") final String paymentAddress,
@JsonProperty("commitment") final byte[] commitment) {
this.version = version;
this.name = name;
this.avatar = avatar;
this.aboutEmoji = aboutEmoji;
this.about = about;
this.paymentAddress = paymentAddress;
this.commitment = commitment;
}
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
byte[] about,
public String getVersion() {
return version;
}
@JsonSerialize(using = ByteArrayBase64WithPaddingAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayBase64WithPaddingAdapter.Deserializing.class)
byte[] paymentAddress,
public String getName() {
return name;
}
public String getAvatar() {
return avatar;
}
public String getAboutEmoji() {
return aboutEmoji;
}
public String getAbout() {
return about;
}
public String getPaymentAddress() {
return paymentAddress;
}
public byte[] getCommitment() {
return commitment;
}
@Override
public boolean equals(final Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
final VersionedProfile that = (VersionedProfile) o;
return Objects.equals(version, that.version) && Objects.equals(name, that.name) && Objects.equals(avatar,
that.avatar) && Objects.equals(aboutEmoji, that.aboutEmoji) && Objects.equals(about, that.about)
&& Objects.equals(paymentAddress, that.paymentAddress) && Arrays.equals(commitment, that.commitment);
}
@Override
public int hashCode() {
int result = Objects.hash(version, name, avatar, aboutEmoji, about, paymentAddress);
result = 31 * result + Arrays.hashCode(commitment);
return result;
}
}
@JsonSerialize(using = ByteArrayAdapter.Serializing.class)
@JsonDeserialize(using = ByteArrayAdapter.Deserializing.class)
byte[] commitment) {}
@@ -0,0 +1,27 @@
package org.whispersystems.textsecuregcm.util;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import java.io.IOException;
import java.util.Base64;
public class ByteArrayBase64WithPaddingAdapter {
public static class Serializing extends JsonSerializer<byte[]> {
@Override
public void serialize(byte[] bytes, JsonGenerator jsonGenerator, SerializerProvider serializerProvider)
throws IOException {
jsonGenerator.writeString(Base64.getEncoder().encodeToString(bytes));
}
}
public static class Deserializing extends JsonDeserializer<byte[]> {
@Override
public byte[] deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
return Base64.getDecoder().decode(jsonParser.getValueAsString());
}
}
}
@@ -357,7 +357,7 @@ public class WebSocketConnection implements MessageAvailabilityListener, Displac
.tap(Micrometer.metrics(Metrics.globalRegistry))
.limitRate(MESSAGE_PUBLISHER_LIMIT_RATE)
.flatMapSequential(envelope ->
Mono.fromFuture(sendMessage(envelope)
Mono.fromFuture(() -> sendMessage(envelope)
.orTimeout(sendFuturesTimeoutMillis, TimeUnit.MILLISECONDS)))
.subscribeOn(messageDeliveryScheduler)
.subscribe(
@@ -39,7 +39,7 @@ public class CommandStopListener implements Managed {
writer.write("stopped");
}
} catch (final IOException e) {
logger.error("Failed to open file {}", path);
logger.error("Failed to open file {}", path, e);
}
}
}
@@ -11,6 +11,7 @@ import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.metrics.MetricsUtil;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.KeysManager;
@@ -42,17 +43,18 @@ public class MigrateSignedECPreKeysCommand extends AbstractSinglePassCrawlAccoun
.flatMap(device -> {
final List<Tuple3<UUID, Long, ECSignedPreKey>> keys = new ArrayList<>(2);
if (device.getSignedPreKey() != null) {
keys.add(Tuples.of(account.getUuid(), device.getId(), device.getSignedPreKey()));
if (device.getSignedPreKey(IdentityType.ACI) != null) {
keys.add(Tuples.of(account.getUuid(), device.getId(), device.getSignedPreKey(IdentityType.ACI)));
}
if (device.getPhoneNumberIdentitySignedPreKey() != null) {
keys.add(Tuples.of(account.getPhoneNumberIdentifier(), device.getId(), device.getPhoneNumberIdentitySignedPreKey()));
if (device.getSignedPreKey(IdentityType.PNI) != null) {
keys.add(Tuples.of(account.getPhoneNumberIdentifier(), device.getId(),
device.getSignedPreKey(IdentityType.PNI)));
}
return Flux.fromIterable(keys);
}))
.flatMap(keyTuple -> Mono.fromFuture(keysManager.storeEcSignedPreKeyIfAbsent(keyTuple.getT1(), keyTuple.getT2(), keyTuple.getT3()))
.flatMap(keyTuple -> Mono.fromFuture(() -> keysManager.storeEcSignedPreKeyIfAbsent(keyTuple.getT1(), keyTuple.getT2(), keyTuple.getT3()))
.retryWhen(Retry.backoff(3, Duration.ofSeconds(1)).onRetryExhaustedThrow((spec, rs) -> rs.failure())),
false, MAX_CONCURRENCY)
.doOnNext(keyStored -> Metrics.counter(STORE_KEY_ATTEMPT_COUNTER_NAME, "stored", String.valueOf(keyStored)).increment())
@@ -68,7 +68,7 @@ public class UnlinkDeviceCommand extends EnvironmentCommand<WhisperServerConfigu
deps.keysManager().delete(account.getUuid(), deviceId).join();
System.out.format("Clearing additional messages for %s::%d\n", aci, deviceId);
deps.messagesManager().clear(account.getUuid(), deviceId);
deps.messagesManager().clear(account.getUuid(), deviceId).join();
System.out.format("Clearing presence state for %s::%d\n", aci, deviceId);
deps.clientPresenceManager().disconnectPresence(aci, deviceId);
@@ -0,0 +1,149 @@
syntax = "proto3";
option java_multiple_files = true;
package org.signal.chat.device;
/**
* Provides methods for working with devices attached to a Signal account.
*/
service Devices {
/**
* Returns a list of devices associated with the caller's account.
*/
rpc GetDevices(GetDevicesRequest) returns (GetDevicesResponse) {}
/**
* Removes a linked device from the caller's account. This call will fail with
* a status of `PERMISSION_DENIED` if not called from the primary device
* associated with an account. It will also fail with a status of
* `INVALID_ARGUMENT` if the targeted device is the primary device associated
* with the account.
*/
rpc RemoveDevice(RemoveDeviceRequest) returns (RemoveDeviceResponse) {}
rpc SetDeviceName(SetDeviceNameRequest) returns (SetDeviceNameResponse) {}
/**
* Sets the token(s) the server should use to send new message notifications
* to the authenticated device.
*/
rpc SetPushToken(SetPushTokenRequest) returns (SetPushTokenResponse) {}
/**
* Removes any push tokens associated with the authenticated device. After
* calling this method, the server will assume that the authenticated device
* will periodically poll for new messages.
*/
rpc ClearPushToken(ClearPushTokenRequest) returns (ClearPushTokenResponse) {}
/**
* Declares that the authenticated device supports certain features.
*/
rpc SetCapabilities(SetCapabilitiesRequest) returns (SetCapabilitiesResponse) {}
}
message GetDevicesRequest {}
message GetDevicesResponse {
message LinkedDevice {
/**
* The identifier for the device within an account.
*/
uint64 id = 1;
/**
* A sequence of bytes that encodes an encrypted human-readable name for
* this device.
*/
bytes name = 2;
/**
* The time, in milliseconds since the epoch, at which this device was
* attached to its parent account.
*/
uint64 created = 3;
/**
* The approximate time, in milliseconds since the epoch, at which this
* device last connected to the server.
*/
uint64 last_seen = 4;
}
/**
* A list of devices linked to the authenticated account.
*/
repeated LinkedDevice devices = 1;
}
message RemoveDeviceRequest {
/**
* The identifier for the device to remove from the authenticated account.
*/
uint64 id = 1;
}
message SetDeviceNameRequest {
/**
* A sequence of bytes that encodes an encrypted human-readable name for this
* device.
*/
bytes name = 1;
}
message SetDeviceNameResponse {}
message RemoveDeviceResponse {}
message SetPushTokenRequest {
message ApnsTokenRequest {
/**
* A "standard" APNs device token.
*/
string apns_token = 1;
/**
* A VoIP APNs device token. If present, the server will prefer to send
* message notifications to the device using this token on a VOIP APNs
* topic.
*/
string apns_voip_token = 2;
}
message FcmTokenRequest {
/**
* An FCM push token.
*/
string fcm_token = 1;
}
oneof token_request {
/**
* If present, specifies the APNs device token(s) the server will use to
* send new message notifications to the authenticated device.
*/
ApnsTokenRequest apns_token_request = 1;
/**
* If present, specifies the FCM push token the server will use to send new
* message notifications to the authenticated device.
*/
FcmTokenRequest fcm_token_request = 2;
}
}
message SetPushTokenResponse {}
message ClearPushTokenRequest {}
message ClearPushTokenResponse {}
message SetCapabilitiesRequest {
bool storage = 1;
bool transfer = 2;
bool pni = 3;
bool paymentActivation = 4;
}
message SetCapabilitiesResponse {}
@@ -17,6 +17,7 @@ import org.junit.jupiter.api.Test;
import org.signal.libsignal.protocol.IdentityKey;
import org.signal.libsignal.protocol.ecc.Curve;
import org.signal.libsignal.protocol.ecc.ECPublicKey;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.Device;
@@ -32,7 +33,7 @@ class CertificateGeneratorTest {
final Device device = mock(Device.class);
final CertificateGenerator certificateGenerator = new CertificateGenerator(Base64.getDecoder().decode(SIGNING_CERTIFICATE), Curve.decodePrivatePoint(Base64.getDecoder().decode(SIGNING_KEY)), 1);
when(account.getIdentityKey()).thenReturn(IDENTITY_KEY);
when(account.getIdentityKey(IdentityType.ACI)).thenReturn(IDENTITY_KEY);
when(account.getUuid()).thenReturn(UUID.randomUUID());
when(account.getNumber()).thenReturn("+18005551234");
when(device.getId()).thenReturn(4L);
@@ -75,6 +75,7 @@ import org.whispersystems.textsecuregcm.entities.AccountIdentityResponse;
import org.whispersystems.textsecuregcm.entities.ChangeNumberRequest;
import org.whispersystems.textsecuregcm.entities.PhoneNumberDiscoverabilityRequest;
import org.whispersystems.textsecuregcm.entities.RegistrationServiceSession;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.limits.RateLimiter;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.mappers.ImpossiblePhoneNumberExceptionMapper;
@@ -151,7 +152,7 @@ class AccountControllerV2Test {
final Account updatedAccount = mock(Account.class);
when(updatedAccount.getUuid()).thenReturn(uuid);
when(updatedAccount.getNumber()).thenReturn(number);
when(updatedAccount.getPhoneNumberIdentityKey()).thenReturn(pniIdentityKey);
when(updatedAccount.getIdentityKey(IdentityType.PNI)).thenReturn(pniIdentityKey);
if (number.equals(account.getNumber())) {
when(updatedAccount.getPhoneNumberIdentifier()).thenReturn(AuthHelper.VALID_PNI);
} else {
@@ -205,7 +206,7 @@ class AccountControllerV2Test {
.header(HttpHeaders.AUTHORIZATION,
AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.put(Entity.entity(
new ChangeNumberRequest(encodeSessionId("session"), null, AuthHelper.VALID_NUMBER, null,
new ChangeNumberRequest(encodeSessionId("session"), null, AuthHelper.VALID_NUMBER, null,
new IdentityKey(Curve.generateKeyPair().getPublicKey()),
Collections.emptyList(),
Collections.emptyMap(), null, Collections.emptyMap()),
@@ -476,7 +477,7 @@ class AccountControllerV2Test {
final Account updatedAccount = mock(Account.class);
when(updatedAccount.getUuid()).thenReturn(uuid);
when(updatedAccount.getNumber()).thenReturn(number);
when(updatedAccount.getPhoneNumberIdentityKey()).thenReturn(pniIdentityKey);
when(updatedAccount.getIdentityKey(IdentityType.PNI)).thenReturn(pniIdentityKey);
when(updatedAccount.getPhoneNumberIdentifier()).thenReturn(pni);
when(updatedAccount.getDevices()).thenReturn(devices);
@@ -487,12 +488,12 @@ class AccountControllerV2Test {
return updatedAccount;
});
}
}
@Test
void pniKeyDistributionSuccess() throws Exception {
when(AuthHelper.VALID_ACCOUNT.isPniSupported()).thenReturn(true);
final AccountIdentityResponse accountIdentityResponse =
resources.getJerseyTest()
.target("/v2/accounts/phone_number_identity_key_distribution")
@@ -506,8 +507,8 @@ class AccountControllerV2Test {
assertEquals(AuthHelper.VALID_UUID, accountIdentityResponse.uuid());
assertEquals(AuthHelper.VALID_NUMBER, accountIdentityResponse.number());
assertEquals(AuthHelper.VALID_PNI, accountIdentityResponse.pni());
}
}
@Test
void unprocessableRequestJson() {
final Invocation.Builder request = resources.getJerseyTest()
@@ -552,7 +553,7 @@ class AccountControllerV2Test {
assertEquals(422, response.getStatus());
}
}
/**
* Valid request JSON for a {@link org.whispersystems.textsecuregcm.entities.PhoneNumberIdentityKeyDistributionRequest}
*/
@@ -596,7 +597,7 @@ class AccountControllerV2Test {
}
}
@Nested
class PhoneNumberDiscoverability {
@@ -4,12 +4,40 @@
*/
package org.whispersystems.textsecuregcm.controllers;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.Mockito.anyString;
import static org.mockito.Mockito.clearInvocations;
import static org.mockito.Mockito.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import com.google.common.collect.ImmutableSet;
import com.google.common.net.HttpHeaders;
import io.dropwizard.auth.PolymorphicAuthValueFactoryProvider;
import io.dropwizard.testing.junit5.DropwizardExtensionsSupport;
import io.dropwizard.testing.junit5.ResourceExtension;
import io.lettuce.core.cluster.api.sync.RedisAdvancedClusterCommands;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.time.Instant;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Stream;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
@@ -26,12 +54,22 @@ import org.signal.libsignal.protocol.ecc.ECKeyPair;
import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
import org.whispersystems.textsecuregcm.auth.DisabledPermittedAuthenticatedAccount;
import org.whispersystems.textsecuregcm.auth.WebsocketRefreshApplicationEventListener;
import org.whispersystems.textsecuregcm.entities.*;
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
import org.whispersystems.textsecuregcm.entities.ApnRegistrationId;
import org.whispersystems.textsecuregcm.entities.DeviceActivationRequest;
import org.whispersystems.textsecuregcm.entities.DeviceResponse;
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
import org.whispersystems.textsecuregcm.entities.GcmRegistrationId;
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
import org.whispersystems.textsecuregcm.entities.LinkDeviceRequest;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.limits.RateLimiter;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.mappers.DeviceLimitExceededExceptionMapper;
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
import org.whispersystems.textsecuregcm.storage.*;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.Device.DeviceCapabilities;
import org.whispersystems.textsecuregcm.storage.KeysManager;
import org.whispersystems.textsecuregcm.storage.MessagesManager;
@@ -42,23 +80,6 @@ import org.whispersystems.textsecuregcm.tests.util.RedisClusterHelper;
import org.whispersystems.textsecuregcm.util.TestClock;
import org.whispersystems.textsecuregcm.util.VerificationCode;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.time.Instant;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Stream;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.Mockito.*;
@ExtendWith(DropwizardExtensionsSupport.class)
class DeviceControllerTest {
@@ -128,6 +149,8 @@ class DeviceControllerTest {
when(keysManager.storePqLastResort(any(), any())).thenReturn(CompletableFuture.completedFuture(null));
when(keysManager.delete(any(), anyLong())).thenReturn(CompletableFuture.completedFuture(null));
when(messagesManager.clear(any(), anyLong())).thenReturn(CompletableFuture.completedFuture(null));
}
@AfterEach
@@ -270,8 +293,8 @@ class DeviceControllerTest {
aciPqLastResortPreKey = Optional.of(KeysHelper.signedKEMPreKey(3, aciIdentityKeyPair));
pniPqLastResortPreKey = Optional.of(KeysHelper.signedKEMPreKey(4, pniIdentityKeyPair));
when(account.getIdentityKey()).thenReturn(new IdentityKey(aciIdentityKeyPair.getPublicKey()));
when(account.getPhoneNumberIdentityKey()).thenReturn(new IdentityKey(pniIdentityKeyPair.getPublicKey()));
when(account.getIdentityKey(IdentityType.ACI)).thenReturn(new IdentityKey(aciIdentityKeyPair.getPublicKey()));
when(account.getIdentityKey(IdentityType.PNI)).thenReturn(new IdentityKey(pniIdentityKeyPair.getPublicKey()));
when(keysManager.storeEcSignedPreKeys(any(), any())).thenReturn(CompletableFuture.completedFuture(null));
when(keysManager.storePqLastResort(any(), any())).thenReturn(CompletableFuture.completedFuture(null));
@@ -293,8 +316,8 @@ class DeviceControllerTest {
final Device device = deviceCaptor.getValue();
assertEquals(aciSignedPreKey.get(), device.getSignedPreKey());
assertEquals(pniSignedPreKey.get(), device.getPhoneNumberIdentitySignedPreKey());
assertEquals(aciSignedPreKey.get(), device.getSignedPreKey(IdentityType.ACI));
assertEquals(pniSignedPreKey.get(), device.getSignedPreKey(IdentityType.PNI));
assertEquals(fetchesMessages, device.getFetchesMessages());
expectedApnsToken.ifPresentOrElse(expectedToken -> assertEquals(expectedToken, device.getApnId()),
@@ -350,8 +373,8 @@ class DeviceControllerTest {
aciPqLastResortPreKey = Optional.of(KeysHelper.signedKEMPreKey(3, aciIdentityKeyPair));
pniPqLastResortPreKey = Optional.of(KeysHelper.signedKEMPreKey(4, pniIdentityKeyPair));
when(account.getIdentityKey()).thenReturn(new IdentityKey(aciIdentityKeyPair.getPublicKey()));
when(account.getPhoneNumberIdentityKey()).thenReturn(new IdentityKey(pniIdentityKeyPair.getPublicKey()));
when(account.getIdentityKey(IdentityType.ACI)).thenReturn(new IdentityKey(aciIdentityKeyPair.getPublicKey()));
when(account.getIdentityKey(IdentityType.PNI)).thenReturn(new IdentityKey(pniIdentityKeyPair.getPublicKey()));
when(keysManager.storeEcSignedPreKeys(any(), any())).thenReturn(CompletableFuture.completedFuture(null));
when(keysManager.storePqLastResort(any(), any())).thenReturn(CompletableFuture.completedFuture(null));
@@ -403,8 +426,8 @@ class DeviceControllerTest {
aciPqLastResortPreKey = Optional.of(KeysHelper.signedKEMPreKey(3, aciIdentityKeyPair));
pniPqLastResortPreKey = Optional.of(KeysHelper.signedKEMPreKey(4, pniIdentityKeyPair));
when(account.getIdentityKey()).thenReturn(new IdentityKey(aciIdentityKeyPair.getPublicKey()));
when(account.getPhoneNumberIdentityKey()).thenReturn(new IdentityKey(pniIdentityKeyPair.getPublicKey()));
when(account.getIdentityKey(IdentityType.ACI)).thenReturn(new IdentityKey(aciIdentityKeyPair.getPublicKey()));
when(account.getIdentityKey(IdentityType.PNI)).thenReturn(new IdentityKey(pniIdentityKeyPair.getPublicKey()));
final LinkDeviceRequest request = new LinkDeviceRequest(deviceCode.verificationCode(),
new AccountAttributes(fetchesMessages, 1234, null, null, true, null),
@@ -451,8 +474,8 @@ class DeviceControllerTest {
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.get(VerificationCode.class);
when(account.getIdentityKey()).thenReturn(aciIdentityKey);
when(account.getPhoneNumberIdentityKey()).thenReturn(pniIdentityKey);
when(account.getIdentityKey(IdentityType.ACI)).thenReturn(aciIdentityKey);
when(account.getIdentityKey(IdentityType.PNI)).thenReturn(pniIdentityKey);
final LinkDeviceRequest request = new LinkDeviceRequest(deviceCode.verificationCode(),
new AccountAttributes(true, 1234, null, null, true, null),
@@ -509,8 +532,8 @@ class DeviceControllerTest {
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.get(VerificationCode.class);
when(account.getIdentityKey()).thenReturn(aciIdentityKey);
when(account.getPhoneNumberIdentityKey()).thenReturn(pniIdentityKey);
when(account.getIdentityKey(IdentityType.ACI)).thenReturn(aciIdentityKey);
when(account.getIdentityKey(IdentityType.PNI)).thenReturn(pniIdentityKey);
final LinkDeviceRequest request = new LinkDeviceRequest(deviceCode.verificationCode(),
new AccountAttributes(true, 1234, null, null, true, null),
@@ -38,6 +38,7 @@ import java.util.concurrent.CompletableFuture;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.glassfish.jersey.server.ServerProperties;
import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
@@ -58,9 +59,11 @@ import org.whispersystems.textsecuregcm.entities.PreKeyResponse;
import org.whispersystems.textsecuregcm.entities.PreKeyState;
import org.whispersystems.textsecuregcm.entities.SignedPreKey;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier;
import org.whispersystems.textsecuregcm.limits.RateLimiter;
import org.whispersystems.textsecuregcm.limits.RateLimiters;
import org.whispersystems.textsecuregcm.mappers.CompletionExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.RateLimitExceededExceptionMapper;
import org.whispersystems.textsecuregcm.mappers.ServerRejectedExceptionMapper;
import org.whispersystems.textsecuregcm.storage.Account;
@@ -89,10 +92,10 @@ class KeysControllerTest {
private final ECKeyPair IDENTITY_KEY_PAIR = Curve.generateKeyPair();
private final IdentityKey IDENTITY_KEY = new IdentityKey(IDENTITY_KEY_PAIR.getPublicKey());
private final ECKeyPair PNI_IDENTITY_KEY_PAIR = Curve.generateKeyPair();
private final IdentityKey PNI_IDENTITY_KEY = new IdentityKey(PNI_IDENTITY_KEY_PAIR.getPublicKey());
private final ECPreKey SAMPLE_KEY = KeysHelper.ecPreKey(1234);
private final ECPreKey SAMPLE_KEY2 = KeysHelper.ecPreKey(5667);
private final ECPreKey SAMPLE_KEY3 = KeysHelper.ecPreKey(334);
@@ -123,7 +126,9 @@ class KeysControllerTest {
private static final RateLimiter rateLimiter = mock(RateLimiter.class );
private static final ResourceExtension resources = ResourceExtension.builder()
.addProperty(ServerProperties.UNWRAP_COMPLETION_STAGE_IN_WRITER_ENABLE, Boolean.TRUE)
.addProvider(AuthHelper.getAuthFilter())
.addProvider(CompletionExceptionMapper.class)
.addProvider(new PolymorphicAuthValueFactoryProvider.Binder<>(ImmutableSet.of(
AuthenticatedAccount.class, DisabledPermittedAuthenticatedAccount.class)))
.setTestContainerFactory(new GrizzlyWebTestContainerFactory())
@@ -186,14 +191,14 @@ class KeysControllerTest {
when(sampleDevice2.isEnabled()).thenReturn(true);
when(sampleDevice3.isEnabled()).thenReturn(false);
when(sampleDevice4.isEnabled()).thenReturn(true);
when(sampleDevice.getSignedPreKey()).thenReturn(SAMPLE_SIGNED_KEY);
when(sampleDevice2.getSignedPreKey()).thenReturn(SAMPLE_SIGNED_KEY2);
when(sampleDevice3.getSignedPreKey()).thenReturn(SAMPLE_SIGNED_KEY3);
when(sampleDevice4.getSignedPreKey()).thenReturn(null);
when(sampleDevice.getPhoneNumberIdentitySignedPreKey()).thenReturn(SAMPLE_SIGNED_PNI_KEY);
when(sampleDevice2.getPhoneNumberIdentitySignedPreKey()).thenReturn(SAMPLE_SIGNED_PNI_KEY2);
when(sampleDevice3.getPhoneNumberIdentitySignedPreKey()).thenReturn(SAMPLE_SIGNED_PNI_KEY3);
when(sampleDevice4.getPhoneNumberIdentitySignedPreKey()).thenReturn(null);
when(sampleDevice.getSignedPreKey(IdentityType.ACI)).thenReturn(SAMPLE_SIGNED_KEY);
when(sampleDevice2.getSignedPreKey(IdentityType.ACI)).thenReturn(SAMPLE_SIGNED_KEY2);
when(sampleDevice3.getSignedPreKey(IdentityType.ACI)).thenReturn(SAMPLE_SIGNED_KEY3);
when(sampleDevice4.getSignedPreKey(IdentityType.ACI)).thenReturn(null);
when(sampleDevice.getSignedPreKey(IdentityType.PNI)).thenReturn(SAMPLE_SIGNED_PNI_KEY);
when(sampleDevice2.getSignedPreKey(IdentityType.PNI)).thenReturn(SAMPLE_SIGNED_PNI_KEY2);
when(sampleDevice3.getSignedPreKey(IdentityType.PNI)).thenReturn(SAMPLE_SIGNED_PNI_KEY3);
when(sampleDevice4.getSignedPreKey(IdentityType.PNI)).thenReturn(null);
when(sampleDevice.getId()).thenReturn(1L);
when(sampleDevice2.getId()).thenReturn(2L);
when(sampleDevice3.getId()).thenReturn(3L);
@@ -208,8 +213,8 @@ class KeysControllerTest {
when(existsAccount.getDevice(22L)).thenReturn(Optional.empty());
when(existsAccount.getDevices()).thenReturn(allDevices);
when(existsAccount.isEnabled()).thenReturn(true);
when(existsAccount.getIdentityKey()).thenReturn(IDENTITY_KEY);
when(existsAccount.getPhoneNumberIdentityKey()).thenReturn(PNI_IDENTITY_KEY);
when(existsAccount.getIdentityKey(IdentityType.ACI)).thenReturn(IDENTITY_KEY);
when(existsAccount.getIdentityKey(IdentityType.PNI)).thenReturn(PNI_IDENTITY_KEY);
when(existsAccount.getNumber()).thenReturn(EXISTS_NUMBER);
when(existsAccount.getUnidentifiedAccessKey()).thenReturn(Optional.of("1337".getBytes()));
@@ -232,9 +237,9 @@ class KeysControllerTest {
when(KEYS.getEcCount(AuthHelper.VALID_UUID, 1)).thenReturn(CompletableFuture.completedFuture(5));
when(KEYS.getPqCount(AuthHelper.VALID_UUID, 1)).thenReturn(CompletableFuture.completedFuture(5));
when(AuthHelper.VALID_DEVICE.getSignedPreKey()).thenReturn(VALID_DEVICE_SIGNED_KEY);
when(AuthHelper.VALID_DEVICE.getPhoneNumberIdentitySignedPreKey()).thenReturn(VALID_DEVICE_PNI_SIGNED_KEY);
when(AuthHelper.VALID_ACCOUNT.getIdentityKey()).thenReturn(null);
when(AuthHelper.VALID_DEVICE.getSignedPreKey(IdentityType.ACI)).thenReturn(VALID_DEVICE_SIGNED_KEY);
when(AuthHelper.VALID_DEVICE.getSignedPreKey(IdentityType.PNI)).thenReturn(VALID_DEVICE_PNI_SIGNED_KEY);
when(AuthHelper.VALID_ACCOUNT.getIdentityKey(IdentityType.ACI)).thenReturn(null);
}
@AfterEach
@@ -322,12 +327,13 @@ class KeysControllerTest {
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.get(PreKeyResponse.class);
assertThat(result.getIdentityKey()).isEqualTo(existsAccount.getIdentityKey());
assertThat(result.getIdentityKey()).isEqualTo(existsAccount.getIdentityKey(IdentityType.ACI));
assertThat(result.getDevicesCount()).isEqualTo(1);
assertEquals(SAMPLE_KEY, result.getDevice(1).getPreKey());
assertThat(result.getDevice(1).getPqPreKey()).isNull();
assertThat(result.getDevice(1).getRegistrationId()).isEqualTo(SAMPLE_REGISTRATION_ID);
assertEquals(existsAccount.getDevice(1).get().getSignedPreKey(), result.getDevice(1).getSignedPreKey());
assertEquals(existsAccount.getDevice(1).get().getSignedPreKey(IdentityType.ACI),
result.getDevice(1).getSignedPreKey());
verify(KEYS).takeEC(EXISTS_UUID, 1);
verify(KEYS).getEcSignedPreKey(EXISTS_UUID, 1);
@@ -345,12 +351,13 @@ class KeysControllerTest {
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.get(PreKeyResponse.class);
assertThat(result.getIdentityKey()).isEqualTo(existsAccount.getIdentityKey());
assertThat(result.getIdentityKey()).isEqualTo(existsAccount.getIdentityKey(IdentityType.ACI));
assertThat(result.getDevicesCount()).isEqualTo(1);
assertEquals(SAMPLE_KEY, result.getDevice(1).getPreKey());
assertThat(result.getDevice(1).getPqPreKey()).isNull();
assertThat(result.getDevice(1).getRegistrationId()).isEqualTo(SAMPLE_REGISTRATION_ID);
assertEquals(existsAccount.getDevice(1).get().getSignedPreKey(), result.getDevice(1).getSignedPreKey());
assertEquals(existsAccount.getDevice(1).get().getSignedPreKey(IdentityType.ACI),
result.getDevice(1).getSignedPreKey());
verify(KEYS).takeEC(EXISTS_UUID, 1);
verify(KEYS).takePQ(EXISTS_UUID, 1);
@@ -367,12 +374,13 @@ class KeysControllerTest {
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.get(PreKeyResponse.class);
assertThat(result.getIdentityKey()).isEqualTo(existsAccount.getIdentityKey());
assertThat(result.getIdentityKey()).isEqualTo(existsAccount.getIdentityKey(IdentityType.ACI));
assertThat(result.getDevicesCount()).isEqualTo(1);
assertEquals(SAMPLE_KEY, result.getDevice(1).getPreKey());
assertEquals(SAMPLE_PQ_KEY, result.getDevice(1).getPqPreKey());
assertThat(result.getDevice(1).getRegistrationId()).isEqualTo(SAMPLE_REGISTRATION_ID);
assertEquals(existsAccount.getDevice(1).get().getSignedPreKey(), result.getDevice(1).getSignedPreKey());
assertEquals(existsAccount.getDevice(1).get().getSignedPreKey(IdentityType.ACI),
result.getDevice(1).getSignedPreKey());
verify(KEYS).takeEC(EXISTS_UUID, 1);
verify(KEYS).takePQ(EXISTS_UUID, 1);
@@ -388,12 +396,13 @@ class KeysControllerTest {
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.get(PreKeyResponse.class);
assertThat(result.getIdentityKey()).isEqualTo(existsAccount.getPhoneNumberIdentityKey());
assertThat(result.getIdentityKey()).isEqualTo(existsAccount.getIdentityKey(IdentityType.PNI));
assertThat(result.getDevicesCount()).isEqualTo(1);
assertEquals(SAMPLE_KEY_PNI, result.getDevice(1).getPreKey());
assertThat(result.getDevice(1).getPqPreKey()).isNull();
assertThat(result.getDevice(1).getRegistrationId()).isEqualTo(SAMPLE_PNI_REGISTRATION_ID);
assertEquals(existsAccount.getDevice(1).get().getPhoneNumberIdentitySignedPreKey(), result.getDevice(1).getSignedPreKey());
assertEquals(existsAccount.getDevice(1).get().getSignedPreKey(IdentityType.PNI),
result.getDevice(1).getSignedPreKey());
verify(KEYS).takeEC(EXISTS_PNI, 1);
verify(KEYS).getEcSignedPreKey(EXISTS_PNI, 1);
@@ -409,12 +418,13 @@ class KeysControllerTest {
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.get(PreKeyResponse.class);
assertThat(result.getIdentityKey()).isEqualTo(existsAccount.getPhoneNumberIdentityKey());
assertThat(result.getIdentityKey()).isEqualTo(existsAccount.getIdentityKey(IdentityType.PNI));
assertThat(result.getDevicesCount()).isEqualTo(1);
assertEquals(SAMPLE_KEY_PNI, result.getDevice(1).getPreKey());
assertThat(result.getDevice(1).getPqPreKey()).isEqualTo(SAMPLE_PQ_KEY_PNI);
assertThat(result.getDevice(1).getRegistrationId()).isEqualTo(SAMPLE_PNI_REGISTRATION_ID);
assertEquals(existsAccount.getDevice(1).get().getPhoneNumberIdentitySignedPreKey(), result.getDevice(1).getSignedPreKey());
assertEquals(existsAccount.getDevice(1).get().getSignedPreKey(IdentityType.PNI),
result.getDevice(1).getSignedPreKey());
verify(KEYS).takeEC(EXISTS_PNI, 1);
verify(KEYS).takePQ(EXISTS_PNI, 1);
@@ -432,12 +442,13 @@ class KeysControllerTest {
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.get(PreKeyResponse.class);
assertThat(result.getIdentityKey()).isEqualTo(existsAccount.getPhoneNumberIdentityKey());
assertThat(result.getIdentityKey()).isEqualTo(existsAccount.getIdentityKey(IdentityType.PNI));
assertThat(result.getDevicesCount()).isEqualTo(1);
assertEquals(SAMPLE_KEY_PNI, result.getDevice(1).getPreKey());
assertThat(result.getDevice(1).getPqPreKey()).isNull();
assertThat(result.getDevice(1).getRegistrationId()).isEqualTo(SAMPLE_REGISTRATION_ID);
assertEquals(existsAccount.getDevice(1).get().getPhoneNumberIdentitySignedPreKey(), result.getDevice(1).getSignedPreKey());
assertEquals(existsAccount.getDevice(1).get().getSignedPreKey(IdentityType.PNI),
result.getDevice(1).getSignedPreKey());
verify(KEYS).takeEC(EXISTS_PNI, 1);
verify(KEYS).getEcSignedPreKey(EXISTS_PNI, 1);
@@ -468,11 +479,12 @@ class KeysControllerTest {
.header(OptionalAccess.UNIDENTIFIED, AuthHelper.getUnidentifiedAccessHeader("1337".getBytes()))
.get(PreKeyResponse.class);
assertThat(result.getIdentityKey()).isEqualTo(existsAccount.getIdentityKey());
assertThat(result.getIdentityKey()).isEqualTo(existsAccount.getIdentityKey(IdentityType.ACI));
assertThat(result.getDevicesCount()).isEqualTo(1);
assertEquals(SAMPLE_KEY, result.getDevice(1).getPreKey());
assertEquals(SAMPLE_PQ_KEY, result.getDevice(1).getPqPreKey());
assertEquals(existsAccount.getDevice(1).get().getSignedPreKey(), result.getDevice(1).getSignedPreKey());
assertEquals(existsAccount.getDevice(1).get().getSignedPreKey(IdentityType.ACI),
result.getDevice(1).getSignedPreKey());
verify(KEYS).takeEC(EXISTS_UUID, 1);
verify(KEYS).takePQ(EXISTS_UUID, 1);
@@ -534,7 +546,7 @@ class KeysControllerTest {
.get(PreKeyResponse.class);
assertThat(results.getDevicesCount()).isEqualTo(3);
assertThat(results.getIdentityKey()).isEqualTo(existsAccount.getIdentityKey());
assertThat(results.getIdentityKey()).isEqualTo(existsAccount.getIdentityKey(IdentityType.ACI));
ECSignedPreKey signedPreKey = results.getDevice(1).getSignedPreKey();
ECPreKey preKey = results.getDevice(1).getPreKey();
@@ -595,7 +607,7 @@ class KeysControllerTest {
.get(PreKeyResponse.class);
assertThat(results.getDevicesCount()).isEqualTo(3);
assertThat(results.getIdentityKey()).isEqualTo(existsAccount.getIdentityKey());
assertThat(results.getIdentityKey()).isEqualTo(existsAccount.getIdentityKey(IdentityType.ACI));
ECSignedPreKey signedPreKey = results.getDevice(1).getSignedPreKey();
ECPreKey preKey = results.getDevice(1).getPreKey();
@@ -48,7 +48,6 @@ import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedHashMap;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import org.apache.commons.lang3.RandomStringUtils;
import org.assertj.core.api.Condition;
import org.glassfish.jersey.server.ServerProperties;
import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory;
@@ -108,6 +107,7 @@ import org.whispersystems.textsecuregcm.storage.ProfilesManager;
import org.whispersystems.textsecuregcm.storage.VersionedProfile;
import org.whispersystems.textsecuregcm.tests.util.AccountsHelper;
import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
import org.whispersystems.textsecuregcm.tests.util.ProfileHelper;
import org.whispersystems.textsecuregcm.util.SystemMapper;
import org.whispersystems.textsecuregcm.util.TestClock;
import org.whispersystems.textsecuregcm.util.Util;
@@ -193,9 +193,7 @@ class ProfileControllerTest {
profileAccount = mock(Account.class);
when(profileAccount.getIdentityKey()).thenReturn(ACCOUNT_TWO_IDENTITY_KEY);
when(profileAccount.getIdentityKey(IdentityType.ACI)).thenReturn(ACCOUNT_TWO_IDENTITY_KEY);
when(profileAccount.getPhoneNumberIdentityKey()).thenReturn(ACCOUNT_TWO_PHONE_NUMBER_IDENTITY_KEY);
when(profileAccount.getIdentityKey(IdentityType.PNI)).thenReturn(ACCOUNT_TWO_PHONE_NUMBER_IDENTITY_KEY);
when(profileAccount.getUuid()).thenReturn(AuthHelper.VALID_UUID_TWO);
when(profileAccount.getPhoneNumberIdentifier()).thenReturn(AuthHelper.VALID_PNI_TWO);
@@ -207,9 +205,7 @@ class ProfileControllerTest {
Account capabilitiesAccount = mock(Account.class);
when(capabilitiesAccount.getUuid()).thenReturn(AuthHelper.VALID_UUID);
when(capabilitiesAccount.getIdentityKey()).thenReturn(ACCOUNT_IDENTITY_KEY);
when(capabilitiesAccount.getIdentityKey(IdentityType.ACI)).thenReturn(ACCOUNT_IDENTITY_KEY);
when(capabilitiesAccount.getPhoneNumberIdentityKey()).thenReturn(ACCOUNT_PHONE_NUMBER_IDENTITY_KEY);
when(capabilitiesAccount.getIdentityKey(IdentityType.PNI)).thenReturn(ACCOUNT_PHONE_NUMBER_IDENTITY_KEY);
when(capabilitiesAccount.isEnabled()).thenReturn(true);
@@ -226,9 +222,13 @@ class ProfileControllerTest {
when(accountsManager.getByAccountIdentifier(AuthHelper.VALID_UUID)).thenReturn(Optional.of(capabilitiesAccount));
when(accountsManager.getByServiceIdentifier(new AciServiceIdentifier(AuthHelper.VALID_UUID))).thenReturn(Optional.of(capabilitiesAccount));
final byte[] name = ProfileHelper.generateRandomByteArray(81);
final byte[] emoji = ProfileHelper.generateRandomByteArray(60);
final byte[] about = ProfileHelper.generateRandomByteArray(156);
when(profilesManager.get(eq(AuthHelper.VALID_UUID), eq("someversion"))).thenReturn(Optional.empty());
when(profilesManager.get(eq(AuthHelper.VALID_UUID_TWO), eq("validversion"))).thenReturn(Optional.of(new VersionedProfile(
"validversion", "validname", "profiles/validavatar", "emoji", "about", null, "validcommitmnet".getBytes())));
"validversion", name, "profiles/validavatar", emoji, about, null, "validcommitmnet".getBytes())));
clearInvocations(rateLimiter);
clearInvocations(accountsManager);
@@ -409,14 +409,14 @@ class ProfileControllerTest {
@Test
void testSetProfileWantAvatarUpload() throws InvalidInputException {
final ProfileKeyCommitment commitment = new ProfileKey(new byte[32]).getCommitment(new ServiceId.Aci(AuthHelper.VALID_UUID));
final byte[] name = ProfileHelper.generateRandomByteArray(81);
final ProfileAvatarUploadAttributes uploadAttributes = resources.getJerseyTest()
.target("/v1/profile/")
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.put(Entity.entity(new CreateProfileRequest(commitment, "someversion",
"123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678",
null, null,
ProfileHelper.encodeToBase64(name), null, null,
null, true, false, List.of()), MediaType.APPLICATION_JSON_TYPE), ProfileAvatarUploadAttributes.class);
final ArgumentCaptor<VersionedProfile> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfile.class);
@@ -426,24 +426,24 @@ class ProfileControllerTest {
verifyNoMoreInteractions(s3client);
assertThat(profileArgumentCaptor.getValue().getCommitment()).isEqualTo(commitment.serialize());
assertThat(profileArgumentCaptor.getValue().getAvatar()).isEqualTo(uploadAttributes.getKey());
assertThat(profileArgumentCaptor.getValue().getVersion()).isEqualTo("someversion");
assertThat(profileArgumentCaptor.getValue().getName()).isEqualTo("123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678");
assertThat(profileArgumentCaptor.getValue().getAboutEmoji()).isNull();
assertThat(profileArgumentCaptor.getValue().getAbout()).isNull();
assertThat(profileArgumentCaptor.getValue().commitment()).isEqualTo(commitment.serialize());
assertThat(profileArgumentCaptor.getValue().avatar()).isEqualTo(uploadAttributes.getKey());
assertThat(profileArgumentCaptor.getValue().version()).isEqualTo("someversion");
assertThat(profileArgumentCaptor.getValue().name()).isEqualTo(name);
assertThat(profileArgumentCaptor.getValue().aboutEmoji()).isNull();
assertThat(profileArgumentCaptor.getValue().about()).isNull();
}
@Test
void testSetProfileWantAvatarUploadWithBadProfileSize() throws InvalidInputException {
final ProfileKeyCommitment commitment = new ProfileKey(new byte[32]).getCommitment(new ServiceId.Aci(AuthHelper.VALID_UUID));
final String name = ProfileHelper.generateRandomBase64FromByteArray(82);
try (final Response response = resources.getJerseyTest()
.target("/v1/profile/")
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.put(Entity.entity(new CreateProfileRequest(commitment, "someversion",
"1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890",
.put(Entity.entity(new CreateProfileRequest(commitment, "someversion", name,
null, null, null, true, false, List.of()), MediaType.APPLICATION_JSON_TYPE))) {
assertThat(response.getStatus()).isEqualTo(422);
@@ -453,6 +453,7 @@ class ProfileControllerTest {
@Test
void testSetProfileWithoutAvatarUpload() throws InvalidInputException {
final ProfileKeyCommitment commitment = new ProfileKey(new byte[32]).getCommitment(new ServiceId.Aci(AuthHelper.VALID_UUID));
final byte[] name = ProfileHelper.generateRandomByteArray(81);
clearInvocations(AuthHelper.VALID_ACCOUNT_TWO);
@@ -460,7 +461,7 @@ class ProfileControllerTest {
.target("/v1/profile/")
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID_TWO, AuthHelper.VALID_PASSWORD_TWO))
.put(Entity.entity(new CreateProfileRequest(commitment, "anotherversion", "123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678", null, null,
.put(Entity.entity(new CreateProfileRequest(commitment, "anotherversion", ProfileHelper.encodeToBase64(name), null, null,
null, false, false, List.of()), MediaType.APPLICATION_JSON_TYPE))) {
assertThat(response.getStatus()).isEqualTo(200);
@@ -473,26 +474,26 @@ class ProfileControllerTest {
verifyNoMoreInteractions(s3client);
assertThat(profileArgumentCaptor.getValue().getCommitment()).isEqualTo(commitment.serialize());
assertThat(profileArgumentCaptor.getValue().getAvatar()).isNull();
assertThat(profileArgumentCaptor.getValue().getVersion()).isEqualTo("anotherversion");
assertThat(profileArgumentCaptor.getValue().getName()).isEqualTo("123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678");
assertThat(profileArgumentCaptor.getValue().getAboutEmoji()).isNull();
assertThat(profileArgumentCaptor.getValue().getAbout()).isNull();
assertThat(profileArgumentCaptor.getValue().commitment()).isEqualTo(commitment.serialize());
assertThat(profileArgumentCaptor.getValue().avatar()).isNull();
assertThat(profileArgumentCaptor.getValue().version()).isEqualTo("anotherversion");
assertThat(profileArgumentCaptor.getValue().name()).isEqualTo(name);
assertThat(profileArgumentCaptor.getValue().aboutEmoji()).isNull();
assertThat(profileArgumentCaptor.getValue().about()).isNull();
}
}
@Test
void testSetProfileWithAvatarUploadAndPreviousAvatar() throws InvalidInputException {
final ProfileKeyCommitment commitment = new ProfileKey(new byte[32]).getCommitment(new ServiceId.Aci(AuthHelper.VALID_UUID_TWO));
final byte[] name = ProfileHelper.generateRandomByteArray(81);
resources.getJerseyTest()
.target("/v1/profile/")
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID_TWO, AuthHelper.VALID_PASSWORD_TWO))
.put(Entity.entity(new CreateProfileRequest(commitment, "validversion",
"123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678",
null, null,
ProfileHelper.encodeToBase64(name), null, null,
null, true, false, List.of()), MediaType.APPLICATION_JSON_TYPE), ProfileAvatarUploadAttributes.class);
final ArgumentCaptor<VersionedProfile> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfile.class);
@@ -501,24 +502,24 @@ class ProfileControllerTest {
verify(profilesManager, times(1)).set(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture());
verify(s3client, times(1)).deleteObject(eq(DeleteObjectRequest.builder().bucket("profilesBucket").key("profiles/validavatar").build()));
assertThat(profileArgumentCaptor.getValue().getCommitment()).isEqualTo(commitment.serialize());
assertThat(profileArgumentCaptor.getValue().getAvatar()).startsWith("profiles/");
assertThat(profileArgumentCaptor.getValue().getVersion()).isEqualTo("validversion");
assertThat(profileArgumentCaptor.getValue().getName()).isEqualTo("123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678");
assertThat(profileArgumentCaptor.getValue().getAboutEmoji()).isNull();
assertThat(profileArgumentCaptor.getValue().getAbout()).isNull();
assertThat(profileArgumentCaptor.getValue().commitment()).isEqualTo(commitment.serialize());
assertThat(profileArgumentCaptor.getValue().avatar()).startsWith("profiles/");
assertThat(profileArgumentCaptor.getValue().version()).isEqualTo("validversion");
assertThat(profileArgumentCaptor.getValue().name()).isEqualTo(name);
assertThat(profileArgumentCaptor.getValue().aboutEmoji()).isNull();
assertThat(profileArgumentCaptor.getValue().about()).isNull();
}
@Test
void testSetProfileClearPreviousAvatar() throws InvalidInputException {
final ProfileKeyCommitment commitment = new ProfileKey(new byte[32]).getCommitment(new ServiceId.Aci(AuthHelper.VALID_UUID_TWO));
final byte[] name = ProfileHelper.generateRandomByteArray(81);
try (final Response response = resources.getJerseyTest()
.target("/v1/profile/")
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID_TWO, AuthHelper.VALID_PASSWORD_TWO))
.put(Entity.entity(new CreateProfileRequest(commitment, "validversion",
"123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678",
.put(Entity.entity(new CreateProfileRequest(commitment, "validversion", ProfileHelper.encodeToBase64(name),
null, null, null, false, false, List.of()), MediaType.APPLICATION_JSON_TYPE))) {
assertThat(response.getStatus()).isEqualTo(200);
@@ -530,25 +531,25 @@ class ProfileControllerTest {
verify(profilesManager, times(1)).set(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture());
verify(s3client, times(1)).deleteObject(eq(DeleteObjectRequest.builder().bucket("profilesBucket").key("profiles/validavatar").build()));
assertThat(profileArgumentCaptor.getValue().getCommitment()).isEqualTo(commitment.serialize());
assertThat(profileArgumentCaptor.getValue().getAvatar()).isNull();
assertThat(profileArgumentCaptor.getValue().getVersion()).isEqualTo("validversion");
assertThat(profileArgumentCaptor.getValue().getName()).isEqualTo("123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678");
assertThat(profileArgumentCaptor.getValue().getAboutEmoji()).isNull();
assertThat(profileArgumentCaptor.getValue().getAbout()).isNull();
assertThat(profileArgumentCaptor.getValue().commitment()).isEqualTo(commitment.serialize());
assertThat(profileArgumentCaptor.getValue().avatar()).isNull();
assertThat(profileArgumentCaptor.getValue().version()).isEqualTo("validversion");
assertThat(profileArgumentCaptor.getValue().name()).isEqualTo(name);
assertThat(profileArgumentCaptor.getValue().aboutEmoji()).isNull();
assertThat(profileArgumentCaptor.getValue().about()).isNull();
}
}
@Test
void testSetProfileWithSameAvatar() throws InvalidInputException {
final ProfileKeyCommitment commitment = new ProfileKey(new byte[32]).getCommitment(new ServiceId.Aci(AuthHelper.VALID_UUID_TWO));
final byte[] name = ProfileHelper.generateRandomByteArray(81);
try (final Response response = resources.getJerseyTest()
.target("/v1/profile/")
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID_TWO, AuthHelper.VALID_PASSWORD_TWO))
.put(Entity.entity(new CreateProfileRequest(commitment, "validversion",
"123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678",
.put(Entity.entity(new CreateProfileRequest(commitment, "validversion", ProfileHelper.encodeToBase64(name),
null, null, null, true, true, List.of()), MediaType.APPLICATION_JSON_TYPE))) {
assertThat(response.getStatus()).isEqualTo(200);
@@ -560,25 +561,25 @@ class ProfileControllerTest {
verify(profilesManager, times(1)).set(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture());
verify(s3client, never()).deleteObject(any(DeleteObjectRequest.class));
assertThat(profileArgumentCaptor.getValue().getCommitment()).isEqualTo(commitment.serialize());
assertThat(profileArgumentCaptor.getValue().getAvatar()).isEqualTo("profiles/validavatar");
assertThat(profileArgumentCaptor.getValue().getVersion()).isEqualTo("validversion");
assertThat(profileArgumentCaptor.getValue().getName()).isEqualTo("123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678");
assertThat(profileArgumentCaptor.getValue().getAboutEmoji()).isNull();
assertThat(profileArgumentCaptor.getValue().getAbout()).isNull();
assertThat(profileArgumentCaptor.getValue().commitment()).isEqualTo(commitment.serialize());
assertThat(profileArgumentCaptor.getValue().avatar()).isEqualTo("profiles/validavatar");
assertThat(profileArgumentCaptor.getValue().version()).isEqualTo("validversion");
assertThat(profileArgumentCaptor.getValue().name()).isEqualTo(name);
assertThat(profileArgumentCaptor.getValue().aboutEmoji()).isNull();
assertThat(profileArgumentCaptor.getValue().about()).isNull();
}
}
@Test
void testSetProfileClearPreviousAvatarDespiteSameAvatarFlagSet() throws InvalidInputException {
final ProfileKeyCommitment commitment = new ProfileKey(new byte[32]).getCommitment(new ServiceId.Aci(AuthHelper.VALID_UUID_TWO));
final byte[] name = ProfileHelper.generateRandomByteArray(81);
try (final Response ignored = resources.getJerseyTest()
.target("/v1/profile/")
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID_TWO, AuthHelper.VALID_PASSWORD_TWO))
.put(Entity.entity(new CreateProfileRequest(commitment, "validversion",
"123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678",
.put(Entity.entity(new CreateProfileRequest(commitment, "validversion", ProfileHelper.encodeToBase64(name),
null, null,
null, false, true, List.of()), MediaType.APPLICATION_JSON_TYPE))) {
@@ -588,25 +589,25 @@ class ProfileControllerTest {
verify(profilesManager, times(1)).set(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture());
verify(s3client, times(1)).deleteObject(eq(DeleteObjectRequest.builder().bucket("profilesBucket").key("profiles/validavatar").build()));
assertThat(profileArgumentCaptor.getValue().getCommitment()).isEqualTo(commitment.serialize());
assertThat(profileArgumentCaptor.getValue().getAvatar()).isNull();
assertThat(profileArgumentCaptor.getValue().getVersion()).isEqualTo("validversion");
assertThat(profileArgumentCaptor.getValue().getName()).isEqualTo("123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678");
assertThat(profileArgumentCaptor.getValue().getAboutEmoji()).isNull();
assertThat(profileArgumentCaptor.getValue().getAbout()).isNull();
assertThat(profileArgumentCaptor.getValue().commitment()).isEqualTo(commitment.serialize());
assertThat(profileArgumentCaptor.getValue().avatar()).isNull();
assertThat(profileArgumentCaptor.getValue().version()).isEqualTo("validversion");
assertThat(profileArgumentCaptor.getValue().name()).isEqualTo(name);
assertThat(profileArgumentCaptor.getValue().aboutEmoji()).isNull();
assertThat(profileArgumentCaptor.getValue().about()).isNull();
}
}
@Test
void testSetProfileWithSameAvatarDespiteNoPreviousAvatar() throws InvalidInputException {
final ProfileKeyCommitment commitment = new ProfileKey(new byte[32]).getCommitment(new ServiceId.Aci(AuthHelper.VALID_UUID));
final byte[] name = ProfileHelper.generateRandomByteArray(81);
try (final Response response = resources.getJerseyTest()
.target("/v1/profile/")
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.put(Entity.entity(new CreateProfileRequest(commitment, "validversion",
"123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678",
.put(Entity.entity(new CreateProfileRequest(commitment, "validversion", ProfileHelper.encodeToBase64(name),
null, null, null, true, true, List.of()), MediaType.APPLICATION_JSON_TYPE))) {
assertThat(response.getStatus()).isEqualTo(200);
@@ -618,12 +619,12 @@ class ProfileControllerTest {
verify(profilesManager, times(1)).set(eq(AuthHelper.VALID_UUID), profileArgumentCaptor.capture());
verify(s3client, never()).deleteObject(any(DeleteObjectRequest.class));
assertThat(profileArgumentCaptor.getValue().getCommitment()).isEqualTo(commitment.serialize());
assertThat(profileArgumentCaptor.getValue().getAvatar()).isNull();
assertThat(profileArgumentCaptor.getValue().getVersion()).isEqualTo("validversion");
assertThat(profileArgumentCaptor.getValue().getName()).isEqualTo("123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678");
assertThat(profileArgumentCaptor.getValue().getAboutEmoji()).isNull();
assertThat(profileArgumentCaptor.getValue().getAbout()).isNull();
assertThat(profileArgumentCaptor.getValue().commitment()).isEqualTo(commitment.serialize());
assertThat(profileArgumentCaptor.getValue().avatar()).isNull();
assertThat(profileArgumentCaptor.getValue().version()).isEqualTo("validversion");
assertThat(profileArgumentCaptor.getValue().name()).isEqualTo(name);
assertThat(profileArgumentCaptor.getValue().aboutEmoji()).isNull();
assertThat(profileArgumentCaptor.getValue().about()).isNull();
}
}
@@ -631,14 +632,15 @@ class ProfileControllerTest {
void testSetProfileExtendedName() throws InvalidInputException {
final ProfileKeyCommitment commitment = new ProfileKey(new byte[32]).getCommitment(new ServiceId.Aci(AuthHelper.VALID_UUID_TWO));
final String name = RandomStringUtils.randomAlphabetic(380);
final byte[] name = ProfileHelper.generateRandomByteArray(285);
resources.getJerseyTest()
.target("/v1/profile/")
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID_TWO, AuthHelper.VALID_PASSWORD_TWO))
.put(Entity.entity(
new CreateProfileRequest(commitment, "validversion", name, null, null, null, true, false, List.of()),
new CreateProfileRequest(commitment, "validversion", ProfileHelper.encodeToBase64(name),
null, null, null, true, false, List.of()),
MediaType.APPLICATION_JSON_TYPE), ProfileAvatarUploadAttributes.class);
final ArgumentCaptor<VersionedProfile> profileArgumentCaptor = ArgumentCaptor.forClass(VersionedProfile.class);
@@ -647,12 +649,12 @@ class ProfileControllerTest {
verify(profilesManager, times(1)).set(eq(AuthHelper.VALID_UUID_TWO), profileArgumentCaptor.capture());
verify(s3client, times(1)).deleteObject(eq(DeleteObjectRequest.builder().bucket("profilesBucket").key("profiles/validavatar").build()));
assertThat(profileArgumentCaptor.getValue().getCommitment()).isEqualTo(commitment.serialize());
assertThat(profileArgumentCaptor.getValue().getAvatar()).startsWith("profiles/");
assertThat(profileArgumentCaptor.getValue().getVersion()).isEqualTo("validversion");
assertThat(profileArgumentCaptor.getValue().getName()).isEqualTo(name);
assertThat(profileArgumentCaptor.getValue().getAboutEmoji()).isNull();
assertThat(profileArgumentCaptor.getValue().getAbout()).isNull();
assertThat(profileArgumentCaptor.getValue().commitment()).isEqualTo(commitment.serialize());
assertThat(profileArgumentCaptor.getValue().avatar()).startsWith("profiles/");
assertThat(profileArgumentCaptor.getValue().version()).isEqualTo("validversion");
assertThat(profileArgumentCaptor.getValue().name()).isEqualTo(name);
assertThat(profileArgumentCaptor.getValue().aboutEmoji()).isNull();
assertThat(profileArgumentCaptor.getValue().about()).isNull();
}
@Test
@@ -661,16 +663,17 @@ class ProfileControllerTest {
clearInvocations(AuthHelper.VALID_ACCOUNT_TWO);
final String name = RandomStringUtils.randomAlphabetic(380);
final String emoji = RandomStringUtils.randomAlphanumeric(80);
final String text = RandomStringUtils.randomAlphanumeric(720);
final byte[] name = ProfileHelper.generateRandomByteArray(81);
final byte[] emoji = ProfileHelper.generateRandomByteArray(60);
final byte[] about = ProfileHelper.generateRandomByteArray(156);
try (final Response response = resources.getJerseyTest()
.target("/v1/profile/")
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID_TWO, AuthHelper.VALID_PASSWORD_TWO))
.put(Entity.entity(
new CreateProfileRequest(commitment, "anotherversion", name, emoji, text, null, false, false, List.of()),
new CreateProfileRequest(commitment, "anotherversion", ProfileHelper.encodeToBase64(name),
ProfileHelper.encodeToBase64(emoji), ProfileHelper.encodeToBase64(about), null, false, false, List.of()),
MediaType.APPLICATION_JSON_TYPE))) {
assertThat(response.getStatus()).isEqualTo(200);
@@ -684,13 +687,13 @@ class ProfileControllerTest {
verifyNoMoreInteractions(s3client);
final VersionedProfile profile = profileArgumentCaptor.getValue();
assertThat(profile.getCommitment()).isEqualTo(commitment.serialize());
assertThat(profile.getAvatar()).isNull();
assertThat(profile.getVersion()).isEqualTo("anotherversion");
assertThat(profile.getName()).isEqualTo(name);
assertThat(profile.getAboutEmoji()).isEqualTo(emoji);
assertThat(profile.getAbout()).isEqualTo(text);
assertThat(profile.getPaymentAddress()).isNull();
assertThat(profile.commitment()).isEqualTo(commitment.serialize());
assertThat(profile.avatar()).isNull();
assertThat(profile.version()).isEqualTo("anotherversion");
assertThat(profile.name()).isEqualTo(name);
assertThat(profile.aboutEmoji()).isEqualTo(emoji);
assertThat(profile.about()).isEqualTo(about);
assertThat(profile.paymentAddress()).isNull();
}
}
@@ -700,15 +703,16 @@ class ProfileControllerTest {
clearInvocations(AuthHelper.VALID_ACCOUNT_TWO);
final String name = RandomStringUtils.randomAlphabetic(380);
final String paymentAddress = RandomStringUtils.randomAlphanumeric(776);
final byte[] name = ProfileHelper.generateRandomByteArray(81);
final byte[] paymentAddress = ProfileHelper.generateRandomByteArray(582);
try (final Response response = resources.getJerseyTest()
.target("/v1/profile")
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID_TWO, AuthHelper.VALID_PASSWORD_TWO))
.put(Entity.entity(
new CreateProfileRequest(commitment, "yetanotherversion", name, null, null, paymentAddress, false, false,
new CreateProfileRequest(commitment, "yetanotherversion", ProfileHelper.encodeToBase64(name),
null, null, ProfileHelper.encodeToBase64(paymentAddress), false, false,
List.of()), MediaType.APPLICATION_JSON_TYPE))) {
assertThat(response.getStatus()).isEqualTo(200);
@@ -722,13 +726,13 @@ class ProfileControllerTest {
verifyNoMoreInteractions(s3client);
final VersionedProfile profile = profileArgumentCaptor.getValue();
assertThat(profile.getCommitment()).isEqualTo(commitment.serialize());
assertThat(profile.getAvatar()).isNull();
assertThat(profile.getVersion()).isEqualTo("yetanotherversion");
assertThat(profile.getName()).isEqualTo(name);
assertThat(profile.getAboutEmoji()).isNull();
assertThat(profile.getAbout()).isNull();
assertThat(profile.getPaymentAddress()).isEqualTo(paymentAddress);
assertThat(profile.commitment()).isEqualTo(commitment.serialize());
assertThat(profile.avatar()).isNull();
assertThat(profile.version()).isEqualTo("yetanotherversion");
assertThat(profile.name()).isEqualTo(name);
assertThat(profile.aboutEmoji()).isNull();
assertThat(profile.about()).isNull();
assertThat(profile.paymentAddress()).isEqualTo(paymentAddress);
}
}
@@ -741,15 +745,16 @@ class ProfileControllerTest {
clearInvocations(AuthHelper.VALID_ACCOUNT_TWO);
final String name = RandomStringUtils.randomAlphabetic(380);
final String paymentAddress = RandomStringUtils.randomAlphanumeric(776);
final String name = ProfileHelper.generateRandomBase64FromByteArray(81);
final String paymentAddress = ProfileHelper.generateRandomBase64FromByteArray(582);
try (final Response response = resources.getJerseyTest()
.target("/v1/profile")
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID_TWO, AuthHelper.VALID_PASSWORD_TWO))
.put(Entity.entity(
new CreateProfileRequest(commitment, "yetanotherversion", name, null, null, paymentAddress, false, false,
new CreateProfileRequest(commitment, "yetanotherversion", name,
null, null, paymentAddress, false, false,
List.of()), MediaType.APPLICATION_JSON_TYPE))) {
assertThat(response.getStatus()).isEqualTo(403);
@@ -767,24 +772,25 @@ class ProfileControllerTest {
.thenReturn(List.of(AuthHelper.VALID_NUMBER_TWO.substring(0, 3)));
final ProfileKeyCommitment commitment = new ProfileKey(new byte[32]).getCommitment(new ServiceId.Aci(AuthHelper.VALID_UUID));
final byte[] name = ProfileHelper.generateRandomByteArray(81);
final byte[] paymentAddress = ProfileHelper.generateRandomByteArray(582);
clearInvocations(AuthHelper.VALID_ACCOUNT_TWO);
when(profilesManager.get(eq(AuthHelper.VALID_UUID_TWO), any()))
.thenReturn(Optional.of(
new VersionedProfile("1", "name", null, null, null,
existingPaymentAddressOnProfile ? RandomStringUtils.randomAlphanumeric(776) : null,
new VersionedProfile("1", name, null, null, null,
existingPaymentAddressOnProfile ? ProfileHelper.generateRandomByteArray(582) : null,
commitment.serialize())));
final String name = RandomStringUtils.randomAlphabetic(380);
final String paymentAddress = RandomStringUtils.randomAlphanumeric(776);
try (final Response response = resources.getJerseyTest()
.target("/v1/profile")
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID_TWO, AuthHelper.VALID_PASSWORD_TWO))
.put(Entity.entity(
new CreateProfileRequest(commitment, "yetanotherversion", name, null, null, paymentAddress, false, false,
new CreateProfileRequest(commitment, "yetanotherversion", ProfileHelper.encodeToBase64(name),
null, null, ProfileHelper.encodeToBase64(paymentAddress), false, false,
List.of()), MediaType.APPLICATION_JSON_TYPE))) {
if (existingPaymentAddressOnProfile) {
@@ -799,13 +805,13 @@ class ProfileControllerTest {
verifyNoMoreInteractions(s3client);
final VersionedProfile profile = profileArgumentCaptor.getValue();
assertThat(profile.getCommitment()).isEqualTo(commitment.serialize());
assertThat(profile.getAvatar()).isNull();
assertThat(profile.getVersion()).isEqualTo("yetanotherversion");
assertThat(profile.getName()).isEqualTo(name);
assertThat(profile.getAboutEmoji()).isNull();
assertThat(profile.getAbout()).isNull();
assertThat(profile.getPaymentAddress()).isEqualTo(paymentAddress);
assertThat(profile.commitment()).isEqualTo(commitment.serialize());
assertThat(profile.avatar()).isNull();
assertThat(profile.version()).isEqualTo("yetanotherversion");
assertThat(profile.name()).isEqualTo(name);
assertThat(profile.aboutEmoji()).isNull();
assertThat(profile.about()).isNull();
assertThat(profile.paymentAddress()).isEqualTo(paymentAddress);
} else {
assertThat(response.getStatus()).isEqualTo(403);
assertThat(response.hasEntity()).isFalse();
@@ -817,6 +823,13 @@ class ProfileControllerTest {
@Test
void testGetProfileByVersion() throws RateLimitExceededException {
final byte[] name = ProfileHelper.generateRandomByteArray(81);
final byte[] emoji = ProfileHelper.generateRandomByteArray(60);
final byte[] about = ProfileHelper.generateRandomByteArray(156);
when(profilesManager.get(eq(AuthHelper.VALID_UUID_TWO), eq("validversion"))).thenReturn(Optional.of(new VersionedProfile(
"validversion", name, "profiles/validavatar", emoji, about, null, "validcommitmnet".getBytes())));
final VersionedProfileResponse profile = resources.getJerseyTest()
.target("/v1/profile/" + AuthHelper.VALID_UUID_TWO + "/validversion")
.request()
@@ -824,9 +837,9 @@ class ProfileControllerTest {
.get(VersionedProfileResponse.class);
assertThat(profile.getBaseProfileResponse().getIdentityKey()).isEqualTo(ACCOUNT_TWO_IDENTITY_KEY);
assertThat(profile.getName()).isEqualTo("validname");
assertThat(profile.getAbout()).isEqualTo("about");
assertThat(profile.getAboutEmoji()).isEqualTo("emoji");
assertThat(profile.getName()).isEqualTo(ProfileHelper.encodeToBase64(name));
assertThat(profile.getAbout()).isEqualTo(ProfileHelper.encodeToBase64(about));
assertThat(profile.getAboutEmoji()).isEqualTo(ProfileHelper.encodeToBase64(emoji));
assertThat(profile.getAvatar()).isEqualTo("profiles/validavatar");
assertThat(profile.getBaseProfileResponse().getCapabilities().gv1Migration()).isTrue();
assertThat(profile.getBaseProfileResponse().getUuid()).isEqualTo(new AciServiceIdentifier(AuthHelper.VALID_UUID_TWO));
@@ -845,8 +858,8 @@ class ProfileControllerTest {
clearInvocations(AuthHelper.VALID_ACCOUNT_TWO);
final String name = RandomStringUtils.randomAlphabetic(380);
final String paymentAddress = RandomStringUtils.randomAlphanumeric(776);
final String name = ProfileHelper.generateRandomBase64FromByteArray(81);
final String paymentAddress = ProfileHelper.generateRandomBase64FromByteArray(582);
try (final Response response = resources.getJerseyTest()
.target("/v1/profile")
@@ -865,8 +878,9 @@ class ProfileControllerTest {
@Test
void testGetProfileReturnsNoPaymentAddressIfCurrentVersionMismatch() {
final byte[] paymentAddress = ProfileHelper.generateRandomByteArray(582);
when(profilesManager.get(AuthHelper.VALID_UUID_TWO, "validversion")).thenReturn(
Optional.of(new VersionedProfile(null, null, null, null, null, "paymentaddress", null)));
Optional.of(new VersionedProfile(null, null, null, null, null, paymentAddress, null)));
{
final VersionedProfileResponse profile = resources.getJerseyTest()
@@ -875,7 +889,7 @@ class ProfileControllerTest {
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.get(VersionedProfileResponse.class);
assertThat(profile.getPaymentAddress()).isEqualTo("paymentaddress");
assertThat(profile.getPaymentAddress()).isEqualTo(ProfileHelper.encodeToBase64(paymentAddress));
}
when(profileAccount.getCurrentProfileVersion()).thenReturn(Optional.of("validversion"));
@@ -887,7 +901,7 @@ class ProfileControllerTest {
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID, AuthHelper.VALID_PASSWORD))
.get(VersionedProfileResponse.class);
assertThat(profile.getPaymentAddress()).isEqualTo("paymentaddress");
assertThat(profile.getPaymentAddress()).isEqualTo(ProfileHelper.encodeToBase64(paymentAddress));
}
when(profileAccount.getCurrentProfileVersion()).thenReturn(Optional.of("someotherversion"));
@@ -934,15 +948,15 @@ class ProfileControllerTest {
clearInvocations(AuthHelper.VALID_ACCOUNT_TWO);
final String name = RandomStringUtils.randomAlphabetic(380);
final String emoji = RandomStringUtils.randomAlphanumeric(80);
final String text = RandomStringUtils.randomAlphanumeric(720);
final String name = ProfileHelper.generateRandomBase64FromByteArray(81);
final String emoji = ProfileHelper.generateRandomBase64FromByteArray(60);
final String about = ProfileHelper.generateRandomBase64FromByteArray(156);
try (final Response response = resources.getJerseyTest()
.target("/v1/profile/")
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID_TWO, AuthHelper.VALID_PASSWORD_TWO))
.put(Entity.entity(new CreateProfileRequest(commitment, "anotherversion", name, emoji, text, null, false, false,
.put(Entity.entity(new CreateProfileRequest(commitment, "anotherversion", name, emoji, about, null, false, false,
List.of("TEST2")), MediaType.APPLICATION_JSON_TYPE))) {
assertThat(response.getStatus()).isEqualTo(200);
@@ -965,7 +979,7 @@ class ProfileControllerTest {
.target("/v1/profile/")
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID_TWO, AuthHelper.VALID_PASSWORD_TWO))
.put(Entity.entity(new CreateProfileRequest(commitment, "anotherversion", name, emoji, text, null, false, false,
.put(Entity.entity(new CreateProfileRequest(commitment, "anotherversion", name, emoji, about, null, false, false,
List.of("TEST3", "TEST2")), MediaType.APPLICATION_JSON_TYPE))) {
assertThat(response.getStatus()).isEqualTo(200);
@@ -991,7 +1005,7 @@ class ProfileControllerTest {
.target("/v1/profile/")
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID_TWO, AuthHelper.VALID_PASSWORD_TWO))
.put(Entity.entity(new CreateProfileRequest(commitment, "anotherversion", name, emoji, text, null, false, false,
.put(Entity.entity(new CreateProfileRequest(commitment, "anotherversion", name, emoji, about, null, false, false,
List.of("TEST2", "TEST3")), MediaType.APPLICATION_JSON_TYPE))) {
assertThat(response.getStatus()).isEqualTo(200);
@@ -1017,7 +1031,7 @@ class ProfileControllerTest {
.target("/v1/profile/")
.request()
.header("Authorization", AuthHelper.getAuthHeader(AuthHelper.VALID_UUID_TWO, AuthHelper.VALID_PASSWORD_TWO))
.put(Entity.entity(new CreateProfileRequest(commitment, "anotherversion", name, emoji, text, null, false, false,
.put(Entity.entity(new CreateProfileRequest(commitment, "anotherversion", name, emoji, about, null, false, false,
List.of("TEST1")), MediaType.APPLICATION_JSON_TYPE))) {
assertThat(response.getStatus()).isEqualTo(200);
@@ -1055,7 +1069,7 @@ class ProfileControllerTest {
final ProfileKeyCommitment profileKeyCommitment = profileKey.getCommitment(new ServiceId.Aci(AuthHelper.VALID_UUID));
final VersionedProfile versionedProfile = mock(VersionedProfile.class);
when(versionedProfile.getCommitment()).thenReturn(profileKeyCommitment.serialize());
when(versionedProfile.commitment()).thenReturn(profileKeyCommitment.serialize());
final ProfileKeyCredentialRequestContext profileKeyCredentialRequestContext =
clientZkProfile.createProfileKeyCredentialRequestContext(new ServiceId.Aci(AuthHelper.VALID_UUID), profileKey);
@@ -1112,9 +1126,9 @@ class ProfileControllerTest {
clearInvocations(AuthHelper.VALID_ACCOUNT_TWO);
final String name = RandomStringUtils.randomAlphabetic(380);
final String emoji = RandomStringUtils.randomAlphanumeric(80);
final String text = RandomStringUtils.randomAlphanumeric(720);
final String name = ProfileHelper.generateRandomBase64FromByteArray(81);
final String emoji = ProfileHelper.generateRandomBase64FromByteArray(60);
final String text = ProfileHelper.generateRandomBase64FromByteArray(156);
when(AuthHelper.VALID_ACCOUNT_TWO.getBadges()).thenReturn(List.of(
new AccountBadge("TEST", Instant.ofEpochSecond(42 + 86400), true)
@@ -1071,7 +1071,7 @@ class VerificationControllerTest {
.request()
.header(HttpHeaders.X_FORWARDED_FOR, "127.0.0.1");
try (Response response = request.post(Entity.json(requestVerificationCodeJson("voice", "ios")))) {
assertEquals(HttpStatus.SC_BAD_GATEWAY, response.getStatus());
assertEquals(RegistrationServiceSenderExceptionMapper.REMOTE_SERVICE_REJECTED_REQUEST_STATUS, response.getStatus());
final Map<String, Object> responseMap = response.readEntity(Map.class);
@@ -12,6 +12,7 @@ import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
import io.grpc.ServerInterceptors;
@@ -102,5 +103,7 @@ class CallingGrpcServiceTest {
assertEquals(Status.Code.RESOURCE_EXHAUSTED, exception.getStatus().getCode());
assertNotNull(exception.getTrailers());
assertEquals(retryAfter, exception.getTrailers().get(RateLimitUtil.RETRY_AFTER_DURATION_KEY));
verifyNoInteractions(turnTokenGenerator);
}
}
@@ -0,0 +1,453 @@
/*
* Copyright 2023 Signal Messenger, LLC
* SPDX-License-Identifier: AGPL-3.0-only
*/
package org.whispersystems.textsecuregcm.grpc;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.google.protobuf.ByteString;
import io.grpc.ServerInterceptors;
import io.grpc.Status;
import io.grpc.StatusRuntimeException;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Base64;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadLocalRandom;
import java.util.function.Consumer;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;
import org.junitpioneer.jupiter.cartesian.CartesianTest;
import org.signal.chat.device.ClearPushTokenRequest;
import org.signal.chat.device.ClearPushTokenResponse;
import org.signal.chat.device.DevicesGrpc;
import org.signal.chat.device.GetDevicesRequest;
import org.signal.chat.device.GetDevicesResponse;
import org.signal.chat.device.RemoveDeviceRequest;
import org.signal.chat.device.RemoveDeviceResponse;
import org.signal.chat.device.SetCapabilitiesRequest;
import org.signal.chat.device.SetCapabilitiesResponse;
import org.signal.chat.device.SetDeviceNameRequest;
import org.signal.chat.device.SetDeviceNameResponse;
import org.signal.chat.device.SetPushTokenRequest;
import org.signal.chat.device.SetPushTokenResponse;
import org.whispersystems.textsecuregcm.auth.grpc.MockAuthenticationInterceptor;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.Device;
import org.whispersystems.textsecuregcm.storage.KeysManager;
import org.whispersystems.textsecuregcm.storage.MessagesManager;
class DevicesGrpcServiceTest {
private AccountsManager accountsManager;
private KeysManager keysManager;
private MessagesManager messagesManager;
private Account authenticatedAccount;
private MockAuthenticationInterceptor mockAuthenticationInterceptor;
private DevicesGrpc.DevicesBlockingStub devicesStub;
@RegisterExtension
static final GrpcServerExtension GRPC_SERVER_EXTENSION = new GrpcServerExtension();
private static final UUID AUTHENTICATED_ACI = UUID.randomUUID();
private static final long AUTHENTICATED_DEVICE_ID = Device.MASTER_ID;
@BeforeEach
void setUp() {
accountsManager = mock(AccountsManager.class);
keysManager = mock(KeysManager.class);
messagesManager = mock(MessagesManager.class);
authenticatedAccount = mock(Account.class);
when(authenticatedAccount.getUuid()).thenReturn(AUTHENTICATED_ACI);
mockAuthenticationInterceptor = new MockAuthenticationInterceptor();
mockAuthenticationInterceptor.setAuthenticatedDevice(AUTHENTICATED_ACI, AUTHENTICATED_DEVICE_ID);
when(accountsManager.getByAccountIdentifierAsync(AUTHENTICATED_ACI))
.thenReturn(CompletableFuture.completedFuture(Optional.of(authenticatedAccount)));
when(accountsManager.updateAsync(any(), any()))
.thenAnswer(invocation -> {
final Account account = invocation.getArgument(0);
final Consumer<Account> updater = invocation.getArgument(1);
updater.accept(account);
return CompletableFuture.completedFuture(account);
});
when(accountsManager.updateDeviceAsync(any(), anyLong(), any()))
.thenAnswer(invocation -> {
final Account account = invocation.getArgument(0);
final Device device = account.getDevice(invocation.getArgument(1)).orElseThrow();
final Consumer<Device> updater = invocation.getArgument(2);
updater.accept(device);
return CompletableFuture.completedFuture(account);
});
when(keysManager.delete(any(), anyLong())).thenReturn(CompletableFuture.completedFuture(null));
when(messagesManager.clear(any(), anyLong())).thenReturn(CompletableFuture.completedFuture(null));
final DevicesGrpcService devicesGrpcService = new DevicesGrpcService(accountsManager, keysManager, messagesManager);
devicesStub = DevicesGrpc.newBlockingStub(GRPC_SERVER_EXTENSION.getChannel());
GRPC_SERVER_EXTENSION.getServiceRegistry()
.addService(ServerInterceptors.intercept(devicesGrpcService, mockAuthenticationInterceptor));
}
@Test
void getDevices() {
final Instant primaryDeviceCreated = Instant.now().minus(Duration.ofDays(7)).truncatedTo(ChronoUnit.MILLIS);
final Instant primaryDeviceLastSeen = primaryDeviceCreated.plus(Duration.ofHours(6));
final Instant linkedDeviceCreated = Instant.now().minus(Duration.ofDays(1)).truncatedTo(ChronoUnit.MILLIS);
final Instant linkedDeviceLastSeen = linkedDeviceCreated.plus(Duration.ofHours(7));
final Device primaryDevice = mock(Device.class);
when(primaryDevice.getId()).thenReturn(Device.MASTER_ID);
when(primaryDevice.getCreated()).thenReturn(primaryDeviceCreated.toEpochMilli());
when(primaryDevice.getLastSeen()).thenReturn(primaryDeviceLastSeen.toEpochMilli());
final String linkedDeviceName = "A linked device";
final Device linkedDevice = mock(Device.class);
when(linkedDevice.getId()).thenReturn(Device.MASTER_ID + 1);
when(linkedDevice.getCreated()).thenReturn(linkedDeviceCreated.toEpochMilli());
when(linkedDevice.getLastSeen()).thenReturn(linkedDeviceLastSeen.toEpochMilli());
when(linkedDevice.getName())
.thenReturn(Base64.getEncoder().encodeToString(linkedDeviceName.getBytes(StandardCharsets.UTF_8)));
when(authenticatedAccount.getDevices()).thenReturn(List.of(primaryDevice, linkedDevice));
final GetDevicesResponse expectedResponse = GetDevicesResponse.newBuilder()
.addDevices(GetDevicesResponse.LinkedDevice.newBuilder()
.setId(Device.MASTER_ID)
.setCreated(primaryDeviceCreated.toEpochMilli())
.setLastSeen(primaryDeviceLastSeen.toEpochMilli())
.build())
.addDevices(GetDevicesResponse.LinkedDevice.newBuilder()
.setId(Device.MASTER_ID + 1)
.setCreated(linkedDeviceCreated.toEpochMilli())
.setLastSeen(linkedDeviceLastSeen.toEpochMilli())
.setName(ByteString.copyFrom(linkedDeviceName.getBytes(StandardCharsets.UTF_8)))
.build())
.build();
assertEquals(expectedResponse, devicesStub.getDevices(GetDevicesRequest.newBuilder().build()));
}
@Test
void removeDevice() {
final long deviceId = 17;
final RemoveDeviceResponse ignored = devicesStub.removeDevice(RemoveDeviceRequest.newBuilder()
.setId(deviceId)
.build());
verify(messagesManager, times(2)).clear(AUTHENTICATED_ACI, deviceId);
verify(keysManager).delete(AUTHENTICATED_ACI, deviceId);
verify(authenticatedAccount).removeDevice(deviceId);
}
@Test
void removeDevicePrimary() {
final StatusRuntimeException exception = assertThrows(StatusRuntimeException.class,
() -> devicesStub.removeDevice(RemoveDeviceRequest.newBuilder()
.setId(1)
.build()));
assertEquals(Status.Code.INVALID_ARGUMENT, exception.getStatus().getCode());
}
@Test
void removeDeviceNonPrimaryAuthenticated() {
mockAuthenticationInterceptor.setAuthenticatedDevice(AUTHENTICATED_ACI, Device.MASTER_ID + 1);
final StatusRuntimeException exception = assertThrows(StatusRuntimeException.class,
() -> devicesStub.removeDevice(RemoveDeviceRequest.newBuilder()
.setId(17)
.build()));
assertEquals(Status.Code.PERMISSION_DENIED, exception.getStatus().getCode());
}
@ParameterizedTest
@ValueSource(longs = {Device.MASTER_ID, Device.MASTER_ID + 1})
void setDeviceName(final long deviceId) {
mockAuthenticationInterceptor.setAuthenticatedDevice(AUTHENTICATED_ACI, deviceId);
final Device device = mock(Device.class);
when(authenticatedAccount.getDevice(deviceId)).thenReturn(Optional.of(device));
final byte[] deviceName = new byte[128];
ThreadLocalRandom.current().nextBytes(deviceName);
final SetDeviceNameResponse ignored = devicesStub.setDeviceName(SetDeviceNameRequest.newBuilder()
.setName(ByteString.copyFrom(deviceName))
.build());
verify(device).setName(Base64.getEncoder().encodeToString(deviceName));
}
@ParameterizedTest
@MethodSource
void setDeviceNameIllegalArgument(final SetDeviceNameRequest request) {
when(authenticatedAccount.getDevice(AUTHENTICATED_DEVICE_ID)).thenReturn(Optional.of(mock(Device.class)));
final StatusRuntimeException exception =
assertThrows(StatusRuntimeException.class, () -> devicesStub.setDeviceName(request));
assertEquals(Status.Code.INVALID_ARGUMENT, exception.getStatus().getCode());
}
private static Stream<Arguments> setDeviceNameIllegalArgument() {
return Stream.of(
// No device name
Arguments.of(SetDeviceNameRequest.newBuilder().build()),
// Excessively-long device name
Arguments.of(SetDeviceNameRequest.newBuilder()
.setName(ByteString.copyFrom(RandomStringUtils.randomAlphanumeric(1024).getBytes(StandardCharsets.UTF_8)))
.build())
);
}
@ParameterizedTest
@MethodSource
void setPushToken(final long deviceId,
final SetPushTokenRequest request,
@Nullable final String expectedApnsToken,
@Nullable final String expectedApnsVoipToken,
@Nullable final String expectedFcmToken) {
mockAuthenticationInterceptor.setAuthenticatedDevice(AUTHENTICATED_ACI, deviceId);
final Device device = mock(Device.class);
when(authenticatedAccount.getDevice(deviceId)).thenReturn(Optional.of(device));
final SetPushTokenResponse ignored = devicesStub.setPushToken(request);
verify(device).setApnId(expectedApnsToken);
verify(device).setVoipApnId(expectedApnsVoipToken);
verify(device).setGcmId(expectedFcmToken);
verify(device).setFetchesMessages(false);
}
private static Stream<Arguments> setPushToken() {
final String apnsToken = "apns-token";
final String apnsVoipToken = "apns-voip-token";
final String fcmToken = "fcm-token";
final Stream.Builder<Arguments> streamBuilder = Stream.builder();
for (final long deviceId : new long[] { Device.MASTER_ID, Device.MASTER_ID + 1 }) {
streamBuilder.add(Arguments.of(deviceId,
SetPushTokenRequest.newBuilder()
.setApnsTokenRequest(SetPushTokenRequest.ApnsTokenRequest.newBuilder()
.setApnsToken(apnsToken)
.setApnsVoipToken(apnsVoipToken)
.build())
.build(),
apnsToken, apnsVoipToken, null));
streamBuilder.add(Arguments.of(deviceId,
SetPushTokenRequest.newBuilder()
.setApnsTokenRequest(SetPushTokenRequest.ApnsTokenRequest.newBuilder()
.setApnsToken(apnsToken)
.build())
.build(),
apnsToken, null, null));
streamBuilder.add(Arguments.of(deviceId,
SetPushTokenRequest.newBuilder()
.setFcmTokenRequest(SetPushTokenRequest.FcmTokenRequest.newBuilder()
.setFcmToken(fcmToken)
.build())
.build(),
null, null, fcmToken));
}
return streamBuilder.build();
}
@ParameterizedTest
@MethodSource
void setPushTokenUnchanged(final SetPushTokenRequest request,
@Nullable final String apnsToken,
@Nullable final String apnsVoipToken,
@Nullable final String fcmToken) {
final Device device = mock(Device.class);
when(device.getApnId()).thenReturn(apnsToken);
when(device.getVoipApnId()).thenReturn(apnsVoipToken);
when(device.getGcmId()).thenReturn(fcmToken);
when(authenticatedAccount.getDevice(AUTHENTICATED_DEVICE_ID)).thenReturn(Optional.of(device));
final SetPushTokenResponse ignored = devicesStub.setPushToken(request);
verify(accountsManager, never()).updateDevice(any(), anyLong(), any());
}
private static Stream<Arguments> setPushTokenUnchanged() {
final String apnsToken = "apns-token";
final String apnsVoipToken = "apns-voip-token";
final String fcmToken = "fcm-token";
return Stream.of(
Arguments.of(SetPushTokenRequest.newBuilder()
.setApnsTokenRequest(SetPushTokenRequest.ApnsTokenRequest.newBuilder()
.setApnsToken(apnsToken)
.setApnsVoipToken(apnsVoipToken)
.build())
.build(),
apnsToken, apnsVoipToken, null, false),
Arguments.of(SetPushTokenRequest.newBuilder()
.setApnsTokenRequest(SetPushTokenRequest.ApnsTokenRequest.newBuilder()
.setApnsToken(apnsToken)
.build())
.build(),
apnsToken, null, null, false),
Arguments.of(SetPushTokenRequest.newBuilder()
.setFcmTokenRequest(SetPushTokenRequest.FcmTokenRequest.newBuilder()
.setFcmToken(fcmToken)
.build())
.build(),
null, null, fcmToken, false)
);
}
@ParameterizedTest
@MethodSource
void setPushTokenIllegalArgument(final SetPushTokenRequest request) {
final Device device = mock(Device.class);
when(authenticatedAccount.getDevice(AUTHENTICATED_DEVICE_ID)).thenReturn(Optional.of(device));
final StatusRuntimeException exception =
assertThrows(StatusRuntimeException.class, () -> devicesStub.setPushToken(request));
assertEquals(Status.Code.INVALID_ARGUMENT, exception.getStatus().getCode());
verify(accountsManager, never()).updateDevice(any(), anyLong(), any());
}
private static Stream<Arguments> setPushTokenIllegalArgument() {
return Stream.of(
Arguments.of(SetPushTokenRequest.newBuilder().build()),
Arguments.of(SetPushTokenRequest.newBuilder()
.setApnsTokenRequest(SetPushTokenRequest.ApnsTokenRequest.newBuilder().build())
.build()),
Arguments.of(SetPushTokenRequest.newBuilder()
.setFcmTokenRequest(SetPushTokenRequest.FcmTokenRequest.newBuilder().build())
.build())
);
}
@ParameterizedTest
@MethodSource
void clearPushToken(final long deviceId,
@Nullable final String apnsToken,
@Nullable final String apnsVoipToken,
@Nullable final String fcmToken,
@Nullable final String expectedUserAgent) {
mockAuthenticationInterceptor.setAuthenticatedDevice(AUTHENTICATED_ACI, deviceId);
final Device device = mock(Device.class);
when(device.getId()).thenReturn(deviceId);
when(device.isMaster()).thenReturn(deviceId == Device.MASTER_ID);
when(device.getApnId()).thenReturn(apnsToken);
when(device.getVoipApnId()).thenReturn(apnsVoipToken);
when(device.getGcmId()).thenReturn(fcmToken);
when(authenticatedAccount.getDevice(deviceId)).thenReturn(Optional.of(device));
final ClearPushTokenResponse ignored = devicesStub.clearPushToken(ClearPushTokenRequest.newBuilder().build());
verify(device).setApnId(null);
verify(device).setVoipApnId(null);
verify(device).setGcmId(null);
verify(device).setFetchesMessages(true);
if (expectedUserAgent != null) {
verify(device).setUserAgent(expectedUserAgent);
} else {
verify(device, never()).setUserAgent(any());
}
}
private static Stream<Arguments> clearPushToken() {
return Stream.of(
Arguments.of(Device.MASTER_ID, "apns-token", null, null, "OWI"),
Arguments.of(Device.MASTER_ID, "apns-token", "apns-voip-token", null, "OWI"),
Arguments.of(Device.MASTER_ID, null, "apns-voip-token", null, "OWI"),
Arguments.of(Device.MASTER_ID, null, null, "fcm-token", "OWA"),
Arguments.of(Device.MASTER_ID, null, null, null, null),
Arguments.of(Device.MASTER_ID + 1, "apns-token", null, null, "OWP"),
Arguments.of(Device.MASTER_ID + 1, "apns-token", "apns-voip-token", null, "OWP"),
Arguments.of(Device.MASTER_ID + 1, null, "apns-voip-token", null, "OWP"),
Arguments.of(Device.MASTER_ID + 1, null, null, "fcm-token", "OWA"),
Arguments.of(Device.MASTER_ID + 1, null, null, null, null)
);
}
@CartesianTest
void setCapabilities(
@CartesianTest.Values(longs = {Device.MASTER_ID, Device.MASTER_ID + 1}) final long deviceId,
@CartesianTest.Values(booleans = {true, false}) final boolean storage,
@CartesianTest.Values(booleans = {true, false}) final boolean transfer,
@CartesianTest.Values(booleans = {true, false}) final boolean pni,
@CartesianTest.Values(booleans = {true, false}) final boolean paymentActivation) {
mockAuthenticationInterceptor.setAuthenticatedDevice(AUTHENTICATED_ACI, deviceId);
final Device device = mock(Device.class);
when(authenticatedAccount.getDevice(deviceId)).thenReturn(Optional.of(device));
final SetCapabilitiesResponse ignored = devicesStub.setCapabilities(SetCapabilitiesRequest.newBuilder()
.setStorage(storage)
.setTransfer(transfer)
.setPni(pni)
.setPaymentActivation(paymentActivation)
.build());
final Device.DeviceCapabilities expectedCapabilities = new Device.DeviceCapabilities(
storage,
transfer,
pni,
paymentActivation);
verify(device).setCapabilities(expectedCapabilities);
}
}
@@ -14,6 +14,7 @@ import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
import com.google.protobuf.ByteString;
@@ -669,5 +670,7 @@ class KeysGrpcServiceTest {
assertEquals(Status.Code.RESOURCE_EXHAUSTED, exception.getStatus().getCode());
assertNotNull(exception.getTrailers());
assertEquals(retryAfterDuration, exception.getTrailers().get(RateLimitUtil.RETRY_AFTER_DURATION_KEY));
verifyNoInteractions(accountsManager);
}
}
@@ -39,7 +39,6 @@ import org.whispersystems.textsecuregcm.tests.util.AuthHelper;
import software.amazon.awssdk.services.s3.S3AsyncClient;
import software.amazon.awssdk.services.s3.model.DeleteObjectRequest;
import java.time.Clock;
import java.util.Base64;
import java.util.Collections;
import java.util.List;
import java.util.Map;
@@ -136,8 +135,8 @@ public class ProfileGrpcServiceTest {
when(account.getNumber()).thenReturn(phoneNumber);
when(account.getBadges()).thenReturn(Collections.emptyList());
when(profile.getPaymentAddress()).thenReturn(null);
when(profile.getAvatar()).thenReturn("");
when(profile.paymentAddress()).thenReturn(null);
when(profile.avatar()).thenReturn("");
when(accountsManager.getByAccountIdentifierAsync(any())).thenReturn(CompletableFuture.completedFuture(Optional.of(account)));
when(accountsManager.updateAsync(any(), any())).thenReturn(CompletableFuture.completedFuture(null));
@@ -178,13 +177,13 @@ public class ProfileGrpcServiceTest {
final VersionedProfile profile = profileArgumentCaptor.getValue();
assertThat(profile.getCommitment()).isEqualTo(commitment);
assertThat(profile.getAvatar()).isNull();
assertThat(profile.getVersion()).isEqualTo(VERSION);
assertThat(profile.getName()).isEqualTo(encodeToBase64(VALID_NAME));
assertThat(profile.getAboutEmoji()).isEqualTo(encodeToBase64(validAboutEmoji));
assertThat(profile.getAbout()).isEqualTo(encodeToBase64(validAbout));
assertThat(profile.getPaymentAddress()).isEqualTo(encodeToBase64(validPaymentAddress));
assertThat(profile.commitment()).isEqualTo(commitment);
assertThat(profile.avatar()).isNull();
assertThat(profile.version()).isEqualTo(VERSION);
assertThat(profile.name()).isEqualTo(VALID_NAME);
assertThat(profile.aboutEmoji()).isEqualTo(validAboutEmoji);
assertThat(profile.about()).isEqualTo(validAbout);
assertThat(profile.paymentAddress()).isEqualTo(validPaymentAddress);
}
@ParameterizedTest
@@ -201,7 +200,7 @@ public class ProfileGrpcServiceTest {
.setCommitment(ByteString.copyFrom(commitment))
.build();
when(profile.getAvatar()).thenReturn(currentAvatar);
when(profile.avatar()).thenReturn(currentAvatar);
when(profilesManager.getAsync(any(), anyString())).thenReturn(CompletableFuture.completedFuture(
hasPreviousProfile ? Optional.of(profile) : Optional.empty()));
@@ -301,7 +300,7 @@ public class ProfileGrpcServiceTest {
final byte[] validPaymentAddress = new byte[582];
if (hasExistingPaymentAddress) {
when(profile.getPaymentAddress()).thenReturn(encodeToBase64(validPaymentAddress));
when(profile.paymentAddress()).thenReturn(validPaymentAddress);
}
final SetProfileRequest request = SetProfileRequest.newBuilder()
@@ -327,8 +326,4 @@ public class ProfileGrpcServiceTest {
assertEquals(Status.PERMISSION_DENIED.getCode(), exception.getStatus().getCode());
}
}
private static String encodeToBase64(byte[] input) {
return Base64.getEncoder().encodeToString(input);
}
}
@@ -5,8 +5,13 @@
package org.whispersystems.textsecuregcm.metrics;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import io.micrometer.core.instrument.Meter;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import java.util.List;
import org.junit.jupiter.api.Test;
@@ -19,4 +24,20 @@ class MetricsUtilTest {
assertEquals("chat.MetricsUtilTest.namespace.metric",
MetricsUtil.name(MetricsUtilTest.class, "namespace", "metric"));
}
@Test
void lettuceTagRejection() {
MeterRegistry registry = new SimpleMeterRegistry();
MetricsUtil.configureMeterFilters(registry.config());
registry.counter("lettuce.command.completion.max", "command", "hello", "remote", "world", "allowed", "!").increment();
final List<Meter> meters = registry.getMeters();
assertThat(meters).hasSize(1);
Meter meter = meters.get(0);
assertThat(meter.getId().getName()).isEqualTo("chat.lettuce.command.completion.max");
assertThat(meter.getId().getTag("command")).isNull();
assertThat(meter.getId().getTag("remote")).isNull();
assertThat(meter.getId().getTag("allowed")).isNotNull();
}
}
@@ -31,6 +31,7 @@ import org.whispersystems.textsecuregcm.controllers.MismatchedDevicesException;
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
import org.whispersystems.textsecuregcm.redis.RedisClusterExtension;
import org.whispersystems.textsecuregcm.securebackup.SecureBackupClient;
@@ -103,6 +104,9 @@ class AccountsManagerChangeNumberIntegrationTest {
final KeysManager keysManager = mock(KeysManager.class);
when(keysManager.delete(any())).thenReturn(CompletableFuture.completedFuture(null));
final MessagesManager messagesManager = mock(MessagesManager.class);
when(messagesManager.clear(any())).thenReturn(CompletableFuture.completedFuture(null));
accountsManager = new AccountsManager(
accounts,
phoneNumberIdentifiers,
@@ -110,7 +114,7 @@ class AccountsManagerChangeNumberIntegrationTest {
accountLockManager,
deletedAccounts,
keysManager,
mock(MessagesManager.class),
messagesManager,
mock(ProfilesManager.class),
secureStorageClient,
secureBackupClient,
@@ -177,12 +181,12 @@ class AccountsManagerChangeNumberIntegrationTest {
assertEquals(Optional.empty(), deletedAccounts.findUuid(originalNumber));
assertEquals(Optional.empty(), deletedAccounts.findUuid(secondNumber));
assertEquals(pniIdentityKey, updatedAccount.getPhoneNumberIdentityKey());
assertEquals(pniIdentityKey, updatedAccount.getIdentityKey(IdentityType.PNI));
assertEquals(OptionalInt.of(rotatedPniRegistrationId),
updatedAccount.getMasterDevice().orElseThrow().getPhoneNumberIdentityRegistrationId());
assertEquals(rotatedSignedPreKey, updatedAccount.getMasterDevice().orElseThrow().getPhoneNumberIdentitySignedPreKey());
assertEquals(rotatedSignedPreKey, updatedAccount.getMasterDevice().orElseThrow().getSignedPreKey(IdentityType.PNI));
}
@Test
@@ -43,6 +43,7 @@ import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.entities.AccountAttributes;
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
import org.whispersystems.textsecuregcm.securebackup.SecureBackupClient;
import org.whispersystems.textsecuregcm.securestorage.SecureStorageClient;
@@ -194,7 +195,7 @@ class AccountsManagerConcurrentModificationIntegrationTest {
assertAll(name,
() -> assertEquals(discoverableByPhoneNumber, account.isDiscoverableByPhoneNumber()),
() -> assertEquals(currentProfileVersion, account.getCurrentProfileVersion().orElseThrow()),
() -> assertEquals(identityKey, account.getIdentityKey()),
() -> assertEquals(identityKey, account.getIdentityKey(IdentityType.ACI)),
() -> assertArrayEquals(unidentifiedAccessKey, account.getUnidentifiedAccessKey().orElseThrow()),
() -> assertTrue(account.getRegistrationLock().verify(clientRegistrationLock)),
() -> assertEquals(unrestrictedUnidentifiedAccess, account.isUnrestrictedUnidentifiedAccess())
@@ -31,6 +31,8 @@ import static org.mockito.Mockito.when;
import io.lettuce.core.RedisException;
import io.lettuce.core.cluster.api.async.RedisAdvancedClusterAsyncCommands;
import io.lettuce.core.cluster.api.sync.RedisAdvancedClusterCommands;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.time.Clock;
import java.time.Duration;
import java.util.ArrayList;
@@ -39,6 +41,7 @@ import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
@@ -63,6 +66,7 @@ import org.whispersystems.textsecuregcm.entities.ECSignedPreKey;
import org.whispersystems.textsecuregcm.entities.KEMSignedPreKey;
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
import org.whispersystems.textsecuregcm.identity.AciServiceIdentifier;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.identity.PniServiceIdentifier;
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
import org.whispersystems.textsecuregcm.securebackup.SecureBackupClient;
@@ -188,6 +192,7 @@ class AccountsManagerTest {
}).when(accountLockManager).withLock(any(), any());
when(keysManager.delete(any())).thenReturn(CompletableFuture.completedFuture(null));
when(messagesManager.clear(any())).thenReturn(CompletableFuture.completedFuture(null));
accountsManager = new AccountsManager(
accounts,
@@ -789,7 +794,7 @@ class AccountsManagerTest {
account = accountsManager.update(account, a -> a.setIdentityKey(identityKey));
assertEquals(1, account.getVersion());
assertEquals(identityKey, account.getIdentityKey());
assertEquals(identityKey, account.getIdentityKey(IdentityType.ACI));
verify(accounts, times(1)).getByAccountIdentifier(uuid);
verify(accounts, times(2)).update(any());
@@ -816,7 +821,7 @@ class AccountsManagerTest {
account = accountsManager.updateAsync(account, a -> a.setIdentityKey(identityKey)).join();
assertEquals(1, account.getVersion());
assertEquals(identityKey, account.getIdentityKey());
assertEquals(identityKey, account.getIdentityKey(IdentityType.ACI));
verify(accounts, times(1)).getByAccountIdentifierAsync(uuid);
verify(accounts, times(2)).updateAsync(any());
@@ -1145,7 +1150,8 @@ class AccountsManagerTest {
UUID oldUuid = account.getUuid();
UUID oldPni = account.getPhoneNumberIdentifier();
Map<Long, ECSignedPreKey> oldSignedPreKeys = account.getDevices().stream().collect(Collectors.toMap(Device::getId, Device::getSignedPreKey));
Map<Long, ECSignedPreKey> oldSignedPreKeys = account.getDevices().stream()
.collect(Collectors.toMap(Device::getId, d -> d.getSignedPreKey(IdentityType.ACI)));
final IdentityKey pniIdentityKey = new IdentityKey(Curve.generateKeyPair().getPublicKey());
@@ -1158,15 +1164,17 @@ class AccountsManagerTest {
assertEquals(oldUuid, updatedAccount.getUuid());
assertEquals(number, updatedAccount.getNumber());
assertEquals(oldPni, updatedAccount.getPhoneNumberIdentifier());
assertNull(updatedAccount.getIdentityKey());
assertEquals(oldSignedPreKeys, updatedAccount.getDevices().stream().collect(Collectors.toMap(Device::getId, Device::getSignedPreKey)));
assertNull(updatedAccount.getIdentityKey(IdentityType.ACI));
assertEquals(oldSignedPreKeys, updatedAccount.getDevices().stream()
.collect(Collectors.toMap(Device::getId, d -> d.getSignedPreKey(IdentityType.ACI))));
assertEquals(Map.of(1L, 101, 2L, 102),
updatedAccount.getDevices().stream().collect(Collectors.toMap(Device::getId, Device::getRegistrationId)));
// PNI stuff should
assertEquals(pniIdentityKey, updatedAccount.getPhoneNumberIdentityKey());
assertEquals(pniIdentityKey, updatedAccount.getIdentityKey(IdentityType.PNI));
assertEquals(newSignedKeys,
updatedAccount.getDevices().stream().collect(Collectors.toMap(Device::getId, Device::getPhoneNumberIdentitySignedPreKey)));
updatedAccount.getDevices().stream()
.collect(Collectors.toMap(Device::getId, d -> d.getSignedPreKey(IdentityType.PNI))));
assertEquals(newRegistrationIds,
updatedAccount.getDevices().stream().collect(Collectors.toMap(Device::getId, d -> d.getPhoneNumberIdentityRegistrationId().getAsInt())));
@@ -1198,7 +1206,8 @@ class AccountsManagerTest {
when(keysManager.storeEcSignedPreKeys(any(), any())).thenReturn(CompletableFuture.completedFuture(null));
when(keysManager.storePqLastResort(any(), any())).thenReturn(CompletableFuture.completedFuture(null));
Map<Long, ECSignedPreKey> oldSignedPreKeys = account.getDevices().stream().collect(Collectors.toMap(Device::getId, Device::getSignedPreKey));
Map<Long, ECSignedPreKey> oldSignedPreKeys = account.getDevices().stream()
.collect(Collectors.toMap(Device::getId, d -> d.getSignedPreKey(IdentityType.ACI)));
final IdentityKey pniIdentityKey = new IdentityKey(Curve.generateKeyPair().getPublicKey());
@@ -1209,15 +1218,17 @@ class AccountsManagerTest {
assertEquals(oldUuid, updatedAccount.getUuid());
assertEquals(number, updatedAccount.getNumber());
assertEquals(oldPni, updatedAccount.getPhoneNumberIdentifier());
assertNull(updatedAccount.getIdentityKey());
assertEquals(oldSignedPreKeys, updatedAccount.getDevices().stream().collect(Collectors.toMap(Device::getId, Device::getSignedPreKey)));
assertNull(updatedAccount.getIdentityKey(IdentityType.ACI));
assertEquals(oldSignedPreKeys, updatedAccount.getDevices().stream()
.collect(Collectors.toMap(Device::getId, d -> d.getSignedPreKey(IdentityType.ACI))));
assertEquals(Map.of(1L, 101, 2L, 102),
updatedAccount.getDevices().stream().collect(Collectors.toMap(Device::getId, Device::getRegistrationId)));
// PNI keys should
assertEquals(pniIdentityKey, updatedAccount.getPhoneNumberIdentityKey());
assertEquals(pniIdentityKey, updatedAccount.getIdentityKey(IdentityType.PNI));
assertEquals(newSignedKeys,
updatedAccount.getDevices().stream().collect(Collectors.toMap(Device::getId, Device::getPhoneNumberIdentitySignedPreKey)));
updatedAccount.getDevices().stream()
.collect(Collectors.toMap(Device::getId, d -> d.getSignedPreKey(IdentityType.PNI))));
assertEquals(newRegistrationIds,
updatedAccount.getDevices().stream().collect(Collectors.toMap(Device::getId, d -> d.getPhoneNumberIdentityRegistrationId().getAsInt())));
@@ -1320,6 +1331,46 @@ class AccountsManagerTest {
assertThrows(AssertionError.class, () -> accountsManager.update(account, a -> a.setUsernameHash(USERNAME_HASH_1)));
}
@Test
void testJsonRoundTripSerialization() throws Exception {
String originalJson;
try (InputStream inputStream = getClass().getResourceAsStream(
"AccountsManagerTest-testJsonRoundTripSerialization.json")) {
Objects.requireNonNull(inputStream);
originalJson = new String(inputStream.readAllBytes(), StandardCharsets.UTF_8);
}
final Account originalAccount = AccountsManager.parseAccountJson(originalJson,
UUID.fromString("111111-1111-1111-1111-111111111111")).orElseThrow();
final String serialized = AccountsManager.writeRedisAccountJson(originalAccount);
final Account parsedAccount = AccountsManager.parseAccountJson(serialized, originalAccount.getUuid()).orElseThrow();
assertEquals(originalAccount.getUuid(), parsedAccount.getUuid());
assertEquals(originalAccount.getPhoneNumberIdentifier(), parsedAccount.getPhoneNumberIdentifier());
assertEquals(originalAccount.getIdentityKey(IdentityType.ACI), parsedAccount.getIdentityKey(IdentityType.ACI));
assertEquals(originalAccount.getIdentityKey(IdentityType.PNI), parsedAccount.getIdentityKey(IdentityType.PNI));
assertEquals(originalAccount.getNumber(), parsedAccount.getNumber());
assertArrayEquals(originalAccount.getUnidentifiedAccessKey().orElseThrow(),
parsedAccount.getUnidentifiedAccessKey().orElseThrow());
assertEquals(originalAccount.isDiscoverableByPhoneNumber(), parsedAccount.isDiscoverableByPhoneNumber());
assertEquals(originalAccount.isUnrestrictedUnidentifiedAccess(), parsedAccount.isUnrestrictedUnidentifiedAccess());
assertEquals(originalAccount.getDevices().size(), parsedAccount.getDevices().size());
final Device originalDevice = originalAccount.getMasterDevice().orElseThrow();
final Device parsedDevice = parsedAccount.getMasterDevice().orElseThrow();
assertEquals(originalDevice.getId(), parsedDevice.getId());
assertEquals(originalDevice.getSignedPreKey(IdentityType.ACI), parsedDevice.getSignedPreKey(IdentityType.ACI));
assertEquals(originalDevice.getSignedPreKey(IdentityType.PNI), parsedDevice.getSignedPreKey(IdentityType.PNI));
assertEquals(originalDevice.getRegistrationId(), parsedDevice.getRegistrationId());
assertEquals(originalDevice.getPhoneNumberIdentityRegistrationId(),
parsedDevice.getPhoneNumberIdentityRegistrationId());
assertEquals(originalDevice.getCapabilities(), parsedDevice.getCapabilities());
assertEquals(originalDevice.getFetchesMessages(), parsedDevice.getFetchesMessages());
}
private void setReservationHash(final Account account, final byte[] reservedUsernameHash) {
account.setReservedUsernameHash(reservedUsernameHash);
}
@@ -48,6 +48,7 @@ import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.whispersystems.textsecuregcm.configuration.dynamic.DynamicConfiguration;
import org.whispersystems.textsecuregcm.experiment.ExperimentEnrollmentManager;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.push.ClientPresenceManager;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
import org.whispersystems.textsecuregcm.securebackup.SecureBackupClient;
@@ -182,13 +183,13 @@ class AccountsTest {
accounts.create(account);
final UUID linkHandle = UUID.randomUUID();
final byte[] encruptedUsername = RandomUtils.nextBytes(32);
accountsManager.update(account, a -> a.setUsernameLinkDetails(linkHandle, encruptedUsername));
final byte[] encryptedUsername = RandomUtils.nextBytes(32);
accountsManager.update(account, a -> a.setUsernameLinkDetails(linkHandle, encryptedUsername));
final Optional<Account> maybeAccount = accountsManager.getByUsernameLinkHandle(linkHandle);
assertTrue(maybeAccount.isPresent());
assertTrue(maybeAccount.get().getEncryptedUsername().isPresent());
assertArrayEquals(encruptedUsername, maybeAccount.get().getEncryptedUsername().get());
assertArrayEquals(encryptedUsername, maybeAccount.get().getEncryptedUsername().get());
// making some unrelated change and updating account to check that username link data is still there
final Optional<Account> accountToChange = accountsManager.getByAccountIdentifier(account.getUuid());
@@ -197,7 +198,7 @@ class AccountsTest {
final Optional<Account> accountAfterChange = accountsManager.getByUsernameLinkHandle(linkHandle);
assertTrue(accountAfterChange.isPresent());
assertTrue(accountAfterChange.get().getEncryptedUsername().isPresent());
assertArrayEquals(encruptedUsername, accountAfterChange.get().getEncryptedUsername().get());
assertArrayEquals(encryptedUsername, accountAfterChange.get().getEncryptedUsername().get());
// now deleting the link
final Optional<Account> accountToDeleteLink = accountsManager.getByAccountIdentifier(account.getUuid());
@@ -746,7 +747,7 @@ class AccountsTest {
accounts.reserveUsernameHash(account, USERNAME_HASH_1, Duration.ofDays(1));
accounts.confirmUsernameHash(account, USERNAME_HASH_1, ENCRYPTED_USERNAME_1);
final UUID oldHandle = account.getUsernameLinkHandle();
{
final Optional<Account> maybeAccount = accounts.getByUsernameHash(USERNAME_HASH_1);
@@ -1116,7 +1117,8 @@ class AccountsTest {
assertThat(resultDevice.getApnId()).isEqualTo(expectingDevice.getApnId());
assertThat(resultDevice.getGcmId()).isEqualTo(expectingDevice.getGcmId());
assertThat(resultDevice.getLastSeen()).isEqualTo(expectingDevice.getLastSeen());
assertThat(resultDevice.getSignedPreKey()).isEqualTo(expectingDevice.getSignedPreKey());
assertThat(resultDevice.getSignedPreKey(IdentityType.ACI)).isEqualTo(
expectingDevice.getSignedPreKey(IdentityType.ACI));
assertThat(resultDevice.getFetchesMessages()).isEqualTo(expectingDevice.getFetchesMessages());
assertThat(resultDevice.getUserAgent()).isEqualTo(expectingDevice.getUserAgent());
assertThat(resultDevice.getName()).isEqualTo(expectingDevice.getName());
@@ -320,7 +320,7 @@ class MessagesCacheTest {
}
}
messagesCache.clear(DESTINATION_UUID, DESTINATION_DEVICE_ID);
messagesCache.clear(DESTINATION_UUID, DESTINATION_DEVICE_ID).join();
assertEquals(Collections.emptyList(), get(DESTINATION_UUID, DESTINATION_DEVICE_ID, messageCount));
assertEquals(messageCount, get(DESTINATION_UUID, DESTINATION_DEVICE_ID + 1, messageCount).size());
@@ -340,18 +340,12 @@ class MessagesCacheTest {
}
}
messagesCache.clear(DESTINATION_UUID);
messagesCache.clear(DESTINATION_UUID).join();
assertEquals(Collections.emptyList(), get(DESTINATION_UUID, DESTINATION_DEVICE_ID, messageCount));
assertEquals(Collections.emptyList(), get(DESTINATION_UUID, DESTINATION_DEVICE_ID + 1, messageCount));
}
@Test
void testClearNullUuid() {
// We're happy as long as this doesn't throw an exception
messagesCache.clear(null);
}
@Test
void testGetAccountFromQueueName() {
assertEquals(DESTINATION_UUID,
@@ -194,7 +194,7 @@ class MessagesDynamoDbTest {
assertThat(load(secondDestinationUuid, 1, MessagesDynamoDb.RESULT_SET_CHUNK_SIZE)).isNotNull()
.hasSize(1).element(0).isEqualTo(MESSAGE2);
messagesDynamoDb.deleteAllMessagesForAccount(destinationUuid);
messagesDynamoDb.deleteAllMessagesForAccount(destinationUuid).join();
assertThat(load(destinationUuid, 1, MessagesDynamoDb.RESULT_SET_CHUNK_SIZE)).isNotNull().isEmpty();
assertThat(load(destinationUuid, 2, MessagesDynamoDb.RESULT_SET_CHUNK_SIZE)).isNotNull().isEmpty();
@@ -217,7 +217,7 @@ class MessagesDynamoDbTest {
assertThat(load(secondDestinationUuid, 1, MessagesDynamoDb.RESULT_SET_CHUNK_SIZE)).isNotNull()
.hasSize(1).element(0).isEqualTo(MESSAGE2);
messagesDynamoDb.deleteAllMessagesForDevice(destinationUuid, 2);
messagesDynamoDb.deleteAllMessagesForDevice(destinationUuid, 2).join();
assertThat(load(destinationUuid, 1, MessagesDynamoDb.RESULT_SET_CHUNK_SIZE)).isNotNull().hasSize(1)
.element(0).isEqualTo(MESSAGE1);
@@ -5,7 +5,7 @@
package org.whispersystems.textsecuregcm.storage;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -21,15 +21,18 @@ import static org.mockito.Mockito.when;
import io.lettuce.core.RedisException;
import io.lettuce.core.cluster.api.async.RedisAdvancedClusterAsyncCommands;
import io.lettuce.core.cluster.api.sync.RedisAdvancedClusterCommands;
import java.util.Base64;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import org.signal.libsignal.protocol.ServiceId;
import org.signal.libsignal.zkgroup.InvalidInputException;
import org.signal.libsignal.zkgroup.profiles.ProfileKey;
import org.whispersystems.textsecuregcm.redis.FaultTolerantRedisCluster;
import org.whispersystems.textsecuregcm.tests.util.MockRedisFuture;
import org.whispersystems.textsecuregcm.tests.util.ProfileHelper;
import org.whispersystems.textsecuregcm.tests.util.RedisClusterHelper;
@Timeout(value = 10, threadMode = Timeout.ThreadMode.SEPARATE_THREAD)
@@ -57,17 +60,21 @@ public class ProfilesManagerTest {
}
@Test
public void testGetProfileInCache() {
UUID uuid = UUID.randomUUID();
when(commands.hget(eq("profiles::" + uuid), eq("someversion"))).thenReturn("{\"version\": \"someversion\", \"name\": \"somename\", \"avatar\": \"someavatar\", \"commitment\":\"" + Base64.getEncoder().encodeToString("somecommitment".getBytes()) + "\"}");
public void testGetProfileInCache() throws InvalidInputException {
final UUID uuid = UUID.randomUUID();
final byte[] name = ProfileHelper.generateRandomByteArray(81);
final byte[] commitment = new ProfileKey(new byte[32]).getCommitment(new ServiceId.Aci(uuid)).serialize();
when(commands.hget(eq("profiles::" + uuid), eq("someversion"))).thenReturn(String.format(
"{\"version\": \"someversion\", \"name\": \"%s\", \"avatar\": \"someavatar\", \"commitment\":\"%s\"}",
ProfileHelper.encodeToBase64(name),
ProfileHelper.encodeToBase64(commitment)));
Optional<VersionedProfile> profile = profilesManager.get(uuid, "someversion");
assertTrue(profile.isPresent());
assertEquals(profile.get().getName(), "somename");
assertEquals(profile.get().getAvatar(), "someavatar");
assertThat(profile.get().getCommitment()).isEqualTo("somecommitment".getBytes());
assertArrayEquals(profile.get().name(), name);
assertEquals(profile.get().avatar(), "someavatar");
assertArrayEquals(profile.get().commitment(), commitment);
verify(commands, times(1)).hget(eq("profiles::" + uuid), eq("someversion"));
verifyNoMoreInteractions(commands);
@@ -75,18 +82,22 @@ public class ProfilesManagerTest {
}
@Test
public void testGetProfileAsyncInCache() {
UUID uuid = UUID.randomUUID();
public void testGetProfileAsyncInCache() throws InvalidInputException {
final UUID uuid = UUID.randomUUID();
final byte[] name = ProfileHelper.generateRandomByteArray(81);
final byte[] commitment = new ProfileKey(new byte[32]).getCommitment(new ServiceId.Aci(uuid)).serialize();
when(asyncCommands.hget(eq("profiles::" + uuid), eq("someversion"))).thenReturn(
MockRedisFuture.completedFuture("{\"version\": \"someversion\", \"name\": \"somename\", \"avatar\": \"someavatar\", \"commitment\":\"" + Base64.getEncoder().encodeToString("somecommitment".getBytes()) + "\"}"));
MockRedisFuture.completedFuture(String.format("{\"version\": \"someversion\", \"name\": \"%s\", \"avatar\": \"someavatar\", \"commitment\":\"%s\"}",
ProfileHelper.encodeToBase64(name),
ProfileHelper.encodeToBase64(commitment))));
Optional<VersionedProfile> profile = profilesManager.getAsync(uuid, "someversion").join();
assertTrue(profile.isPresent());
assertEquals(profile.get().getName(), "somename");
assertEquals(profile.get().getAvatar(), "someavatar");
assertThat(profile.get().getCommitment()).isEqualTo("somecommitment".getBytes());
assertArrayEquals(profile.get().name(), name);
assertEquals(profile.get().avatar(), "someavatar");
assertArrayEquals(profile.get().commitment(), commitment);
verify(asyncCommands, times(1)).hget(eq("profiles::" + uuid), eq("someversion"));
verifyNoMoreInteractions(asyncCommands);
@@ -95,8 +106,9 @@ public class ProfilesManagerTest {
@Test
public void testGetProfileNotInCache() {
UUID uuid = UUID.randomUUID();
VersionedProfile profile = new VersionedProfile("someversion", "somename", "someavatar", null, null,
final UUID uuid = UUID.randomUUID();
final byte[] name = ProfileHelper.generateRandomByteArray(81);
final VersionedProfile profile = new VersionedProfile("someversion", name, "someavatar", null, null,
null, "somecommitment".getBytes());
when(commands.hget(eq("profiles::" + uuid), eq("someversion"))).thenReturn(null);
@@ -117,8 +129,9 @@ public class ProfilesManagerTest {
@Test
public void testGetProfileAsyncNotInCache() {
UUID uuid = UUID.randomUUID();
VersionedProfile profile = new VersionedProfile("someversion", "somename", "someavatar", null, null,
final UUID uuid = UUID.randomUUID();
final byte[] name = ProfileHelper.generateRandomByteArray(81);
final VersionedProfile profile = new VersionedProfile("someversion", name, "someavatar", null, null,
null, "somecommitment".getBytes());
when(asyncCommands.hget(eq("profiles::" + uuid), eq("someversion"))).thenReturn(MockRedisFuture.completedFuture(null));
@@ -140,8 +153,9 @@ public class ProfilesManagerTest {
@Test
public void testGetProfileBrokenCache() {
UUID uuid = UUID.randomUUID();
VersionedProfile profile = new VersionedProfile("someversion", "somename", "someavatar", null, null,
final UUID uuid = UUID.randomUUID();
final byte[] name = ProfileHelper.generateRandomByteArray(81);
final VersionedProfile profile = new VersionedProfile("someversion", name, "someavatar", null, null,
null, "somecommitment".getBytes());
when(commands.hget(eq("profiles::" + uuid), eq("someversion"))).thenThrow(new RedisException("Connection lost"));
@@ -162,8 +176,9 @@ public class ProfilesManagerTest {
@Test
public void testGetProfileAsyncBrokenCache() {
UUID uuid = UUID.randomUUID();
VersionedProfile profile = new VersionedProfile("someversion", "somename", "someavatar", null, null,
final UUID uuid = UUID.randomUUID();
final byte[] name = ProfileHelper.generateRandomByteArray(81);
final VersionedProfile profile = new VersionedProfile("someversion", name, "someavatar", null, null,
null, "somecommitment".getBytes());
when(asyncCommands.hget(eq("profiles::" + uuid), eq("someversion"))).thenReturn(MockRedisFuture.failedFuture(new RedisException("Connection lost")));
@@ -185,8 +200,9 @@ public class ProfilesManagerTest {
@Test
public void testSet() {
UUID uuid = UUID.randomUUID();
VersionedProfile profile = new VersionedProfile("someversion", "somename", "someavatar", null, null,
final UUID uuid = UUID.randomUUID();
final byte[] name = ProfileHelper.generateRandomByteArray(81);
final VersionedProfile profile = new VersionedProfile("someversion", name, "someavatar", null, null,
null, "somecommitment".getBytes());
profilesManager.set(uuid, profile);
@@ -200,8 +216,9 @@ public class ProfilesManagerTest {
@Test
public void testSetAsync() {
UUID uuid = UUID.randomUUID();
VersionedProfile profile = new VersionedProfile("someversion", "somename", "someavatar", null, null,
final UUID uuid = UUID.randomUUID();
final byte[] name = ProfileHelper.generateRandomByteArray(81);
final VersionedProfile profile = new VersionedProfile("someversion", name, "someavatar", null, null,
null, "somecommitment".getBytes());
when(asyncCommands.hset(eq("profiles::" + uuid), eq("someversion"), anyString())).thenReturn(MockRedisFuture.completedFuture(null));
@@ -15,6 +15,7 @@ import org.junit.jupiter.params.provider.MethodSource;
import org.signal.libsignal.protocol.ServiceId;
import org.signal.libsignal.zkgroup.InvalidInputException;
import org.signal.libsignal.zkgroup.profiles.ProfileKey;
import org.whispersystems.textsecuregcm.tests.util.ProfileHelper;
import org.whispersystems.textsecuregcm.util.AttributeValues;
import org.whispersystems.textsecuregcm.storage.DynamoDbExtensionSchema.Tables;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
@@ -22,10 +23,8 @@ import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Base64;
import java.util.Map;
import java.util.Optional;
import java.util.Random;
import java.util.UUID;
import java.util.stream.Stream;
@@ -45,10 +44,10 @@ public class ProfilesTest {
Tables.PROFILES.tableName());
final byte[] commitment = new ProfileKey(new byte[32]).getCommitment(new ServiceId.Aci(ACI)).serialize();
final String version = "someVersion";
final String name = generateRandomBase64FromByteArray(81);
final String validAboutEmoji = generateRandomBase64FromByteArray(60);
final String validAbout = generateRandomBase64FromByteArray(156);
final String avatar = "profiles/" + generateRandomBase64FromByteArray(16);
final byte[] name = ProfileHelper.generateRandomByteArray(81);
final byte[] validAboutEmoji = ProfileHelper.generateRandomByteArray(60);
final byte[] validAbout = ProfileHelper.generateRandomByteArray(156);
final String avatar = "profiles/" + ProfileHelper.generateRandomBase64FromByteArray(16);
validProfile = new VersionedProfile(version, name, avatar, validAboutEmoji, validAbout, null, commitment);
}
@@ -57,28 +56,28 @@ public class ProfilesTest {
void testSetGet() {
profiles.set(ACI, validProfile);
Optional<VersionedProfile> retrieved = profiles.get(ACI, validProfile.getVersion());
Optional<VersionedProfile> retrieved = profiles.get(ACI, validProfile.version());
assertThat(retrieved.isPresent()).isTrue();
assertThat(retrieved.get().getName()).isEqualTo(validProfile.getName());
assertThat(retrieved.get().getAvatar()).isEqualTo(validProfile.getAvatar());
assertThat(retrieved.get().getCommitment()).isEqualTo(validProfile.getCommitment());
assertThat(retrieved.get().getAbout()).isEqualTo(validProfile.getAbout());
assertThat(retrieved.get().getAboutEmoji()).isEqualTo(validProfile.getAboutEmoji());
assertThat(retrieved.get().name()).isEqualTo(validProfile.name());
assertThat(retrieved.get().avatar()).isEqualTo(validProfile.avatar());
assertThat(retrieved.get().commitment()).isEqualTo(validProfile.commitment());
assertThat(retrieved.get().about()).isEqualTo(validProfile.about());
assertThat(retrieved.get().aboutEmoji()).isEqualTo(validProfile.aboutEmoji());
}
@Test
void testSetGetAsync() {
profiles.setAsync(ACI, validProfile).join();
Optional<VersionedProfile> retrieved = profiles.getAsync(ACI, validProfile.getVersion()).join();
Optional<VersionedProfile> retrieved = profiles.getAsync(ACI, validProfile.version()).join();
assertThat(retrieved.isPresent()).isTrue();
assertThat(retrieved.get().getName()).isEqualTo(validProfile.getName());
assertThat(retrieved.get().getAvatar()).isEqualTo(validProfile.getAvatar());
assertThat(retrieved.get().getCommitment()).isEqualTo(validProfile.getCommitment());
assertThat(retrieved.get().getAbout()).isEqualTo(validProfile.getAbout());
assertThat(retrieved.get().getAboutEmoji()).isEqualTo(validProfile.getAboutEmoji());
assertThat(retrieved.get().name()).isEqualTo(validProfile.name());
assertThat(retrieved.get().avatar()).isEqualTo(validProfile.avatar());
assertThat(retrieved.get().commitment()).isEqualTo(validProfile.commitment());
assertThat(retrieved.get().about()).isEqualTo(validProfile.about());
assertThat(retrieved.get().aboutEmoji()).isEqualTo(validProfile.aboutEmoji());
}
@Test
@@ -88,12 +87,12 @@ public class ProfilesTest {
profiles.deleteAll(ACI);
final String version = "someVersion";
final String name = generateRandomBase64FromByteArray(81);
final String differentAvatar = "profiles/" + generateRandomBase64FromByteArray(16);
final String differentEmoji = generateRandomBase64FromByteArray(60);
final String differentAbout = generateRandomBase64FromByteArray(156);
final String paymentAddress = generateRandomBase64FromByteArray(582);
final byte[] commitment = new ProfileKey(generateRandomByteArray(32)).getCommitment(new ServiceId.Aci(ACI)).serialize();
final byte[] name = ProfileHelper.generateRandomByteArray(81);
final String differentAvatar = "profiles/" + ProfileHelper.generateRandomBase64FromByteArray(16);
final byte[] differentEmoji = ProfileHelper.generateRandomByteArray(60);
final byte[] differentAbout = ProfileHelper.generateRandomByteArray(156);
final byte[] paymentAddress = ProfileHelper.generateRandomByteArray(582);
final byte[] commitment = new ProfileKey(ProfileHelper.generateRandomByteArray(32)).getCommitment(new ServiceId.Aci(ACI)).serialize();
VersionedProfile updatedProfile = new VersionedProfile(version, name, differentAvatar,
differentEmoji, differentAbout, paymentAddress, commitment);
@@ -103,18 +102,18 @@ public class ProfilesTest {
Optional<VersionedProfile> retrieved = profiles.get(ACI, version);
assertThat(retrieved.isPresent()).isTrue();
assertThat(retrieved.get().getName()).isEqualTo(updatedProfile.getName());
assertThat(retrieved.get().getAvatar()).isEqualTo(updatedProfile.getAvatar());
assertThat(retrieved.get().getCommitment()).isEqualTo(updatedProfile.getCommitment());
assertThat(retrieved.get().getAbout()).isEqualTo(updatedProfile.getAbout());
assertThat(retrieved.get().getAboutEmoji()).isEqualTo(updatedProfile.getAboutEmoji());
assertThat(retrieved.get().name()).isEqualTo(updatedProfile.name());
assertThat(retrieved.get().avatar()).isEqualTo(updatedProfile.avatar());
assertThat(retrieved.get().commitment()).isEqualTo(updatedProfile.commitment());
assertThat(retrieved.get().about()).isEqualTo(updatedProfile.about());
assertThat(retrieved.get().aboutEmoji()).isEqualTo(updatedProfile.aboutEmoji());
}
@Test
void testSetGetNullOptionalFields() throws InvalidInputException {
final String version = "someVersion";
final String name = generateRandomBase64FromByteArray(81);
final byte[] commitment = new ProfileKey(generateRandomByteArray(32)).getCommitment(new ServiceId.Aci(ACI)).serialize();
final byte[] name = ProfileHelper.generateRandomByteArray(81);
final byte[] commitment = new ProfileKey(ProfileHelper.generateRandomByteArray(32)).getCommitment(new ServiceId.Aci(ACI)).serialize();
VersionedProfile profile = new VersionedProfile(version, name, null, null, null, null,
commitment);
@@ -123,47 +122,47 @@ public class ProfilesTest {
Optional<VersionedProfile> retrieved = profiles.get(ACI, version);
assertThat(retrieved.isPresent()).isTrue();
assertThat(retrieved.get().getName()).isEqualTo(profile.getName());
assertThat(retrieved.get().getAvatar()).isEqualTo(profile.getAvatar());
assertThat(retrieved.get().getCommitment()).isEqualTo(profile.getCommitment());
assertThat(retrieved.get().getAbout()).isEqualTo(profile.getAbout());
assertThat(retrieved.get().getAboutEmoji()).isEqualTo(profile.getAboutEmoji());
assertThat(retrieved.get().name()).isEqualTo(profile.name());
assertThat(retrieved.get().avatar()).isEqualTo(profile.avatar());
assertThat(retrieved.get().commitment()).isEqualTo(profile.commitment());
assertThat(retrieved.get().about()).isEqualTo(profile.about());
assertThat(retrieved.get().aboutEmoji()).isEqualTo(profile.aboutEmoji());
}
@Test
void testSetReplace() throws InvalidInputException {
profiles.set(ACI, validProfile);
Optional<VersionedProfile> retrieved = profiles.get(ACI, validProfile.getVersion());
Optional<VersionedProfile> retrieved = profiles.get(ACI, validProfile.version());
assertThat(retrieved.isPresent()).isTrue();
assertThat(retrieved.get().getName()).isEqualTo(validProfile.getName());
assertThat(retrieved.get().getAvatar()).isEqualTo(validProfile.getAvatar());
assertThat(retrieved.get().getCommitment()).isEqualTo(validProfile.getCommitment());
assertThat(retrieved.get().getAbout()).isEqualTo(validProfile.getAbout());
assertThat(retrieved.get().getAboutEmoji()).isEqualTo(validProfile.getAboutEmoji());
assertThat(retrieved.get().getPaymentAddress()).isNull();
assertThat(retrieved.get().name()).isEqualTo(validProfile.name());
assertThat(retrieved.get().avatar()).isEqualTo(validProfile.avatar());
assertThat(retrieved.get().commitment()).isEqualTo(validProfile.commitment());
assertThat(retrieved.get().about()).isEqualTo(validProfile.about());
assertThat(retrieved.get().aboutEmoji()).isEqualTo(validProfile.aboutEmoji());
assertThat(retrieved.get().paymentAddress()).isNull();
final String differentName = generateRandomBase64FromByteArray(81);
final String differentEmoji = generateRandomBase64FromByteArray(60);
final String differentAbout = generateRandomBase64FromByteArray(156);
final String differentAvatar = "profiles/" + generateRandomBase64FromByteArray(16);
final byte[] differentCommitment = new ProfileKey(generateRandomByteArray(32)).getCommitment(new ServiceId.Aci(ACI)).serialize();
final byte[] differentName = ProfileHelper.generateRandomByteArray(81);
final byte[] differentEmoji = ProfileHelper.generateRandomByteArray(60);
final byte[] differentAbout = ProfileHelper.generateRandomByteArray(156);
final String differentAvatar = "profiles/" + ProfileHelper.generateRandomBase64FromByteArray(16);
final byte[] differentCommitment = new ProfileKey(ProfileHelper.generateRandomByteArray(32)).getCommitment(new ServiceId.Aci(ACI)).serialize();
VersionedProfile updated = new VersionedProfile(validProfile.getVersion(), differentName, differentAvatar, differentEmoji, differentAbout, null,
VersionedProfile updated = new VersionedProfile(validProfile.version(), differentName, differentAvatar, differentEmoji, differentAbout, null,
differentCommitment);
profiles.set(ACI, updated);
retrieved = profiles.get(ACI, updated.getVersion());
retrieved = profiles.get(ACI, updated.version());
assertThat(retrieved.isPresent()).isTrue();
assertThat(retrieved.get().getName()).isEqualTo(updated.getName());
assertThat(retrieved.get().getAbout()).isEqualTo(updated.getAbout());
assertThat(retrieved.get().getAboutEmoji()).isEqualTo(updated.getAboutEmoji());
assertThat(retrieved.get().getAvatar()).isEqualTo(updated.getAvatar());
assertThat(retrieved.get().name()).isEqualTo(updated.name());
assertThat(retrieved.get().about()).isEqualTo(updated.about());
assertThat(retrieved.get().aboutEmoji()).isEqualTo(updated.aboutEmoji());
assertThat(retrieved.get().avatar()).isEqualTo(updated.avatar());
// Commitment should be unchanged after an overwrite
assertThat(retrieved.get().getCommitment()).isEqualTo(validProfile.getCommitment());
assertThat(retrieved.get().commitment()).isEqualTo(validProfile.commitment());
}
@Test
@@ -171,17 +170,17 @@ public class ProfilesTest {
final String versionOne = "versionOne";
final String versionTwo = "versionTwo";
final String nameOne = generateRandomBase64FromByteArray(81);
final String nameTwo = generateRandomBase64FromByteArray(81);
final byte[] nameOne = ProfileHelper.generateRandomByteArray(81);
final byte[] nameTwo = ProfileHelper.generateRandomByteArray(81);
final String avatarOne = "profiles/" + generateRandomBase64FromByteArray(16);
final String avatarTwo = "profiles/" + generateRandomBase64FromByteArray(16);
final String avatarOne = "profiles/" + ProfileHelper.generateRandomBase64FromByteArray(16);
final String avatarTwo = "profiles/" + ProfileHelper.generateRandomBase64FromByteArray(16);
final String aboutEmoji = generateRandomBase64FromByteArray(60);
final String about = generateRandomBase64FromByteArray(156);
final byte[] aboutEmoji = ProfileHelper.generateRandomByteArray(60);
final byte[] about = ProfileHelper.generateRandomByteArray(156);
final byte[] commitmentOne = new ProfileKey(generateRandomByteArray(32)).getCommitment(new ServiceId.Aci(ACI)).serialize();
final byte[] commitmentTwo = new ProfileKey(generateRandomByteArray(32)).getCommitment(new ServiceId.Aci(ACI)).serialize();
final byte[] commitmentOne = new ProfileKey(ProfileHelper.generateRandomByteArray(32)).getCommitment(new ServiceId.Aci(ACI)).serialize();
final byte[] commitmentTwo = new ProfileKey(ProfileHelper.generateRandomByteArray(32)).getCommitment(new ServiceId.Aci(ACI)).serialize();
VersionedProfile profileOne = new VersionedProfile(versionOne, nameOne, avatarOne, null, null,
null, commitmentOne);
@@ -193,20 +192,20 @@ public class ProfilesTest {
Optional<VersionedProfile> retrieved = profiles.get(ACI, versionOne);
assertThat(retrieved.isPresent()).isTrue();
assertThat(retrieved.get().getName()).isEqualTo(profileOne.getName());
assertThat(retrieved.get().getAvatar()).isEqualTo(profileOne.getAvatar());
assertThat(retrieved.get().getCommitment()).isEqualTo(profileOne.getCommitment());
assertThat(retrieved.get().getAbout()).isEqualTo(profileOne.getAbout());
assertThat(retrieved.get().getAboutEmoji()).isEqualTo(profileOne.getAboutEmoji());
assertThat(retrieved.get().name()).isEqualTo(profileOne.name());
assertThat(retrieved.get().avatar()).isEqualTo(profileOne.avatar());
assertThat(retrieved.get().commitment()).isEqualTo(profileOne.commitment());
assertThat(retrieved.get().about()).isEqualTo(profileOne.about());
assertThat(retrieved.get().aboutEmoji()).isEqualTo(profileOne.aboutEmoji());
retrieved = profiles.get(ACI, versionTwo);
assertThat(retrieved.isPresent()).isTrue();
assertThat(retrieved.get().getName()).isEqualTo(profileTwo.getName());
assertThat(retrieved.get().getAvatar()).isEqualTo(profileTwo.getAvatar());
assertThat(retrieved.get().getCommitment()).isEqualTo(profileTwo.getCommitment());
assertThat(retrieved.get().getAbout()).isEqualTo(profileTwo.getAbout());
assertThat(retrieved.get().getAboutEmoji()).isEqualTo(profileTwo.getAboutEmoji());
assertThat(retrieved.get().name()).isEqualTo(profileTwo.name());
assertThat(retrieved.get().avatar()).isEqualTo(profileTwo.avatar());
assertThat(retrieved.get().commitment()).isEqualTo(profileTwo.commitment());
assertThat(retrieved.get().about()).isEqualTo(profileTwo.about());
assertThat(retrieved.get().aboutEmoji()).isEqualTo(profileTwo.aboutEmoji());
}
@Test
@@ -224,17 +223,17 @@ public class ProfilesTest {
final String versionOne = "versionOne";
final String versionTwo = "versionTwo";
final String nameOne = generateRandomBase64FromByteArray(81);
final String nameTwo = generateRandomBase64FromByteArray(81);
final byte[] nameOne = ProfileHelper.generateRandomByteArray(81);
final byte[] nameTwo = ProfileHelper.generateRandomByteArray(81);
final String aboutEmoji = generateRandomBase64FromByteArray(60);
final String about = generateRandomBase64FromByteArray(156);
final byte[] aboutEmoji = ProfileHelper.generateRandomByteArray(60);
final byte[] about = ProfileHelper.generateRandomByteArray(156);
final String avatarOne = "profiles/" + generateRandomBase64FromByteArray(16);
final String avatarTwo = "profiles/" + generateRandomBase64FromByteArray(16);
final String avatarOne = "profiles/" + ProfileHelper.generateRandomBase64FromByteArray(16);
final String avatarTwo = "profiles/" + ProfileHelper.generateRandomBase64FromByteArray(16);
final byte[] commitmentOne = new ProfileKey(generateRandomByteArray(32)).getCommitment(new ServiceId.Aci(ACI)).serialize();
final byte[] commitmentTwo = new ProfileKey(generateRandomByteArray(32)).getCommitment(new ServiceId.Aci(ACI)).serialize();
final byte[] commitmentOne = new ProfileKey(ProfileHelper.generateRandomByteArray(32)).getCommitment(new ServiceId.Aci(ACI)).serialize();
final byte[] commitmentTwo = new ProfileKey(ProfileHelper.generateRandomByteArray(32)).getCommitment(new ServiceId.Aci(ACI)).serialize();
VersionedProfile profileOne = new VersionedProfile(versionOne, nameOne, avatarOne, null, null,
null, commitmentOne);
@@ -262,12 +261,12 @@ public class ProfilesTest {
private static Stream<Arguments> buildUpdateExpression() throws InvalidInputException {
final String version = "someVersion";
final String name = generateRandomBase64FromByteArray(81);
final String avatar = "profiles/" + generateRandomBase64FromByteArray(16);;
final String emoji = generateRandomBase64FromByteArray(60);
final String about = generateRandomBase64FromByteArray(156);
final String paymentAddress = generateRandomBase64FromByteArray(582);
final byte[] commitment = new ProfileKey(generateRandomByteArray(32)).getCommitment(new ServiceId.Aci(ACI)).serialize();
final byte[] name = ProfileHelper.generateRandomByteArray(81);
final String avatar = "profiles/" + ProfileHelper.generateRandomBase64FromByteArray(16);;
final byte[] emoji = ProfileHelper.generateRandomByteArray(60);
final byte[] about = ProfileHelper.generateRandomByteArray(156);
final byte[] paymentAddress = ProfileHelper.generateRandomByteArray(582);
final byte[] commitment = new ProfileKey(ProfileHelper.generateRandomByteArray(32)).getCommitment(new ServiceId.Aci(ACI)).serialize();
return Stream.of(
Arguments.of(
@@ -304,67 +303,57 @@ public class ProfilesTest {
private static Stream<Arguments> buildUpdateExpressionAttributeValues() throws InvalidInputException {
final String version = "someVersion";
final String name = generateRandomBase64FromByteArray(81);
final String avatar = "profiles/" + generateRandomBase64FromByteArray(16);;
final String emoji = generateRandomBase64FromByteArray(60);
final String about = generateRandomBase64FromByteArray(156);
final String paymentAddress = generateRandomBase64FromByteArray(582);
final byte[] commitment = new ProfileKey(generateRandomByteArray(32)).getCommitment(new ServiceId.Aci(ACI)).serialize();
final byte[] name = ProfileHelper.generateRandomByteArray(81);
final String avatar = "profiles/" + ProfileHelper.generateRandomBase64FromByteArray(16);;
final byte[] emoji = ProfileHelper.generateRandomByteArray(60);
final byte[] about = ProfileHelper.generateRandomByteArray(156);
final byte[] paymentAddress = ProfileHelper.generateRandomByteArray(582);
final byte[] commitment = new ProfileKey(ProfileHelper.generateRandomByteArray(32)).getCommitment(new ServiceId.Aci(ACI)).serialize();
return Stream.of(
Arguments.of(
new VersionedProfile(version, name, avatar, emoji, about, paymentAddress, commitment),
Map.of(
":commitment", AttributeValues.fromByteArray(commitment),
":name", AttributeValues.fromString(name),
":name", AttributeValues.fromByteArray(name),
":avatar", AttributeValues.fromString(avatar),
":aboutEmoji", AttributeValues.fromString(emoji),
":about", AttributeValues.fromString(about),
":paymentAddress", AttributeValues.fromString(paymentAddress))),
":aboutEmoji", AttributeValues.fromByteArray(emoji),
":about", AttributeValues.fromByteArray(about),
":paymentAddress", AttributeValues.fromByteArray(paymentAddress))),
Arguments.of(
new VersionedProfile(version, name, avatar, emoji, about, null, commitment),
Map.of(
":commitment", AttributeValues.fromByteArray(commitment),
":name", AttributeValues.fromString(name),
":name", AttributeValues.fromByteArray(name),
":avatar", AttributeValues.fromString(avatar),
":aboutEmoji", AttributeValues.fromString(emoji),
":about", AttributeValues.fromString(about))),
":aboutEmoji", AttributeValues.fromByteArray(emoji),
":about", AttributeValues.fromByteArray(about))),
Arguments.of(
new VersionedProfile(version, name, avatar, emoji, null, null, commitment),
Map.of(
":commitment", AttributeValues.fromByteArray(commitment),
":name", AttributeValues.fromString(name),
":name",AttributeValues.fromByteArray(name),
":avatar", AttributeValues.fromString(avatar),
":aboutEmoji", AttributeValues.fromString(emoji))),
":aboutEmoji", AttributeValues.fromByteArray(emoji))),
Arguments.of(
new VersionedProfile(version, name, avatar, null, null, null, commitment),
Map.of(
":commitment", AttributeValues.fromByteArray(commitment),
":name", AttributeValues.fromString(name),
":name", AttributeValues.fromByteArray(name),
":avatar", AttributeValues.fromString(avatar))),
Arguments.of(
new VersionedProfile(version, name, null, null, null, null, commitment),
Map.of(
":commitment", AttributeValues.fromByteArray(commitment),
":name", AttributeValues.fromString(name))),
":name", AttributeValues.fromByteArray(name))),
Arguments.of(
new VersionedProfile(version, null, null, null, null, null, commitment),
Map.of(":commitment", AttributeValues.fromByteArray(commitment)))
);
}
private static String generateRandomBase64FromByteArray(final int byteArrayLength) {
return Base64.getEncoder().encodeToString(generateRandomByteArray(byteArrayLength));
}
private static byte[] generateRandomByteArray(final int length) {
byte[] byteArray = new byte[length];
new Random().nextBytes(byteArray);
return byteArray;
}
}
@@ -125,8 +125,8 @@ public class AccountsHelper {
case "isPaymentActivationSupported" -> when(updatedAccount.isPaymentActivationSupported()).thenAnswer(stubbing);
case "getEnabledDeviceCount" -> when(updatedAccount.getEnabledDeviceCount()).thenAnswer(stubbing);
case "getRegistrationLock" -> when(updatedAccount.getRegistrationLock()).thenAnswer(stubbing);
case "getIdentityKey" -> when(updatedAccount.getIdentityKey()).thenAnswer(stubbing);
case "getPhoneNumberIdentityKey" -> when(updatedAccount.getPhoneNumberIdentityKey()).thenAnswer(stubbing);
case "getIdentityKey" ->
when(updatedAccount.getIdentityKey(stubbing.getInvocation().getArgument(0))).thenAnswer(stubbing);
case "getBadges" -> when(updatedAccount.getBadges()).thenAnswer(stubbing);
case "getLastSeen" -> when(updatedAccount.getLastSeen()).thenAnswer(stubbing);
case "hasLockedCredentials" -> when(updatedAccount.hasLockedCredentials()).thenAnswer(stubbing);
@@ -27,6 +27,7 @@ import org.whispersystems.textsecuregcm.auth.AuthenticatedAccount;
import org.whispersystems.textsecuregcm.auth.DisabledPermittedAccountAuthenticator;
import org.whispersystems.textsecuregcm.auth.DisabledPermittedAuthenticatedAccount;
import org.whispersystems.textsecuregcm.auth.SaltedTokenHash;
import org.whispersystems.textsecuregcm.identity.IdentityType;
import org.whispersystems.textsecuregcm.storage.Account;
import org.whispersystems.textsecuregcm.storage.AccountsManager;
import org.whispersystems.textsecuregcm.storage.Device;
@@ -165,7 +166,7 @@ public class AuthHelper {
when(UNDISCOVERABLE_ACCOUNT.isDiscoverableByPhoneNumber()).thenReturn(false);
when(VALID_ACCOUNT_3.isDiscoverableByPhoneNumber()).thenReturn(true);
when(VALID_ACCOUNT.getIdentityKey()).thenReturn(VALID_IDENTITY);
when(VALID_ACCOUNT.getIdentityKey(IdentityType.ACI)).thenReturn(VALID_IDENTITY);
reset(ACCOUNTS_MANAGER);
@@ -0,0 +1,20 @@
package org.whispersystems.textsecuregcm.tests.util;
import java.util.Base64;
import java.util.Random;
public class ProfileHelper {
public static String generateRandomBase64FromByteArray(final int byteArrayLength) {
return encodeToBase64(generateRandomByteArray(byteArrayLength));
}
public static byte[] generateRandomByteArray(final int length) {
byte[] byteArray = new byte[length];
new Random().nextBytes(byteArray);
return byteArray;
}
public static String encodeToBase64(final byte[] input) {
return Base64.getEncoder().encodeToString(input);
}
}
@@ -1,3 +0,0 @@
{
"token" : "BQVVHxMt5zAFXA"
}
@@ -1,4 +0,0 @@
{
"token" : "BQVVHxMt5zAFXA",
"relay" : "whisper"
}
@@ -1,6 +0,0 @@
{
"token" : "BQVVHxMt5zAFXA",
"voice" : true,
"video" : true,
"relay" : "whisper"
}
@@ -1,5 +0,0 @@
{
"token" : "BQVVHxMt5zAFXA",
"voice" : true,
"relay" : "whisper"
}
@@ -1,7 +0,0 @@
{
"deviceId" : 1,
"keyId" : 1234,
"publicKey" : "test",
"identityKey" : "identityTest",
"registrationId" : 987
}
@@ -1 +0,0 @@
{"devices":[{"id":1,"name":"foo","authToken":"bar","salt":"salt","signalingKey":"keykey","gcmId":"gcm-id","apnId":"apn-id","voipApnId":"voipapn-id","pushTimestamp":0,"uninstalledFeedback":0,"fetchesMessages":true,"registrationId":1234,"signedPreKey":{"keyId":5,"publicKey":"public-signed","signature":"signtture-signed"},"lastSeen":31337,"created":31336,"userAgent":"CoolClient","unauthenticatedDelivery":true}],"identityKey":"identity_key_value","name":"OneProfileName","avatar":null,"avatarDigest":null,"pin":"******","registrationLock":null, "registrationLockSalt":null,"uak":"AAAAAAAAAAAAAAAAAAAAAA==","uua":false}
@@ -1 +0,0 @@
{"devices":[{"id":1,"name":"2foo","authToken":"2bar","salt":"2salt","signalingKey":"2keykey","gcmId":"2gcm-id","apnId":"2apn-id","voipApnId":"2voipapn-id","pushTimestamp":0,"uninstalledFeedback":0,"fetchesMessages":true,"registrationId":1234,"signedPreKey":{"keyId":5,"publicKey":"public-signed","signature":"signtture-signed"},"lastSeen":31337,"created":31336,"userAgent":"CoolClient","unauthenticatedDelivery":true}],"identityKey":"different_identity_key_value","name":"TwoProfileName","avatar":null,"avatarDigest":null,"pin":"******","registrationLock":null,"registrationLockSalt":null,"uak":"AAAAAAAAAAAAAAAAAAAAAA==","uua":false}
@@ -0,0 +1,48 @@
{
"number": "+14152222222",
"usernameHash": null,
"reservedUsernameHash": null,
"usernameLinkHandle": null,
"devices": [
{
"id": 1,
"name": null,
"authToken": null,
"salt": null,
"gcmId": null,
"apnId": null,
"voipApnId": null,
"pushTimestamp": 0,
"uninstalledFeedback": 0,
"fetchesMessages": true,
"registrationId": 1,
"signedPreKey": {
"keyId": 1,
"publicKey": "BerKjYSh1PdniL5bhI9kwbH/Et3mx/8CypR1TYo/+d5o",
"signature": "iK2yJkl0l6qe58Fy1dVo31X5sp6EiXSS5FZfa3W//E+Abylfa6ZRmM97CzTdXNu2DjgxZYF43G6HfJ49+99hgg"
},
"lastSeen" : 1692748800000,
"created" : 1692718240137,
"userAgent": null,
"capabilities": null,
"pniRegistrationId": 2,
"pniSignedPreKey": {
"keyId": 2,
"publicKey": "BXcLL1VLft3tUnr/5UIW5Q0Hsr8/Az0CGJ+EuFqiXCYc",
"signature": "YoKqyeOCHC0E9mqMoc1UPeyuLqGc8nvY+3D3YX5HC1bhxS48ZLYo40xql51A2CpIBqVmA+2gV3PXCV1Yhq4UAQ"
}
}
],
"identityKey": "BaMV4k/+jSn7jmHnRAPvfc7XBZOcayrhOmHFbGJwMyFS",
"badges": [],
"registrationLock": null,
"registrationLockSalt": null,
"version": 0,
"pni": "22222222-2222-2222-2222-222222222222",
"eu": null,
"pniIdentityKey": "Bc0Myhpf2D+iCgUfIs+UStgffR/VGQRfP9mwFHI4U2x4",
"cpv": null,
"uak": "p5uWNi83Muqsd16PLi0/tQ==",
"uua": true,
"inCds": true
}